Compare commits

...

247 Commits

Author SHA1 Message Date
fatedier
595aba5a9b Merge pull request #3248 from fatedier/dev
bump version
2023-01-10 10:26:56 +08:00
fatedier
679992db25 update version (#3247) 2023-01-10 10:24:44 +08:00
fatedier
5cfbb976f4 pkg/util/net: fix quic streams leak (#3246) 2023-01-10 10:19:37 +08:00
Craig O'Donnell
b03f0ad1e6 fix: incorrect op for newWorkConn (#3244)
(cherry picked from commit 53b6bbf0b14ab632dc89416d7fffa9b1d0887c0a)
2023-01-09 10:34:09 +08:00
0x7fff
804f2910fd refactor: ifelse (#3224) 2022-12-22 17:55:06 +08:00
fatedier
a4189ba474 Merge branch 'dev' 2022-12-18 19:27:22 +08:00
fatedier
e2d28d9929 update goreleaser.yaml 2022-12-18 19:18:09 +08:00
fatedier
9ec84f8143 Merge pull request #3218 from fatedier/dev
release v0.46.0
2022-12-18 18:46:52 +08:00
fatedier
7678938c08 support quic options (#3211) 2022-12-18 18:43:42 +08:00
0x7fff
b2e3946800 feat: release (#3205)
Co-authored-by: blizard863 <760076784@qq.com>
2022-12-13 22:37:06 +08:00
0x7fff
af0b7939a7 feat: odic refine (#3202)
Co-authored-by: Matt Feury <mattfeury@gmail.com>
2022-12-12 15:10:38 +08:00
fatedier
2f66dc3e99 support protocol quic between frpc and frps (#3198) 2022-12-12 11:04:10 +08:00
Matt Feury
649df8827c feat: Support OIDC scope parameter (#3192) 2022-12-09 11:46:34 +08:00
Ashish Kurmi
da51adc276 Set least privileged token permission for GitHub Actions (#3155)
Signed-off-by: Ashish Kurmi <akurmi@stepsecurity.io>
2022-10-31 15:46:46 +08:00
fatedier
e5af37bc8c upgrade github actions version (#3150) 2022-10-27 14:22:14 +08:00
fatedier
8ab474cc97 remove unsupported platform (#3148) 2022-10-27 10:22:47 +08:00
fatedier
e8c8d5903a remove unsupported platform 2022-10-27 10:19:30 +08:00
fatedier
a301046f3d Merge pull request #3147 from fatedier/dev
bump version
2022-10-26 23:18:40 +08:00
fatedier
34ab6b0e74 add release notes 2022-10-26 23:09:17 +08:00
fatedier
cf66ca10b4 improve http group load balancing (#3131) 2022-10-19 12:14:35 +08:00
fatedier
3fbe6b659e adjust sponsors (#3136) 2022-10-19 12:14:09 +08:00
fatedier
6a71d71e58 improve not found response (#3121) 2022-10-09 12:13:27 +08:00
fatedier
6ecc97c857 update deps (#3094) 2022-09-08 17:16:45 +08:00
Abirdcfly
ba492f07c3 chore: remove duplicate word in comments (#3081) 2022-08-29 12:25:36 +08:00
fatedier
9d077b02cf lint by golangci-lint (#3080) 2022-08-29 01:02:53 +08:00
Dingli Zhang
f4e4fbea62 Add support for riscv64 (#3071) 2022-08-23 10:10:04 +08:00
Yonatan Koren
3e721d122b Update README.md (#3062) 2022-08-16 20:47:56 +08:00
chenjiayao
1bc899ec12 [client] Remove redundant function parameters (#3016) 2022-07-14 15:31:32 +08:00
ChristLZS
6f2571980c [client] Fixed a bug where service loops reconnection after disconnection.service is shut down and can not exit goroutine (#3012)
Co-authored-by: lizhisheng <zhishengli@deepglint.com>
2022-07-12 18:43:58 +08:00
fatedier
8888610d83 Merge pull request #3010 from fatedier/dev
release v0.44.0
2022-07-11 00:10:43 +08:00
fatedier
fa7c05c617 release note for v0.44.0 2022-07-11 00:06:57 +08:00
EMRE ÇELİK
218b354f82 Server Dashboard SSL Support (#2982) 2022-06-27 10:08:02 +08:00
fatedier
c652b8ef07 fix ipv6 address parsing (#2978) 2022-06-14 14:24:34 +08:00
fatedier
5b8b145577 Use auto generated certificates if plugin_key_path and plugin_crt_path are empty for plugin https2https and https2http. (#2968) 2022-06-05 17:15:28 +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
0711295b0a release note for v0.43.0 (#2954) 2022-05-27 16:02:36 +08:00
fatedier
4af85da0c2 type http/tcpmux proxy support route_by_http_user, tcpmux support passthourgh mode (#2932) 2022-05-26 23:57:30 +08:00
fatedier
bd89eaba2f remove systemd files 2022-04-29 21:31:48 +08:00
fatedier
a72259c604 docker build&push: some adjustments 2022-04-29 01:15:42 +08:00
蓝云Reyes
44eb513f05 Update docker image build file (#2892)
* update docker image building
2022-04-29 01:12:07 +08:00
fatedier
eb1e19a821 Merge pull request #2906 from fatedier/dev
bump version
2022-04-22 11:32:27 +08:00
fatedier
6c658586f6 bump version to v0.42.0 2022-04-22 11:15:23 +08:00
fatedier
888ed25314 dependency: update github.com/pires/go-proxyproto to v0.6.2 (#2894) 2022-04-15 11:36:00 +08:00
fatedier
21240ed962 some improvements 2022-04-14 11:24:36 +08:00
Colin Adler
6481870d03 fix: data races when accessing github.com/fatedier/frp/client.(*Service).ctl (#2891)
* fix: data race in client/service.go

* review fixes
2022-04-14 11:14:19 +08:00
fatedier
a7a4ba270d fix error parsing env values (#2886) 2022-04-05 12:48:57 +08:00
cui fliter
915d9f4c09 fix some typos (#2882)
Signed-off-by: cuishuang <imcusg@gmail.com>
2022-04-02 17:35:51 +08:00
fatedier
18a2af4703 frpc: support multiple confs (#2873) 2022-03-28 12:12:35 +08:00
fatedier
305e40fa8a update .goreleaser.yml 2022-03-23 21:47:43 +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
4acae540c8 support go1.18 and remove go1.16 (#2868) 2022-03-23 21:15:01 +08:00
fatedier
11b13533a0 add release note (#2867) 2022-03-23 20:14:55 +08:00
fatedier
100d556336 support tcp keepalive params (#2863) 2022-03-22 19:29:30 +08:00
Blizard
452fe25cc6 feat: SUDP alway reconnect and print too much log when no data ready (#2844)
* feat: random sleep duration before reconnecting

* fix: bug
2022-03-17 12:03:20 +08:00
fatedier
63efa6b776 support pprof (#2849) 2022-03-17 11:42:59 +08:00
fatedier
37c27169ac workflows: update stale action (#2846) 2022-03-15 11:53:14 +08:00
fatedier
ce677820c6 Merge pull request #2834 from fatedier/dev
bump version
2022-03-11 19:51:32 +08:00
fatedier
1f88a7a0b8 bump version to v0.40.0 (#2833) 2022-03-11 19:45:34 +08:00
Johan Hernefeldt
eeea7602d9 bugfix: Issue #2831 - Cant connect to frps behind ingress with tls (#2832)
Co-authored-by: Johan Hernefeldt <johan.hernefeldt@moralis.io>
2022-03-11 14:51:47 +08:00
Harry Cheng
bf635c0e90 Notify server plugins when a proxy is closed (#2823)
* add close proxy op

* Move to actual closing routine

* Fix e2e tests for CloseProxy

* Add warning on resource exhaustion

* Add CloseProxy to manual close

* retuen errors to `CloseProxy` callers
2022-03-08 15:08:09 +08:00
Blizard
cd31359a27 feat: support add additional params for OIDC (#2814)
* feat: support add additional params and test access by auth0

* fix: config name

Co-authored-by: blizard863 <760076784@qq.com>
2022-03-07 14:23:49 +08:00
fatedier
19739ed31a random sleep duration before reconnecting (#2816) 2022-02-24 11:59:36 +08:00
fatedier
10100c28d9 client: add dial_server_timeout (#2805) 2022-02-19 16:49:21 +08:00
fatedier
88fcc079e8 Merge pull request #2792 from fatedier/dev
bump version
2022-02-09 16:11:20 +08:00
fatedier
ddc1e163c4 update README 2022-02-09 15:42:34 +08:00
fatedier
d20a6d3d75 update release note 2022-02-09 15:23:01 +08:00
fatedier
6194273615 use net.JoinHostPort instead of fmt.Sprintf (#2791) 2022-02-09 15:19:35 +08:00
fatedier
b2311e55e7 add new sponsor logo (#2785) 2022-01-28 15:29:43 +08:00
fatedier
07873d471f doc: update donation section (#2783) 2022-01-26 20:56:00 +08:00
fatedier
2dab5d0bca Merge pull request #2782 from fatedier/dev
bump version
2022-01-26 20:17:54 +08:00
fatedier
9ca2b586f8 update release note 2022-01-26 20:13:25 +08:00
fatedier
e59eacb8a2 version: bump to v0.39.0 2022-01-26 19:53:22 +08:00
Blizard
0db4fc07fb feat: support set local ip in client when connect server (#2774)
* feat: support set local ip in client when connect server

* fix: typo

Co-authored-by: blizard863 <760076784@qq.com>
2022-01-26 19:47:40 +08:00
fatedier
70f4caac23 move dial functions into golib (#2767) 2022-01-20 20:03:07 +08:00
fatedier
293003fcdb allow to disable application layer heartbeat to reduce traffic cost (#2758)
fix #2754
2022-01-13 14:26:07 +08:00
fatedier
4bfc89d988 update doc for Login operation 2022-01-11 16:36:56 +08:00
fatedier
22412851b4 server plugin: add client address in Login operation, fix #2742 (#2751) 2022-01-11 16:32:20 +08:00
bobo liu
e9775bd70f doc: no X-Real-IP in http proxy (#2743) 2022-01-09 23:47:28 +08:00
nitinSophos
ff7b8b0b62 ISSUE: 2730 Alpine version update for security fixes (#2731)
update docker file to pick alpine:3
2022-01-04 10:40:45 +08:00
fatedier
491c1d7dc4 add new sponsor (#2729) 2022-01-02 14:31:08 +08:00
Blizard
ea568e8a4f refactor: refine pkg net utils (#2720)
* refactor: refine pkg net utils

* fix: x

Co-authored-by: blizard863 <760076784@qq.com>
2021-12-28 21:14:57 +08:00
fatedier
0fb6aeef58 update sponsor content 2021-12-17 15:09:23 +08:00
fatedier
032f33fe5a update readme add sponsor pic (#2704) 2021-12-17 15:05:39 +08:00
fatedier
bbc8b438d5 doc: add local_port for tcpmux example (#2695) 2021-12-08 18:41:21 +08:00
fatedier
05b1ace21f remove authentication for healthz api (#2672) 2021-11-23 14:14:27 +08:00
fatedier
cbdd73b94f typo 2021-11-12 22:18:36 +08:00
fatedier
bf06e3b107 doc for v2 (#2648) 2021-11-09 14:18:40 +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
71489d194c e2e: add delay duration for monitor case 2021-10-25 20:27:22 +08:00
fatedier
85aa3df256 bump version 2021-10-25 20:14:21 +08:00
fatedier
f1a51eba18 client: lint 2021-10-19 15:02:45 +08:00
Blizard
1d26ea440b fix: kcp protocol cause delay release resource (#2621)
Co-authored-by: blizard863 <760076784@qq.com>
2021-10-19 14:57:26 +08:00
Blizard
998e678a7f fix: typo (#2614)
Co-authored-by: blizard863 <760076784@qq.com>
2021-10-11 12:11:59 +08:00
kekeimiku
0cee1877e3 refactor: move from io/ioutil to io and os package (#2592) 2021-09-29 10:33:57 +08:00
fatedier
72a7fd948e Update bug_report.yaml 2021-09-03 11:52:04 +08:00
fatedier
357c9b0dcb use github issue form (#2563) 2021-09-03 11:47:55 +08:00
fatedier
14bd0716d0 Create FUNDING.yml (#2558) 2021-08-31 20:28:13 +08:00
bobo liu
2f74f54f18 Let's get rid of ugly statik (#2255)
* Get rid of ugly statik

go1.16 introduced the embed package, it's the more graceful solution for embedding file into binary.
https://golang.org/pkg/embed/

* remove statik totally

* split go and static files in assets
2021-08-17 20:20:04 +08:00
fatedier
a62a9431b1 support go1.17 and remove go1.15 (#2532) 2021-08-17 15:26:43 +08:00
fatedier
42745a3da2 frpc: add disable_custom_tls_first_byte to not send first custom tls to frps (#2520) 2021-08-11 23:10:35 +08:00
fatedier
82f80a22be add healthz api (#2511) 2021-08-04 14:33:53 +08:00
fatedier
f570dcb307 update stale action 2021-08-04 10:51:18 +08:00
fatedier
997d406ec2 Merge pull request #2508 from fatedier/dev
bump version
2021-08-03 23:13:31 +08:00
fatedier
87e60683ed add release note for v0.37.1 (#2507) 2021-08-03 23:10:27 +08:00
fatedier
86b2e686a5 vhost: use new readClientHello function (#2504) 2021-08-03 22:58:03 +08:00
fatedier
09f39de74e add more e2e test (#2505) 2021-08-02 13:07:28 +08:00
fatedier
2a68c1152f dep: update github.com/hashicorp/yamux to latest (#2472) 2021-07-08 10:42:28 +08:00
Fishbone
df5859b5f7 Fix server-side proxy inappropriate quit when met accept: too many open files error (#2467) 2021-07-05 10:27:15 +08:00
Blizard
3dd888a9ea fix: stuct name typo (#2458)
Co-authored-by: tanghuafa <tanghuafa@bytedance.com>
2021-06-24 16:33:52 +08:00
fatedier
a51e221db3 add real ip test 2021-06-21 19:35:52 +08:00
fatedier
fe4e9b55f3 update github.com/pires/go-proxyproto to v0.5.0 2021-06-21 19:35:52 +08:00
fatedier
3f11b6a082 update k8s.io/apimachinery to v0.21.2 2021-06-21 19:35:52 +08:00
fatedier
8a333c2ae0 update github.com/stretchr/testify to v1.7.0 2021-06-21 19:35:52 +08:00
fatedier
1fd6ba2738 update github.com/spf13/cobra to v1.1.3 2021-06-21 19:35:52 +08:00
fatedier
a98a9616f6 update dependency github.com/rodaine/table to v1.0.1 2021-06-21 19:35:52 +08:00
fatedier
95cd9ab900 update dependency github.com/prometheus/client_golang to v1.11.0 2021-06-21 19:35:52 +08:00
fatedier
900454e58b more e2e test cases (#2450) 2021-06-18 16:48:36 +08:00
fatedier
c7d4637382 fix web js (#2444) 2021-06-09 11:53:39 +08:00
ztz
56925961df Typo: josn => json (#2429) 2021-06-04 11:21:52 +08:00
fatedier
cfd1a3128a Merge pull request #2426 from fatedier/dev
update workflow file
2021-06-03 00:59:21 +08:00
fatedier
2393923870 update build image go version 2021-06-03 00:56:07 +08:00
fatedier
5f594e9a71 fix goreleaser 2021-06-03 00:46:56 +08:00
fatedier
57577ea044 Merge pull request #2425 from fatedier/dev
bump version
2021-06-03 00:14:32 +08:00
fatedier
8637077d90 update version 2021-06-03 00:10:35 +08:00
fatedier
ccb85a9926 update README 2021-06-03 00:07:51 +08:00
fatedier
02b12df887 frpc: consider include configs for verify and reload command (#2424) 2021-06-02 23:54:22 +08:00
fatedier
c32a2ed140 frpc: support 'includes' in common section to include proxy configs in other files(#2421) 2021-06-02 00:39:05 +08:00
Wu Han
9ae322cccf readme: fix toc hyperlinx (#2401) 2021-05-17 17:29:13 +08:00
fatedier
9cebfccb39 cmd: add verify command to verify if config file syntax is valid (#2389) 2021-05-12 12:15:22 +08:00
fatedier
630dad50ed web: support sudp in dashboard (#2385) 2021-05-11 13:37:14 +08:00
fatedier
0d84da91d4 change default value of dashboard_user and dashboard_pwd to empty string (#2383) 2021-05-10 23:04:26 +08:00
fatedier
2408f1df04 frpc: fix that login_fail_exit invalid if protocol=kcp (#2363) 2021-04-22 18:33:10 +08:00
fatedier
fbaa5f866e add e2e tests (#2334) 2021-03-31 16:57:39 +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
9a849a29e9 fix config parse logic (#2323) 2021-03-22 14:53:30 +08:00
Splash
6b80861bd6 Fix log_file does not work in config files (#2316) 2021-03-22 11:30:12 +08:00
fatedier
fa0e84382e autogen code 2021-03-19 17:39:26 +08:00
bobo liu
1a11b28f8d config: inline is NOT SUPPORTED in encoding/json (#2304) 2021-03-19 17:36:39 +08:00
YK-Samgo
bed13d7ef1 Support reverseproxy to dashboard with additional parts in path (#2289)
/api/ -> ../api/   in vendor.js
    Support reverseproxy to dashboard with addtional parts in path.
2021-03-19 17:31:16 +08:00
fatedier
e7d76b180d update README.md (#2314) 2021-03-19 16:06:22 +08:00
wuqing
dba8925eaa makefile add arm64 2021-03-19 14:01:26 +08:00
fatedier
55da58eca4 Merge pull request #2310 from fatedier/dev
bump version
2021-03-18 11:14:56 +08:00
wuqing
fdef7448a7 update version 2021-03-18 11:12:10 +08:00
Chotow
0ff27fc9ac fix(server): listen udp port failed (#2308)
fix #2306
2021-03-18 11:05:03 +08:00
fatedier
76a1efccd9 update 2021-03-17 11:43:23 +08:00
fatedier
9f8db314d6 update 2021-03-17 11:43:03 +08:00
fatedier
980f084ad1 Merge pull request #2302 from fatedier/dev
bump version
2021-03-15 21:54:52 +08:00
fatedier
0c35863d97 bump version to v0.36.0 (#2301) 2021-03-15 21:50:47 +08:00
fatedier
184a0ff9ab update Makefile.cross-compiles and support darwin/arm64 (#2295) 2021-03-15 21:02:56 +08:00
yuyulei
8e25f13201 update: support ipv6 (#2288) 2021-03-10 20:19:58 +08:00
yuyulei
b5aee82ca9 update: support custom tls server name (#2278) 2021-03-07 14:57:23 +08:00
iikira
0a2384a283 fix XTCP error handling (#2273) 2021-03-03 20:54:46 +08:00
yuyulei
78b8bb7bc6 update docs: add example for building tls certificates (#2251) 2021-02-22 13:59:21 +08:00
fatedier
8fcd4f4a95 client: reconnect more quickly if it's a dial error (#2240) 2021-02-18 16:15:35 +08:00
Albert Zhao
976fd81d4d modify gitignore;fix a typo (#2237) 2021-02-07 14:07:20 +08:00
Kevin Crawley
52d5c9e25b initial commit for https2https plugin (#2201) 2021-01-27 13:14:16 +08:00
Asher Oto
fa89671452 Update README (#2221)
* Updated README.md

- Fixed spelling of PayPal
- Added information to TLS section, fixed spelling
2021-01-27 13:07:44 +08:00
yuyulei
3621aad1c1 Reconstruct config (#2098)
* refactoring config

* Update by comments
2021-01-26 11:31:08 +08:00
fatedier
3bf1eb8565 Merge pull request #2216 from fatedier/dev
bump version
2021-01-25 16:15:52 +08:00
fatedier
a821db3f45 add release note 2021-01-25 16:06:38 +08:00
fatedier
ecb6ed9258 revert web code (#2215) 2021-01-25 16:04:33 +08:00
fatedier
b2ae433e18 Merge pull request #2206 from fatedier/dev
bump version
2021-01-19 20:56:06 +08:00
fatedier
b26080589b bump version 2021-01-19 20:51:06 +08:00
yuyulei
aff979c2b6 Merge pull request #2199 from fatedier/fix
vhost: set DisableKeepAlives = false and fix websocket not work
2021-01-19 15:40:41 +08:00
fatedier
46f809d711 vhost: set DisableKeepAlives = false and fix websocket not work 2021-01-18 21:49:44 +08:00
yuyulei
72595b2da8 Add user remote address info log (#2184) 2021-01-11 16:52:17 +08:00
XNG
c842558ace Reduced log level of "get hostname error" (#2165)
Reduced log level of "get hostname from http/https request error" to debug so that it won't overwhelms the log file when user is using apache/ngix as their own SSL backend
2020-12-25 13:39:26 +08:00
yuyulei
ed61049041 Bugfix: add ipv6 parsing with address of frps (#2163) 2020-12-24 21:48:26 +08:00
fatedier
abe6f580c0 update README 2020-12-03 20:41:37 +08:00
fatedier
e940066012 auto generate web assets 2020-12-03 20:23:43 +08:00
hubery
1e846df870 some dashboard refactor (#2101) 2020-12-03 20:20:48 +08:00
Mike Cardwell
0ab055e946 Allow server plugin to talk to https services. Option for skipping tls verification (#2103)
* Allow server plugin to talk to https services. Option for skipping tls verification

* Rename TlsVerify to TLSVerify

* Server plugin should use default http transport when scheme is not https
2020-12-03 14:36:14 +08:00
fatedier
fca59c71e2 clear Release.md 2020-11-23 17:34:09 +08:00
wxiaoguang
fae2f8768d tweak logs: (#2100)
* show what config frps uses (config file / command line)
* optimize the "start successfully" log message
2020-11-23 17:01:31 +08:00
fatedier
3d9499f554 autogen web assets 2020-11-23 15:21:07 +08:00
hubery
7adeeedd55 fix dashboard horizontal scrollbar (#2096) 2020-11-23 14:52:55 +08:00
yuyulei
127a31ea6a Fix typo (#2089) 2020-11-23 11:38:21 +08:00
fatedier
a85bd9a4d9 update 2020-11-20 20:10:08 +08:00
fatedier
01d551ec8d update 2020-11-20 18:10:33 +08:00
fatedier
16cabf4127 add .circleci 2020-11-20 18:04:44 +08:00
fatedier
968be4a2c2 use self token 2020-11-20 17:35: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
8a779eb88c add goreleaser action (#2087)
* add goreleaser action

* change version
2020-11-20 17:00:14 +08:00
蓝云Reyes
0138dbd352 update ISSUE_TEMPLATE (#2061) 2020-11-09 19:39:56 +08:00
yuyulei
9b45c93c14 Fix set-env in github actions of frp (#2060) 2020-11-09 16:56:53 +08:00
fatedier
191da54980 .travis.yml add go1.15 and remove go1.13 2020-11-06 15:49:03 +08:00
Dan Ordille
c3b7575453 Add enable_prometheus option as command line flag (#2057) 2020-11-06 15:33:59 +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
7f7305fa03 update version 2020-11-06 14:39:04 +08:00
yuyulei
644a0cfdb6 Update ReverseProxy code from official golang repo (#2051)
Fix #1192
2020-11-05 16:34:17 +08:00
Chirag Sukhala
3c2e2bcea5 Update frpc_full.ini (#2023)
Added authenticate_heartbeats and authenticate_new_work_conns
2020-10-08 14:25:03 +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
e52dfc4a5c bump version to v0.34.1 2020-09-30 14:40:08 +08:00
lonwern
cc003a2570 reduce docker image size (#2014) 2020-09-30 11:05:34 +08:00
lonwern
0f8040b875 fix create tls work connection (#2013) 2020-09-29 15:44:52 +08:00
harmy
ef5ae3e598 fix: a reconnected proxy will disappear from dashboard after 7 days (#2008) 2020-09-25 16:10:20 +08:00
fatedier
3acf1bb6e9 update stale workflow 2020-09-25 15:15:34 +08:00
fatedier
1089eb9d22 update stale workflow 2020-09-25 15:00:41 +08:00
vesta
edf9596ca8 ci: add close stale (#2001) 2020-09-25 14:40:01 +08:00
fatedier
26e54b901f dockerfile: remove ca-certificates 2020-09-23 16:38:44 +08:00
fatedier
008933f304 typo fix 2020-09-23 15:53:08 +08:00
fatedier
317f901c1c typo 2020-09-23 14:40:22 +08:00
fatedier
cd5314466c update workflows build-and-push-image 2020-09-23 14:20:46 +08:00
fatedier
3fbdea0f6b rename models to pkg (#2005) 2020-09-23 13:49:14 +08:00
vesta
710ecf44f5 feat: support ntlm proxy set in http_proxy env (#2002) 2020-09-23 12:05:05 +08:00
yuyulei
04dafd7ff0 Remove comments (#2004) 2020-09-23 11:57:04 +08:00
yuyulei
c6aa74a2bb Add action to build and push image to dockerhub&github packages (#1998) 2020-09-23 11:05:50 +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
c0e05bb41e bump version to v0.34.0 2020-09-20 00:29:27 +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
1e420cc766 update tls 2020-09-18 20:06:33 +08:00
yuyulei
4fff3c7472 Add tls configuration to both client and server (#1974) 2020-09-18 19:58:58 +08:00
fatedier
48fa618c34 update e2e tests (#1973) 2020-09-07 15:45:44 +08:00
fatedier
c9fe23eb10 more e2e tests (#1845) 2020-09-07 14:57:23 +08:00
Luka Čehovin Zajc
268afb3438 Sorting plugins so that execution order is deterministic (#1961) 2020-08-31 19:49:46 +08:00
fzhyzamt
b1181fd17a support non-preemptive authentication (#1888) 2020-07-01 11:18:23 +08:00
Albert Zhao
b23548eeff fix grammar issue (#1850) (#1852) 2020-06-11 15:39:59 +08:00
fatedier
262317192c new e2e framework (#1835) 2020-06-02 22:48:55 +08:00
fatedier
8b75b8b837 fix by golint (#1822) 2020-05-24 17:48:37 +08:00
fatedier
2170c481ce update doc (#1821) 2020-05-24 14:05:31 +08:00
Tank
dfbf9c4542 style: adjust frps files (#1820) 2020-05-24 11:28:57 +08:00
Tank
964a1bbf39 refine: frpc flags (#1811) 2020-05-19 10:49:29 +08:00
Tank
228e225f84 fix: sync/atomic bug, fix #1804 (#1805)
Co-authored-by: tanghuafa <tanghuafa@bytedance.com>
2020-05-12 22:09:16 +08:00
Tank
bd6435c982 fix: frps plugin manager (#1803) 2020-05-12 15:55:35 +08:00
Tank
591023a1f0 fix: add frpc tls_enable flag and frps tls_only flag (#1798) 2020-05-12 14:33:34 +08:00
Tank
1ab23b5e0e fix: typo (#1799) 2020-05-10 17:58:35 +08:00
Tank
d193519329 feat: Support user specify udp packet size in config (#1794) 2020-05-07 17:47:36 +08:00
fatedier
2406ecdfea Merge pull request #1780 from fatedier/dev
bump version
2020-04-27 16:50:34 +08:00
fatedier
7266154d54 bump version to v0.33.0 2020-04-27 16:24:17 +08:00
Tank
4797136965 feat: support sudp proxy (#1730) 2020-04-22 21:37:45 +08:00
Guy Lewin
6d78af6144 feat: group TCP mux proxies (#1765) 2020-04-20 13:35:47 +08:00
Tank
7728e35c52 fix: frps handle multi conn may happen data race (#1768) 2020-04-19 16:16:24 +08:00
Tank
5a61fd84ad fix: auth token bug (#1762) 2020-04-16 20:20:36 +08:00
zhang-wei
ad0c449a75 Server manager support the NewUserConn operation (#1740)
support NewUserConn operation
2020-04-16 13:06:46 +08:00
fatedier
1c330185c4 typo 2020-04-03 01:24:37 +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
7491b327f8 update ISSUE_TEMPLATE 2020-04-03 01:03:13 +08:00
fatedier
abb5b05d49 update package.sh 2020-04-03 00:59:47 +08:00
fatedier
b6ec9dad28 bump version to v0.32.1 2020-04-02 11:49:16 +08:00
Tank
caa6e8cf01 fix: frpc reconnect frps frequently lead to memory leak (#1722) 2020-04-02 10:58:37 +08:00
fatedier
ffb932390f remove qq info 2020-03-28 22:29:02 +08:00
xcffl
a8efaee1f3 Improve basic examples for newbies (#1711) 2020-03-26 17:41:18 +08:00
fatedier
4c2afb5c28 doc: add plugin repo link (#1710) 2020-03-20 20:54:22 +08:00
fatedier
809f517db8 server plugin: set version and op in http request query (#1707) 2020-03-20 20:53:14 +08:00
Guy Lewin
a4b105dedb [Feature] Server Plugin - Ping and NewWorkConn RPC (#1702) 2020-03-18 01:52:44 +08:00
Guy Lewin
10acf638f8 [Feature] Include RunId in FRP Server Plugin NewProxy message (#1700)
* feat: include RunId in FRP Server Plugin NewProxy message

* doc: rewrite server plugin documentation
2020-03-14 23:26:35 +08:00
fatedier
f65ffe2812 remove vendor 2020-03-11 14:34:17 +08:00
264 changed files with 24544 additions and 30251 deletions

25
.circleci/config.yml Normal file
View File

@@ -0,0 +1,25 @@
version: 2
jobs:
go-version-latest:
docker:
- image: cimg/go:1.19-node
resource_class: large
steps:
- checkout
- run: make
- run: make alltest
go-version-last:
docker:
- image: cimg/go:1.18-node
resource_class: large
steps:
- checkout
- run: make
- run: make alltest
workflows:
version: 2
build_and_test:
jobs:
- go-version-latest
- go-version-last

3
.github/FUNDING.yml vendored Normal file
View File

@@ -0,0 +1,3 @@
# These are supported funding model platforms
github: [fatedier]

View File

@@ -1,32 +0,0 @@
Issue is only used for submiting bug report and documents typo. If there are same issues or answers can be found in documents, we will close it directly.
(为了节约时间,提高处理问题的效率,不按照格式填写的 issue 将会直接关闭。)
(请不要在 issue 评论中出现无意义的 **加1****我也是** 等内容,将会被直接删除。)
(由于个人精力有限,和系统环境,网络环境等相关的求助问题请转至其他论坛或社交平台。)
Use the commands below to provide key information from your environment:
You do NOT have to include this information if this is a FEATURE REQUEST
**What version of frp are you using (./frpc -v or ./frps -v)?**
**What operating system and processor architecture are you using (`go env`)?**
**Configures you used:**
**Steps to reproduce the issue:**
1.
2.
3.
**Describe the results you received:**
**Describe the results you expected:**
**Additional information you deem important (e.g. issue happens only occasionally):**
**Can you point out what caused this issue (optional)**

77
.github/ISSUE_TEMPLATE/bug_report.yaml vendored Normal file
View File

@@ -0,0 +1,77 @@
name: Bug report
description: Report a bug to help us improve frp
body:
- type: markdown
attributes:
value: |
Thanks for taking the time to fill out this bug report!
- type: textarea
id: bug-description
attributes:
label: Bug Description
description: Tell us what issues you ran into
placeholder: Include information about what you tried, what you expected to happen, and what actually happened. The more details, the better!
validations:
required: true
- type: input
id: frpc-version
attributes:
label: frpc Version
description: Include the output of `frpc -v`
validations:
required: true
- type: input
id: frps-version
attributes:
label: frps Version
description: Include the output of `frps -v`
validations:
required: true
- type: input
id: system-architecture
attributes:
label: System Architecture
description: Include which architecture you used, such as `linux/amd64`, `windows/amd64`
validations:
required: true
- type: textarea
id: config
attributes:
label: Configurations
description: Include what configurrations you used and ran into this problem
placeholder: Pay attention to hiding the token and password in your output
validations:
required: true
- type: textarea
id: log
attributes:
label: Logs
description: Prefer you providing releated error logs here
placeholder: Pay attention to hiding your personal informations
- type: textarea
id: steps-to-reproduce
attributes:
label: Steps to reproduce
description: How to reproduce it? It's important for us to find the bug
value: |
1.
2.
3.
...
- type: checkboxes
id: area
attributes:
label: Affected area
options:
- label: "Docs"
- label: "Installation"
- label: "Performance and Scalability"
- label: "Security"
- label: "User Experience"
- label: "Test and Release"
- label: "Developer Infrastructure"
- label: "Client Plugin"
- label: "Server Plugin"
- label: "Extensions"
- label: "Others"

1
.github/ISSUE_TEMPLATE/config.yml vendored Normal file
View File

@@ -0,0 +1 @@
blank_issues_enabled: false

View File

@@ -0,0 +1,36 @@
name: Feature Request
description: Suggest an idea to improve frp
title: "[Feature Request] "
body:
- type: markdown
attributes:
value: |
This is only used to request new product features.
- type: textarea
id: feature-request
attributes:
label: Describe the feature request
description: Tell us what's you want and why it should be added in frp.
validations:
required: true
- type: textarea
id: alternatives
attributes:
label: Describe alternatives you've considered
- type: checkboxes
id: area
attributes:
label: Affected area
options:
- label: "Docs"
- label: "Installation"
- label: "Performance and Scalability"
- label: "Security"
- label: "User Experience"
- label: "Test and Release"
- label: "Developer Infrastructure"
- label: "Client Plugin"
- label: "Server Plugin"
- label: "Extensions"
- label: "Others"

View File

@@ -0,0 +1,83 @@
name: Build Image and Publish to Dockerhub & GPR
on:
release:
types: [ created ]
workflow_dispatch:
inputs:
tag:
description: 'Image tag'
required: true
default: 'test'
permissions:
contents: read
jobs:
image:
name: Build Image from Dockerfile and binaries
runs-on: ubuntu-latest
steps:
# environment
- name: Checkout
uses: actions/checkout@v3
with:
fetch-depth: '0'
- name: Set up QEMU
uses: docker/setup-qemu-action@v2
- name: Set up Docker Buildx
uses: docker/setup-buildx-action@v2
# get image tag name
- name: Get Image Tag Name
run: |
if [ x${{ github.event.inputs.tag }} == x"" ]; then
echo "TAG_NAME=${GITHUB_REF#refs/*/}" >> $GITHUB_ENV
else
echo "TAG_NAME=${{ github.event.inputs.tag }}" >> $GITHUB_ENV
fi
- name: Login to DockerHub
uses: docker/login-action@v2
with:
username: ${{ secrets.DOCKERHUB_USERNAME }}
password: ${{ secrets.DOCKERHUB_PASSWORD }}
- name: Login to the GPR
uses: docker/login-action@v2
with:
registry: ghcr.io
username: ${{ github.repository_owner }}
password: ${{ secrets.GPR_TOKEN }}
# prepare image tags
- name: Prepare Image Tags
run: |
echo "DOCKERFILE_FRPC_PATH=dockerfiles/Dockerfile-for-frpc" >> $GITHUB_ENV
echo "DOCKERFILE_FRPS_PATH=dockerfiles/Dockerfile-for-frps" >> $GITHUB_ENV
echo "TAG_FRPC=fatedier/frpc:${{ env.TAG_NAME }}" >> $GITHUB_ENV
echo "TAG_FRPS=fatedier/frps:${{ env.TAG_NAME }}" >> $GITHUB_ENV
echo "TAG_FRPC_GPR=ghcr.io/fatedier/frpc:${{ env.TAG_NAME }}" >> $GITHUB_ENV
echo "TAG_FRPS_GPR=ghcr.io/fatedier/frps:${{ env.TAG_NAME }}" >> $GITHUB_ENV
- name: Build and push frpc
uses: docker/build-push-action@v3
with:
context: .
file: ./dockerfiles/Dockerfile-for-frpc
platforms: linux/amd64,linux/arm/v7,linux/arm64,linux/ppc64le,linux/s390x
push: true
tags: |
${{ env.TAG_FRPC }}
${{ env.TAG_FRPC_GPR }}
- name: Build and push frps
uses: docker/build-push-action@v3
with:
context: .
file: ./dockerfiles/Dockerfile-for-frps
platforms: linux/amd64,linux/arm/v7,linux/arm64,linux/ppc64le,linux/s390x
push: true
tags: |
${{ env.TAG_FRPS }}
${{ env.TAG_FRPS_GPR }}

41
.github/workflows/golangci-lint.yml vendored Normal file
View File

@@ -0,0 +1,41 @@
name: golangci-lint
on:
push:
branches:
- master
- dev
pull_request:
permissions:
contents: read
# Optional: allow read access to pull request. Use with `only-new-issues` option.
pull-requests: read
jobs:
golangci:
name: lint
runs-on: ubuntu-latest
steps:
- uses: actions/setup-go@v3
with:
go-version: 1.19
- uses: actions/checkout@v3
- name: golangci-lint
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.49.0
# Optional: golangci-lint command line arguments.
# args: --issues-exit-code=0
# Optional: show only new issues if it's a pull request. The default value is `false`.
# only-new-issues: true
# Optional: if set to true then the all caching functionality will be complete disabled,
# takes precedence over all other caching options.
# skip-cache: true
# Optional: if set to true then the action don't cache or restore ~/go/pkg.
# skip-pkg-cache: true
# Optional: if set to true then the action don't cache or restore ~/.cache/go-build.
# skip-build-cache: true

30
.github/workflows/goreleaser.yml vendored Normal file
View File

@@ -0,0 +1,30 @@
name: goreleaser
on:
workflow_dispatch:
jobs:
goreleaser:
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@v3
with:
fetch-depth: 0
- name: Set up Go
uses: actions/setup-go@v3
with:
go-version: 1.19
- name: Make All
run: |
./package.sh
- name: Run GoReleaser
uses: goreleaser/goreleaser-action@v3
with:
version: latest
args: release --rm-dist --release-notes=./Release.md
env:
GITHUB_TOKEN: ${{ secrets.GPR_TOKEN }}

34
.github/workflows/stale.yml vendored Normal file
View File

@@ -0,0 +1,34 @@
name: "Close stale issues"
on:
schedule:
- cron: "20 0 * * *"
workflow_dispatch:
inputs:
debug-only:
description: 'In debug mod'
required: false
default: 'false'
permissions:
contents: read
jobs:
stale:
permissions:
issues: write # for actions/stale to close stale issues
pull-requests: write # for actions/stale to close stale PRs
runs-on: ubuntu-latest
steps:
- uses: actions/stale@v6
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.'
stale-pr-message: "PRs go stale after 30d of inactivity. Stale PRs rot after an additional 7d of inactivity and eventually close."
stale-issue-label: 'lifecycle/stale'
exempt-issue-labels: 'bug,doc,enhancement,future,proposal,question,testing,todo,easy,help wanted,assigned'
stale-pr-label: 'lifecycle/stale'
exempt-pr-labels: 'bug,doc,enhancement,future,proposal,question,testing,todo,easy,help wanted,assigned'
days-before-stale: 30
days-before-close: 7
debug-only: ${{ github.event.inputs.debug-only }}
exempt-all-pr-milestones: true
exempt-all-pr-assignees: true

4
.gitignore vendored
View File

@@ -26,8 +26,12 @@ _testmain.go
# Self # Self
bin/ bin/
packages/ packages/
release/
test/bin/ test/bin/
vendor/ vendor/
dist/
.idea/
.vscode/
# Cache # Cache
*.swp *.swp

140
.golangci.yml Normal file
View File

@@ -0,0 +1,140 @@
service:
# When updating this, also update the version stored in docker/build-tools/Dockerfile in the istio/tools repo.
golangci-lint-version: 1.49.x # use the fixed version to not introduce new linters unexpectedly
run:
concurrency: 4
# timeout for analysis, e.g. 30s, 5m, default is 1m
deadline: 20m
build-tags:
- integ
- integfuzz
# which dirs to skip: they won't be analyzed;
# can use regexp here: generated.*, regexp is applied on full path;
# default value is empty list, but next dirs are always skipped independently
# from this option's value:
# vendor$, third_party$, testdata$, examples$, Godeps$, builtin$
skip-dirs:
- genfiles$
- vendor$
- bin$
# which files to skip: they will be analyzed, but issues from them
# won't be reported. Default value is empty list, but there is
# no need to include all autogenerated files, we confidently recognize
# autogenerated files. If it's not please let us know.
skip-files:
- ".*\\.pb\\.go"
- ".*\\.gen\\.go"
linters:
disable-all: true
enable:
- unused
- errcheck
- exportloopref
- gocritic
- gofumpt
- goimports
- revive
- gosimple
- govet
- ineffassign
- lll
- misspell
- staticcheck
- stylecheck
- typecheck
- unconvert
- unparam
- gci
- gosec
- asciicheck
- prealloc
- predeclared
- makezero
fast: false
linters-settings:
errcheck:
# report about not checking of errors in type assetions: `a := b.(MyStruct)`;
# default is false: such cases aren't reported by default.
check-type-assertions: false
# report about assignment of errors to blank identifier: `num, _ := strconv.Atoi(numStr)`;
# default is false: such cases aren't reported by default.
check-blank: false
govet:
# report about shadowed variables
check-shadowing: false
maligned:
# print struct with more effective memory layout or not, false by default
suggest-new: true
misspell:
# Correct spellings using locale preferences for US or UK.
# Default is to use a neutral variety of English.
# Setting locale to US will correct the British spelling of 'colour' to 'color'.
locale: US
ignore-words:
- cancelled
- marshalled
lll:
# max line length, lines longer will be reported. Default is 120.
# '\t' is counted as 1 character by default, and can be changed with the tab-width option
line-length: 160
# tab width in spaces. Default to 1.
tab-width: 1
gocritic:
disabled-checks:
- exitAfterDefer
unused:
check-exported: false
unparam:
# Inspect exported functions, default is false. Set to true if no external program/library imports your code.
# XXX: if you enable this setting, unparam will report a lot of false-positives in text editors:
# if it's called for subdir of a project it can't find external interfaces. All text editor integrations
# with golangci-lint call it on a directory with the changed file.
check-exported: false
gci:
sections:
- standard
- default
- prefix(github.com/fatedier/frp/)
gosec:
severity: "low"
confidence: "low"
excludes:
- G102
- G112
- G306
- G401
- G402
- G404
- G501
issues:
# List of regexps of issue texts to exclude, empty list by default.
# But independently from this option we use default exclude patterns,
# it can be disabled by `exclude-use-default: false`. To list all
# excluded by default patterns execute `golangci-lint run --help`
# exclude:
# - composite literal uses unkeyed fields
exclude-rules:
# Exclude some linters from running on test files.
- path: _test\.go$|^tests/|^samples/
linters:
- errcheck
- maligned
# Independently from option `exclude` we use default exclude patterns,
# it can be disabled by this option. To list all
# excluded by default patterns execute `golangci-lint run --help`.
# Default value for this option is true.
exclude-use-default: true
# Maximum issues count per one linter. Set to 0 to disable. Default is 50.
max-per-linter: 0
# Maximum count of issues with the same text. Set to 0 to disable. Default is 3.
max-same-issues: 0

22
.goreleaser.yml Normal file
View File

@@ -0,0 +1,22 @@
builds:
- skip: true
checksum:
name_template: '{{ .ProjectName }}_sha256_checksums.txt'
algorithm: sha256
extra_files:
- glob: ./release/packages/*
release:
# Same as for github
# Note: it can only be one: either github, gitlab or gitea
github:
owner: fatedier
name: frp
draft: false
# You can add extra pre-existing files to the release.
# The filename on the release will be the last part of the path (base). If
# another file with the same name exists, the latest one found will be used.
# Defaults to empty.
extra_files:
- glob: ./release/packages/*

View File

@@ -1,12 +0,0 @@
sudo: false
language: go
go:
- 1.12.x
- 1.13.x
install:
- make
script:
- make alltest

View File

@@ -1,5 +1,6 @@
export PATH := $(GOPATH)/bin:$(PATH) export PATH := $(GOPATH)/bin:$(PATH)
export GO111MODULE=on export GO111MODULE=on
LDFLAGS := -s -w
all: fmt build all: fmt build
@@ -11,33 +12,35 @@ file:
rm -rf ./assets/frpc/static/* rm -rf ./assets/frpc/static/*
cp -rf ./web/frps/dist/* ./assets/frps/static cp -rf ./web/frps/dist/* ./assets/frps/static
cp -rf ./web/frpc/dist/* ./assets/frpc/static cp -rf ./web/frpc/dist/* ./assets/frpc/static
rm -rf ./assets/frps/statik
rm -rf ./assets/frpc/statik
go generate ./assets/...
fmt: fmt:
go fmt ./... go fmt ./...
vet:
go vet ./...
frps: frps:
go build -o bin/frps ./cmd/frps env CGO_ENABLED=0 go build -trimpath -ldflags "$(LDFLAGS)" -o bin/frps ./cmd/frps
frpc: frpc:
go build -o bin/frpc ./cmd/frpc env CGO_ENABLED=0 go build -trimpath -ldflags "$(LDFLAGS)" -o bin/frpc ./cmd/frpc
test: gotest test: gotest
gotest: gotest:
go test -v --cover ./assets/... go test -v --cover ./assets/...
go test -v --cover ./client/...
go test -v --cover ./cmd/... go test -v --cover ./cmd/...
go test -v --cover ./models/... go test -v --cover ./client/...
go test -v --cover ./server/... go test -v --cover ./server/...
go test -v --cover ./utils/... go test -v --cover ./pkg/...
ci: e2e:
go test -count=1 -p=1 -v ./tests/... ./hack/run-e2e.sh
alltest: gotest ci e2e-trace:
DEBUG=true LOG_LEVEL=trace ./hack/run-e2e.sh
alltest: vet gotest e2e
clean: clean:
rm -f ./bin/frpc rm -f ./bin/frpc

View File

@@ -1,37 +1,25 @@
export PATH := $(GOPATH)/bin:$(PATH) export PATH := $(GOPATH)/bin:$(PATH)
export GO111MODULE=on
LDFLAGS := -s -w LDFLAGS := -s -w
os-archs=darwin:amd64 darwin:arm64 freebsd:386 freebsd:amd64 linux:386 linux:amd64 linux:arm linux:arm64 windows:386 windows:amd64 linux:mips64 linux:mips64le linux:mips:softfloat linux:mipsle:softfloat linux:riscv64
all: build all: build
build: app build: app
app: app:
env CGO_ENABLED=0 GOOS=darwin GOARCH=amd64 go build -ldflags "$(LDFLAGS)" -o ./frpc_darwin_amd64 ./cmd/frpc @$(foreach n, $(os-archs),\
env CGO_ENABLED=0 GOOS=darwin GOARCH=amd64 go build -ldflags "$(LDFLAGS)" -o ./frps_darwin_amd64 ./cmd/frps os=$(shell echo "$(n)" | cut -d : -f 1);\
env CGO_ENABLED=0 GOOS=freebsd GOARCH=386 go build -ldflags "$(LDFLAGS)" -o ./frpc_freebsd_386 ./cmd/frpc arch=$(shell echo "$(n)" | cut -d : -f 2);\
env CGO_ENABLED=0 GOOS=freebsd GOARCH=386 go build -ldflags "$(LDFLAGS)" -o ./frps_freebsd_386 ./cmd/frps gomips=$(shell echo "$(n)" | cut -d : -f 3);\
env CGO_ENABLED=0 GOOS=freebsd GOARCH=amd64 go build -ldflags "$(LDFLAGS)" -o ./frpc_freebsd_amd64 ./cmd/frpc target_suffix=$${os}_$${arch};\
env CGO_ENABLED=0 GOOS=freebsd GOARCH=amd64 go build -ldflags "$(LDFLAGS)" -o ./frps_freebsd_amd64 ./cmd/frps echo "Build $${os}-$${arch}...";\
env CGO_ENABLED=0 GOOS=linux GOARCH=386 go build -ldflags "$(LDFLAGS)" -o ./frpc_linux_386 ./cmd/frpc env CGO_ENABLED=0 GOOS=$${os} GOARCH=$${arch} GOMIPS=$${gomips} go build -trimpath -ldflags "$(LDFLAGS)" -o ./release/frpc_$${target_suffix} ./cmd/frpc;\
env CGO_ENABLED=0 GOOS=linux GOARCH=386 go build -ldflags "$(LDFLAGS)" -o ./frps_linux_386 ./cmd/frps env CGO_ENABLED=0 GOOS=$${os} GOARCH=$${arch} GOMIPS=$${gomips} go build -trimpath -ldflags "$(LDFLAGS)" -o ./release/frps_$${target_suffix} ./cmd/frps;\
env CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build -ldflags "$(LDFLAGS)" -o ./frpc_linux_amd64 ./cmd/frpc echo "Build $${os}-$${arch} done";\
env CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build -ldflags "$(LDFLAGS)" -o ./frps_linux_amd64 ./cmd/frps )
env CGO_ENABLED=0 GOOS=linux GOARCH=arm go build -ldflags "$(LDFLAGS)" -o ./frpc_linux_arm ./cmd/frpc @mv ./release/frpc_windows_386 ./release/frpc_windows_386.exe
env CGO_ENABLED=0 GOOS=linux GOARCH=arm go build -ldflags "$(LDFLAGS)" -o ./frps_linux_arm ./cmd/frps @mv ./release/frps_windows_386 ./release/frps_windows_386.exe
env CGO_ENABLED=0 GOOS=linux GOARCH=arm64 go build -ldflags "$(LDFLAGS)" -o ./frpc_linux_arm64 ./cmd/frpc @mv ./release/frpc_windows_amd64 ./release/frpc_windows_amd64.exe
env CGO_ENABLED=0 GOOS=linux GOARCH=arm64 go build -ldflags "$(LDFLAGS)" -o ./frps_linux_arm64 ./cmd/frps @mv ./release/frps_windows_amd64 ./release/frps_windows_amd64.exe
env CGO_ENABLED=0 GOOS=windows GOARCH=386 go build -ldflags "$(LDFLAGS)" -o ./frpc_windows_386.exe ./cmd/frpc
env CGO_ENABLED=0 GOOS=windows GOARCH=386 go build -ldflags "$(LDFLAGS)" -o ./frps_windows_386.exe ./cmd/frps
env CGO_ENABLED=0 GOOS=windows GOARCH=amd64 go build -ldflags "$(LDFLAGS)" -o ./frpc_windows_amd64.exe ./cmd/frpc
env CGO_ENABLED=0 GOOS=windows GOARCH=amd64 go build -ldflags "$(LDFLAGS)" -o ./frps_windows_amd64.exe ./cmd/frps
env CGO_ENABLED=0 GOOS=linux GOARCH=mips64 go build -ldflags "$(LDFLAGS)" -o ./frpc_linux_mips64 ./cmd/frpc
env CGO_ENABLED=0 GOOS=linux GOARCH=mips64 go build -ldflags "$(LDFLAGS)" -o ./frps_linux_mips64 ./cmd/frps
env CGO_ENABLED=0 GOOS=linux GOARCH=mips64le go build -ldflags "$(LDFLAGS)" -o ./frpc_linux_mips64le ./cmd/frpc
env CGO_ENABLED=0 GOOS=linux GOARCH=mips64le go build -ldflags "$(LDFLAGS)" -o ./frps_linux_mips64le ./cmd/frps
env CGO_ENABLED=0 GOOS=linux GOARCH=mips GOMIPS=softfloat go build -ldflags "$(LDFLAGS)" -o ./frpc_linux_mips ./cmd/frpc
env CGO_ENABLED=0 GOOS=linux GOARCH=mips GOMIPS=softfloat go build -ldflags "$(LDFLAGS)" -o ./frps_linux_mips ./cmd/frps
env CGO_ENABLED=0 GOOS=linux GOARCH=mipsle GOMIPS=softfloat go build -ldflags "$(LDFLAGS)" -o ./frpc_linux_mipsle ./cmd/frpc
env CGO_ENABLED=0 GOOS=linux GOARCH=mipsle GOMIPS=softfloat go build -ldflags "$(LDFLAGS)" -o ./frps_linux_mipsle ./cmd/frps
temp:
env CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build -ldflags "$(LDFLAGS)" -o ./frps_linux_amd64 ./cmd/frps

236
README.md
View File

@@ -1,9 +1,26 @@
# frp # frp
[![Build Status](https://travis-ci.org/fatedier/frp.svg?branch=master)](https://travis-ci.org/fatedier/frp) [![Build Status](https://circleci.com/gh/fatedier/frp.svg?style=shield)](https://circleci.com/gh/fatedier/frp)
[![GitHub release](https://img.shields.io/github/tag/fatedier/frp.svg?label=release)](https://github.com/fatedier/frp/releases)
[README](README.md) | [中文文档](README_zh.md) [README](README.md) | [中文文档](README_zh.md)
<h3 align="center">Gold Sponsors</h3>
<!--gold sponsors start-->
<p align="center">
<a href="https://workos.com/?utm_campaign=github_repo&utm_medium=referral&utm_content=frp&utm_source=github" target="_blank">
<img width="300px" src="https://raw.githubusercontent.com/fatedier/frp/dev/doc/pic/sponsor_workos.png">
</a>
</p>
<!--gold sponsors end-->
<h3 align="center">Silver Sponsors</h3>
* Sakura Frp - 欢迎点击 "加入我们"
## What is frp? ## What is frp?
frp is a fast reverse proxy to help you expose a local server behind a NAT or firewall to the Internet. As of now, it supports **TCP** and **UDP**, as well as **HTTP** and **HTTPS** protocols, where requests can be forwarded to internal services by domain name. frp is a fast reverse proxy to help you expose a local server behind a NAT or firewall to the Internet. As of now, it supports **TCP** and **UDP**, as well as **HTTP** and **HTTPS** protocols, where requests can be forwarded to internal services by domain name.
@@ -22,12 +39,13 @@ frp also has a P2P connect mode.
* [Forward DNS query request](#forward-dns-query-request) * [Forward DNS query request](#forward-dns-query-request)
* [Forward Unix domain socket](#forward-unix-domain-socket) * [Forward Unix domain socket](#forward-unix-domain-socket)
* [Expose a simple HTTP file server](#expose-a-simple-http-file-server) * [Expose a simple HTTP file server](#expose-a-simple-http-file-server)
* [Enable HTTPS for local HTTP service](#enable-https-for-local-http-service) * [Enable HTTPS for local HTTP(S) service](#enable-https-for-local-https-service)
* [Expose your service privately](#expose-your-service-privately) * [Expose your service privately](#expose-your-service-privately)
* [P2P Mode](#p2p-mode) * [P2P Mode](#p2p-mode)
* [Features](#features) * [Features](#features)
* [Configuration Files](#configuration-files) * [Configuration Files](#configuration-files)
* [Using Environment Variables](#using-environment-variables) * [Using Environment Variables](#using-environment-variables)
* [Split Configures Into Different Files](#split-configures-into-different-files)
* [Dashboard](#dashboard) * [Dashboard](#dashboard)
* [Admin UI](#admin-ui) * [Admin UI](#admin-ui)
* [Monitor](#monitor) * [Monitor](#monitor)
@@ -45,6 +63,7 @@ frp also has a P2P connect mode.
* [For Each Proxy](#for-each-proxy) * [For Each Proxy](#for-each-proxy)
* [TCP Stream Multiplexing](#tcp-stream-multiplexing) * [TCP Stream Multiplexing](#tcp-stream-multiplexing)
* [Support KCP Protocol](#support-kcp-protocol) * [Support KCP Protocol](#support-kcp-protocol)
* [Support QUIC Protocol](#support-quic-protocol)
* [Connection Pooling](#connection-pooling) * [Connection Pooling](#connection-pooling)
* [Load balancing](#load-balancing) * [Load balancing](#load-balancing)
* [Service Health Check](#service-health-check) * [Service Health Check](#service-health-check)
@@ -64,9 +83,8 @@ frp also has a P2P connect mode.
* [Development Plan](#development-plan) * [Development Plan](#development-plan)
* [Contributing](#contributing) * [Contributing](#contributing)
* [Donation](#donation) * [Donation](#donation)
* [AliPay](#alipay) * [GitHub Sponsors](#github-sponsors)
* [Wechat Pay](#wechat-pay) * [PayPal](#paypal)
* [Paypal](#paypal)
<!-- vim-markdown-toc --> <!-- vim-markdown-toc -->
@@ -74,7 +92,9 @@ frp also has a P2P connect mode.
frp is under development. Try the latest release version in the `master` branch, or use the `dev` branch for the version in development. frp is under development. Try the latest release version in the `master` branch, or use the `dev` branch for the version in development.
**The protocol might change at a release and we don't promise backwards compatibility. Please check the release log when upgrading the client and the server.** We are working on v2 version and trying to do some code refactor and improvements. It won't be compatible with v1.
We will switch v0 to v1 at the right time and only accept bug fixes and improvements instead of big feature requirements.
## Architecture ## Architecture
@@ -90,7 +110,7 @@ Put `frpc` and `frpc.ini` onto your server B in LAN (that can't be connected fro
### Access your computer in LAN by SSH ### Access your computer in LAN by SSH
1. Modify `frps.ini` on server A: 1. Modify `frps.ini` on server A and set the `bind_port` to be connected to frp clients:
```ini ```ini
# frps.ini # frps.ini
@@ -117,6 +137,8 @@ Put `frpc` and `frpc.ini` onto your server B in LAN (that can't be connected fro
remote_port = 6000 remote_port = 6000
``` ```
Note that `local_port` (listened on client) and `remote_port` (exposed on server) are for traffic goes in/out the frp system, whereas `server_port` is used between frps.
4. Start `frpc` on server B: 4. Start `frpc` on server B:
`./frpc -c ./frpc.ini` `./frpc -c ./frpc.ini`
@@ -254,7 +276,9 @@ Configure `frps` same as above.
2. Visit `http://x.x.x.x:6000/static/` from your browser and specify correct user and password to view files in `/tmp/files` on the `frpc` machine. 2. Visit `http://x.x.x.x:6000/static/` from your browser and specify correct user and password to view files in `/tmp/files` on the `frpc` machine.
### Enable HTTPS for local HTTP service ### Enable HTTPS for local HTTP(S) service
You may substitute `https2https` for the plugin, and point the `plugin_local_addr` to a HTTPS endpoint.
1. Start `frpc` with configuration: 1. Start `frpc` with configuration:
@@ -406,6 +430,27 @@ export FRP_SSH_REMOTE_PORT="6000"
`frpc` will render configuration file template using OS environment variables. Remember to prefix your reference with `.Envs`. `frpc` will render configuration file template using OS environment variables. Remember to prefix your reference with `.Envs`.
### Split Configures Into Different Files
You can split multiple proxy configs into different files and include them in the main file.
```ini
# frpc.ini
[common]
server_addr = x.x.x.x
server_port = 7000
includes=./confd/*.ini
```
```ini
# ./confd/test.ini
[ssh]
type = tcp
local_ip = 127.0.0.1
local_port = 22
remote_port = 6000
```
### Dashboard ### Dashboard
Check frp's status and proxies' statistics information by Dashboard. Check frp's status and proxies' statistics information by Dashboard.
@@ -415,12 +460,27 @@ Configure a port for dashboard to enable this feature:
```ini ```ini
[common] [common]
dashboard_port = 7500 dashboard_port = 7500
# dashboard's username and password are both optionalif not set, default is admin. # dashboard's username and password are both optional
dashboard_user = admin dashboard_user = admin
dashboard_pwd = admin dashboard_pwd = admin
``` ```
Then visit `http://[server_addr]:7500` to see the dashboard, with username and password both being `admin` by default. Then visit `http://[server_addr]:7500` to see the dashboard, with username and password both being `admin`.
Additionally, you can use HTTPS port by using your domains wildcard or normal SSL certificate:
```ini
[common]
dashboard_port = 7500
# dashboard's username and password are both optional
dashboard_user = admin
dashboard_pwd = admin
dashboard_tls_mode = true
dashboard_tls_cert_file = server.crt
dashboard_tls_key_file = server.key
```
Then visit `https://[server_addr]:7500` to see the dashboard in secure HTTPS connection, with username and password both being `admin`.
![dashboard](/doc/pic/dashboard.png) ![dashboard](/doc/pic/dashboard.png)
@@ -438,7 +498,7 @@ admin_user = admin
admin_pwd = admin admin_pwd = admin
``` ```
Then visit `http://127.0.0.1:7400` to see admin UI, with username and password both being `admin` by default. Then visit `http://127.0.0.1:7400` to see admin UI, with username and password both being `admin`.
### Monitor ### Monitor
@@ -512,11 +572,100 @@ use_compression = true
frp supports the TLS protocol between `frpc` and `frps` since v0.25.0. frp supports the TLS protocol between `frpc` and `frps` since v0.25.0.
Config `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. For port multiplexing, frp sends a first byte `0x17` to dial a TLS connection.
To enforce `frps` to only accept TLS connections - configure `tls_only = true` in the `[common]` section in `frps.ini`. Configure `tls_enable = true` in the `[common]` section to `frpc.ini` to enable this feature.
To **enforce** `frps` to only accept TLS connections - configure `tls_only = true` in the `[common]` section in `frps.ini`. **This is optional.**
**`frpc` TLS settings (under the `[common]` section):**
```ini
tls_enable = true
tls_cert_file = certificate.crt
tls_key_file = certificate.key
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
```
You will need **a root CA cert** and **at least one SSL/TLS certificate**. It **can** be self-signed or regular (such as Let's Encrypt or another SSL/TLS certificate provider).
If you using `frp` via IP address and not hostname, make sure to set the appropriate IP address in the Subject Alternative Name (SAN) area when generating SSL/TLS Certificates.
Given an example:
* Prepare openssl config file. It exists at `/etc/pki/tls/openssl.cnf` in Linux System and `/System/Library/OpenSSL/openssl.cnf` in MacOS, and you can copy it to current path, like `cp /etc/pki/tls/openssl.cnf ./my-openssl.cnf`. If not, you can build it by yourself, like:
```
cat > my-openssl.cnf << EOF
[ ca ]
default_ca = CA_default
[ CA_default ]
x509_extensions = usr_cert
[ req ]
default_bits = 2048
default_md = sha256
default_keyfile = privkey.pem
distinguished_name = req_distinguished_name
attributes = req_attributes
x509_extensions = v3_ca
string_mask = utf8only
[ req_distinguished_name ]
[ req_attributes ]
[ usr_cert ]
basicConstraints = CA:FALSE
nsComment = "OpenSSL Generated Certificate"
subjectKeyIdentifier = hash
authorityKeyIdentifier = keyid,issuer
[ v3_ca ]
subjectKeyIdentifier = hash
authorityKeyIdentifier = keyid:always,issuer
basicConstraints = CA:true
EOF
```
* build ca certificates:
```
openssl genrsa -out ca.key 2048
openssl req -x509 -new -nodes -key ca.key -subj "/CN=example.ca.com" -days 5000 -out ca.crt
```
* build frps certificates:
```
openssl genrsa -out server.key 2048
openssl req -new -sha256 -key server.key \
-subj "/C=XX/ST=DEFAULT/L=DEFAULT/O=DEFAULT/CN=server.com" \
-reqexts SAN \
-config <(cat my-openssl.cnf <(printf "\n[SAN]\nsubjectAltName=DNS:localhost,IP:127.0.0.1,DNS:example.server.com")) \
-out server.csr
openssl x509 -req -days 365 -sha256 \
-in server.csr -CA ca.crt -CAkey ca.key -CAcreateserial \
-extfile <(printf "subjectAltName=DNS:localhost,IP:127.0.0.1,DNS:example.server.com") \
-out server.crt
```
* build frpc certificates
```
openssl genrsa -out client.key 2048
openssl req -new -sha256 -key client.key \
-subj "/C=XX/ST=DEFAULT/L=DEFAULT/O=DEFAULT/CN=client.com" \
-reqexts SAN \
-config <(cat my-openssl.cnf <(printf "\n[SAN]\nsubjectAltName=DNS:client.com,DNS:example.client.com")) \
-out client.csr
openssl x509 -req -days 365 -sha256 \
-in client.csr -CA ca.crt -CAkey ca.key -CAcreateserial \
-extfile <(printf "subjectAltName=DNS:client.com,DNS:example.client.com") \
-out client.crt
```
### Hot-Reloading frpc configuration ### Hot-Reloading frpc configuration
@@ -529,10 +678,12 @@ admin_addr = 127.0.0.1
admin_port = 7400 admin_port = 7400
``` ```
Then run command `frpc reload -c ./frpc.ini` and wait for about 10 seconds to let `frpc` create or update or delete proxies. Then run command `frpc reload -c ./frpc.ini` and wait for about 10 seconds to let `frpc` create or update or remove proxies.
**Note that parameters in [common] section won't be modified except 'start'.** **Note that parameters in [common] section won't be modified except 'start'.**
You can run command `frpc verify -c ./frpc.ini` before reloading to check if there are config errors.
### Get proxy status from client ### Get proxy status from client
Use `frpc status -c ./frpc.ini` to get status of all proxies. The `admin_addr` and `admin_port` fields are required for enabling HTTP API. Use `frpc status -c ./frpc.ini` to get status of all proxies. The `admin_addr` and `admin_port` fields are required for enabling HTTP API.
@@ -611,6 +762,35 @@ KCP mode uses UDP as the underlying transport. Using KCP in frp:
protocol = kcp protocol = kcp
``` ```
### Support QUIC Protocol
QUIC is a new multiplexed transport built on top of UDP.
Using QUIC in frp:
1. Enable QUIC in frps:
```ini
# frps.ini
[common]
bind_port = 7000
# Specify a UDP port for QUIC.
quic_bind_port = 7000
```
The `quic_bind_port` number can be the same number as `bind_port`, since `bind_port` field specifies a TCP port.
2. Configure `frpc.ini` to use QUIC to connect to frps:
```ini
# frpc.ini
[common]
server_addr = x.x.x.x
# Same as the 'quic_bind_port' in frps.ini
server_port = 7000
protocol = quic
```
### Connection Pooling ### Connection Pooling
By default, frps creates a new frpc connection to the backend service upon a user request. With connection pooling, frps keeps a certain number of pre-established connections, reducing the time needed to establish a connection. By default, frps creates a new frpc connection to the backend service upon a user request. With connection pooling, frps keeps a certain number of pre-established connections, reducing the time needed to establish a connection.
@@ -637,7 +817,7 @@ This feature is suitable for a large number of short connections.
Load balancing is supported by `group`. Load balancing is supported by `group`.
This feature is only available for types `tcp` and `http` now. This feature is only available for types `tcp`, `http`, `tcpmux` now.
```ini ```ini
# frpc.ini # frpc.ini
@@ -722,7 +902,7 @@ custom_domains = test.example.com
host_header_rewrite = dev.example.com host_header_rewrite = dev.example.com
``` ```
The HTTP request will have the the `Host` header rewritten to `Host: dev.example.com` when it reaches the actual web server, although the request from the browser probably has `Host: test.example.com`. The HTTP request will have the `Host` header rewritten to `Host: dev.example.com` when it reaches the actual web server, although the request from the browser probably has `Host: test.example.com`.
### Setting other HTTP Headers ### Setting other HTTP Headers
@@ -748,7 +928,7 @@ In this example, it will set header `X-From-Where: frp` in the HTTP request.
This feature is for http proxy only. This feature is for http proxy only.
You can get user's real IP from HTTP request headers `X-Forwarded-For` and `X-Real-IP`. You can get user's real IP from HTTP request headers `X-Forwarded-For`.
#### Proxy Protocol #### Proxy Protocol
@@ -864,11 +1044,13 @@ server_port = 7000
type = tcpmux type = tcpmux
multiplexer = httpconnect multiplexer = httpconnect
custom_domains = test1 custom_domains = test1
local_port = 80
[proxy2] [proxy2]
type = tcpmux type = tcpmux
multiplexer = httpconnect multiplexer = httpconnect
custom_domains = test2 custom_domains = test2
local_port = 8080
``` ```
In the above configuration - frps can be contacted on port 1337 with a HTTP CONNECT header such as: In the above configuration - frps can be contacted on port 1337 with a HTTP CONNECT header such as:
@@ -911,7 +1093,7 @@ frpc will generate 8 proxies like `test_tcp_0`, `test_tcp_1`, ..., `test_tcp_7`.
frpc only forwards requests to local TCP or UDP ports by default. frpc only forwards requests to local TCP or UDP ports by default.
Plugins are used for providing rich features. There are built-in plugins such as `unix_domain_socket`, `http_proxy`, `socks5`, `static_file` and you can see [example usage](#example-usage). Plugins are used for providing rich features. There are built-in plugins such as `unix_domain_socket`, `http_proxy`, `socks5`, `static_file`, `http2https`, `https2http`, `https2https` and you can see [example usage](#example-usage).
Specify which plugin to use with the `plugin` parameter. Configuration parameters of plugin should be started with `plugin_`. `local_ip` and `local_port` are not used for plugin. Specify which plugin to use with the `plugin` parameter. Configuration parameters of plugin should be started with `plugin_`. `local_ip` and `local_port` are not used for plugin.
@@ -933,6 +1115,8 @@ plugin_http_passwd = abc
Read the [document](/doc/server_plugin.md). Read the [document](/doc/server_plugin.md).
Find more plugins in [gofrp/plugin](https://github.com/gofrp/plugin).
## Development Plan ## Development Plan
* Log HTTP request information in frps. * Log HTTP request information in frps.
@@ -952,16 +1136,12 @@ Interested in getting involved? We would like to help you!
If frp helps you a lot, you can support us by: If frp helps you a lot, you can support us by:
frp QQ group: 606194980 ### GitHub Sponsors
### AliPay Support us by [Github Sponsors](https://github.com/sponsors/fatedier).
![donation-alipay](/doc/pic/donate-alipay.png) You can have your company's logo placed on README file of this project.
### Wechat Pay ### PayPal
![donation-wechatpay](/doc/pic/donate-wechatpay.png) Donate money by [PayPal](https://www.paypal.me/fatedier) to my account **fatedier@gmail.com**.
### Paypal
Donate money by [paypal](https://www.paypal.me/fatedier) to my account **fatedier@gmail.com**.

File diff suppressed because it is too large Load Diff

4
Release.md Normal file
View File

@@ -0,0 +1,4 @@
### Fix
* Server Plugin send incorrect op name for NewWorkConn.
* QUIC stream leak.

View File

@@ -14,22 +14,15 @@
package assets package assets
//go:generate statik -src=./frps/static -dest=./frps
//go:generate statik -src=./frpc/static -dest=./frpc
//go:generate go fmt ./frps/statik/statik.go
//go:generate go fmt ./frpc/statik/statik.go
import ( import (
"io/ioutil" "io/fs"
"net/http" "net/http"
"os"
"path"
"github.com/rakyll/statik/fs"
) )
var ( var (
// store static files in memory by statik // read-only filesystem created by "embed" for embedded files
content fs.FS
FileSystem http.FileSystem FileSystem http.FileSystem
// if prefix is not empty, we get file content from disk // if prefix is not empty, we get file content from disk
@@ -38,40 +31,18 @@ var (
// if path is empty, load assets in memory // if path is empty, load assets in memory
// or set FileSystem using disk files // or set FileSystem using disk files
func Load(path string) (err error) { func Load(path string) {
prefixPath = path prefixPath = path
if prefixPath != "" { if prefixPath != "" {
FileSystem = http.Dir(prefixPath) FileSystem = http.Dir(prefixPath)
return nil
} else { } else {
FileSystem, err = fs.New() FileSystem = http.FS(content)
} }
return err
} }
func ReadFile(file string) (content string, err error) { func Register(fileSystem fs.FS) {
if prefixPath == "" { subFs, err := fs.Sub(fileSystem, "static")
file, err := FileSystem.Open(path.Join("/", file)) if err == nil {
if err != nil { content = subFs
return content, err
}
defer file.Close()
buf, err := ioutil.ReadAll(file)
if err != nil {
return content, err
}
content = string(buf)
} else {
file, err := os.Open(path.Join(prefixPath, file))
if err != nil {
return content, err
}
defer file.Close()
buf, err := ioutil.ReadAll(file)
if err != nil {
return content, err
}
content = string(buf)
} }
return content, err
} }

14
assets/frpc/embed.go Normal file
View File

@@ -0,0 +1,14 @@
package frpc
import (
"embed"
"github.com/fatedier/frp/assets"
)
//go:embed static/*
var content embed.FS
func init() {
assets.Register(content)
}

View File

@@ -1 +1 @@
<!doctype html> <html lang=en> <head> <meta charset=utf-8> <title>frp client admin UI</title> <link rel="shortcut icon" href="favicon.ico"></head> <body> <div id=app></div> <script type="text/javascript" src="manifest.js?d2cd6337d30c7b22e836"></script><script type="text/javascript" src="vendor.js?edb271e1d9c81f857840"></script></body> </html> <!doctype html> <html lang=en> <head> <meta charset=utf-8> <title>frp client admin UI</title> <link rel="shortcut icon" href="favicon.ico"></head> <body> <div id=app></div> <script type="text/javascript" src="manifest.js?5d5774096cf5c1b4d5af"></script><script type="text/javascript" src="vendor.js?dc42700731a508d39009"></script></body> </html>

View File

@@ -1 +1 @@
!function(e){function n(r){if(t[r])return t[r].exports;var o=t[r]={i:r,l:!1,exports:{}};return e[r].call(o.exports,o,o.exports,n),o.l=!0,o.exports}var r=window.webpackJsonp;window.webpackJsonp=function(t,c,u){for(var i,a,f,l=0,s=[];l<t.length;l++)a=t[l],o[a]&&s.push(o[a][0]),o[a]=0;for(i in c)Object.prototype.hasOwnProperty.call(c,i)&&(e[i]=c[i]);for(r&&r(t,c,u);s.length;)s.shift()();if(u)for(l=0;l<u.length;l++)f=n(n.s=u[l]);return f};var t={},o={1:0};n.e=function(e){function r(){i.onerror=i.onload=null,clearTimeout(a);var n=o[e];0!==n&&(n&&n[1](new Error("Loading chunk "+e+" failed.")),o[e]=void 0)}var t=o[e];if(0===t)return new Promise(function(e){e()});if(t)return t[2];var c=new Promise(function(n,r){t=o[e]=[n,r]});t[2]=c;var u=document.getElementsByTagName("head")[0],i=document.createElement("script");i.type="text/javascript",i.charset="utf-8",i.async=!0,i.timeout=12e4,n.nc&&i.setAttribute("nonce",n.nc),i.src=n.p+""+e+".js?"+{0:"edb271e1d9c81f857840"}[e];var a=setTimeout(r,12e4);return i.onerror=i.onload=r,u.appendChild(i),c},n.m=e,n.c=t,n.i=function(e){return e},n.d=function(e,r,t){n.o(e,r)||Object.defineProperty(e,r,{configurable:!1,enumerable:!0,get:t})},n.n=function(e){var r=e&&e.__esModule?function(){return e.default}:function(){return e};return n.d(r,"a",r),r},n.o=function(e,n){return Object.prototype.hasOwnProperty.call(e,n)},n.p="",n.oe=function(e){throw console.error(e),e}}([]); !function(e){function n(r){if(t[r])return t[r].exports;var o=t[r]={i:r,l:!1,exports:{}};return e[r].call(o.exports,o,o.exports,n),o.l=!0,o.exports}var r=window.webpackJsonp;window.webpackJsonp=function(t,c,u){for(var i,a,f,l=0,s=[];l<t.length;l++)a=t[l],o[a]&&s.push(o[a][0]),o[a]=0;for(i in c)Object.prototype.hasOwnProperty.call(c,i)&&(e[i]=c[i]);for(r&&r(t,c,u);s.length;)s.shift()();if(u)for(l=0;l<u.length;l++)f=n(n.s=u[l]);return f};var t={},o={1:0};n.e=function(e){function r(){i.onerror=i.onload=null,clearTimeout(a);var n=o[e];0!==n&&(n&&n[1](new Error("Loading chunk "+e+" failed.")),o[e]=void 0)}var t=o[e];if(0===t)return new Promise(function(e){e()});if(t)return t[2];var c=new Promise(function(n,r){t=o[e]=[n,r]});t[2]=c;var u=document.getElementsByTagName("head")[0],i=document.createElement("script");i.type="text/javascript",i.charset="utf-8",i.async=!0,i.timeout=12e4,n.nc&&i.setAttribute("nonce",n.nc),i.src=n.p+""+e+".js?"+{0:"dc42700731a508d39009"}[e];var a=setTimeout(r,12e4);return i.onerror=i.onload=r,u.appendChild(i),c},n.m=e,n.c=t,n.i=function(e){return e},n.d=function(e,r,t){n.o(e,r)||Object.defineProperty(e,r,{configurable:!1,enumerable:!0,get:t})},n.n=function(e){var r=e&&e.__esModule?function(){return e.default}:function(){return e};return n.d(r,"a",r),r},n.o=function(e,n){return Object.prototype.hasOwnProperty.call(e,n)},n.p="",n.oe=function(e){throw console.error(e),e}}([]);

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

14
assets/frps/embed.go Normal file
View File

@@ -0,0 +1,14 @@
package frpc
import (
"embed"
"github.com/fatedier/frp/assets"
)
//go:embed static/*
var content embed.FS
func init() {
assets.Register(content)
}

View File

@@ -1 +1 @@
<!DOCTYPE html> <html lang=en> <head> <meta charset=utf-8> <title>frps dashboard</title> <link rel="shortcut icon" href="favicon.ico"></head> <body> <div id=app></div> <script type="text/javascript" src="manifest.js?14bea8276eef86cc7c61"></script><script type="text/javascript" src="vendor.js?51925ec1a77936b64d61"></script></body> </html> <!doctype html> <html lang=en> <head> <meta charset=utf-8> <title>frps dashboard</title> <link rel="shortcut icon" href="favicon.ico"></head> <body> <div id=app></div> <script type="text/javascript" src="manifest.js?5d154ba4c6b342d8c0c3"></script><script type="text/javascript" src="vendor.js?ddbd1f69fb6e67be4b78"></script></body> </html>

View File

@@ -1 +1 @@
!function(e){function n(r){if(t[r])return t[r].exports;var o=t[r]={i:r,l:!1,exports:{}};return e[r].call(o.exports,o,o.exports,n),o.l=!0,o.exports}var r=window.webpackJsonp;window.webpackJsonp=function(t,c,u){for(var i,a,f,l=0,s=[];l<t.length;l++)a=t[l],o[a]&&s.push(o[a][0]),o[a]=0;for(i in c)Object.prototype.hasOwnProperty.call(c,i)&&(e[i]=c[i]);for(r&&r(t,c,u);s.length;)s.shift()();if(u)for(l=0;l<u.length;l++)f=n(n.s=u[l]);return f};var t={},o={1:0};n.e=function(e){function r(){i.onerror=i.onload=null,clearTimeout(a);var n=o[e];0!==n&&(n&&n[1](new Error("Loading chunk "+e+" failed.")),o[e]=void 0)}var t=o[e];if(0===t)return new Promise(function(e){e()});if(t)return t[2];var c=new Promise(function(n,r){t=o[e]=[n,r]});t[2]=c;var u=document.getElementsByTagName("head")[0],i=document.createElement("script");i.type="text/javascript",i.charset="utf-8",i.async=!0,i.timeout=12e4,n.nc&&i.setAttribute("nonce",n.nc),i.src=n.p+""+e+".js?"+{0:"51925ec1a77936b64d61"}[e];var a=setTimeout(r,12e4);return i.onerror=i.onload=r,u.appendChild(i),c},n.m=e,n.c=t,n.i=function(e){return e},n.d=function(e,r,t){n.o(e,r)||Object.defineProperty(e,r,{configurable:!1,enumerable:!0,get:t})},n.n=function(e){var r=e&&e.__esModule?function(){return e.default}:function(){return e};return n.d(r,"a",r),r},n.o=function(e,n){return Object.prototype.hasOwnProperty.call(e,n)},n.p="",n.oe=function(e){throw console.error(e),e}}([]); !function(e){function n(r){if(t[r])return t[r].exports;var o=t[r]={i:r,l:!1,exports:{}};return e[r].call(o.exports,o,o.exports,n),o.l=!0,o.exports}var r=window.webpackJsonp;window.webpackJsonp=function(t,u,c){for(var i,a,f,l=0,s=[];l<t.length;l++)a=t[l],o[a]&&s.push(o[a][0]),o[a]=0;for(i in u)Object.prototype.hasOwnProperty.call(u,i)&&(e[i]=u[i]);for(r&&r(t,u,c);s.length;)s.shift()();if(c)for(l=0;l<c.length;l++)f=n(n.s=c[l]);return f};var t={},o={1:0};n.e=function(e){function r(){i.onerror=i.onload=null,clearTimeout(a);var n=o[e];0!==n&&(n&&n[1](new Error("Loading chunk "+e+" failed.")),o[e]=void 0)}var t=o[e];if(0===t)return new Promise(function(e){e()});if(t)return t[2];var u=new Promise(function(n,r){t=o[e]=[n,r]});t[2]=u;var c=document.getElementsByTagName("head")[0],i=document.createElement("script");i.type="text/javascript",i.charset="utf-8",i.async=!0,i.timeout=12e4,n.nc&&i.setAttribute("nonce",n.nc),i.src=n.p+""+e+".js?"+{0:"ddbd1f69fb6e67be4b78"}[e];var a=setTimeout(r,12e4);return i.onerror=i.onload=r,c.appendChild(i),u},n.m=e,n.c=t,n.i=function(e){return e},n.d=function(e,r,t){n.o(e,r)||Object.defineProperty(e,r,{configurable:!1,enumerable:!0,get:t})},n.n=function(e){var r=e&&e.__esModule?function(){return e.default}:function(){return e};return n.d(r,"a",r),r},n.o=function(e,n){return Object.prototype.hasOwnProperty.call(e,n)},n.p="",n.oe=function(e){throw console.error(e),e}}([]);

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

View File

@@ -15,43 +15,54 @@
package client package client
import ( import (
"fmt"
"net" "net"
"net/http" "net/http"
"net/http/pprof"
"time" "time"
"github.com/fatedier/frp/assets"
frpNet "github.com/fatedier/frp/utils/net"
"github.com/gorilla/mux" "github.com/gorilla/mux"
"github.com/fatedier/frp/assets"
frpNet "github.com/fatedier/frp/pkg/util/net"
) )
var ( var (
httpServerReadTimeout = 10 * time.Second httpServerReadTimeout = 60 * time.Second
httpServerWriteTimeout = 10 * time.Second httpServerWriteTimeout = 60 * time.Second
) )
func (svr *Service) RunAdminServer(addr string, port int) (err error) { func (svr *Service) RunAdminServer(address string) (err error) {
// url router // url router
router := mux.NewRouter() router := mux.NewRouter()
user, passwd := svr.cfg.AdminUser, svr.cfg.AdminPwd router.HandleFunc("/healthz", svr.healthz)
router.Use(frpNet.NewHttpAuthMiddleware(user, passwd).Middleware)
// api, see dashboard_api.go // debug
router.HandleFunc("/api/reload", svr.apiReload).Methods("GET") if svr.cfg.PprofEnable {
router.HandleFunc("/api/status", svr.apiStatus).Methods("GET") router.HandleFunc("/debug/pprof/cmdline", pprof.Cmdline)
router.HandleFunc("/api/config", svr.apiGetConfig).Methods("GET") router.HandleFunc("/debug/pprof/profile", pprof.Profile)
router.HandleFunc("/api/config", svr.apiPutConfig).Methods("PUT") router.HandleFunc("/debug/pprof/symbol", pprof.Symbol)
router.HandleFunc("/debug/pprof/trace", pprof.Trace)
router.PathPrefix("/debug/pprof/").HandlerFunc(pprof.Index)
}
subRouter := router.NewRoute().Subrouter()
user, passwd := svr.cfg.AdminUser, svr.cfg.AdminPwd
subRouter.Use(frpNet.NewHTTPAuthMiddleware(user, passwd).Middleware)
// api, see admin_api.go
subRouter.HandleFunc("/api/reload", svr.apiReload).Methods("GET")
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 // view
router.Handle("/favicon.ico", http.FileServer(assets.FileSystem)).Methods("GET") subRouter.Handle("/favicon.ico", http.FileServer(assets.FileSystem)).Methods("GET")
router.PathPrefix("/static/").Handler(frpNet.MakeHttpGzipHandler(http.StripPrefix("/static/", http.FileServer(assets.FileSystem)))).Methods("GET") subRouter.PathPrefix("/static/").Handler(frpNet.MakeHTTPGzipHandler(http.StripPrefix("/static/", http.FileServer(assets.FileSystem)))).Methods("GET")
router.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { subRouter.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
http.Redirect(w, r, "/static/", http.StatusMovedPermanently) http.Redirect(w, r, "/static/", http.StatusMovedPermanently)
}) })
address := fmt.Sprintf("%s:%d", addr, port)
server := &http.Server{ server := &http.Server{
Addr: address, Addr: address,
Handler: router, Handler: router,
@@ -66,6 +77,8 @@ func (svr *Service) RunAdminServer(addr string, port int) (err error) {
return err return err
} }
go server.Serve(ln) go func() {
_ = server.Serve(ln)
}()
return return
} }

View File

@@ -17,14 +17,17 @@ package client
import ( import (
"encoding/json" "encoding/json"
"fmt" "fmt"
"io/ioutil" "io"
"net"
"net/http" "net/http"
"os"
"sort" "sort"
"strconv"
"strings" "strings"
"github.com/fatedier/frp/client/proxy" "github.com/fatedier/frp/client/proxy"
"github.com/fatedier/frp/models/config" "github.com/fatedier/frp/pkg/config"
"github.com/fatedier/frp/utils/log" "github.com/fatedier/frp/pkg/util/log"
) )
type GeneralResponse struct { type GeneralResponse struct {
@@ -32,37 +35,25 @@ type GeneralResponse struct {
Msg string Msg string
} }
// GET api/reload // /healthz
func (svr *Service) healthz(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(200)
}
// GET api/reload
func (svr *Service) apiReload(w http.ResponseWriter, r *http.Request) { func (svr *Service) apiReload(w http.ResponseWriter, r *http.Request) {
res := GeneralResponse{Code: 200} res := GeneralResponse{Code: 200}
log.Info("Http request [/api/reload]") log.Info("api request [/api/reload]")
defer func() { defer func() {
log.Info("Http response [/api/reload], code [%d]", res.Code) log.Info("api response [/api/reload], code [%d]", res.Code)
w.WriteHeader(res.Code) w.WriteHeader(res.Code)
if len(res.Msg) > 0 { if len(res.Msg) > 0 {
w.Write([]byte(res.Msg)) _, _ = w.Write([]byte(res.Msg))
} }
}() }()
content, err := config.GetRenderedConfFromFile(svr.cfgFile) _, pxyCfgs, visitorCfgs, err := config.ParseClientConfig(svr.cfgFile)
if err != nil {
res.Code = 400
res.Msg = err.Error()
log.Warn("reload frpc config file error: %s", res.Msg)
return
}
newCommonCfg, err := config.UnmarshalClientConfFromIni(content)
if err != nil {
res.Code = 400
res.Msg = err.Error()
log.Warn("reload frpc common section error: %s", res.Msg)
return
}
pxyCfgs, visitorCfgs, err := config.LoadAllConfFromIni(svr.cfg.User, content, newCommonCfg.Start)
if err != nil { if err != nil {
res.Code = 400 res.Code = 400
res.Msg = err.Error() res.Msg = err.Error()
@@ -70,24 +61,23 @@ func (svr *Service) apiReload(w http.ResponseWriter, r *http.Request) {
return return
} }
err = svr.ReloadConf(pxyCfgs, visitorCfgs) if err = svr.ReloadConf(pxyCfgs, visitorCfgs); err != nil {
if err != nil {
res.Code = 500 res.Code = 500
res.Msg = err.Error() res.Msg = err.Error()
log.Warn("reload frpc proxy config error: %s", res.Msg) log.Warn("reload frpc proxy config error: %s", res.Msg)
return return
} }
log.Info("success reload conf") log.Info("success reload conf")
return
} }
type StatusResp struct { type StatusResp struct {
Tcp []ProxyStatusResp `json:"tcp"` TCP []ProxyStatusResp `json:"tcp"`
Udp []ProxyStatusResp `json:"udp"` UDP []ProxyStatusResp `json:"udp"`
Http []ProxyStatusResp `json:"http"` HTTP []ProxyStatusResp `json:"http"`
Https []ProxyStatusResp `json:"https"` HTTPS []ProxyStatusResp `json:"https"`
Stcp []ProxyStatusResp `json:"stcp"` STCP []ProxyStatusResp `json:"stcp"`
Xtcp []ProxyStatusResp `json:"xtcp"` XTCP []ProxyStatusResp `json:"xtcp"`
SUDP []ProxyStatusResp `json:"sudp"`
} }
type ProxyStatusResp struct { type ProxyStatusResp struct {
@@ -106,53 +96,58 @@ func (a ByProxyStatusResp) Len() int { return len(a) }
func (a ByProxyStatusResp) Swap(i, j int) { a[i], a[j] = a[j], a[i] } func (a ByProxyStatusResp) Swap(i, j int) { a[i], a[j] = a[j], a[i] }
func (a ByProxyStatusResp) Less(i, j int) bool { return strings.Compare(a[i].Name, a[j].Name) < 0 } func (a ByProxyStatusResp) Less(i, j int) bool { return strings.Compare(a[i].Name, a[j].Name) < 0 }
func NewProxyStatusResp(status *proxy.ProxyStatus, serverAddr string) ProxyStatusResp { func NewProxyStatusResp(status *proxy.WorkingStatus, serverAddr string) ProxyStatusResp {
psr := ProxyStatusResp{ psr := ProxyStatusResp{
Name: status.Name, Name: status.Name,
Type: status.Type, Type: status.Type,
Status: status.Status, Status: status.Phase,
Err: status.Err, Err: status.Err,
} }
switch cfg := status.Cfg.(type) { switch cfg := status.Cfg.(type) {
case *config.TcpProxyConf: case *config.TCPProxyConf:
if cfg.LocalPort != 0 { if cfg.LocalPort != 0 {
psr.LocalAddr = fmt.Sprintf("%s:%d", cfg.LocalIp, cfg.LocalPort) psr.LocalAddr = net.JoinHostPort(cfg.LocalIP, strconv.Itoa(cfg.LocalPort))
} }
psr.Plugin = cfg.Plugin psr.Plugin = cfg.Plugin
if status.Err != "" { if status.Err != "" {
psr.RemoteAddr = fmt.Sprintf("%s:%d", serverAddr, cfg.RemotePort) psr.RemoteAddr = net.JoinHostPort(serverAddr, strconv.Itoa(cfg.RemotePort))
} else { } else {
psr.RemoteAddr = serverAddr + status.RemoteAddr psr.RemoteAddr = serverAddr + status.RemoteAddr
} }
case *config.UdpProxyConf: case *config.UDPProxyConf:
if cfg.LocalPort != 0 { if cfg.LocalPort != 0 {
psr.LocalAddr = fmt.Sprintf("%s:%d", cfg.LocalIp, cfg.LocalPort) psr.LocalAddr = net.JoinHostPort(cfg.LocalIP, strconv.Itoa(cfg.LocalPort))
} }
if status.Err != "" { if status.Err != "" {
psr.RemoteAddr = fmt.Sprintf("%s:%d", serverAddr, cfg.RemotePort) psr.RemoteAddr = net.JoinHostPort(serverAddr, strconv.Itoa(cfg.RemotePort))
} else { } else {
psr.RemoteAddr = serverAddr + status.RemoteAddr psr.RemoteAddr = serverAddr + status.RemoteAddr
} }
case *config.HttpProxyConf: case *config.HTTPProxyConf:
if cfg.LocalPort != 0 { if cfg.LocalPort != 0 {
psr.LocalAddr = fmt.Sprintf("%s:%d", cfg.LocalIp, cfg.LocalPort) psr.LocalAddr = net.JoinHostPort(cfg.LocalIP, strconv.Itoa(cfg.LocalPort))
} }
psr.Plugin = cfg.Plugin psr.Plugin = cfg.Plugin
psr.RemoteAddr = status.RemoteAddr psr.RemoteAddr = status.RemoteAddr
case *config.HttpsProxyConf: case *config.HTTPSProxyConf:
if cfg.LocalPort != 0 { if cfg.LocalPort != 0 {
psr.LocalAddr = fmt.Sprintf("%s:%d", cfg.LocalIp, cfg.LocalPort) psr.LocalAddr = net.JoinHostPort(cfg.LocalIP, strconv.Itoa(cfg.LocalPort))
} }
psr.Plugin = cfg.Plugin psr.Plugin = cfg.Plugin
psr.RemoteAddr = status.RemoteAddr psr.RemoteAddr = status.RemoteAddr
case *config.StcpProxyConf: case *config.STCPProxyConf:
if cfg.LocalPort != 0 { if cfg.LocalPort != 0 {
psr.LocalAddr = fmt.Sprintf("%s:%d", cfg.LocalIp, cfg.LocalPort) psr.LocalAddr = net.JoinHostPort(cfg.LocalIP, strconv.Itoa(cfg.LocalPort))
} }
psr.Plugin = cfg.Plugin psr.Plugin = cfg.Plugin
case *config.XtcpProxyConf: case *config.XTCPProxyConf:
if cfg.LocalPort != 0 { if cfg.LocalPort != 0 {
psr.LocalAddr = fmt.Sprintf("%s:%d", cfg.LocalIp, cfg.LocalPort) psr.LocalAddr = net.JoinHostPort(cfg.LocalIP, strconv.Itoa(cfg.LocalPort))
}
psr.Plugin = cfg.Plugin
case *config.SUDPProxyConf:
if cfg.LocalPort != 0 {
psr.LocalAddr = net.JoinHostPort(cfg.LocalIP, strconv.Itoa(cfg.LocalPort))
} }
psr.Plugin = cfg.Plugin psr.Plugin = cfg.Plugin
} }
@@ -165,44 +160,47 @@ func (svr *Service) apiStatus(w http.ResponseWriter, r *http.Request) {
buf []byte buf []byte
res StatusResp res StatusResp
) )
res.Tcp = make([]ProxyStatusResp, 0) res.TCP = make([]ProxyStatusResp, 0)
res.Udp = make([]ProxyStatusResp, 0) res.UDP = make([]ProxyStatusResp, 0)
res.Http = make([]ProxyStatusResp, 0) res.HTTP = make([]ProxyStatusResp, 0)
res.Https = make([]ProxyStatusResp, 0) res.HTTPS = make([]ProxyStatusResp, 0)
res.Stcp = make([]ProxyStatusResp, 0) res.STCP = make([]ProxyStatusResp, 0)
res.Xtcp = make([]ProxyStatusResp, 0) res.XTCP = make([]ProxyStatusResp, 0)
res.SUDP = make([]ProxyStatusResp, 0)
log.Info("Http request [/api/status]") log.Info("Http request [/api/status]")
defer func() { defer func() {
log.Info("Http response [/api/status]") log.Info("Http response [/api/status]")
buf, _ = json.Marshal(&res) buf, _ = json.Marshal(&res)
w.Write(buf) _, _ = w.Write(buf)
}() }()
ps := svr.ctl.pm.GetAllProxyStatus() ps := svr.ctl.pm.GetAllProxyStatus()
for _, status := range ps { for _, status := range ps {
switch status.Type { switch status.Type {
case "tcp": case "tcp":
res.Tcp = append(res.Tcp, NewProxyStatusResp(status, svr.cfg.ServerAddr)) res.TCP = append(res.TCP, NewProxyStatusResp(status, svr.cfg.ServerAddr))
case "udp": case "udp":
res.Udp = append(res.Udp, NewProxyStatusResp(status, svr.cfg.ServerAddr)) res.UDP = append(res.UDP, NewProxyStatusResp(status, svr.cfg.ServerAddr))
case "http": case "http":
res.Http = append(res.Http, NewProxyStatusResp(status, svr.cfg.ServerAddr)) res.HTTP = append(res.HTTP, NewProxyStatusResp(status, svr.cfg.ServerAddr))
case "https": case "https":
res.Https = append(res.Https, NewProxyStatusResp(status, svr.cfg.ServerAddr)) res.HTTPS = append(res.HTTPS, NewProxyStatusResp(status, svr.cfg.ServerAddr))
case "stcp": case "stcp":
res.Stcp = append(res.Stcp, NewProxyStatusResp(status, svr.cfg.ServerAddr)) res.STCP = append(res.STCP, NewProxyStatusResp(status, svr.cfg.ServerAddr))
case "xtcp": case "xtcp":
res.Xtcp = append(res.Xtcp, NewProxyStatusResp(status, svr.cfg.ServerAddr)) res.XTCP = append(res.XTCP, NewProxyStatusResp(status, svr.cfg.ServerAddr))
case "sudp":
res.SUDP = append(res.SUDP, NewProxyStatusResp(status, svr.cfg.ServerAddr))
} }
} }
sort.Sort(ByProxyStatusResp(res.Tcp)) sort.Sort(ByProxyStatusResp(res.TCP))
sort.Sort(ByProxyStatusResp(res.Udp)) sort.Sort(ByProxyStatusResp(res.UDP))
sort.Sort(ByProxyStatusResp(res.Http)) sort.Sort(ByProxyStatusResp(res.HTTP))
sort.Sort(ByProxyStatusResp(res.Https)) sort.Sort(ByProxyStatusResp(res.HTTPS))
sort.Sort(ByProxyStatusResp(res.Stcp)) sort.Sort(ByProxyStatusResp(res.STCP))
sort.Sort(ByProxyStatusResp(res.Xtcp)) sort.Sort(ByProxyStatusResp(res.XTCP))
return sort.Sort(ByProxyStatusResp(res.SUDP))
} }
// GET api/config // GET api/config
@@ -214,7 +212,7 @@ func (svr *Service) apiGetConfig(w http.ResponseWriter, r *http.Request) {
log.Info("Http get response [/api/config], code [%d]", res.Code) log.Info("Http get response [/api/config], code [%d]", res.Code)
w.WriteHeader(res.Code) w.WriteHeader(res.Code)
if len(res.Msg) > 0 { if len(res.Msg) > 0 {
w.Write([]byte(res.Msg)) _, _ = w.Write([]byte(res.Msg))
} }
}() }()
@@ -233,7 +231,7 @@ func (svr *Service) apiGetConfig(w http.ResponseWriter, r *http.Request) {
return return
} }
rows := strings.Split(content, "\n") rows := strings.Split(string(content), "\n")
newRows := make([]string, 0, len(rows)) newRows := make([]string, 0, len(rows))
for _, row := range rows { for _, row := range rows {
row = strings.TrimSpace(row) row = strings.TrimSpace(row)
@@ -254,12 +252,12 @@ func (svr *Service) apiPutConfig(w http.ResponseWriter, r *http.Request) {
log.Info("Http put response [/api/config], code [%d]", res.Code) log.Info("Http put response [/api/config], code [%d]", res.Code)
w.WriteHeader(res.Code) w.WriteHeader(res.Code)
if len(res.Msg) > 0 { if len(res.Msg) > 0 {
w.Write([]byte(res.Msg)) _, _ = w.Write([]byte(res.Msg))
} }
}() }()
// get new config content // get new config content
body, err := ioutil.ReadAll(r.Body) body, err := io.ReadAll(r.Body)
if err != nil { if err != nil {
res.Code = 400 res.Code = 400
res.Msg = fmt.Sprintf("read request body error: %v", err) res.Msg = fmt.Sprintf("read request body error: %v", err)
@@ -276,7 +274,7 @@ func (svr *Service) apiPutConfig(w http.ResponseWriter, r *http.Request) {
// get token from origin content // get token from origin content
token := "" token := ""
b, err := ioutil.ReadFile(svr.cfgFile) b, err := os.ReadFile(svr.cfgFile)
if err != nil { if err != nil {
res.Code = 400 res.Code = 400
res.Msg = err.Error() res.Msg = err.Error()
@@ -315,7 +313,7 @@ func (svr *Service) apiPutConfig(w http.ResponseWriter, r *http.Request) {
} }
content = strings.Join(newRows, "\n") content = strings.Join(newRows, "\n")
err = ioutil.WriteFile(svr.cfgFile, []byte(content), 0644) err = os.WriteFile(svr.cfgFile, []byte(content), 0o644)
if err != nil { if err != nil {
res.Code = 500 res.Code = 500
res.Msg = fmt.Sprintf("write content to frpc config file error: %v", err) res.Msg = fmt.Sprintf("write content to frpc config file error: %v", err)

View File

@@ -16,33 +16,28 @@ package client
import ( import (
"context" "context"
"crypto/tls"
"fmt"
"io" "io"
"net" "net"
"runtime/debug" "runtime/debug"
"sync"
"time" "time"
"github.com/fatedier/frp/client/proxy"
"github.com/fatedier/frp/models/auth"
"github.com/fatedier/frp/models/config"
"github.com/fatedier/frp/models/msg"
frpNet "github.com/fatedier/frp/utils/net"
"github.com/fatedier/frp/utils/xlog"
"github.com/fatedier/golib/control/shutdown" "github.com/fatedier/golib/control/shutdown"
"github.com/fatedier/golib/crypto" "github.com/fatedier/golib/crypto"
fmux "github.com/hashicorp/yamux"
"github.com/fatedier/frp/client/proxy"
"github.com/fatedier/frp/pkg/auth"
"github.com/fatedier/frp/pkg/config"
"github.com/fatedier/frp/pkg/msg"
"github.com/fatedier/frp/pkg/util/xlog"
) )
type Control struct { type Control struct {
// uniq id got from frps, attach it in loginMsg // uniq id got from frps, attach it in loginMsg
runId string runID string
// manage all proxies // manage all proxies
pxyCfgs map[string]config.ProxyConf pxyCfgs map[string]config.ProxyConf
pm *proxy.ProxyManager pm *proxy.Manager
// manage all visitors // manage all visitors
vm *VisitorManager vm *VisitorManager
@@ -50,8 +45,7 @@ type Control struct {
// control connection // control connection
conn net.Conn conn net.Conn
// tcp stream multiplexing, if enabled cm *ConnectionManager
session *fmux.Session
// put a message in this channel to send it over control connection to server // put a message in this channel to send it over control connection to server
sendCh chan (msg.Message) sendCh chan (msg.Message)
@@ -77,8 +71,6 @@ type Control struct {
// The UDP port that the server is listening on // The UDP port that the server is listening on
serverUDPPort int serverUDPPort int
mu sync.RWMutex
xl *xlog.Logger xl *xlog.Logger
// service context // service context
@@ -88,18 +80,19 @@ type Control struct {
authSetter auth.Setter authSetter auth.Setter
} }
func NewControl(ctx context.Context, runId string, conn net.Conn, session *fmux.Session, func NewControl(
ctx context.Context, runID string, conn net.Conn, cm *ConnectionManager,
clientCfg config.ClientCommonConf, clientCfg config.ClientCommonConf,
pxyCfgs map[string]config.ProxyConf, pxyCfgs map[string]config.ProxyConf,
visitorCfgs map[string]config.VisitorConf, visitorCfgs map[string]config.VisitorConf,
serverUDPPort int, serverUDPPort int,
authSetter auth.Setter) *Control { authSetter auth.Setter,
) *Control {
// new xlog instance // new xlog instance
ctl := &Control{ ctl := &Control{
runId: runId, runID: runID,
conn: conn, conn: conn,
session: session, cm: cm,
pxyCfgs: pxyCfgs, pxyCfgs: pxyCfgs,
sendCh: make(chan msg.Message, 100), sendCh: make(chan msg.Message, 100),
readCh: make(chan msg.Message, 100), readCh: make(chan msg.Message, 100),
@@ -114,7 +107,7 @@ func NewControl(ctx context.Context, runId string, conn net.Conn, session *fmux.
ctx: ctx, ctx: ctx,
authSetter: authSetter, authSetter: authSetter,
} }
ctl.pm = proxy.NewProxyManager(ctl.ctx, ctl.sendCh, clientCfg, serverUDPPort) ctl.pm = proxy.NewManager(ctl.ctx, ctl.sendCh, clientCfg, serverUDPPort)
ctl.vm = NewVisitorManager(ctl.ctx, ctl) ctl.vm = NewVisitorManager(ctl.ctx, ctl)
ctl.vm.Reload(visitorCfgs) ctl.vm.Reload(visitorCfgs)
@@ -129,18 +122,18 @@ func (ctl *Control) Run() {
// start all visitors // start all visitors
go ctl.vm.Run() go ctl.vm.Run()
return
} }
func (ctl *Control) HandleReqWorkConn(inMsg *msg.ReqWorkConn) { func (ctl *Control) HandleReqWorkConn(inMsg *msg.ReqWorkConn) {
xl := ctl.xl xl := ctl.xl
workConn, err := ctl.connectServer() workConn, err := ctl.connectServer()
if err != nil { if err != nil {
xl.Warn("start new connection to server error: %v", err)
return return
} }
m := &msg.NewWorkConn{ m := &msg.NewWorkConn{
RunId: ctl.runId, RunID: ctl.runID,
} }
if err = ctl.authSetter.SetNewWorkConn(m); err != nil { if err = ctl.authSetter.SetNewWorkConn(m); err != nil {
xl.Warn("error during NewWorkConn authentication: %v", err) xl.Warn("error during NewWorkConn authentication: %v", err)
@@ -154,7 +147,7 @@ func (ctl *Control) HandleReqWorkConn(inMsg *msg.ReqWorkConn) {
var startMsg msg.StartWorkConn var startMsg msg.StartWorkConn
if err = msg.ReadMsgInto(workConn, &startMsg); err != nil { if err = msg.ReadMsgInto(workConn, &startMsg); err != nil {
xl.Error("work connection closed before response StartWorkConn message: %v", err) xl.Trace("work connection closed before response StartWorkConn message: %v", err)
workConn.Close() workConn.Close()
return return
} }
@@ -181,11 +174,17 @@ func (ctl *Control) HandleNewProxyResp(inMsg *msg.NewProxyResp) {
} }
func (ctl *Control) Close() error { func (ctl *Control) Close() error {
return ctl.GracefulClose(0)
}
func (ctl *Control) GracefulClose(d time.Duration) error {
ctl.pm.Close() ctl.pm.Close()
ctl.vm.Close()
time.Sleep(d)
ctl.conn.Close() ctl.conn.Close()
if ctl.session != nil { ctl.cm.Close()
ctl.session.Close()
}
return nil return nil
} }
@@ -196,30 +195,7 @@ func (ctl *Control) ClosedDoneCh() <-chan struct{} {
// connectServer return a new connection to frps // connectServer return a new connection to frps
func (ctl *Control) connectServer() (conn net.Conn, err error) { func (ctl *Control) connectServer() (conn net.Conn, err error) {
xl := ctl.xl return ctl.cm.Connect()
if ctl.clientCfg.TcpMux {
stream, errRet := ctl.session.OpenStream()
if errRet != nil {
err = errRet
xl.Warn("start new connection to server error: %v", err)
return
}
conn = stream
} else {
var tlsConfig *tls.Config
if ctl.clientCfg.TLSEnable {
tlsConfig = &tls.Config{
InsecureSkipVerify: true,
}
}
conn, err = frpNet.ConnectServerByProxyWithTLS(ctl.clientCfg.HttpProxy, ctl.clientCfg.Protocol,
fmt.Sprintf("%s:%d", ctl.clientCfg.ServerAddr, ctl.clientCfg.ServerPort), tlsConfig)
if err != nil {
xl.Warn("start new connection to server error: %v", err)
return
}
}
return
} }
// reader read all messages from frps and send to readCh // reader read all messages from frps and send to readCh
@@ -236,18 +212,17 @@ func (ctl *Control) reader() {
encReader := crypto.NewReader(ctl.conn, []byte(ctl.clientCfg.Token)) encReader := crypto.NewReader(ctl.conn, []byte(ctl.clientCfg.Token))
for { for {
if m, err := msg.ReadMsg(encReader); err != nil { m, err := msg.ReadMsg(encReader)
if err != nil {
if err == io.EOF { if err == io.EOF {
xl.Debug("read from control connection EOF") xl.Debug("read from control connection EOF")
return return
} else {
xl.Warn("read error: %v", err)
ctl.conn.Close()
return
} }
} else { xl.Warn("read error: %v", err)
ctl.readCh <- m ctl.conn.Close()
return
} }
ctl.readCh <- m
} }
} }
@@ -262,14 +237,15 @@ func (ctl *Control) writer() {
return return
} }
for { for {
if m, ok := <-ctl.sendCh; !ok { m, ok := <-ctl.sendCh
if !ok {
xl.Info("control writer is closing") xl.Info("control writer is closing")
return return
} else { }
if err := msg.WriteMsg(encWriter, m); err != nil {
xl.Warn("write message to control connection error: %v", err) if err := msg.WriteMsg(encWriter, m); err != nil {
return xl.Warn("write message to control connection error: %v", err)
} return
} }
} }
} }
@@ -285,16 +261,27 @@ func (ctl *Control) msgHandler() {
}() }()
defer ctl.msgHandlerShutdown.Done() defer ctl.msgHandlerShutdown.Done()
hbSend := time.NewTicker(time.Duration(ctl.clientCfg.HeartBeatInterval) * time.Second) var hbSendCh <-chan time.Time
defer hbSend.Stop() // TODO(fatedier): disable heartbeat if TCPMux is enabled.
hbCheck := time.NewTicker(time.Second) // Just keep it here to keep compatible with old version frps.
defer hbCheck.Stop() if ctl.clientCfg.HeartbeatInterval > 0 {
hbSend := time.NewTicker(time.Duration(ctl.clientCfg.HeartbeatInterval) * time.Second)
defer hbSend.Stop()
hbSendCh = hbSend.C
}
var hbCheckCh <-chan time.Time
// Check heartbeat timeout only if TCPMux is not enabled and users don't disable heartbeat feature.
if ctl.clientCfg.HeartbeatInterval > 0 && ctl.clientCfg.HeartbeatTimeout > 0 && !ctl.clientCfg.TCPMux {
hbCheck := time.NewTicker(time.Second)
defer hbCheck.Stop()
hbCheckCh = hbCheck.C
}
ctl.lastPong = time.Now() ctl.lastPong = time.Now()
for { for {
select { select {
case <-hbSend.C: case <-hbSendCh:
// send heartbeat to server // send heartbeat to server
xl.Debug("send heartbeat to server") xl.Debug("send heartbeat to server")
pingMsg := &msg.Ping{} pingMsg := &msg.Ping{}
@@ -303,8 +290,8 @@ func (ctl *Control) msgHandler() {
return return
} }
ctl.sendCh <- pingMsg ctl.sendCh <- pingMsg
case <-hbCheck.C: case <-hbCheckCh:
if time.Since(ctl.lastPong) > time.Duration(ctl.clientCfg.HeartBeatTimeout)*time.Second { if time.Since(ctl.lastPong) > time.Duration(ctl.clientCfg.HeartbeatTimeout)*time.Second {
xl.Warn("heartbeat timeout") xl.Warn("heartbeat timeout")
// let reader() stop // let reader() stop
ctl.conn.Close() ctl.conn.Close()
@@ -339,25 +326,20 @@ func (ctl *Control) worker() {
go ctl.reader() go ctl.reader()
go ctl.writer() go ctl.writer()
select { <-ctl.closedCh
case <-ctl.closedCh: // close related channels and wait until other goroutines done
// close related channels and wait until other goroutines done close(ctl.readCh)
close(ctl.readCh) ctl.readerShutdown.WaitDone()
ctl.readerShutdown.WaitDone() ctl.msgHandlerShutdown.WaitDone()
ctl.msgHandlerShutdown.WaitDone()
close(ctl.sendCh) close(ctl.sendCh)
ctl.writerShutdown.WaitDone() ctl.writerShutdown.WaitDone()
ctl.pm.Close() ctl.pm.Close()
ctl.vm.Close() ctl.vm.Close()
close(ctl.closedDoneCh) close(ctl.closedDoneCh)
if ctl.session != nil { ctl.cm.Close()
ctl.session.Close()
}
return
}
} }
func (ctl *Control) ReloadConf(pxyCfgs map[string]config.ProxyConf, visitorCfgs map[string]config.VisitorConf) error { func (ctl *Control) ReloadConf(pxyCfgs map[string]config.ProxyConf, visitorCfgs map[string]config.VisitorConf) error {

View File

@@ -3,21 +3,12 @@ package event
import ( import (
"errors" "errors"
"github.com/fatedier/frp/models/msg" "github.com/fatedier/frp/pkg/msg"
) )
type EventType int var ErrPayloadType = errors.New("error payload type")
const ( type Handler func(payload interface{}) error
EvStartProxy EventType = iota
EvCloseProxy
)
var (
ErrPayloadType = errors.New("error payload type")
)
type EventHandler func(evType EventType, payload interface{}) error
type StartProxyPayload struct { type StartProxyPayload struct {
NewProxyMsg *msg.NewProxy NewProxyMsg *msg.NewProxy

View File

@@ -19,19 +19,16 @@ import (
"errors" "errors"
"fmt" "fmt"
"io" "io"
"io/ioutil"
"net" "net"
"net/http" "net/http"
"time" "time"
"github.com/fatedier/frp/utils/xlog" "github.com/fatedier/frp/pkg/util/xlog"
) )
var ( var ErrHealthCheckType = errors.New("error health check type")
ErrHealthCheckType = errors.New("error health check type")
)
type HealthCheckMonitor struct { type Monitor struct {
checkType string checkType string
interval time.Duration interval time.Duration
timeout time.Duration timeout time.Duration
@@ -52,11 +49,11 @@ type HealthCheckMonitor struct {
cancel context.CancelFunc cancel context.CancelFunc
} }
func NewHealthCheckMonitor(ctx context.Context, checkType string, func NewMonitor(ctx context.Context, checkType string,
intervalS int, timeoutS int, maxFailedTimes int, intervalS int, timeoutS int, maxFailedTimes int,
addr string, url string, addr string, url string,
statusNormalFn func(), statusFailedFn func()) *HealthCheckMonitor { statusNormalFn func(), statusFailedFn func(),
) *Monitor {
if intervalS <= 0 { if intervalS <= 0 {
intervalS = 10 intervalS = 10
} }
@@ -67,7 +64,7 @@ func NewHealthCheckMonitor(ctx context.Context, checkType string,
maxFailedTimes = 1 maxFailedTimes = 1
} }
newctx, cancel := context.WithCancel(ctx) newctx, cancel := context.WithCancel(ctx)
return &HealthCheckMonitor{ return &Monitor{
checkType: checkType, checkType: checkType,
interval: time.Duration(intervalS) * time.Second, interval: time.Duration(intervalS) * time.Second,
timeout: time.Duration(timeoutS) * time.Second, timeout: time.Duration(timeoutS) * time.Second,
@@ -82,15 +79,15 @@ func NewHealthCheckMonitor(ctx context.Context, checkType string,
} }
} }
func (monitor *HealthCheckMonitor) Start() { func (monitor *Monitor) Start() {
go monitor.checkWorker() go monitor.checkWorker()
} }
func (monitor *HealthCheckMonitor) Stop() { func (monitor *Monitor) Stop() {
monitor.cancel() monitor.cancel()
} }
func (monitor *HealthCheckMonitor) checkWorker() { func (monitor *Monitor) checkWorker() {
xl := xlog.FromContextSafe(monitor.ctx) xl := xlog.FromContextSafe(monitor.ctx)
for { for {
doCtx, cancel := context.WithDeadline(monitor.ctx, time.Now().Add(monitor.timeout)) doCtx, cancel := context.WithDeadline(monitor.ctx, time.Now().Add(monitor.timeout))
@@ -126,18 +123,18 @@ func (monitor *HealthCheckMonitor) checkWorker() {
} }
} }
func (monitor *HealthCheckMonitor) doCheck(ctx context.Context) error { func (monitor *Monitor) doCheck(ctx context.Context) error {
switch monitor.checkType { switch monitor.checkType {
case "tcp": case "tcp":
return monitor.doTcpCheck(ctx) return monitor.doTCPCheck(ctx)
case "http": case "http":
return monitor.doHttpCheck(ctx) return monitor.doHTTPCheck(ctx)
default: default:
return ErrHealthCheckType return ErrHealthCheckType
} }
} }
func (monitor *HealthCheckMonitor) doTcpCheck(ctx context.Context) error { func (monitor *Monitor) doTCPCheck(ctx context.Context) error {
// if tcp address is not specified, always return nil // if tcp address is not specified, always return nil
if monitor.addr == "" { if monitor.addr == "" {
return nil return nil
@@ -152,8 +149,8 @@ func (monitor *HealthCheckMonitor) doTcpCheck(ctx context.Context) error {
return nil return nil
} }
func (monitor *HealthCheckMonitor) doHttpCheck(ctx context.Context) error { func (monitor *Monitor) doHTTPCheck(ctx context.Context) error {
req, err := http.NewRequest("GET", monitor.url, nil) req, err := http.NewRequestWithContext(ctx, "GET", monitor.url, nil)
if err != nil { if err != nil {
return err return err
} }
@@ -162,7 +159,7 @@ func (monitor *HealthCheckMonitor) doHttpCheck(ctx context.Context) error {
return err return err
} }
defer resp.Body.Close() defer resp.Body.Close()
io.Copy(ioutil.Discard, resp.Body) _, _ = io.Copy(io.Discard, resp.Body)
if resp.StatusCode/100 != 2 { if resp.StatusCode/100 != 2 {
return fmt.Errorf("do http health check, StatusCode is [%d] not 2xx", resp.StatusCode) return fmt.Errorf("do http health check, StatusCode is [%d] not 2xx", resp.StatusCode)

View File

@@ -17,29 +17,28 @@ package proxy
import ( import (
"bytes" "bytes"
"context" "context"
"fmt"
"io" "io"
"io/ioutil"
"net" "net"
"strconv" "strconv"
"strings" "strings"
"sync" "sync"
"time" "time"
"github.com/fatedier/frp/models/config"
"github.com/fatedier/frp/models/msg"
plugin "github.com/fatedier/frp/models/plugin/client"
"github.com/fatedier/frp/models/proto/udp"
"github.com/fatedier/frp/utils/limit"
frpNet "github.com/fatedier/frp/utils/net"
"github.com/fatedier/frp/utils/xlog"
"github.com/fatedier/golib/errors" "github.com/fatedier/golib/errors"
frpIo "github.com/fatedier/golib/io" frpIo "github.com/fatedier/golib/io"
libdial "github.com/fatedier/golib/net/dial"
"github.com/fatedier/golib/pool" "github.com/fatedier/golib/pool"
fmux "github.com/hashicorp/yamux" fmux "github.com/hashicorp/yamux"
pp "github.com/pires/go-proxyproto" pp "github.com/pires/go-proxyproto"
"golang.org/x/time/rate" "golang.org/x/time/rate"
"github.com/fatedier/frp/pkg/config"
"github.com/fatedier/frp/pkg/msg"
plugin "github.com/fatedier/frp/pkg/plugin/client"
"github.com/fatedier/frp/pkg/proto/udp"
"github.com/fatedier/frp/pkg/util/limit"
frpNet "github.com/fatedier/frp/pkg/util/net"
"github.com/fatedier/frp/pkg/util/xlog"
) )
// Proxy defines how to handle work connections for different proxy type. // Proxy defines how to handle work connections for different proxy type.
@@ -67,41 +66,47 @@ func NewProxy(ctx context.Context, pxyConf config.ProxyConf, clientCfg config.Cl
ctx: ctx, ctx: ctx,
} }
switch cfg := pxyConf.(type) { switch cfg := pxyConf.(type) {
case *config.TcpProxyConf: case *config.TCPProxyConf:
pxy = &TcpProxy{ pxy = &TCPProxy{
BaseProxy: &baseProxy, BaseProxy: &baseProxy,
cfg: cfg, cfg: cfg,
} }
case *config.TcpMuxProxyConf: case *config.TCPMuxProxyConf:
pxy = &TcpMuxProxy{ pxy = &TCPMuxProxy{
BaseProxy: &baseProxy, BaseProxy: &baseProxy,
cfg: cfg, cfg: cfg,
} }
case *config.UdpProxyConf: case *config.UDPProxyConf:
pxy = &UdpProxy{ pxy = &UDPProxy{
BaseProxy: &baseProxy, BaseProxy: &baseProxy,
cfg: cfg, cfg: cfg,
} }
case *config.HttpProxyConf: case *config.HTTPProxyConf:
pxy = &HttpProxy{ pxy = &HTTPProxy{
BaseProxy: &baseProxy, BaseProxy: &baseProxy,
cfg: cfg, cfg: cfg,
} }
case *config.HttpsProxyConf: case *config.HTTPSProxyConf:
pxy = &HttpsProxy{ pxy = &HTTPSProxy{
BaseProxy: &baseProxy, BaseProxy: &baseProxy,
cfg: cfg, cfg: cfg,
} }
case *config.StcpProxyConf: case *config.STCPProxyConf:
pxy = &StcpProxy{ pxy = &STCPProxy{
BaseProxy: &baseProxy, BaseProxy: &baseProxy,
cfg: cfg, cfg: cfg,
} }
case *config.XtcpProxyConf: case *config.XTCPProxyConf:
pxy = &XtcpProxy{ pxy = &XTCPProxy{
BaseProxy: &baseProxy, BaseProxy: &baseProxy,
cfg: cfg, cfg: cfg,
} }
case *config.SUDPProxyConf:
pxy = &SUDPProxy{
BaseProxy: &baseProxy,
cfg: cfg,
closeCh: make(chan struct{}),
}
} }
return return
} }
@@ -118,14 +123,14 @@ type BaseProxy struct {
} }
// TCP // TCP
type TcpProxy struct { type TCPProxy struct {
*BaseProxy *BaseProxy
cfg *config.TcpProxyConf cfg *config.TCPProxyConf
proxyPlugin plugin.Plugin proxyPlugin plugin.Plugin
} }
func (pxy *TcpProxy) Run() (err error) { func (pxy *TCPProxy) Run() (err error) {
if pxy.cfg.Plugin != "" { if pxy.cfg.Plugin != "" {
pxy.proxyPlugin, err = plugin.Create(pxy.cfg.Plugin, pxy.cfg.PluginParams) pxy.proxyPlugin, err = plugin.Create(pxy.cfg.Plugin, pxy.cfg.PluginParams)
if err != nil { if err != nil {
@@ -135,26 +140,26 @@ func (pxy *TcpProxy) Run() (err error) {
return return
} }
func (pxy *TcpProxy) Close() { func (pxy *TCPProxy) Close() {
if pxy.proxyPlugin != nil { if pxy.proxyPlugin != nil {
pxy.proxyPlugin.Close() pxy.proxyPlugin.Close()
} }
} }
func (pxy *TcpProxy) InWorkConn(conn net.Conn, m *msg.StartWorkConn) { func (pxy *TCPProxy) InWorkConn(conn net.Conn, m *msg.StartWorkConn) {
HandleTcpWorkConnection(pxy.ctx, &pxy.cfg.LocalSvrConf, pxy.proxyPlugin, &pxy.cfg.BaseProxyConf, pxy.limiter, HandleTCPWorkConnection(pxy.ctx, &pxy.cfg.LocalSvrConf, pxy.proxyPlugin, pxy.cfg.GetBaseInfo(), pxy.limiter,
conn, []byte(pxy.clientCfg.Token), m) conn, []byte(pxy.clientCfg.Token), m)
} }
// TCP Multiplexer // TCP Multiplexer
type TcpMuxProxy struct { type TCPMuxProxy struct {
*BaseProxy *BaseProxy
cfg *config.TcpMuxProxyConf cfg *config.TCPMuxProxyConf
proxyPlugin plugin.Plugin proxyPlugin plugin.Plugin
} }
func (pxy *TcpMuxProxy) Run() (err error) { func (pxy *TCPMuxProxy) Run() (err error) {
if pxy.cfg.Plugin != "" { if pxy.cfg.Plugin != "" {
pxy.proxyPlugin, err = plugin.Create(pxy.cfg.Plugin, pxy.cfg.PluginParams) pxy.proxyPlugin, err = plugin.Create(pxy.cfg.Plugin, pxy.cfg.PluginParams)
if err != nil { if err != nil {
@@ -164,26 +169,26 @@ func (pxy *TcpMuxProxy) Run() (err error) {
return return
} }
func (pxy *TcpMuxProxy) Close() { func (pxy *TCPMuxProxy) Close() {
if pxy.proxyPlugin != nil { if pxy.proxyPlugin != nil {
pxy.proxyPlugin.Close() pxy.proxyPlugin.Close()
} }
} }
func (pxy *TcpMuxProxy) InWorkConn(conn net.Conn, m *msg.StartWorkConn) { func (pxy *TCPMuxProxy) InWorkConn(conn net.Conn, m *msg.StartWorkConn) {
HandleTcpWorkConnection(pxy.ctx, &pxy.cfg.LocalSvrConf, pxy.proxyPlugin, &pxy.cfg.BaseProxyConf, pxy.limiter, HandleTCPWorkConnection(pxy.ctx, &pxy.cfg.LocalSvrConf, pxy.proxyPlugin, pxy.cfg.GetBaseInfo(), pxy.limiter,
conn, []byte(pxy.clientCfg.Token), m) conn, []byte(pxy.clientCfg.Token), m)
} }
// HTTP // HTTP
type HttpProxy struct { type HTTPProxy struct {
*BaseProxy *BaseProxy
cfg *config.HttpProxyConf cfg *config.HTTPProxyConf
proxyPlugin plugin.Plugin proxyPlugin plugin.Plugin
} }
func (pxy *HttpProxy) Run() (err error) { func (pxy *HTTPProxy) Run() (err error) {
if pxy.cfg.Plugin != "" { if pxy.cfg.Plugin != "" {
pxy.proxyPlugin, err = plugin.Create(pxy.cfg.Plugin, pxy.cfg.PluginParams) pxy.proxyPlugin, err = plugin.Create(pxy.cfg.Plugin, pxy.cfg.PluginParams)
if err != nil { if err != nil {
@@ -193,26 +198,26 @@ func (pxy *HttpProxy) Run() (err error) {
return return
} }
func (pxy *HttpProxy) Close() { func (pxy *HTTPProxy) Close() {
if pxy.proxyPlugin != nil { if pxy.proxyPlugin != nil {
pxy.proxyPlugin.Close() pxy.proxyPlugin.Close()
} }
} }
func (pxy *HttpProxy) InWorkConn(conn net.Conn, m *msg.StartWorkConn) { func (pxy *HTTPProxy) InWorkConn(conn net.Conn, m *msg.StartWorkConn) {
HandleTcpWorkConnection(pxy.ctx, &pxy.cfg.LocalSvrConf, pxy.proxyPlugin, &pxy.cfg.BaseProxyConf, pxy.limiter, HandleTCPWorkConnection(pxy.ctx, &pxy.cfg.LocalSvrConf, pxy.proxyPlugin, pxy.cfg.GetBaseInfo(), pxy.limiter,
conn, []byte(pxy.clientCfg.Token), m) conn, []byte(pxy.clientCfg.Token), m)
} }
// HTTPS // HTTPS
type HttpsProxy struct { type HTTPSProxy struct {
*BaseProxy *BaseProxy
cfg *config.HttpsProxyConf cfg *config.HTTPSProxyConf
proxyPlugin plugin.Plugin proxyPlugin plugin.Plugin
} }
func (pxy *HttpsProxy) Run() (err error) { func (pxy *HTTPSProxy) Run() (err error) {
if pxy.cfg.Plugin != "" { if pxy.cfg.Plugin != "" {
pxy.proxyPlugin, err = plugin.Create(pxy.cfg.Plugin, pxy.cfg.PluginParams) pxy.proxyPlugin, err = plugin.Create(pxy.cfg.Plugin, pxy.cfg.PluginParams)
if err != nil { if err != nil {
@@ -222,26 +227,26 @@ func (pxy *HttpsProxy) Run() (err error) {
return return
} }
func (pxy *HttpsProxy) Close() { func (pxy *HTTPSProxy) Close() {
if pxy.proxyPlugin != nil { if pxy.proxyPlugin != nil {
pxy.proxyPlugin.Close() pxy.proxyPlugin.Close()
} }
} }
func (pxy *HttpsProxy) InWorkConn(conn net.Conn, m *msg.StartWorkConn) { func (pxy *HTTPSProxy) InWorkConn(conn net.Conn, m *msg.StartWorkConn) {
HandleTcpWorkConnection(pxy.ctx, &pxy.cfg.LocalSvrConf, pxy.proxyPlugin, &pxy.cfg.BaseProxyConf, pxy.limiter, HandleTCPWorkConnection(pxy.ctx, &pxy.cfg.LocalSvrConf, pxy.proxyPlugin, pxy.cfg.GetBaseInfo(), pxy.limiter,
conn, []byte(pxy.clientCfg.Token), m) conn, []byte(pxy.clientCfg.Token), m)
} }
// STCP // STCP
type StcpProxy struct { type STCPProxy struct {
*BaseProxy *BaseProxy
cfg *config.StcpProxyConf cfg *config.STCPProxyConf
proxyPlugin plugin.Plugin proxyPlugin plugin.Plugin
} }
func (pxy *StcpProxy) Run() (err error) { func (pxy *STCPProxy) Run() (err error) {
if pxy.cfg.Plugin != "" { if pxy.cfg.Plugin != "" {
pxy.proxyPlugin, err = plugin.Create(pxy.cfg.Plugin, pxy.cfg.PluginParams) pxy.proxyPlugin, err = plugin.Create(pxy.cfg.Plugin, pxy.cfg.PluginParams)
if err != nil { if err != nil {
@@ -251,26 +256,26 @@ func (pxy *StcpProxy) Run() (err error) {
return return
} }
func (pxy *StcpProxy) Close() { func (pxy *STCPProxy) Close() {
if pxy.proxyPlugin != nil { if pxy.proxyPlugin != nil {
pxy.proxyPlugin.Close() pxy.proxyPlugin.Close()
} }
} }
func (pxy *StcpProxy) InWorkConn(conn net.Conn, m *msg.StartWorkConn) { func (pxy *STCPProxy) InWorkConn(conn net.Conn, m *msg.StartWorkConn) {
HandleTcpWorkConnection(pxy.ctx, &pxy.cfg.LocalSvrConf, pxy.proxyPlugin, &pxy.cfg.BaseProxyConf, pxy.limiter, HandleTCPWorkConnection(pxy.ctx, &pxy.cfg.LocalSvrConf, pxy.proxyPlugin, pxy.cfg.GetBaseInfo(), pxy.limiter,
conn, []byte(pxy.clientCfg.Token), m) conn, []byte(pxy.clientCfg.Token), m)
} }
// XTCP // XTCP
type XtcpProxy struct { type XTCPProxy struct {
*BaseProxy *BaseProxy
cfg *config.XtcpProxyConf cfg *config.XTCPProxyConf
proxyPlugin plugin.Plugin proxyPlugin plugin.Plugin
} }
func (pxy *XtcpProxy) Run() (err error) { func (pxy *XTCPProxy) Run() (err error) {
if pxy.cfg.Plugin != "" { if pxy.cfg.Plugin != "" {
pxy.proxyPlugin, err = plugin.Create(pxy.cfg.Plugin, pxy.cfg.PluginParams) pxy.proxyPlugin, err = plugin.Create(pxy.cfg.Plugin, pxy.cfg.PluginParams)
if err != nil { if err != nil {
@@ -280,13 +285,13 @@ func (pxy *XtcpProxy) Run() (err error) {
return return
} }
func (pxy *XtcpProxy) Close() { func (pxy *XTCPProxy) Close() {
if pxy.proxyPlugin != nil { if pxy.proxyPlugin != nil {
pxy.proxyPlugin.Close() pxy.proxyPlugin.Close()
} }
} }
func (pxy *XtcpProxy) InWorkConn(conn net.Conn, m *msg.StartWorkConn) { func (pxy *XTCPProxy) InWorkConn(conn net.Conn, m *msg.StartWorkConn) {
xl := pxy.xl xl := pxy.xl
defer conn.Close() defer conn.Close()
var natHoleSidMsg msg.NatHoleSid var natHoleSidMsg msg.NatHoleSid
@@ -301,8 +306,12 @@ func (pxy *XtcpProxy) InWorkConn(conn net.Conn, m *msg.StartWorkConn) {
Sid: natHoleSidMsg.Sid, Sid: natHoleSidMsg.Sid,
} }
raddr, _ := net.ResolveUDPAddr("udp", raddr, _ := net.ResolveUDPAddr("udp",
fmt.Sprintf("%s:%d", pxy.clientCfg.ServerAddr, pxy.serverUDPPort)) net.JoinHostPort(pxy.clientCfg.ServerAddr, strconv.Itoa(pxy.serverUDPPort)))
clientConn, err := net.DialUDP("udp", nil, raddr) clientConn, err := net.DialUDP("udp", nil, raddr)
if err != nil {
xl.Error("dial server udp addr error: %v", err)
return
}
defer clientConn.Close() defer clientConn.Close()
err = msg.WriteMsg(clientConn, natHoleClientMsg) err = msg.WriteMsg(clientConn, natHoleClientMsg)
@@ -313,7 +322,7 @@ func (pxy *XtcpProxy) InWorkConn(conn net.Conn, m *msg.StartWorkConn) {
// Wait for client address at most 5 seconds. // Wait for client address at most 5 seconds.
var natHoleRespMsg msg.NatHoleResp var natHoleRespMsg msg.NatHoleResp
clientConn.SetReadDeadline(time.Now().Add(5 * time.Second)) _ = clientConn.SetReadDeadline(time.Now().Add(5 * time.Second))
buf := pool.GetBuf(1024) buf := pool.GetBuf(1024)
n, err := clientConn.Read(buf) n, err := clientConn.Read(buf)
@@ -326,8 +335,8 @@ func (pxy *XtcpProxy) InWorkConn(conn net.Conn, m *msg.StartWorkConn) {
xl.Error("get natHoleRespMsg error: %v", err) xl.Error("get natHoleRespMsg error: %v", err)
return return
} }
clientConn.SetReadDeadline(time.Time{}) _ = clientConn.SetReadDeadline(time.Time{})
clientConn.Close() _ = clientConn.Close()
if natHoleRespMsg.Error != "" { if natHoleRespMsg.Error != "" {
xl.Error("natHoleRespMsg get error info: %s", natHoleRespMsg.Error) xl.Error("natHoleRespMsg get error info: %s", natHoleRespMsg.Error)
@@ -337,35 +346,34 @@ func (pxy *XtcpProxy) InWorkConn(conn net.Conn, m *msg.StartWorkConn) {
xl.Trace("get natHoleRespMsg, sid [%s], client address [%s] visitor address [%s]", natHoleRespMsg.Sid, natHoleRespMsg.ClientAddr, natHoleRespMsg.VisitorAddr) xl.Trace("get natHoleRespMsg, sid [%s], client address [%s] visitor address [%s]", natHoleRespMsg.Sid, natHoleRespMsg.ClientAddr, natHoleRespMsg.VisitorAddr)
// Send detect message // Send detect message
array := strings.Split(natHoleRespMsg.VisitorAddr, ":") host, portStr, err := net.SplitHostPort(natHoleRespMsg.VisitorAddr)
if len(array) <= 1 { if err != nil {
xl.Error("get NatHoleResp visitor address error: %v", natHoleRespMsg.VisitorAddr) xl.Error("get NatHoleResp visitor address [%s] error: %v", natHoleRespMsg.VisitorAddr, err)
} }
laddr, _ := net.ResolveUDPAddr("udp", clientConn.LocalAddr().String()) laddr, _ := net.ResolveUDPAddr("udp", clientConn.LocalAddr().String())
/*
for i := 1000; i < 65000; i++ { port, err := strconv.ParseInt(portStr, 10, 64)
pxy.sendDetectMsg(array[0], int64(i), laddr, "a")
}
*/
port, err := strconv.ParseInt(array[1], 10, 64)
if err != nil { if err != nil {
xl.Error("get natHoleResp visitor address error: %v", natHoleRespMsg.VisitorAddr) xl.Error("get natHoleResp visitor address error: %v", natHoleRespMsg.VisitorAddr)
return return
} }
pxy.sendDetectMsg(array[0], int(port), laddr, []byte(natHoleRespMsg.Sid)) _ = pxy.sendDetectMsg(host, int(port), laddr, []byte(natHoleRespMsg.Sid))
xl.Trace("send all detect msg done") xl.Trace("send all detect msg done")
msg.WriteMsg(conn, &msg.NatHoleClientDetectOK{}) if err := msg.WriteMsg(conn, &msg.NatHoleClientDetectOK{}); err != nil {
xl.Error("write message error: %v", err)
return
}
// Listen for clientConn's address and wait for visitor connection // Listen for clientConn's address and wait for visitor connection
lConn, err := net.ListenUDP("udp", laddr) lConn, err := net.ListenUDP("udp", laddr)
if err != nil { if err != nil {
xl.Error("listen on visitorConn's local adress error: %v", err) xl.Error("listen on visitorConn's local address error: %v", err)
return return
} }
defer lConn.Close() defer lConn.Close()
lConn.SetReadDeadline(time.Now().Add(8 * time.Second)) _ = lConn.SetReadDeadline(time.Now().Add(8 * time.Second))
sidBuf := pool.GetBuf(1024) sidBuf := pool.GetBuf(1024)
var uAddr *net.UDPAddr var uAddr *net.UDPAddr
n, uAddr, err = lConn.ReadFromUDP(sidBuf) n, uAddr, err = lConn.ReadFromUDP(sidBuf)
@@ -373,7 +381,7 @@ func (pxy *XtcpProxy) InWorkConn(conn net.Conn, m *msg.StartWorkConn) {
xl.Warn("get sid from visitor error: %v", err) xl.Warn("get sid from visitor error: %v", err)
return return
} }
lConn.SetReadDeadline(time.Time{}) _ = lConn.SetReadDeadline(time.Time{})
if string(sidBuf[:n]) != natHoleRespMsg.Sid { if string(sidBuf[:n]) != natHoleRespMsg.Sid {
xl.Warn("incorrect sid from visitor") xl.Warn("incorrect sid from visitor")
return return
@@ -381,9 +389,12 @@ func (pxy *XtcpProxy) InWorkConn(conn net.Conn, m *msg.StartWorkConn) {
pool.PutBuf(sidBuf) pool.PutBuf(sidBuf)
xl.Info("nat hole connection make success, sid [%s]", natHoleRespMsg.Sid) xl.Info("nat hole connection make success, sid [%s]", natHoleRespMsg.Sid)
lConn.WriteToUDP(sidBuf[:n], uAddr) if _, err := lConn.WriteToUDP(sidBuf[:n], uAddr); err != nil {
xl.Error("write uaddr error: %v", err)
return
}
kcpConn, err := frpNet.NewKcpConnFromUdp(lConn, false, uAddr.String()) kcpConn, err := frpNet.NewKCPConnFromUDP(lConn, false, uAddr.String())
if err != nil { if err != nil {
xl.Error("create kcp connection from udp connection error: %v", err) xl.Error("create kcp connection from udp connection error: %v", err)
return return
@@ -391,7 +402,7 @@ func (pxy *XtcpProxy) InWorkConn(conn net.Conn, m *msg.StartWorkConn) {
fmuxCfg := fmux.DefaultConfig() fmuxCfg := fmux.DefaultConfig()
fmuxCfg.KeepAliveInterval = 5 * time.Second fmuxCfg.KeepAliveInterval = 5 * time.Second
fmuxCfg.LogOutput = ioutil.Discard fmuxCfg.LogOutput = io.Discard
sess, err := fmux.Server(kcpConn, fmuxCfg) sess, err := fmux.Server(kcpConn, fmuxCfg)
if err != nil { if err != nil {
xl.Error("create yamux server from kcp connection error: %v", err) xl.Error("create yamux server from kcp connection error: %v", err)
@@ -404,12 +415,12 @@ func (pxy *XtcpProxy) InWorkConn(conn net.Conn, m *msg.StartWorkConn) {
return return
} }
HandleTcpWorkConnection(pxy.ctx, &pxy.cfg.LocalSvrConf, pxy.proxyPlugin, &pxy.cfg.BaseProxyConf, pxy.limiter, HandleTCPWorkConnection(pxy.ctx, &pxy.cfg.LocalSvrConf, pxy.proxyPlugin, pxy.cfg.GetBaseInfo(), pxy.limiter,
muxConn, []byte(pxy.cfg.Sk), m) muxConn, []byte(pxy.cfg.Sk), m)
} }
func (pxy *XtcpProxy) sendDetectMsg(addr string, port int, laddr *net.UDPAddr, content []byte) (err error) { func (pxy *XTCPProxy) sendDetectMsg(addr string, port int, laddr *net.UDPAddr, content []byte) (err error) {
daddr, err := net.ResolveUDPAddr("udp", fmt.Sprintf("%s:%d", addr, port)) daddr, err := net.ResolveUDPAddr("udp", net.JoinHostPort(addr, strconv.Itoa(port)))
if err != nil { if err != nil {
return err return err
} }
@@ -419,37 +430,38 @@ func (pxy *XtcpProxy) sendDetectMsg(addr string, port int, laddr *net.UDPAddr, c
return err return err
} }
//uConn := ipv4.NewConn(tConn) // uConn := ipv4.NewConn(tConn)
//uConn.SetTTL(3) // uConn.SetTTL(3)
tConn.Write(content) if _, err := tConn.Write(content); err != nil {
tConn.Close() return err
return nil }
return tConn.Close()
} }
// UDP // UDP
type UdpProxy struct { type UDPProxy struct {
*BaseProxy *BaseProxy
cfg *config.UdpProxyConf cfg *config.UDPProxyConf
localAddr *net.UDPAddr localAddr *net.UDPAddr
readCh chan *msg.UdpPacket readCh chan *msg.UDPPacket
// include msg.UdpPacket and msg.Ping // include msg.UDPPacket and msg.Ping
sendCh chan msg.Message sendCh chan msg.Message
workConn net.Conn workConn net.Conn
} }
func (pxy *UdpProxy) Run() (err error) { func (pxy *UDPProxy) Run() (err error) {
pxy.localAddr, err = net.ResolveUDPAddr("udp", fmt.Sprintf("%s:%d", pxy.cfg.LocalIp, pxy.cfg.LocalPort)) pxy.localAddr, err = net.ResolveUDPAddr("udp", net.JoinHostPort(pxy.cfg.LocalIP, strconv.Itoa(pxy.cfg.LocalPort)))
if err != nil { if err != nil {
return return
} }
return return
} }
func (pxy *UdpProxy) Close() { func (pxy *UDPProxy) Close() {
pxy.mu.Lock() pxy.mu.Lock()
defer pxy.mu.Unlock() defer pxy.mu.Unlock()
@@ -467,29 +479,42 @@ func (pxy *UdpProxy) Close() {
} }
} }
func (pxy *UdpProxy) InWorkConn(conn net.Conn, m *msg.StartWorkConn) { func (pxy *UDPProxy) InWorkConn(conn net.Conn, m *msg.StartWorkConn) {
xl := pxy.xl xl := pxy.xl
xl.Info("incoming a new work connection for udp proxy, %s", conn.RemoteAddr().String()) xl.Info("incoming a new work connection for udp proxy, %s", conn.RemoteAddr().String())
// close resources releated with old workConn // close resources releated with old workConn
pxy.Close() pxy.Close()
var rwc io.ReadWriteCloser = conn
var err error
if pxy.limiter != nil { if pxy.limiter != nil {
rwc := frpIo.WrapReadWriteCloser(limit.NewReader(conn, pxy.limiter), limit.NewWriter(conn, pxy.limiter), func() error { rwc = frpIo.WrapReadWriteCloser(limit.NewReader(conn, pxy.limiter), limit.NewWriter(conn, pxy.limiter), func() error {
return conn.Close() return conn.Close()
}) })
conn = frpNet.WrapReadWriteCloserToConn(rwc, conn)
} }
if pxy.cfg.UseEncryption {
rwc, err = frpIo.WithEncryption(rwc, []byte(pxy.clientCfg.Token))
if err != nil {
conn.Close()
xl.Error("create encryption stream error: %v", err)
return
}
}
if pxy.cfg.UseCompression {
rwc = frpIo.WithCompression(rwc)
}
conn = frpNet.WrapReadWriteCloserToConn(rwc, conn)
pxy.mu.Lock() pxy.mu.Lock()
pxy.workConn = conn pxy.workConn = conn
pxy.readCh = make(chan *msg.UdpPacket, 1024) pxy.readCh = make(chan *msg.UDPPacket, 1024)
pxy.sendCh = make(chan msg.Message, 1024) pxy.sendCh = make(chan msg.Message, 1024)
pxy.closed = false pxy.closed = false
pxy.mu.Unlock() pxy.mu.Unlock()
workConnReaderFn := func(conn net.Conn, readCh chan *msg.UdpPacket) { workConnReaderFn := func(conn net.Conn, readCh chan *msg.UDPPacket) {
for { for {
var udpMsg msg.UdpPacket var udpMsg msg.UDPPacket
if errRet := msg.ReadMsgInto(conn, &udpMsg); errRet != nil { if errRet := msg.ReadMsgInto(conn, &udpMsg); errRet != nil {
xl.Warn("read from workConn for udp error: %v", errRet) xl.Warn("read from workConn for udp error: %v", errRet)
return return
@@ -510,7 +535,7 @@ func (pxy *UdpProxy) InWorkConn(conn net.Conn, m *msg.StartWorkConn) {
var errRet error var errRet error
for rawMsg := range sendCh { for rawMsg := range sendCh {
switch m := rawMsg.(type) { switch m := rawMsg.(type) {
case *msg.UdpPacket: case *msg.UDPPacket:
xl.Trace("send udp package to workConn: %s", m.Content) xl.Trace("send udp package to workConn: %s", m.Content)
case *msg.Ping: case *msg.Ping:
xl.Trace("send ping message to udp workConn") xl.Trace("send ping message to udp workConn")
@@ -521,7 +546,7 @@ func (pxy *UdpProxy) InWorkConn(conn net.Conn, m *msg.StartWorkConn) {
} }
} }
} }
heartbeatFn := func(conn net.Conn, sendCh chan msg.Message) { heartbeatFn := func(sendCh chan msg.Message) {
var errRet error var errRet error
for { for {
time.Sleep(time.Duration(30) * time.Second) time.Sleep(time.Duration(30) * time.Second)
@@ -536,13 +561,172 @@ func (pxy *UdpProxy) InWorkConn(conn net.Conn, m *msg.StartWorkConn) {
go workConnSenderFn(pxy.workConn, pxy.sendCh) go workConnSenderFn(pxy.workConn, pxy.sendCh)
go workConnReaderFn(pxy.workConn, pxy.readCh) go workConnReaderFn(pxy.workConn, pxy.readCh)
go heartbeatFn(pxy.workConn, pxy.sendCh) go heartbeatFn(pxy.sendCh)
udp.Forwarder(pxy.localAddr, pxy.readCh, pxy.sendCh) udp.Forwarder(pxy.localAddr, pxy.readCh, pxy.sendCh, int(pxy.clientCfg.UDPPacketSize))
}
type SUDPProxy struct {
*BaseProxy
cfg *config.SUDPProxyConf
localAddr *net.UDPAddr
closeCh chan struct{}
}
func (pxy *SUDPProxy) Run() (err error) {
pxy.localAddr, err = net.ResolveUDPAddr("udp", net.JoinHostPort(pxy.cfg.LocalIP, strconv.Itoa(pxy.cfg.LocalPort)))
if err != nil {
return
}
return
}
func (pxy *SUDPProxy) Close() {
pxy.mu.Lock()
defer pxy.mu.Unlock()
select {
case <-pxy.closeCh:
return
default:
close(pxy.closeCh)
}
}
func (pxy *SUDPProxy) InWorkConn(conn net.Conn, m *msg.StartWorkConn) {
xl := pxy.xl
xl.Info("incoming a new work connection for sudp proxy, %s", conn.RemoteAddr().String())
var rwc io.ReadWriteCloser = conn
var err error
if pxy.limiter != nil {
rwc = frpIo.WrapReadWriteCloser(limit.NewReader(conn, pxy.limiter), limit.NewWriter(conn, pxy.limiter), func() error {
return conn.Close()
})
}
if pxy.cfg.UseEncryption {
rwc, err = frpIo.WithEncryption(rwc, []byte(pxy.clientCfg.Token))
if err != nil {
conn.Close()
xl.Error("create encryption stream error: %v", err)
return
}
}
if pxy.cfg.UseCompression {
rwc = frpIo.WithCompression(rwc)
}
conn = frpNet.WrapReadWriteCloserToConn(rwc, conn)
workConn := conn
readCh := make(chan *msg.UDPPacket, 1024)
sendCh := make(chan msg.Message, 1024)
isClose := false
mu := &sync.Mutex{}
closeFn := func() {
mu.Lock()
defer mu.Unlock()
if isClose {
return
}
isClose = true
if workConn != nil {
workConn.Close()
}
close(readCh)
close(sendCh)
}
// udp service <- frpc <- frps <- frpc visitor <- user
workConnReaderFn := func(conn net.Conn, readCh chan *msg.UDPPacket) {
defer closeFn()
for {
// first to check sudp proxy is closed or not
select {
case <-pxy.closeCh:
xl.Trace("frpc sudp proxy is closed")
return
default:
}
var udpMsg msg.UDPPacket
if errRet := msg.ReadMsgInto(conn, &udpMsg); errRet != nil {
xl.Warn("read from workConn for sudp error: %v", errRet)
return
}
if errRet := errors.PanicToError(func() {
readCh <- &udpMsg
}); errRet != nil {
xl.Warn("reader goroutine for sudp work connection closed: %v", errRet)
return
}
}
}
// udp service -> frpc -> frps -> frpc visitor -> user
workConnSenderFn := func(conn net.Conn, sendCh chan msg.Message) {
defer func() {
closeFn()
xl.Info("writer goroutine for sudp work connection closed")
}()
var errRet error
for rawMsg := range sendCh {
switch m := rawMsg.(type) {
case *msg.UDPPacket:
xl.Trace("frpc send udp package to frpc visitor, [udp local: %v, remote: %v], [tcp work conn local: %v, remote: %v]",
m.LocalAddr.String(), m.RemoteAddr.String(), conn.LocalAddr().String(), conn.RemoteAddr().String())
case *msg.Ping:
xl.Trace("frpc send ping message to frpc visitor")
}
if errRet = msg.WriteMsg(conn, rawMsg); errRet != nil {
xl.Error("sudp work write error: %v", errRet)
return
}
}
}
heartbeatFn := func(sendCh chan msg.Message) {
ticker := time.NewTicker(30 * time.Second)
defer func() {
ticker.Stop()
closeFn()
}()
var errRet error
for {
select {
case <-ticker.C:
if errRet = errors.PanicToError(func() {
sendCh <- &msg.Ping{}
}); errRet != nil {
xl.Warn("heartbeat goroutine for sudp work connection closed")
return
}
case <-pxy.closeCh:
xl.Trace("frpc sudp proxy is closed")
return
}
}
}
go workConnSenderFn(workConn, sendCh)
go workConnReaderFn(workConn, readCh)
go heartbeatFn(sendCh)
udp.Forwarder(pxy.localAddr, readCh, sendCh, int(pxy.clientCfg.UDPPacketSize))
} }
// Common handler for tcp work connections. // Common handler for tcp work connections.
func HandleTcpWorkConnection(ctx context.Context, localInfo *config.LocalSvrConf, proxyPlugin plugin.Plugin, func HandleTCPWorkConnection(ctx context.Context, localInfo *config.LocalSvrConf, proxyPlugin plugin.Plugin,
baseInfo *config.BaseProxyConf, limiter *rate.Limiter, workConn net.Conn, encKey []byte, m *msg.StartWorkConn) { baseInfo *config.BaseProxyConf, limiter *rate.Limiter, workConn net.Conn, encKey []byte, m *msg.StartWorkConn,
) {
xl := xlog.FromContextSafe(ctx) xl := xlog.FromContextSafe(ctx)
var ( var (
remote io.ReadWriteCloser remote io.ReadWriteCloser
@@ -576,12 +760,12 @@ func HandleTcpWorkConnection(ctx context.Context, localInfo *config.LocalSvrConf
if m.DstAddr == "" { if m.DstAddr == "" {
m.DstAddr = "127.0.0.1" m.DstAddr = "127.0.0.1"
} }
srcAddr, _ := net.ResolveTCPAddr("tcp", net.JoinHostPort(m.SrcAddr, strconv.Itoa(int(m.SrcPort))))
dstAddr, _ := net.ResolveTCPAddr("tcp", net.JoinHostPort(m.DstAddr, strconv.Itoa(int(m.DstPort))))
h := &pp.Header{ h := &pp.Header{
Command: pp.PROXY, Command: pp.PROXY,
SourceAddress: net.ParseIP(m.SrcAddr), SourceAddr: srcAddr,
SourcePort: m.SrcPort, DestinationAddr: dstAddr,
DestinationAddress: net.ParseIP(m.DstAddr),
DestinationPort: m.DstPort,
} }
if strings.Contains(m.SrcAddr, ".") { if strings.Contains(m.SrcAddr, ".") {
@@ -597,7 +781,7 @@ func HandleTcpWorkConnection(ctx context.Context, localInfo *config.LocalSvrConf
} }
buf := bytes.NewBuffer(nil) buf := bytes.NewBuffer(nil)
h.WriteTo(buf) _, _ = h.WriteTo(buf)
extraInfo = buf.Bytes() extraInfo = buf.Bytes()
} }
} }
@@ -608,22 +792,29 @@ func HandleTcpWorkConnection(ctx context.Context, localInfo *config.LocalSvrConf
proxyPlugin.Handle(remote, workConn, extraInfo) proxyPlugin.Handle(remote, workConn, extraInfo)
xl.Debug("handle by plugin finished") xl.Debug("handle by plugin finished")
return return
} else { }
localConn, err := frpNet.ConnectServer("tcp", fmt.Sprintf("%s:%d", localInfo.LocalIp, localInfo.LocalPort))
if err != nil { localConn, err := libdial.Dial(
net.JoinHostPort(localInfo.LocalIP, strconv.Itoa(localInfo.LocalPort)),
libdial.WithTimeout(10*time.Second),
)
if err != nil {
workConn.Close()
xl.Error("connect to local service [%s:%d] error: %v", localInfo.LocalIP, localInfo.LocalPort, err)
return
}
xl.Debug("join connections, localConn(l[%s] r[%s]) workConn(l[%s] r[%s])", localConn.LocalAddr().String(),
localConn.RemoteAddr().String(), workConn.LocalAddr().String(), workConn.RemoteAddr().String())
if len(extraInfo) > 0 {
if _, err := localConn.Write(extraInfo); err != nil {
workConn.Close() workConn.Close()
xl.Error("connect to local service [%s:%d] error: %v", localInfo.LocalIp, localInfo.LocalPort, err) xl.Error("write extraInfo to local conn error: %v", err)
return return
} }
xl.Debug("join connections, localConn(l[%s] r[%s]) workConn(l[%s] r[%s])", localConn.LocalAddr().String(),
localConn.RemoteAddr().String(), workConn.LocalAddr().String(), workConn.RemoteAddr().String())
if len(extraInfo) > 0 {
localConn.Write(extraInfo)
}
frpIo.Join(localConn, remote)
xl.Debug("join connections closed")
} }
frpIo.Join(localConn, remote)
xl.Debug("join connections closed")
} }

View File

@@ -6,17 +6,17 @@ import (
"net" "net"
"sync" "sync"
"github.com/fatedier/frp/client/event"
"github.com/fatedier/frp/models/config"
"github.com/fatedier/frp/models/msg"
"github.com/fatedier/frp/utils/xlog"
"github.com/fatedier/golib/errors" "github.com/fatedier/golib/errors"
"github.com/fatedier/frp/client/event"
"github.com/fatedier/frp/pkg/config"
"github.com/fatedier/frp/pkg/msg"
"github.com/fatedier/frp/pkg/util/xlog"
) )
type ProxyManager struct { type Manager struct {
sendCh chan (msg.Message) sendCh chan (msg.Message)
proxies map[string]*ProxyWrapper proxies map[string]*Wrapper
closed bool closed bool
mu sync.RWMutex mu sync.RWMutex
@@ -29,10 +29,10 @@ type ProxyManager struct {
ctx context.Context ctx context.Context
} }
func NewProxyManager(ctx context.Context, msgSendCh chan (msg.Message), clientCfg config.ClientCommonConf, serverUDPPort int) *ProxyManager { func NewManager(ctx context.Context, msgSendCh chan (msg.Message), clientCfg config.ClientCommonConf, serverUDPPort int) *Manager {
return &ProxyManager{ return &Manager{
sendCh: msgSendCh, sendCh: msgSendCh,
proxies: make(map[string]*ProxyWrapper), proxies: make(map[string]*Wrapper),
closed: false, closed: false,
clientCfg: clientCfg, clientCfg: clientCfg,
serverUDPPort: serverUDPPort, serverUDPPort: serverUDPPort,
@@ -40,7 +40,7 @@ func NewProxyManager(ctx context.Context, msgSendCh chan (msg.Message), clientCf
} }
} }
func (pm *ProxyManager) StartProxy(name string, remoteAddr string, serverRespErr string) error { func (pm *Manager) StartProxy(name string, remoteAddr string, serverRespErr string) error {
pm.mu.RLock() pm.mu.RLock()
pxy, ok := pm.proxies[name] pxy, ok := pm.proxies[name]
pm.mu.RUnlock() pm.mu.RUnlock()
@@ -55,16 +55,16 @@ func (pm *ProxyManager) StartProxy(name string, remoteAddr string, serverRespErr
return nil return nil
} }
func (pm *ProxyManager) Close() { func (pm *Manager) Close() {
pm.mu.Lock() pm.mu.Lock()
defer pm.mu.Unlock() defer pm.mu.Unlock()
for _, pxy := range pm.proxies { for _, pxy := range pm.proxies {
pxy.Stop() pxy.Stop()
} }
pm.proxies = make(map[string]*ProxyWrapper) pm.proxies = make(map[string]*Wrapper)
} }
func (pm *ProxyManager) HandleWorkConn(name string, workConn net.Conn, m *msg.StartWorkConn) { func (pm *Manager) HandleWorkConn(name string, workConn net.Conn, m *msg.StartWorkConn) {
pm.mu.RLock() pm.mu.RLock()
pw, ok := pm.proxies[name] pw, ok := pm.proxies[name]
pm.mu.RUnlock() pm.mu.RUnlock()
@@ -75,7 +75,7 @@ func (pm *ProxyManager) HandleWorkConn(name string, workConn net.Conn, m *msg.St
} }
} }
func (pm *ProxyManager) HandleEvent(evType event.EventType, payload interface{}) error { func (pm *Manager) HandleEvent(payload interface{}) error {
var m msg.Message var m msg.Message
switch e := payload.(type) { switch e := payload.(type) {
case *event.StartProxyPayload: case *event.StartProxyPayload:
@@ -92,8 +92,8 @@ func (pm *ProxyManager) HandleEvent(evType event.EventType, payload interface{})
return err return err
} }
func (pm *ProxyManager) GetAllProxyStatus() []*ProxyStatus { func (pm *Manager) GetAllProxyStatus() []*WorkingStatus {
ps := make([]*ProxyStatus, 0) ps := make([]*WorkingStatus, 0)
pm.mu.RLock() pm.mu.RLock()
defer pm.mu.RUnlock() defer pm.mu.RUnlock()
for _, pxy := range pm.proxies { for _, pxy := range pm.proxies {
@@ -102,7 +102,7 @@ func (pm *ProxyManager) GetAllProxyStatus() []*ProxyStatus {
return ps return ps
} }
func (pm *ProxyManager) Reload(pxyCfgs map[string]config.ProxyConf) { func (pm *Manager) Reload(pxyCfgs map[string]config.ProxyConf) {
xl := xlog.FromContextSafe(pm.ctx) xl := xlog.FromContextSafe(pm.ctx)
pm.mu.Lock() pm.mu.Lock()
defer pm.mu.Unlock() defer pm.mu.Unlock()
@@ -113,10 +113,8 @@ func (pm *ProxyManager) Reload(pxyCfgs map[string]config.ProxyConf) {
cfg, ok := pxyCfgs[name] cfg, ok := pxyCfgs[name]
if !ok { if !ok {
del = true del = true
} else { } else if !pxy.Cfg.Compare(cfg) {
if !pxy.Cfg.Compare(cfg) { del = true
del = true
}
} }
if del { if del {
@@ -133,7 +131,7 @@ func (pm *ProxyManager) Reload(pxyCfgs map[string]config.ProxyConf) {
addPxyNames := make([]string, 0) addPxyNames := make([]string, 0)
for name, cfg := range pxyCfgs { for name, cfg := range pxyCfgs {
if _, ok := pm.proxies[name]; !ok { if _, ok := pm.proxies[name]; !ok {
pxy := NewProxyWrapper(pm.ctx, cfg, pm.clientCfg, pm.HandleEvent, pm.serverUDPPort) pxy := NewWrapper(pm.ctx, cfg, pm.clientCfg, pm.HandleEvent, pm.serverUDPPort)
pm.proxies[name] = pxy pm.proxies[name] = pxy
addPxyNames = append(addPxyNames, name) addPxyNames = append(addPxyNames, name)

View File

@@ -8,53 +8,53 @@ import (
"sync/atomic" "sync/atomic"
"time" "time"
"github.com/fatedier/golib/errors"
"github.com/fatedier/frp/client/event" "github.com/fatedier/frp/client/event"
"github.com/fatedier/frp/client/health" "github.com/fatedier/frp/client/health"
"github.com/fatedier/frp/models/config" "github.com/fatedier/frp/pkg/config"
"github.com/fatedier/frp/models/msg" "github.com/fatedier/frp/pkg/msg"
"github.com/fatedier/frp/utils/xlog" "github.com/fatedier/frp/pkg/util/xlog"
"github.com/fatedier/golib/errors"
) )
const ( const (
ProxyStatusNew = "new" ProxyPhaseNew = "new"
ProxyStatusWaitStart = "wait start" ProxyPhaseWaitStart = "wait start"
ProxyStatusStartErr = "start error" ProxyPhaseStartErr = "start error"
ProxyStatusRunning = "running" ProxyPhaseRunning = "running"
ProxyStatusCheckFailed = "check failed" ProxyPhaseCheckFailed = "check failed"
ProxyStatusClosed = "closed" ProxyPhaseClosed = "closed"
) )
var ( var (
statusCheckInterval time.Duration = 3 * time.Second statusCheckInterval = 3 * time.Second
waitResponseTimeout = 20 * time.Second waitResponseTimeout = 20 * time.Second
startErrTimeout = 30 * time.Second startErrTimeout = 30 * time.Second
) )
type ProxyStatus struct { type WorkingStatus struct {
Name string `json:"name"` Name string `json:"name"`
Type string `json:"type"` Type string `json:"type"`
Status string `json:"status"` Phase string `json:"status"`
Err string `json:"err"` Err string `json:"err"`
Cfg config.ProxyConf `json:"cfg"` Cfg config.ProxyConf `json:"cfg"`
// Got from server. // Got from server.
RemoteAddr string `json:"remote_addr"` RemoteAddr string `json:"remote_addr"`
} }
type ProxyWrapper struct { type Wrapper struct {
ProxyStatus WorkingStatus
// underlying proxy // underlying proxy
pxy Proxy pxy Proxy
// if ProxyConf has healcheck config // if ProxyConf has healcheck config
// monitor will watch if it is alive // monitor will watch if it is alive
monitor *health.HealthCheckMonitor monitor *health.Monitor
// event handler // event handler
handler event.EventHandler handler event.Handler
health uint32 health uint32
lastSendStartMsg time.Time lastSendStartMsg time.Time
@@ -67,15 +67,15 @@ type ProxyWrapper struct {
ctx context.Context ctx context.Context
} }
func NewProxyWrapper(ctx context.Context, cfg config.ProxyConf, clientCfg config.ClientCommonConf, eventHandler event.EventHandler, serverUDPPort int) *ProxyWrapper { func NewWrapper(ctx context.Context, cfg config.ProxyConf, clientCfg config.ClientCommonConf, eventHandler event.Handler, serverUDPPort int) *Wrapper {
baseInfo := cfg.GetBaseInfo() baseInfo := cfg.GetBaseInfo()
xl := xlog.FromContextSafe(ctx).Spawn().AppendPrefix(baseInfo.ProxyName) xl := xlog.FromContextSafe(ctx).Spawn().AppendPrefix(baseInfo.ProxyName)
pw := &ProxyWrapper{ pw := &Wrapper{
ProxyStatus: ProxyStatus{ WorkingStatus: WorkingStatus{
Name: baseInfo.ProxyName, Name: baseInfo.ProxyName,
Type: baseInfo.ProxyType, Type: baseInfo.ProxyType,
Status: ProxyStatusNew, Phase: ProxyPhaseNew,
Cfg: cfg, Cfg: cfg,
}, },
closeCh: make(chan struct{}), closeCh: make(chan struct{}),
healthNotifyCh: make(chan struct{}), healthNotifyCh: make(chan struct{}),
@@ -86,9 +86,9 @@ func NewProxyWrapper(ctx context.Context, cfg config.ProxyConf, clientCfg config
if baseInfo.HealthCheckType != "" { if baseInfo.HealthCheckType != "" {
pw.health = 1 // means failed pw.health = 1 // means failed
pw.monitor = health.NewHealthCheckMonitor(pw.ctx, baseInfo.HealthCheckType, baseInfo.HealthCheckIntervalS, pw.monitor = health.NewMonitor(pw.ctx, baseInfo.HealthCheckType, baseInfo.HealthCheckIntervalS,
baseInfo.HealthCheckTimeoutS, baseInfo.HealthCheckMaxFailed, baseInfo.HealthCheckAddr, baseInfo.HealthCheckTimeoutS, baseInfo.HealthCheckMaxFailed, baseInfo.HealthCheckAddr,
baseInfo.HealthCheckUrl, pw.statusNormalCallback, pw.statusFailedCallback) baseInfo.HealthCheckURL, pw.statusNormalCallback, pw.statusFailedCallback)
xl.Trace("enable health check monitor") xl.Trace("enable health check monitor")
} }
@@ -96,16 +96,16 @@ func NewProxyWrapper(ctx context.Context, cfg config.ProxyConf, clientCfg config
return pw return pw
} }
func (pw *ProxyWrapper) SetRunningStatus(remoteAddr string, respErr string) error { func (pw *Wrapper) SetRunningStatus(remoteAddr string, respErr string) error {
pw.mu.Lock() pw.mu.Lock()
defer pw.mu.Unlock() defer pw.mu.Unlock()
if pw.Status != ProxyStatusWaitStart { if pw.Phase != ProxyPhaseWaitStart {
return fmt.Errorf("status not wait start, ignore start message") return fmt.Errorf("status not wait start, ignore start message")
} }
pw.RemoteAddr = remoteAddr pw.RemoteAddr = remoteAddr
if respErr != "" { if respErr != "" {
pw.Status = ProxyStatusStartErr pw.Phase = ProxyPhaseStartErr
pw.Err = respErr pw.Err = respErr
pw.lastStartErr = time.Now() pw.lastStartErr = time.Now()
return fmt.Errorf(pw.Err) return fmt.Errorf(pw.Err)
@@ -113,25 +113,25 @@ func (pw *ProxyWrapper) SetRunningStatus(remoteAddr string, respErr string) erro
if err := pw.pxy.Run(); err != nil { if err := pw.pxy.Run(); err != nil {
pw.close() pw.close()
pw.Status = ProxyStatusStartErr pw.Phase = ProxyPhaseStartErr
pw.Err = err.Error() pw.Err = err.Error()
pw.lastStartErr = time.Now() pw.lastStartErr = time.Now()
return err return err
} }
pw.Status = ProxyStatusRunning pw.Phase = ProxyPhaseRunning
pw.Err = "" pw.Err = ""
return nil return nil
} }
func (pw *ProxyWrapper) Start() { func (pw *Wrapper) Start() {
go pw.checkWorker() go pw.checkWorker()
if pw.monitor != nil { if pw.monitor != nil {
go pw.monitor.Start() go pw.monitor.Start()
} }
} }
func (pw *ProxyWrapper) Stop() { func (pw *Wrapper) Stop() {
pw.mu.Lock() pw.mu.Lock()
defer pw.mu.Unlock() defer pw.mu.Unlock()
close(pw.closeCh) close(pw.closeCh)
@@ -140,19 +140,19 @@ func (pw *ProxyWrapper) Stop() {
if pw.monitor != nil { if pw.monitor != nil {
pw.monitor.Stop() pw.monitor.Stop()
} }
pw.Status = ProxyStatusClosed pw.Phase = ProxyPhaseClosed
pw.close() pw.close()
} }
func (pw *ProxyWrapper) close() { func (pw *Wrapper) close() {
pw.handler(event.EvCloseProxy, &event.CloseProxyPayload{ _ = pw.handler(&event.CloseProxyPayload{
CloseProxyMsg: &msg.CloseProxy{ CloseProxyMsg: &msg.CloseProxy{
ProxyName: pw.Name, ProxyName: pw.Name,
}, },
}) })
} }
func (pw *ProxyWrapper) checkWorker() { func (pw *Wrapper) checkWorker() {
xl := pw.xl xl := pw.xl
if pw.monitor != nil { if pw.monitor != nil {
// let monitor do check request first // let monitor do check request first
@@ -163,28 +163,28 @@ func (pw *ProxyWrapper) checkWorker() {
now := time.Now() now := time.Now()
if atomic.LoadUint32(&pw.health) == 0 { if atomic.LoadUint32(&pw.health) == 0 {
pw.mu.Lock() pw.mu.Lock()
if pw.Status == ProxyStatusNew || if pw.Phase == ProxyPhaseNew ||
pw.Status == ProxyStatusCheckFailed || pw.Phase == ProxyPhaseCheckFailed ||
(pw.Status == ProxyStatusWaitStart && now.After(pw.lastSendStartMsg.Add(waitResponseTimeout))) || (pw.Phase == ProxyPhaseWaitStart && now.After(pw.lastSendStartMsg.Add(waitResponseTimeout))) ||
(pw.Status == ProxyStatusStartErr && now.After(pw.lastStartErr.Add(startErrTimeout))) { (pw.Phase == ProxyPhaseStartErr && now.After(pw.lastStartErr.Add(startErrTimeout))) {
xl.Trace("change status from [%s] to [%s]", pw.Status, ProxyStatusWaitStart) xl.Trace("change status from [%s] to [%s]", pw.Phase, ProxyPhaseWaitStart)
pw.Status = ProxyStatusWaitStart pw.Phase = ProxyPhaseWaitStart
var newProxyMsg msg.NewProxy var newProxyMsg msg.NewProxy
pw.Cfg.MarshalToMsg(&newProxyMsg) pw.Cfg.MarshalToMsg(&newProxyMsg)
pw.lastSendStartMsg = now pw.lastSendStartMsg = now
pw.handler(event.EvStartProxy, &event.StartProxyPayload{ _ = pw.handler(&event.StartProxyPayload{
NewProxyMsg: &newProxyMsg, NewProxyMsg: &newProxyMsg,
}) })
} }
pw.mu.Unlock() pw.mu.Unlock()
} else { } else {
pw.mu.Lock() pw.mu.Lock()
if pw.Status == ProxyStatusRunning || pw.Status == ProxyStatusWaitStart { if pw.Phase == ProxyPhaseRunning || pw.Phase == ProxyPhaseWaitStart {
pw.close() pw.close()
xl.Trace("change status from [%s] to [%s]", pw.Status, ProxyStatusCheckFailed) xl.Trace("change status from [%s] to [%s]", pw.Phase, ProxyPhaseCheckFailed)
pw.Status = ProxyStatusCheckFailed pw.Phase = ProxyPhaseCheckFailed
} }
pw.mu.Unlock() pw.mu.Unlock()
} }
@@ -198,10 +198,10 @@ func (pw *ProxyWrapper) checkWorker() {
} }
} }
func (pw *ProxyWrapper) statusNormalCallback() { func (pw *Wrapper) statusNormalCallback() {
xl := pw.xl xl := pw.xl
atomic.StoreUint32(&pw.health, 0) atomic.StoreUint32(&pw.health, 0)
errors.PanicToError(func() { _ = errors.PanicToError(func() {
select { select {
case pw.healthNotifyCh <- struct{}{}: case pw.healthNotifyCh <- struct{}{}:
default: default:
@@ -210,10 +210,10 @@ func (pw *ProxyWrapper) statusNormalCallback() {
xl.Info("health check success") xl.Info("health check success")
} }
func (pw *ProxyWrapper) statusFailedCallback() { func (pw *Wrapper) statusFailedCallback() {
xl := pw.xl xl := pw.xl
atomic.StoreUint32(&pw.health, 1) atomic.StoreUint32(&pw.health, 1)
errors.PanicToError(func() { _ = errors.PanicToError(func() {
select { select {
case pw.healthNotifyCh <- struct{}{}: case pw.healthNotifyCh <- struct{}{}:
default: default:
@@ -222,12 +222,12 @@ func (pw *ProxyWrapper) statusFailedCallback() {
xl.Info("health check failed") xl.Info("health check failed")
} }
func (pw *ProxyWrapper) InWorkConn(workConn net.Conn, m *msg.StartWorkConn) { func (pw *Wrapper) InWorkConn(workConn net.Conn, m *msg.StartWorkConn) {
xl := pw.xl xl := pw.xl
pw.mu.RLock() pw.mu.RLock()
pxy := pw.pxy pxy := pw.pxy
pw.mu.RUnlock() pw.mu.RUnlock()
if pxy != nil { if pxy != nil && pw.Phase == ProxyPhaseRunning {
xl.Debug("start a new work connection, localAddr: %s remoteAddr: %s", workConn.LocalAddr().String(), workConn.RemoteAddr().String()) xl.Debug("start a new work connection, localAddr: %s remoteAddr: %s", workConn.LocalAddr().String(), workConn.RemoteAddr().String())
go pxy.InWorkConn(workConn, m) go pxy.InWorkConn(workConn, m)
} else { } else {
@@ -235,13 +235,13 @@ func (pw *ProxyWrapper) InWorkConn(workConn net.Conn, m *msg.StartWorkConn) {
} }
} }
func (pw *ProxyWrapper) GetStatus() *ProxyStatus { func (pw *Wrapper) GetStatus() *WorkingStatus {
pw.mu.RLock() pw.mu.RLock()
defer pw.mu.RUnlock() defer pw.mu.RUnlock()
ps := &ProxyStatus{ ps := &WorkingStatus{
Name: pw.Name, Name: pw.Name,
Type: pw.Type, Type: pw.Type,
Status: pw.Status, Phase: pw.Phase,
Err: pw.Err, Err: pw.Err,
Cfg: pw.Cfg, Cfg: pw.Cfg,
RemoteAddr: pw.RemoteAddr, RemoteAddr: pw.RemoteAddr,

View File

@@ -18,29 +18,42 @@ import (
"context" "context"
"crypto/tls" "crypto/tls"
"fmt" "fmt"
"io/ioutil" "io"
"math/rand"
"net" "net"
"runtime" "runtime"
"strconv"
"strings"
"sync" "sync"
"sync/atomic" "sync/atomic"
"time" "time"
"github.com/fatedier/frp/assets" "github.com/fatedier/golib/crypto"
"github.com/fatedier/frp/models/auth" libdial "github.com/fatedier/golib/net/dial"
"github.com/fatedier/frp/models/config"
"github.com/fatedier/frp/models/msg"
"github.com/fatedier/frp/utils/log"
frpNet "github.com/fatedier/frp/utils/net"
"github.com/fatedier/frp/utils/version"
"github.com/fatedier/frp/utils/xlog"
fmux "github.com/hashicorp/yamux" fmux "github.com/hashicorp/yamux"
quic "github.com/lucas-clemente/quic-go"
"github.com/fatedier/frp/assets"
"github.com/fatedier/frp/pkg/auth"
"github.com/fatedier/frp/pkg/config"
"github.com/fatedier/frp/pkg/msg"
"github.com/fatedier/frp/pkg/transport"
"github.com/fatedier/frp/pkg/util/log"
frpNet "github.com/fatedier/frp/pkg/util/net"
"github.com/fatedier/frp/pkg/util/util"
"github.com/fatedier/frp/pkg/util/version"
"github.com/fatedier/frp/pkg/util/xlog"
) )
func init() {
crypto.DefaultSalt = "frp"
rand.Seed(time.Now().UnixNano())
}
// Service is a client service. // Service is a client service.
type Service struct { type Service struct {
// uniq id got from frps, attach it in loginMsg // uniq id got from frps, attach it in loginMsg
runId string runID string
// manager control connection with server // manager control connection with server
ctl *Control ctl *Control
@@ -69,11 +82,15 @@ type Service struct {
cancel context.CancelFunc cancel context.CancelFunc
} }
func NewService(cfg config.ClientCommonConf, pxyCfgs map[string]config.ProxyConf, visitorCfgs map[string]config.VisitorConf, cfgFile string) (svr *Service, err error) { func NewService(
cfg config.ClientCommonConf,
pxyCfgs map[string]config.ProxyConf,
visitorCfgs map[string]config.VisitorConf,
cfgFile string,
) (svr *Service, err error) {
ctx, cancel := context.WithCancel(context.Background()) ctx, cancel := context.WithCancel(context.Background())
svr = &Service{ svr = &Service{
authSetter: auth.NewAuthSetter(cfg.AuthClientConfig), authSetter: auth.NewAuthSetter(cfg.ClientConfig),
cfg: cfg, cfg: cfg,
cfgFile: cfgFile, cfgFile: cfgFile,
pxyCfgs: pxyCfgs, pxyCfgs: pxyCfgs,
@@ -94,9 +111,24 @@ func (svr *Service) GetController() *Control {
func (svr *Service) Run() error { func (svr *Service) Run() error {
xl := xlog.FromContextSafe(svr.ctx) xl := xlog.FromContextSafe(svr.ctx)
// set custom DNSServer
if svr.cfg.DNSServer != "" {
dnsAddr := svr.cfg.DNSServer
if !strings.Contains(dnsAddr, ":") {
dnsAddr += ":53"
}
// Change default dns server for frpc
net.DefaultResolver = &net.Resolver{
PreferGo: true,
Dial: func(ctx context.Context, network, address string) (net.Conn, error) {
return net.Dial("udp", dnsAddr)
},
}
}
// login to frps // login to frps
for { for {
conn, session, err := svr.login() conn, cm, err := svr.login()
if err != nil { if err != nil {
xl.Warn("login to server failed: %v", err) xl.Warn("login to server failed: %v", err)
@@ -104,12 +136,11 @@ func (svr *Service) Run() error {
// otherwise sleep a while and try again to connect to server // otherwise sleep a while and try again to connect to server
if svr.cfg.LoginFailExit { if svr.cfg.LoginFailExit {
return err return err
} else {
time.Sleep(10 * time.Second)
} }
util.RandomSleep(10*time.Second, 0.9, 1.1)
} else { } else {
// login success // login success
ctl := NewControl(svr.ctx, svr.runId, conn, session, svr.cfg, svr.pxyCfgs, svr.visitorCfgs, svr.serverUDPPort, svr.authSetter) ctl := NewControl(svr.ctx, svr.runID, conn, cm, svr.cfg, svr.pxyCfgs, svr.visitorCfgs, svr.serverUDPPort, svr.authSetter)
ctl.Run() ctl.Run()
svr.ctlMu.Lock() svr.ctlMu.Lock()
svr.ctl = ctl svr.ctl = ctl
@@ -122,12 +153,10 @@ func (svr *Service) Run() error {
if svr.cfg.AdminPort != 0 { if svr.cfg.AdminPort != 0 {
// Init admin server assets // Init admin server assets
err := assets.Load(svr.cfg.AssetsDir) assets.Load(svr.cfg.AssetsDir)
if err != nil {
return fmt.Errorf("Load assets error: %v", err)
}
err = svr.RunAdminServer(svr.cfg.AdminAddr, svr.cfg.AdminPort) address := net.JoinHostPort(svr.cfg.AdminAddr, strconv.Itoa(svr.cfg.AdminPort))
err := svr.RunAdminServer(address)
if err != nil { if err != nil {
log.Warn("run admin server error: %v", err) log.Warn("run admin server error: %v", err)
} }
@@ -142,19 +171,49 @@ func (svr *Service) keepControllerWorking() {
maxDelayTime := 20 * time.Second maxDelayTime := 20 * time.Second
delayTime := time.Second delayTime := time.Second
// if frpc reconnect frps, we need to limit retry times in 1min
// current retry logic is sleep 0s, 0s, 0s, 1s, 2s, 4s, 8s, ...
// when exceed 1min, we will reset delay and counts
cutoffTime := time.Now().Add(time.Minute)
reconnectDelay := time.Second
reconnectCounts := 1
for { for {
<-svr.ctl.ClosedDoneCh() <-svr.ctl.ClosedDoneCh()
if atomic.LoadUint32(&svr.exit) != 0 { if atomic.LoadUint32(&svr.exit) != 0 {
return return
} }
// the first three retry with no delay
if reconnectCounts > 3 {
util.RandomSleep(reconnectDelay, 0.9, 1.1)
xl.Info("wait %v to reconnect", reconnectDelay)
reconnectDelay *= 2
} else {
util.RandomSleep(time.Second, 0, 0.5)
}
reconnectCounts++
now := time.Now()
if now.After(cutoffTime) {
// reset
cutoffTime = now.Add(time.Minute)
reconnectDelay = time.Second
reconnectCounts = 1
}
for { for {
if atomic.LoadUint32(&svr.exit) != 0 {
return
}
xl.Info("try to reconnect to server...") xl.Info("try to reconnect to server...")
conn, session, err := svr.login() conn, cm, err := svr.login()
if err != nil { if err != nil {
xl.Warn("reconnect to server error: %v", err) xl.Warn("reconnect to server error: %v, wait %v for another retry", err, delayTime)
time.Sleep(delayTime) util.RandomSleep(delayTime, 0.9, 1.1)
delayTime = delayTime * 2
delayTime *= 2
if delayTime > maxDelayTime { if delayTime > maxDelayTime {
delayTime = maxDelayTime delayTime = maxDelayTime
} }
@@ -163,9 +222,12 @@ func (svr *Service) keepControllerWorking() {
// reconnect success, init delayTime // reconnect success, init delayTime
delayTime = time.Second delayTime = time.Second
ctl := NewControl(svr.ctx, svr.runId, conn, session, svr.cfg, svr.pxyCfgs, svr.visitorCfgs, svr.serverUDPPort, svr.authSetter) ctl := NewControl(svr.ctx, svr.runID, conn, cm, svr.cfg, svr.pxyCfgs, svr.visitorCfgs, svr.serverUDPPort, svr.authSetter)
ctl.Run() ctl.Run()
svr.ctlMu.Lock() svr.ctlMu.Lock()
if svr.ctl != nil {
svr.ctl.Close()
}
svr.ctl = ctl svr.ctl = ctl
svr.ctlMu.Unlock() svr.ctlMu.Unlock()
break break
@@ -176,44 +238,23 @@ func (svr *Service) keepControllerWorking() {
// login creates a connection to frps and registers it self as a client // login creates a connection to frps and registers it self as a client
// conn: control connection // conn: control connection
// session: if it's not nil, using tcp mux // session: if it's not nil, using tcp mux
func (svr *Service) login() (conn net.Conn, session *fmux.Session, err error) { func (svr *Service) login() (conn net.Conn, cm *ConnectionManager, err error) {
xl := xlog.FromContextSafe(svr.ctx) xl := xlog.FromContextSafe(svr.ctx)
var tlsConfig *tls.Config cm = NewConnectionManager(svr.ctx, &svr.cfg)
if svr.cfg.TLSEnable {
tlsConfig = &tls.Config{ if err = cm.OpenConnection(); err != nil {
InsecureSkipVerify: true, return nil, nil, err
}
}
conn, err = frpNet.ConnectServerByProxyWithTLS(svr.cfg.HttpProxy, svr.cfg.Protocol,
fmt.Sprintf("%s:%d", svr.cfg.ServerAddr, svr.cfg.ServerPort), tlsConfig)
if err != nil {
return
} }
defer func() { defer func() {
if err != nil { if err != nil {
conn.Close() cm.Close()
if session != nil {
session.Close()
}
} }
}() }()
if svr.cfg.TcpMux { conn, err = cm.Connect()
fmuxCfg := fmux.DefaultConfig() if err != nil {
fmuxCfg.KeepAliveInterval = 20 * time.Second return
fmuxCfg.LogOutput = ioutil.Discard
session, err = fmux.Client(conn, fmuxCfg)
if err != nil {
return
}
stream, errRet := session.OpenStream()
if errRet != nil {
session.Close()
err = errRet
return
}
conn = stream
} }
loginMsg := &msg.Login{ loginMsg := &msg.Login{
@@ -223,7 +264,7 @@ func (svr *Service) login() (conn net.Conn, session *fmux.Session, err error) {
User: svr.cfg.User, User: svr.cfg.User,
Version: version.Full(), Version: version.Full(),
Timestamp: time.Now().Unix(), Timestamp: time.Now().Unix(),
RunId: svr.runId, RunID: svr.runID,
Metas: svr.cfg.Metas, Metas: svr.cfg.Metas,
} }
@@ -237,11 +278,11 @@ func (svr *Service) login() (conn net.Conn, session *fmux.Session, err error) {
} }
var loginRespMsg msg.LoginResp var loginRespMsg msg.LoginResp
conn.SetReadDeadline(time.Now().Add(10 * time.Second)) _ = conn.SetReadDeadline(time.Now().Add(10 * time.Second))
if err = msg.ReadMsgInto(conn, &loginRespMsg); err != nil { if err = msg.ReadMsgInto(conn, &loginRespMsg); err != nil {
return return
} }
conn.SetReadDeadline(time.Time{}) _ = conn.SetReadDeadline(time.Time{})
if loginRespMsg.Error != "" { if loginRespMsg.Error != "" {
err = fmt.Errorf("%s", loginRespMsg.Error) err = fmt.Errorf("%s", loginRespMsg.Error)
@@ -249,12 +290,12 @@ func (svr *Service) login() (conn net.Conn, session *fmux.Session, err error) {
return return
} }
svr.runId = loginRespMsg.RunId svr.runID = loginRespMsg.RunID
xl.ResetPrefixes() xl.ResetPrefixes()
xl.AppendPrefix(svr.runId) xl.AppendPrefix(svr.runID)
svr.serverUDPPort = loginRespMsg.ServerUdpPort svr.serverUDPPort = loginRespMsg.ServerUDPPort
xl.Info("login to server success, get run id [%s], server udp port [%d]", loginRespMsg.RunId, loginRespMsg.ServerUdpPort) xl.Info("login to server success, get run id [%s], server udp port [%d]", loginRespMsg.RunID, loginRespMsg.ServerUDPPort)
return return
} }
@@ -264,11 +305,184 @@ func (svr *Service) ReloadConf(pxyCfgs map[string]config.ProxyConf, visitorCfgs
svr.visitorCfgs = visitorCfgs svr.visitorCfgs = visitorCfgs
svr.cfgMu.Unlock() svr.cfgMu.Unlock()
return svr.ctl.ReloadConf(pxyCfgs, visitorCfgs) svr.ctlMu.RLock()
ctl := svr.ctl
svr.ctlMu.RUnlock()
if ctl != nil {
return svr.ctl.ReloadConf(pxyCfgs, visitorCfgs)
}
return nil
} }
func (svr *Service) Close() { func (svr *Service) Close() {
svr.GracefulClose(time.Duration(0))
}
func (svr *Service) GracefulClose(d time.Duration) {
atomic.StoreUint32(&svr.exit, 1) atomic.StoreUint32(&svr.exit, 1)
svr.ctl.Close()
svr.ctlMu.RLock()
if svr.ctl != nil {
svr.ctl.GracefulClose(d)
}
svr.ctlMu.RUnlock()
svr.cancel() svr.cancel()
} }
type ConnectionManager struct {
ctx context.Context
cfg *config.ClientCommonConf
muxSession *fmux.Session
quicConn quic.Connection
}
func NewConnectionManager(ctx context.Context, cfg *config.ClientCommonConf) *ConnectionManager {
return &ConnectionManager{
ctx: ctx,
cfg: cfg,
}
}
func (cm *ConnectionManager) OpenConnection() error {
xl := xlog.FromContextSafe(cm.ctx)
// special for quic
if strings.EqualFold(cm.cfg.Protocol, "quic") {
var tlsConfig *tls.Config
var err error
sn := cm.cfg.TLSServerName
if sn == "" {
sn = cm.cfg.ServerAddr
}
if cm.cfg.TLSEnable {
tlsConfig, err = transport.NewClientTLSConfig(
cm.cfg.TLSCertFile,
cm.cfg.TLSKeyFile,
cm.cfg.TLSTrustedCaFile,
sn)
} else {
tlsConfig, err = transport.NewClientTLSConfig("", "", "", sn)
}
if err != nil {
xl.Warn("fail to build tls configuration, err: %v", err)
return err
}
tlsConfig.NextProtos = []string{"frp"}
conn, err := quic.DialAddr(
net.JoinHostPort(cm.cfg.ServerAddr, strconv.Itoa(cm.cfg.ServerPort)),
tlsConfig, &quic.Config{
MaxIdleTimeout: time.Duration(cm.cfg.QUICMaxIdleTimeout) * time.Second,
MaxIncomingStreams: int64(cm.cfg.QUICMaxIncomingStreams),
KeepAlivePeriod: time.Duration(cm.cfg.QUICKeepalivePeriod) * time.Second,
})
if err != nil {
return err
}
cm.quicConn = conn
return nil
}
if !cm.cfg.TCPMux {
return nil
}
conn, err := cm.realConnect()
if err != nil {
return err
}
fmuxCfg := fmux.DefaultConfig()
fmuxCfg.KeepAliveInterval = time.Duration(cm.cfg.TCPMuxKeepaliveInterval) * time.Second
fmuxCfg.LogOutput = io.Discard
session, err := fmux.Client(conn, fmuxCfg)
if err != nil {
return err
}
cm.muxSession = session
return nil
}
func (cm *ConnectionManager) Connect() (net.Conn, error) {
if cm.quicConn != nil {
stream, err := cm.quicConn.OpenStreamSync(context.Background())
if err != nil {
return nil, err
}
return frpNet.QuicStreamToNetConn(stream, cm.quicConn), nil
} else if cm.muxSession != nil {
stream, err := cm.muxSession.OpenStream()
if err != nil {
return nil, err
}
return stream, nil
}
return cm.realConnect()
}
func (cm *ConnectionManager) realConnect() (net.Conn, error) {
xl := xlog.FromContextSafe(cm.ctx)
var tlsConfig *tls.Config
var err error
if cm.cfg.TLSEnable {
sn := cm.cfg.TLSServerName
if sn == "" {
sn = cm.cfg.ServerAddr
}
tlsConfig, err = transport.NewClientTLSConfig(
cm.cfg.TLSCertFile,
cm.cfg.TLSKeyFile,
cm.cfg.TLSTrustedCaFile,
sn)
if err != nil {
xl.Warn("fail to build tls configuration, err: %v", err)
return nil, err
}
}
proxyType, addr, auth, err := libdial.ParseProxyURL(cm.cfg.HTTPProxy)
if err != nil {
xl.Error("fail to parse proxy url")
return nil, err
}
dialOptions := []libdial.DialOption{}
protocol := cm.cfg.Protocol
if protocol == "websocket" {
protocol = "tcp"
dialOptions = append(dialOptions, libdial.WithAfterHook(libdial.AfterHook{Hook: frpNet.DialHookWebsocket()}))
}
if cm.cfg.ConnectServerLocalIP != "" {
dialOptions = append(dialOptions, libdial.WithLocalAddr(cm.cfg.ConnectServerLocalIP))
}
dialOptions = append(dialOptions,
libdial.WithProtocol(protocol),
libdial.WithTimeout(time.Duration(cm.cfg.DialServerTimeout)*time.Second),
libdial.WithKeepAlive(time.Duration(cm.cfg.DialServerKeepAlive)*time.Second),
libdial.WithProxy(proxyType, addr),
libdial.WithProxyAuth(auth),
libdial.WithTLSConfig(tlsConfig),
libdial.WithAfterHook(libdial.AfterHook{
Hook: frpNet.DialHookCustomTLSHeadByte(tlsConfig != nil, cm.cfg.DisableCustomTLSFirstByte),
}),
)
conn, err := libdial.Dial(
net.JoinHostPort(cm.cfg.ServerAddr, strconv.Itoa(cm.cfg.ServerPort)),
dialOptions...,
)
return conn, err
}
func (cm *ConnectionManager) Close() error {
if cm.quicConn != nil {
_ = cm.quicConn.CloseWithError(0, "")
}
if cm.muxSession != nil {
_ = cm.muxSession.Close()
}
return nil
}

View File

@@ -19,20 +19,22 @@ import (
"context" "context"
"fmt" "fmt"
"io" "io"
"io/ioutil"
"net" "net"
"strconv"
"sync" "sync"
"time" "time"
"github.com/fatedier/frp/models/config" "github.com/fatedier/golib/errors"
"github.com/fatedier/frp/models/msg"
frpNet "github.com/fatedier/frp/utils/net"
"github.com/fatedier/frp/utils/util"
"github.com/fatedier/frp/utils/xlog"
frpIo "github.com/fatedier/golib/io" frpIo "github.com/fatedier/golib/io"
"github.com/fatedier/golib/pool" "github.com/fatedier/golib/pool"
fmux "github.com/hashicorp/yamux" fmux "github.com/hashicorp/yamux"
"github.com/fatedier/frp/pkg/config"
"github.com/fatedier/frp/pkg/msg"
"github.com/fatedier/frp/pkg/proto/udp"
frpNet "github.com/fatedier/frp/pkg/util/net"
"github.com/fatedier/frp/pkg/util/util"
"github.com/fatedier/frp/pkg/util/xlog"
) )
// Visitor is used for forward traffics from local port tot remote service. // Visitor is used for forward traffics from local port tot remote service.
@@ -48,37 +50,42 @@ func NewVisitor(ctx context.Context, ctl *Control, cfg config.VisitorConf) (visi
ctx: xlog.NewContext(ctx, xl), ctx: xlog.NewContext(ctx, xl),
} }
switch cfg := cfg.(type) { switch cfg := cfg.(type) {
case *config.StcpVisitorConf: case *config.STCPVisitorConf:
visitor = &StcpVisitor{ visitor = &STCPVisitor{
BaseVisitor: &baseVisitor, BaseVisitor: &baseVisitor,
cfg: cfg, cfg: cfg,
} }
case *config.XtcpVisitorConf: case *config.XTCPVisitorConf:
visitor = &XtcpVisitor{ visitor = &XTCPVisitor{
BaseVisitor: &baseVisitor, BaseVisitor: &baseVisitor,
cfg: cfg, cfg: cfg,
} }
case *config.SUDPVisitorConf:
visitor = &SUDPVisitor{
BaseVisitor: &baseVisitor,
cfg: cfg,
checkCloseCh: make(chan struct{}),
}
} }
return return
} }
type BaseVisitor struct { type BaseVisitor struct {
ctl *Control ctl *Control
l net.Listener l net.Listener
closed bool
mu sync.RWMutex mu sync.RWMutex
ctx context.Context ctx context.Context
} }
type StcpVisitor struct { type STCPVisitor struct {
*BaseVisitor *BaseVisitor
cfg *config.StcpVisitorConf cfg *config.STCPVisitorConf
} }
func (sv *StcpVisitor) Run() (err error) { func (sv *STCPVisitor) Run() (err error) {
sv.l, err = net.Listen("tcp", fmt.Sprintf("%s:%d", sv.cfg.BindAddr, sv.cfg.BindPort)) sv.l, err = net.Listen("tcp", net.JoinHostPort(sv.cfg.BindAddr, strconv.Itoa(sv.cfg.BindPort)))
if err != nil { if err != nil {
return return
} }
@@ -87,11 +94,11 @@ func (sv *StcpVisitor) Run() (err error) {
return return
} }
func (sv *StcpVisitor) Close() { func (sv *STCPVisitor) Close() {
sv.l.Close() sv.l.Close()
} }
func (sv *StcpVisitor) worker() { func (sv *STCPVisitor) worker() {
xl := xlog.FromContextSafe(sv.ctx) xl := xlog.FromContextSafe(sv.ctx)
for { for {
conn, err := sv.l.Accept() conn, err := sv.l.Accept()
@@ -104,7 +111,7 @@ func (sv *StcpVisitor) worker() {
} }
} }
func (sv *StcpVisitor) handleConn(userConn net.Conn) { func (sv *STCPVisitor) handleConn(userConn net.Conn) {
xl := xlog.FromContextSafe(sv.ctx) xl := xlog.FromContextSafe(sv.ctx)
defer userConn.Close() defer userConn.Close()
@@ -130,13 +137,13 @@ func (sv *StcpVisitor) handleConn(userConn net.Conn) {
} }
var newVisitorConnRespMsg msg.NewVisitorConnResp var newVisitorConnRespMsg msg.NewVisitorConnResp
visitorConn.SetReadDeadline(time.Now().Add(10 * time.Second)) _ = visitorConn.SetReadDeadline(time.Now().Add(10 * time.Second))
err = msg.ReadMsgInto(visitorConn, &newVisitorConnRespMsg) err = msg.ReadMsgInto(visitorConn, &newVisitorConnRespMsg)
if err != nil { if err != nil {
xl.Warn("get newVisitorConnRespMsg error: %v", err) xl.Warn("get newVisitorConnRespMsg error: %v", err)
return return
} }
visitorConn.SetReadDeadline(time.Time{}) _ = visitorConn.SetReadDeadline(time.Time{})
if newVisitorConnRespMsg.Error != "" { if newVisitorConnRespMsg.Error != "" {
xl.Warn("start new visitor connection error: %s", newVisitorConnRespMsg.Error) xl.Warn("start new visitor connection error: %s", newVisitorConnRespMsg.Error)
@@ -160,14 +167,14 @@ func (sv *StcpVisitor) handleConn(userConn net.Conn) {
frpIo.Join(userConn, remote) frpIo.Join(userConn, remote)
} }
type XtcpVisitor struct { type XTCPVisitor struct {
*BaseVisitor *BaseVisitor
cfg *config.XtcpVisitorConf cfg *config.XTCPVisitorConf
} }
func (sv *XtcpVisitor) Run() (err error) { func (sv *XTCPVisitor) Run() (err error) {
sv.l, err = net.Listen("tcp", fmt.Sprintf("%s:%d", sv.cfg.BindAddr, sv.cfg.BindPort)) sv.l, err = net.Listen("tcp", net.JoinHostPort(sv.cfg.BindAddr, strconv.Itoa(sv.cfg.BindPort)))
if err != nil { if err != nil {
return return
} }
@@ -176,11 +183,11 @@ func (sv *XtcpVisitor) Run() (err error) {
return return
} }
func (sv *XtcpVisitor) Close() { func (sv *XTCPVisitor) Close() {
sv.l.Close() sv.l.Close()
} }
func (sv *XtcpVisitor) worker() { func (sv *XTCPVisitor) worker() {
xl := xlog.FromContextSafe(sv.ctx) xl := xlog.FromContextSafe(sv.ctx)
for { for {
conn, err := sv.l.Accept() conn, err := sv.l.Accept()
@@ -193,7 +200,7 @@ func (sv *XtcpVisitor) worker() {
} }
} }
func (sv *XtcpVisitor) handleConn(userConn net.Conn) { func (sv *XTCPVisitor) handleConn(userConn net.Conn) {
xl := xlog.FromContextSafe(sv.ctx) xl := xlog.FromContextSafe(sv.ctx)
defer userConn.Close() defer userConn.Close()
@@ -204,7 +211,7 @@ func (sv *XtcpVisitor) handleConn(userConn net.Conn) {
} }
raddr, err := net.ResolveUDPAddr("udp", raddr, err := net.ResolveUDPAddr("udp",
fmt.Sprintf("%s:%d", sv.ctl.clientCfg.ServerAddr, sv.ctl.serverUDPPort)) net.JoinHostPort(sv.ctl.clientCfg.ServerAddr, strconv.Itoa(sv.ctl.serverUDPPort)))
if err != nil { if err != nil {
xl.Error("resolve server UDP addr error") xl.Error("resolve server UDP addr error")
return return
@@ -231,7 +238,7 @@ func (sv *XtcpVisitor) handleConn(userConn net.Conn) {
// Wait for client address at most 10 seconds. // Wait for client address at most 10 seconds.
var natHoleRespMsg msg.NatHoleResp var natHoleRespMsg msg.NatHoleResp
visitorConn.SetReadDeadline(time.Now().Add(10 * time.Second)) _ = visitorConn.SetReadDeadline(time.Now().Add(10 * time.Second))
buf := pool.GetBuf(1024) buf := pool.GetBuf(1024)
n, err := visitorConn.Read(buf) n, err := visitorConn.Read(buf)
if err != nil { if err != nil {
@@ -244,7 +251,7 @@ func (sv *XtcpVisitor) handleConn(userConn net.Conn) {
xl.Warn("get natHoleRespMsg error: %v", err) xl.Warn("get natHoleRespMsg error: %v", err)
return return
} }
visitorConn.SetReadDeadline(time.Time{}) _ = visitorConn.SetReadDeadline(time.Time{})
pool.PutBuf(buf) pool.PutBuf(buf)
if natHoleRespMsg.Error != "" { if natHoleRespMsg.Error != "" {
@@ -271,17 +278,20 @@ func (sv *XtcpVisitor) handleConn(userConn net.Conn) {
} }
defer lConn.Close() defer lConn.Close()
lConn.Write([]byte(natHoleRespMsg.Sid)) if _, err := lConn.Write([]byte(natHoleRespMsg.Sid)); err != nil {
xl.Error("write sid error: %v", err)
return
}
// read ack sid from client // read ack sid from client
sidBuf := pool.GetBuf(1024) sidBuf := pool.GetBuf(1024)
lConn.SetReadDeadline(time.Now().Add(8 * time.Second)) _ = lConn.SetReadDeadline(time.Now().Add(8 * time.Second))
n, err = lConn.Read(sidBuf) n, err = lConn.Read(sidBuf)
if err != nil { if err != nil {
xl.Warn("get sid from client error: %v", err) xl.Warn("get sid from client error: %v", err)
return return
} }
lConn.SetReadDeadline(time.Time{}) _ = lConn.SetReadDeadline(time.Time{})
if string(sidBuf[:n]) != natHoleRespMsg.Sid { if string(sidBuf[:n]) != natHoleRespMsg.Sid {
xl.Warn("incorrect sid from client") xl.Warn("incorrect sid from client")
return return
@@ -292,7 +302,7 @@ func (sv *XtcpVisitor) handleConn(userConn net.Conn) {
// wrap kcp connection // wrap kcp connection
var remote io.ReadWriteCloser var remote io.ReadWriteCloser
remote, err = frpNet.NewKcpConnFromUdp(lConn, true, natHoleRespMsg.ClientAddr) remote, err = frpNet.NewKCPConnFromUDP(lConn, true, natHoleRespMsg.ClientAddr)
if err != nil { if err != nil {
xl.Error("create kcp connection from udp connection error: %v", err) xl.Error("create kcp connection from udp connection error: %v", err)
return return
@@ -300,7 +310,7 @@ func (sv *XtcpVisitor) handleConn(userConn net.Conn) {
fmuxCfg := fmux.DefaultConfig() fmuxCfg := fmux.DefaultConfig()
fmuxCfg.KeepAliveInterval = 5 * time.Second fmuxCfg.KeepAliveInterval = 5 * time.Second
fmuxCfg.LogOutput = ioutil.Discard fmuxCfg.LogOutput = io.Discard
sess, err := fmux.Client(remote, fmuxCfg) sess, err := fmux.Client(remote, fmuxCfg)
if err != nil { if err != nil {
xl.Error("create yamux session error: %v", err) xl.Error("create yamux session error: %v", err)
@@ -328,3 +338,231 @@ func (sv *XtcpVisitor) handleConn(userConn net.Conn) {
frpIo.Join(userConn, muxConnRWCloser) frpIo.Join(userConn, muxConnRWCloser)
xl.Debug("join connections closed") xl.Debug("join connections closed")
} }
type SUDPVisitor struct {
*BaseVisitor
checkCloseCh chan struct{}
// udpConn is the listener of udp packet
udpConn *net.UDPConn
readCh chan *msg.UDPPacket
sendCh chan *msg.UDPPacket
cfg *config.SUDPVisitorConf
}
// SUDP Run start listen a udp port
func (sv *SUDPVisitor) Run() (err error) {
xl := xlog.FromContextSafe(sv.ctx)
addr, err := net.ResolveUDPAddr("udp", net.JoinHostPort(sv.cfg.BindAddr, strconv.Itoa(sv.cfg.BindPort)))
if err != nil {
return fmt.Errorf("sudp ResolveUDPAddr error: %v", err)
}
sv.udpConn, err = net.ListenUDP("udp", addr)
if err != nil {
return fmt.Errorf("listen udp port %s error: %v", addr.String(), err)
}
sv.sendCh = make(chan *msg.UDPPacket, 1024)
sv.readCh = make(chan *msg.UDPPacket, 1024)
xl.Info("sudp start to work, listen on %s", addr)
go sv.dispatcher()
go udp.ForwardUserConn(sv.udpConn, sv.readCh, sv.sendCh, int(sv.ctl.clientCfg.UDPPacketSize))
return
}
func (sv *SUDPVisitor) dispatcher() {
xl := xlog.FromContextSafe(sv.ctx)
var (
visitorConn net.Conn
err error
firstPacket *msg.UDPPacket
)
for {
select {
case firstPacket = <-sv.sendCh:
if firstPacket == nil {
xl.Info("frpc sudp visitor proxy is closed")
return
}
case <-sv.checkCloseCh:
xl.Info("frpc sudp visitor proxy is closed")
return
}
visitorConn, err = sv.getNewVisitorConn()
if err != nil {
xl.Warn("newVisitorConn to frps error: %v, try to reconnect", err)
continue
}
// visitorConn always be closed when worker done.
sv.worker(visitorConn, firstPacket)
select {
case <-sv.checkCloseCh:
return
default:
}
}
}
func (sv *SUDPVisitor) worker(workConn net.Conn, firstPacket *msg.UDPPacket) {
xl := xlog.FromContextSafe(sv.ctx)
xl.Debug("starting sudp proxy worker")
wg := &sync.WaitGroup{}
wg.Add(2)
closeCh := make(chan struct{})
// udp service -> frpc -> frps -> frpc visitor -> user
workConnReaderFn := func(conn net.Conn) {
defer func() {
conn.Close()
close(closeCh)
wg.Done()
}()
for {
var (
rawMsg msg.Message
errRet error
)
// frpc will send heartbeat in workConn to frpc visitor for keeping alive
_ = conn.SetReadDeadline(time.Now().Add(60 * time.Second))
if rawMsg, errRet = msg.ReadMsg(conn); errRet != nil {
xl.Warn("read from workconn for user udp conn error: %v", errRet)
return
}
_ = conn.SetReadDeadline(time.Time{})
switch m := rawMsg.(type) {
case *msg.Ping:
xl.Debug("frpc visitor get ping message from frpc")
continue
case *msg.UDPPacket:
if errRet := errors.PanicToError(func() {
sv.readCh <- m
xl.Trace("frpc visitor get udp packet from workConn: %s", m.Content)
}); errRet != nil {
xl.Info("reader goroutine for udp work connection closed")
return
}
}
}
}
// udp service <- frpc <- frps <- frpc visitor <- user
workConnSenderFn := func(conn net.Conn) {
defer func() {
conn.Close()
wg.Done()
}()
var errRet error
if firstPacket != nil {
if errRet = msg.WriteMsg(conn, firstPacket); errRet != nil {
xl.Warn("sender goroutine for udp work connection closed: %v", errRet)
return
}
xl.Trace("send udp package to workConn: %s", firstPacket.Content)
}
for {
select {
case udpMsg, ok := <-sv.sendCh:
if !ok {
xl.Info("sender goroutine for udp work connection closed")
return
}
if errRet = msg.WriteMsg(conn, udpMsg); errRet != nil {
xl.Warn("sender goroutine for udp work connection closed: %v", errRet)
return
}
xl.Trace("send udp package to workConn: %s", udpMsg.Content)
case <-closeCh:
return
}
}
}
go workConnReaderFn(workConn)
go workConnSenderFn(workConn)
wg.Wait()
xl.Info("sudp worker is closed")
}
func (sv *SUDPVisitor) getNewVisitorConn() (net.Conn, error) {
xl := xlog.FromContextSafe(sv.ctx)
visitorConn, err := sv.ctl.connectServer()
if err != nil {
return nil, fmt.Errorf("frpc connect frps error: %v", err)
}
now := time.Now().Unix()
newVisitorConnMsg := &msg.NewVisitorConn{
ProxyName: sv.cfg.ServerName,
SignKey: util.GetAuthKey(sv.cfg.Sk, now),
Timestamp: now,
UseEncryption: sv.cfg.UseEncryption,
UseCompression: sv.cfg.UseCompression,
}
err = msg.WriteMsg(visitorConn, newVisitorConnMsg)
if err != nil {
return nil, fmt.Errorf("frpc send newVisitorConnMsg to frps error: %v", err)
}
var newVisitorConnRespMsg msg.NewVisitorConnResp
_ = visitorConn.SetReadDeadline(time.Now().Add(10 * time.Second))
err = msg.ReadMsgInto(visitorConn, &newVisitorConnRespMsg)
if err != nil {
return nil, fmt.Errorf("frpc read newVisitorConnRespMsg error: %v", err)
}
_ = visitorConn.SetReadDeadline(time.Time{})
if newVisitorConnRespMsg.Error != "" {
return nil, fmt.Errorf("start new visitor connection error: %s", newVisitorConnRespMsg.Error)
}
var remote io.ReadWriteCloser
remote = visitorConn
if sv.cfg.UseEncryption {
remote, err = frpIo.WithEncryption(remote, []byte(sv.cfg.Sk))
if err != nil {
xl.Error("create encryption stream error: %v", err)
return nil, err
}
}
if sv.cfg.UseCompression {
remote = frpIo.WithCompression(remote)
}
return frpNet.WrapReadWriteCloserToConn(remote, visitorConn), nil
}
func (sv *SUDPVisitor) Close() {
sv.mu.Lock()
defer sv.mu.Unlock()
select {
case <-sv.checkCloseCh:
return
default:
close(sv.checkCloseCh)
}
if sv.udpConn != nil {
sv.udpConn.Close()
}
close(sv.readCh)
close(sv.sendCh)
}

View File

@@ -19,8 +19,8 @@ import (
"sync" "sync"
"time" "time"
"github.com/fatedier/frp/models/config" "github.com/fatedier/frp/pkg/config"
"github.com/fatedier/frp/utils/xlog" "github.com/fatedier/frp/pkg/util/xlog"
) )
type VisitorManager struct { type VisitorManager struct {
@@ -33,6 +33,8 @@ type VisitorManager struct {
mu sync.Mutex mu sync.Mutex
ctx context.Context ctx context.Context
stopCh chan struct{}
} }
func NewVisitorManager(ctx context.Context, ctl *Control) *VisitorManager { func NewVisitorManager(ctx context.Context, ctl *Control) *VisitorManager {
@@ -42,22 +44,32 @@ func NewVisitorManager(ctx context.Context, ctl *Control) *VisitorManager {
visitors: make(map[string]Visitor), visitors: make(map[string]Visitor),
checkInterval: 10 * time.Second, checkInterval: 10 * time.Second,
ctx: ctx, ctx: ctx,
stopCh: make(chan struct{}),
} }
} }
func (vm *VisitorManager) Run() { func (vm *VisitorManager) Run() {
xl := xlog.FromContextSafe(vm.ctx) xl := xlog.FromContextSafe(vm.ctx)
ticker := time.NewTicker(vm.checkInterval)
defer ticker.Stop()
for { for {
time.Sleep(vm.checkInterval) select {
vm.mu.Lock() case <-vm.stopCh:
for _, cfg := range vm.cfgs { xl.Info("gracefully shutdown visitor manager")
name := cfg.GetBaseInfo().ProxyName return
if _, exist := vm.visitors[name]; !exist { case <-ticker.C:
xl.Info("try to start visitor [%s]", name) vm.mu.Lock()
vm.startVisitor(cfg) for _, cfg := range vm.cfgs {
name := cfg.GetBaseInfo().ProxyName
if _, exist := vm.visitors[name]; !exist {
xl.Info("try to start visitor [%s]", name)
_ = vm.startVisitor(cfg)
}
} }
vm.mu.Unlock()
} }
vm.mu.Unlock()
} }
} }
@@ -87,10 +99,8 @@ func (vm *VisitorManager) Reload(cfgs map[string]config.VisitorConf) {
cfg, ok := cfgs[name] cfg, ok := cfgs[name]
if !ok { if !ok {
del = true del = true
} else { } else if !oldCfg.Compare(cfg) {
if !oldCfg.Compare(cfg) { del = true
del = true
}
} }
if del { if del {
@@ -111,13 +121,12 @@ func (vm *VisitorManager) Reload(cfgs map[string]config.VisitorConf) {
if _, ok := vm.cfgs[name]; !ok { if _, ok := vm.cfgs[name]; !ok {
vm.cfgs[name] = cfg vm.cfgs[name] = cfg
addNames = append(addNames, name) addNames = append(addNames, name)
vm.startVisitor(cfg) _ = vm.startVisitor(cfg)
} }
} }
if len(addNames) > 0 { if len(addNames) > 0 {
xl.Info("visitor added: %v", addNames) xl.Info("visitor added: %v", addNames)
} }
return
} }
func (vm *VisitorManager) Close() { func (vm *VisitorManager) Close() {
@@ -126,4 +135,9 @@ func (vm *VisitorManager) Close() {
for _, v := range vm.visitors { for _, v := range vm.visitors {
v.Close() v.Close()
} }
select {
case <-vm.stopCh:
default:
close(vm.stopCh)
}
} }

View File

@@ -15,18 +15,10 @@
package main package main
import ( import (
"math/rand" _ "github.com/fatedier/frp/assets/frpc"
"time"
_ "github.com/fatedier/frp/assets/frpc/statik"
"github.com/fatedier/frp/cmd/frpc/sub" "github.com/fatedier/frp/cmd/frpc/sub"
"github.com/fatedier/golib/crypto"
) )
func main() { func main() {
crypto.DefaultSalt = "frp"
rand.Seed(time.Now().UnixNano())
sub.Execute() sub.Execute()
} }

View File

@@ -21,22 +21,15 @@ import (
"github.com/spf13/cobra" "github.com/spf13/cobra"
"github.com/fatedier/frp/models/config" "github.com/fatedier/frp/pkg/config"
"github.com/fatedier/frp/models/consts" "github.com/fatedier/frp/pkg/consts"
) )
func init() { func init() {
httpCmd.PersistentFlags().StringVarP(&serverAddr, "server_addr", "s", "127.0.0.1:7000", "frp server's address") RegisterCommonFlags(httpCmd)
httpCmd.PersistentFlags().StringVarP(&user, "user", "u", "", "user")
httpCmd.PersistentFlags().StringVarP(&protocol, "protocol", "p", "tcp", "tcp or kcp or websocket")
httpCmd.PersistentFlags().StringVarP(&token, "token", "t", "", "auth token")
httpCmd.PersistentFlags().StringVarP(&logLevel, "log_level", "", "info", "log level")
httpCmd.PersistentFlags().StringVarP(&logFile, "log_file", "", "console", "console or file path")
httpCmd.PersistentFlags().IntVarP(&logMaxDays, "log_max_days", "", 3, "log file reversed days")
httpCmd.PersistentFlags().BoolVarP(&disableLogColor, "disable_log_color", "", false, "disable log color in console")
httpCmd.PersistentFlags().StringVarP(&proxyName, "proxy_name", "n", "", "proxy name") httpCmd.PersistentFlags().StringVarP(&proxyName, "proxy_name", "n", "", "proxy name")
httpCmd.PersistentFlags().StringVarP(&localIp, "local_ip", "i", "127.0.0.1", "local ip") httpCmd.PersistentFlags().StringVarP(&localIP, "local_ip", "i", "127.0.0.1", "local ip")
httpCmd.PersistentFlags().IntVarP(&localPort, "local_port", "l", 0, "local port") httpCmd.PersistentFlags().IntVarP(&localPort, "local_port", "l", 0, "local port")
httpCmd.PersistentFlags().StringVarP(&customDomains, "custom_domain", "d", "", "custom domain") httpCmd.PersistentFlags().StringVarP(&customDomains, "custom_domain", "d", "", "custom domain")
httpCmd.PersistentFlags().StringVarP(&subDomain, "sd", "", "", "sub domain") httpCmd.PersistentFlags().StringVarP(&subDomain, "sd", "", "", "sub domain")
@@ -54,26 +47,26 @@ var httpCmd = &cobra.Command{
Use: "http", Use: "http",
Short: "Run frpc with a single http proxy", Short: "Run frpc with a single http proxy",
RunE: func(cmd *cobra.Command, args []string) error { RunE: func(cmd *cobra.Command, args []string) error {
clientCfg, err := parseClientCommonCfg(CfgFileTypeCmd, "") clientCfg, err := parseClientCommonCfgFromCmd()
if err != nil { if err != nil {
fmt.Println(err) fmt.Println(err)
os.Exit(1) os.Exit(1)
} }
cfg := &config.HttpProxyConf{} cfg := &config.HTTPProxyConf{}
var prefix string var prefix string
if user != "" { if user != "" {
prefix = user + "." prefix = user + "."
} }
cfg.ProxyName = prefix + proxyName cfg.ProxyName = prefix + proxyName
cfg.ProxyType = consts.HttpProxy cfg.ProxyType = consts.HTTPProxy
cfg.LocalIp = localIp cfg.LocalIP = localIP
cfg.LocalPort = localPort cfg.LocalPort = localPort
cfg.CustomDomains = strings.Split(customDomains, ",") cfg.CustomDomains = strings.Split(customDomains, ",")
cfg.SubDomain = subDomain cfg.SubDomain = subDomain
cfg.Locations = strings.Split(locations, ",") cfg.Locations = strings.Split(locations, ",")
cfg.HttpUser = httpUser cfg.HTTPUser = httpUser
cfg.HttpPwd = httpPwd cfg.HTTPPwd = httpPwd
cfg.HostHeaderRewrite = hostHeaderRewrite cfg.HostHeaderRewrite = hostHeaderRewrite
cfg.UseEncryption = useEncryption cfg.UseEncryption = useEncryption
cfg.UseCompression = useCompression cfg.UseCompression = useCompression

View File

@@ -21,22 +21,15 @@ import (
"github.com/spf13/cobra" "github.com/spf13/cobra"
"github.com/fatedier/frp/models/config" "github.com/fatedier/frp/pkg/config"
"github.com/fatedier/frp/models/consts" "github.com/fatedier/frp/pkg/consts"
) )
func init() { func init() {
httpsCmd.PersistentFlags().StringVarP(&serverAddr, "server_addr", "s", "127.0.0.1:7000", "frp server's address") RegisterCommonFlags(httpsCmd)
httpsCmd.PersistentFlags().StringVarP(&user, "user", "u", "", "user")
httpsCmd.PersistentFlags().StringVarP(&protocol, "protocol", "p", "tcp", "tcp or kcp or websocket")
httpsCmd.PersistentFlags().StringVarP(&token, "token", "t", "", "auth token")
httpsCmd.PersistentFlags().StringVarP(&logLevel, "log_level", "", "info", "log level")
httpsCmd.PersistentFlags().StringVarP(&logFile, "log_file", "", "console", "console or file path")
httpsCmd.PersistentFlags().IntVarP(&logMaxDays, "log_max_days", "", 3, "log file reversed days")
httpsCmd.PersistentFlags().BoolVarP(&disableLogColor, "disable_log_color", "", false, "disable log color in console")
httpsCmd.PersistentFlags().StringVarP(&proxyName, "proxy_name", "n", "", "proxy name") httpsCmd.PersistentFlags().StringVarP(&proxyName, "proxy_name", "n", "", "proxy name")
httpsCmd.PersistentFlags().StringVarP(&localIp, "local_ip", "i", "127.0.0.1", "local ip") httpsCmd.PersistentFlags().StringVarP(&localIP, "local_ip", "i", "127.0.0.1", "local ip")
httpsCmd.PersistentFlags().IntVarP(&localPort, "local_port", "l", 0, "local port") httpsCmd.PersistentFlags().IntVarP(&localPort, "local_port", "l", 0, "local port")
httpsCmd.PersistentFlags().StringVarP(&customDomains, "custom_domain", "d", "", "custom domain") httpsCmd.PersistentFlags().StringVarP(&customDomains, "custom_domain", "d", "", "custom domain")
httpsCmd.PersistentFlags().StringVarP(&subDomain, "sd", "", "", "sub domain") httpsCmd.PersistentFlags().StringVarP(&subDomain, "sd", "", "", "sub domain")
@@ -50,20 +43,20 @@ var httpsCmd = &cobra.Command{
Use: "https", Use: "https",
Short: "Run frpc with a single https proxy", Short: "Run frpc with a single https proxy",
RunE: func(cmd *cobra.Command, args []string) error { RunE: func(cmd *cobra.Command, args []string) error {
clientCfg, err := parseClientCommonCfg(CfgFileTypeCmd, "") clientCfg, err := parseClientCommonCfgFromCmd()
if err != nil { if err != nil {
fmt.Println(err) fmt.Println(err)
os.Exit(1) os.Exit(1)
} }
cfg := &config.HttpsProxyConf{} cfg := &config.HTTPSProxyConf{}
var prefix string var prefix string
if user != "" { if user != "" {
prefix = user + "." prefix = user + "."
} }
cfg.ProxyName = prefix + proxyName cfg.ProxyName = prefix + proxyName
cfg.ProxyType = consts.HttpsProxy cfg.ProxyType = consts.HTTPSProxy
cfg.LocalIp = localIp cfg.LocalIP = localIP
cfg.LocalPort = localPort cfg.LocalPort = localPort
cfg.CustomDomains = strings.Split(customDomains, ",") cfg.CustomDomains = strings.Split(customDomains, ",")
cfg.SubDomain = subDomain cfg.SubDomain = subDomain

View File

@@ -17,14 +17,14 @@ package sub
import ( import (
"encoding/base64" "encoding/base64"
"fmt" "fmt"
"io/ioutil" "io"
"net/http" "net/http"
"os" "os"
"strings" "strings"
"github.com/spf13/cobra" "github.com/spf13/cobra"
"github.com/fatedier/frp/models/config" "github.com/fatedier/frp/pkg/config"
) )
func init() { func init() {
@@ -35,19 +35,13 @@ var reloadCmd = &cobra.Command{
Use: "reload", Use: "reload",
Short: "Hot-Reload frpc configuration", Short: "Hot-Reload frpc configuration",
RunE: func(cmd *cobra.Command, args []string) error { RunE: func(cmd *cobra.Command, args []string) error {
iniContent, err := config.GetRenderedConfFromFile(cfgFile) cfg, _, _, err := config.ParseClientConfig(cfgFile)
if err != nil { if err != nil {
fmt.Println(err) fmt.Println(err)
os.Exit(1) os.Exit(1)
} }
clientCfg, err := parseClientCommonCfg(CfgFileTypeIni, iniContent) err = reload(cfg)
if err != nil {
fmt.Println(err)
os.Exit(1)
}
err = reload(clientCfg)
if err != nil { if err != nil {
fmt.Printf("frpc reload error: %v\n", err) fmt.Printf("frpc reload error: %v\n", err)
os.Exit(1) os.Exit(1)
@@ -82,7 +76,7 @@ func reload(clientCfg config.ClientCommonConf) error {
return nil return nil
} }
body, err := ioutil.ReadAll(resp.Body) body, err := io.ReadAll(resp.Body)
if err != nil { if err != nil {
return err return err
} }

View File

@@ -15,23 +15,24 @@
package sub package sub
import ( import (
"context"
"fmt" "fmt"
"io/fs"
"net" "net"
"os" "os"
"os/signal" "os/signal"
"path/filepath"
"strconv" "strconv"
"strings" "sync"
"syscall" "syscall"
"time" "time"
"github.com/spf13/cobra" "github.com/spf13/cobra"
"github.com/fatedier/frp/client" "github.com/fatedier/frp/client"
"github.com/fatedier/frp/models/auth" "github.com/fatedier/frp/pkg/auth"
"github.com/fatedier/frp/models/config" "github.com/fatedier/frp/pkg/config"
"github.com/fatedier/frp/utils/log" "github.com/fatedier/frp/pkg/util/log"
"github.com/fatedier/frp/utils/version" "github.com/fatedier/frp/pkg/util/version"
) )
const ( const (
@@ -41,6 +42,7 @@ const (
var ( var (
cfgFile string cfgFile string
cfgDir string
showVersion bool showVersion bool
serverAddr string serverAddr string
@@ -53,7 +55,7 @@ var (
disableLogColor bool disableLogColor bool
proxyName string proxyName string
localIp string localIP string
localPort int localPort int
remotePort int remotePort int
useEncryption bool useEncryption bool
@@ -71,14 +73,25 @@ var (
bindAddr string bindAddr string
bindPort int bindPort int
kcpDoneCh chan struct{} tlsEnable bool
) )
func init() { func init() {
rootCmd.PersistentFlags().StringVarP(&cfgFile, "config", "c", "./frpc.ini", "config file of frpc") rootCmd.PersistentFlags().StringVarP(&cfgFile, "config", "c", "./frpc.ini", "config file of frpc")
rootCmd.PersistentFlags().StringVarP(&cfgDir, "config_dir", "", "", "config directory, run one frpc service for each file in config directory")
rootCmd.PersistentFlags().BoolVarP(&showVersion, "version", "v", false, "version of frpc") rootCmd.PersistentFlags().BoolVarP(&showVersion, "version", "v", false, "version of frpc")
}
kcpDoneCh = make(chan struct{}) 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(&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")
} }
var rootCmd = &cobra.Command{ var rootCmd = &cobra.Command{
@@ -90,6 +103,32 @@ var rootCmd = &cobra.Command{
return nil return nil
} }
// If cfgDir is not empty, run multiple frpc service for each config file in cfgDir.
// Note that it's only designed for testing. It's not guaranteed to be stable.
if cfgDir != "" {
var wg sync.WaitGroup
_ = filepath.WalkDir(cfgDir, func(path string, d fs.DirEntry, err error) error {
if err != nil {
return nil
}
if d.IsDir() {
return nil
}
wg.Add(1)
time.Sleep(time.Millisecond)
go func() {
defer wg.Done()
err := runClient(path)
if err != nil {
fmt.Printf("frpc service error for config file [%s]\n", path)
}
}()
return nil
})
wg.Wait()
return nil
}
// Do not show command usage here. // Do not show command usage here.
err := runClient(cfgFile) err := runClient(cfgFile)
if err != nil { if err != nil {
@@ -106,54 +145,27 @@ func Execute() {
} }
} }
func handleSignal(svr *client.Service) { func handleSignal(svr *client.Service, doneCh chan struct{}) {
ch := make(chan os.Signal) ch := make(chan os.Signal, 1)
signal.Notify(ch, syscall.SIGINT, syscall.SIGTERM) signal.Notify(ch, syscall.SIGINT, syscall.SIGTERM)
<-ch <-ch
svr.Close() svr.GracefulClose(500 * time.Millisecond)
time.Sleep(250 * time.Millisecond) close(doneCh)
close(kcpDoneCh)
}
func parseClientCommonCfg(fileType int, content string) (cfg config.ClientCommonConf, err error) {
if fileType == CfgFileTypeIni {
cfg, err = parseClientCommonCfgFromIni(content)
} else if fileType == CfgFileTypeCmd {
cfg, err = parseClientCommonCfgFromCmd()
}
if err != nil {
return
}
err = cfg.Check()
if err != nil {
return
}
return
}
func parseClientCommonCfgFromIni(content string) (config.ClientCommonConf, error) {
cfg, err := config.UnmarshalClientConfFromIni(content)
if err != nil {
return config.ClientCommonConf{}, err
}
return cfg, err
} }
func parseClientCommonCfgFromCmd() (cfg config.ClientCommonConf, err error) { func parseClientCommonCfgFromCmd() (cfg config.ClientCommonConf, err error) {
cfg = config.GetDefaultClientConf() cfg = config.GetDefaultClientConf()
strs := strings.Split(serverAddr, ":") ipStr, portStr, err := net.SplitHostPort(serverAddr)
if len(strs) < 2 { if err != nil {
err = fmt.Errorf("invalid server_addr") err = fmt.Errorf("invalid server_addr: %v", err)
return return
} }
if strs[0] != "" {
cfg.ServerAddr = strs[0] cfg.ServerAddr = ipStr
} cfg.ServerPort, err = strconv.Atoi(portStr)
cfg.ServerPort, err = strconv.Atoi(strs[1])
if err != nil { if err != nil {
err = fmt.Errorf("invalid server_addr") err = fmt.Errorf("invalid server_addr: %v", err)
return return
} }
@@ -162,57 +174,41 @@ func parseClientCommonCfgFromCmd() (cfg config.ClientCommonConf, err error) {
cfg.LogLevel = logLevel cfg.LogLevel = logLevel
cfg.LogFile = logFile cfg.LogFile = logFile
cfg.LogMaxDays = int64(logMaxDays) cfg.LogMaxDays = int64(logMaxDays)
if logFile == "console" {
cfg.LogWay = "console"
} else {
cfg.LogWay = "file"
}
cfg.DisableLogColor = disableLogColor cfg.DisableLogColor = disableLogColor
// Only token authentication is supported in cmd mode // Only token authentication is supported in cmd mode
cfg.AuthClientConfig = auth.GetDefaultAuthClientConf() cfg.ClientConfig = auth.GetDefaultClientConf()
cfg.Token = token cfg.Token = token
cfg.TLSEnable = tlsEnable
cfg.Complete()
if err = cfg.Validate(); err != nil {
err = fmt.Errorf("parse config error: %v", err)
return
}
return return
} }
func runClient(cfgFilePath string) (err error) { func runClient(cfgFilePath string) error {
var content string cfg, pxyCfgs, visitorCfgs, err := config.ParseClientConfig(cfgFilePath)
content, err = config.GetRenderedConfFromFile(cfgFilePath)
if err != nil {
return
}
cfg, err := parseClientCommonCfg(CfgFileTypeIni, content)
if err != nil {
return
}
pxyCfgs, visitorCfgs, err := config.LoadAllConfFromIni(cfg.User, content, cfg.Start)
if err != nil { if err != nil {
return err return err
} }
return startService(cfg, pxyCfgs, visitorCfgs, cfgFilePath)
err = startService(cfg, pxyCfgs, visitorCfgs, cfgFilePath)
return
} }
func startService(cfg config.ClientCommonConf, pxyCfgs map[string]config.ProxyConf, visitorCfgs map[string]config.VisitorConf, cfgFile string) (err error) { func startService(
cfg config.ClientCommonConf,
pxyCfgs map[string]config.ProxyConf,
visitorCfgs map[string]config.VisitorConf,
cfgFile string,
) (err error) {
log.InitLog(cfg.LogWay, cfg.LogFile, cfg.LogLevel, log.InitLog(cfg.LogWay, cfg.LogFile, cfg.LogLevel,
cfg.LogMaxDays, cfg.DisableLogColor) cfg.LogMaxDays, cfg.DisableLogColor)
if cfg.DnsServer != "" { if cfgFile != "" {
s := cfg.DnsServer log.Trace("start frpc service for config file [%s]", cfgFile)
if !strings.Contains(s, ":") { defer log.Trace("frpc service for config file [%s] stopped", cfgFile)
s += ":53"
}
// Change default dns server for frpc
net.DefaultResolver = &net.Resolver{
PreferGo: true,
Dial: func(ctx context.Context, network, address string) (net.Conn, error) {
return net.Dial("udp", s)
},
}
} }
svr, errRet := client.NewService(cfg, pxyCfgs, visitorCfgs, cfgFile) svr, errRet := client.NewService(cfg, pxyCfgs, visitorCfgs, cfgFile)
if errRet != nil { if errRet != nil {
@@ -220,13 +216,14 @@ func startService(cfg config.ClientCommonConf, pxyCfgs map[string]config.ProxyCo
return return
} }
kcpDoneCh := make(chan struct{})
// Capture the exit signal if we use kcp. // Capture the exit signal if we use kcp.
if cfg.Protocol == "kcp" { if cfg.Protocol == "kcp" {
go handleSignal(svr) go handleSignal(svr, kcpDoneCh)
} }
err = svr.Run() err = svr.Run()
if cfg.Protocol == "kcp" { if err == nil && cfg.Protocol == "kcp" {
<-kcpDoneCh <-kcpDoneCh
} }
return return

View File

@@ -18,7 +18,7 @@ import (
"encoding/base64" "encoding/base64"
"encoding/json" "encoding/json"
"fmt" "fmt"
"io/ioutil" "io"
"net/http" "net/http"
"os" "os"
"strings" "strings"
@@ -27,7 +27,7 @@ import (
"github.com/spf13/cobra" "github.com/spf13/cobra"
"github.com/fatedier/frp/client" "github.com/fatedier/frp/client"
"github.com/fatedier/frp/models/config" "github.com/fatedier/frp/pkg/config"
) )
func init() { func init() {
@@ -38,20 +38,13 @@ var statusCmd = &cobra.Command{
Use: "status", Use: "status",
Short: "Overview of all proxies status", Short: "Overview of all proxies status",
RunE: func(cmd *cobra.Command, args []string) error { RunE: func(cmd *cobra.Command, args []string) error {
iniContent, err := config.GetRenderedConfFromFile(cfgFile) cfg, _, _, err := config.ParseClientConfig(cfgFile)
if err != nil { if err != nil {
fmt.Println(err) fmt.Println(err)
os.Exit(1) os.Exit(1)
} }
clientCfg, err := parseClientCommonCfg(CfgFileTypeIni, iniContent) if err = status(cfg); err != nil {
if err != nil {
fmt.Println(err)
os.Exit(1)
}
err = status(clientCfg)
if err != nil {
fmt.Printf("frpc get status error: %v\n", err) fmt.Printf("frpc get status error: %v\n", err)
os.Exit(1) os.Exit(1)
} }
@@ -84,7 +77,7 @@ func status(clientCfg config.ClientCommonConf) error {
return fmt.Errorf("admin api status code [%d]", resp.StatusCode) return fmt.Errorf("admin api status code [%d]", resp.StatusCode)
} }
body, err := ioutil.ReadAll(resp.Body) body, err := io.ReadAll(resp.Body)
if err != nil { if err != nil {
return err return err
} }
@@ -95,55 +88,55 @@ func status(clientCfg config.ClientCommonConf) error {
} }
fmt.Println("Proxy Status...") fmt.Println("Proxy Status...")
if len(res.Tcp) > 0 { if len(res.TCP) > 0 {
fmt.Printf("TCP") fmt.Println("TCP")
tbl := table.New("Name", "Status", "LocalAddr", "Plugin", "RemoteAddr", "Error") tbl := table.New("Name", "Status", "LocalAddr", "Plugin", "RemoteAddr", "Error")
for _, ps := range res.Tcp { for _, ps := range res.TCP {
tbl.AddRow(ps.Name, ps.Status, ps.LocalAddr, ps.Plugin, ps.RemoteAddr, ps.Err) tbl.AddRow(ps.Name, ps.Status, ps.LocalAddr, ps.Plugin, ps.RemoteAddr, ps.Err)
} }
tbl.Print() tbl.Print()
fmt.Println("") fmt.Println("")
} }
if len(res.Udp) > 0 { if len(res.UDP) > 0 {
fmt.Printf("UDP") fmt.Println("UDP")
tbl := table.New("Name", "Status", "LocalAddr", "Plugin", "RemoteAddr", "Error") tbl := table.New("Name", "Status", "LocalAddr", "Plugin", "RemoteAddr", "Error")
for _, ps := range res.Udp { for _, ps := range res.UDP {
tbl.AddRow(ps.Name, ps.Status, ps.LocalAddr, ps.Plugin, ps.RemoteAddr, ps.Err) tbl.AddRow(ps.Name, ps.Status, ps.LocalAddr, ps.Plugin, ps.RemoteAddr, ps.Err)
} }
tbl.Print() tbl.Print()
fmt.Println("") fmt.Println("")
} }
if len(res.Http) > 0 { if len(res.HTTP) > 0 {
fmt.Printf("HTTP") fmt.Println("HTTP")
tbl := table.New("Name", "Status", "LocalAddr", "Plugin", "RemoteAddr", "Error") tbl := table.New("Name", "Status", "LocalAddr", "Plugin", "RemoteAddr", "Error")
for _, ps := range res.Http { for _, ps := range res.HTTP {
tbl.AddRow(ps.Name, ps.Status, ps.LocalAddr, ps.Plugin, ps.RemoteAddr, ps.Err) tbl.AddRow(ps.Name, ps.Status, ps.LocalAddr, ps.Plugin, ps.RemoteAddr, ps.Err)
} }
tbl.Print() tbl.Print()
fmt.Println("") fmt.Println("")
} }
if len(res.Https) > 0 { if len(res.HTTPS) > 0 {
fmt.Printf("HTTPS") fmt.Println("HTTPS")
tbl := table.New("Name", "Status", "LocalAddr", "Plugin", "RemoteAddr", "Error") tbl := table.New("Name", "Status", "LocalAddr", "Plugin", "RemoteAddr", "Error")
for _, ps := range res.Https { for _, ps := range res.HTTPS {
tbl.AddRow(ps.Name, ps.Status, ps.LocalAddr, ps.Plugin, ps.RemoteAddr, ps.Err) tbl.AddRow(ps.Name, ps.Status, ps.LocalAddr, ps.Plugin, ps.RemoteAddr, ps.Err)
} }
tbl.Print() tbl.Print()
fmt.Println("") fmt.Println("")
} }
if len(res.Stcp) > 0 { if len(res.STCP) > 0 {
fmt.Printf("STCP") fmt.Println("STCP")
tbl := table.New("Name", "Status", "LocalAddr", "Plugin", "RemoteAddr", "Error") tbl := table.New("Name", "Status", "LocalAddr", "Plugin", "RemoteAddr", "Error")
for _, ps := range res.Stcp { for _, ps := range res.STCP {
tbl.AddRow(ps.Name, ps.Status, ps.LocalAddr, ps.Plugin, ps.RemoteAddr, ps.Err) tbl.AddRow(ps.Name, ps.Status, ps.LocalAddr, ps.Plugin, ps.RemoteAddr, ps.Err)
} }
tbl.Print() tbl.Print()
fmt.Println("") fmt.Println("")
} }
if len(res.Xtcp) > 0 { if len(res.XTCP) > 0 {
fmt.Printf("XTCP") fmt.Println("XTCP")
tbl := table.New("Name", "Status", "LocalAddr", "Plugin", "RemoteAddr", "Error") tbl := table.New("Name", "Status", "LocalAddr", "Plugin", "RemoteAddr", "Error")
for _, ps := range res.Xtcp { for _, ps := range res.XTCP {
tbl.AddRow(ps.Name, ps.Status, ps.LocalAddr, ps.Plugin, ps.RemoteAddr, ps.Err) tbl.AddRow(ps.Name, ps.Status, ps.LocalAddr, ps.Plugin, ps.RemoteAddr, ps.Err)
} }
tbl.Print() tbl.Print()

View File

@@ -20,25 +20,18 @@ import (
"github.com/spf13/cobra" "github.com/spf13/cobra"
"github.com/fatedier/frp/models/config" "github.com/fatedier/frp/pkg/config"
"github.com/fatedier/frp/models/consts" "github.com/fatedier/frp/pkg/consts"
) )
func init() { func init() {
stcpCmd.PersistentFlags().StringVarP(&serverAddr, "server_addr", "s", "127.0.0.1:7000", "frp server's address") RegisterCommonFlags(stcpCmd)
stcpCmd.PersistentFlags().StringVarP(&user, "user", "u", "", "user")
stcpCmd.PersistentFlags().StringVarP(&protocol, "protocol", "p", "tcp", "tcp or kcp or websocket")
stcpCmd.PersistentFlags().StringVarP(&token, "token", "t", "", "auth token")
stcpCmd.PersistentFlags().StringVarP(&logLevel, "log_level", "", "info", "log level")
stcpCmd.PersistentFlags().StringVarP(&logFile, "log_file", "", "console", "console or file path")
stcpCmd.PersistentFlags().IntVarP(&logMaxDays, "log_max_days", "", 3, "log file reversed days")
stcpCmd.PersistentFlags().BoolVarP(&disableLogColor, "disable_log_color", "", false, "disable log color in console")
stcpCmd.PersistentFlags().StringVarP(&proxyName, "proxy_name", "n", "", "proxy name") stcpCmd.PersistentFlags().StringVarP(&proxyName, "proxy_name", "n", "", "proxy name")
stcpCmd.PersistentFlags().StringVarP(&role, "role", "", "server", "role") stcpCmd.PersistentFlags().StringVarP(&role, "role", "", "server", "role")
stcpCmd.PersistentFlags().StringVarP(&sk, "sk", "", "", "secret key") stcpCmd.PersistentFlags().StringVarP(&sk, "sk", "", "", "secret key")
stcpCmd.PersistentFlags().StringVarP(&serverName, "server_name", "", "", "server name") stcpCmd.PersistentFlags().StringVarP(&serverName, "server_name", "", "", "server name")
stcpCmd.PersistentFlags().StringVarP(&localIp, "local_ip", "i", "127.0.0.1", "local ip") stcpCmd.PersistentFlags().StringVarP(&localIP, "local_ip", "i", "127.0.0.1", "local ip")
stcpCmd.PersistentFlags().IntVarP(&localPort, "local_port", "l", 0, "local port") stcpCmd.PersistentFlags().IntVarP(&localPort, "local_port", "l", 0, "local port")
stcpCmd.PersistentFlags().StringVarP(&bindAddr, "bind_addr", "", "", "bind addr") stcpCmd.PersistentFlags().StringVarP(&bindAddr, "bind_addr", "", "", "bind addr")
stcpCmd.PersistentFlags().IntVarP(&bindPort, "bind_port", "", 0, "bind port") stcpCmd.PersistentFlags().IntVarP(&bindPort, "bind_port", "", 0, "bind port")
@@ -52,7 +45,7 @@ var stcpCmd = &cobra.Command{
Use: "stcp", Use: "stcp",
Short: "Run frpc with a single stcp proxy", Short: "Run frpc with a single stcp proxy",
RunE: func(cmd *cobra.Command, args []string) error { RunE: func(cmd *cobra.Command, args []string) error {
clientCfg, err := parseClientCommonCfg(CfgFileTypeCmd, "") clientCfg, err := parseClientCommonCfgFromCmd()
if err != nil { if err != nil {
fmt.Println(err) fmt.Println(err)
os.Exit(1) os.Exit(1)
@@ -66,15 +59,16 @@ var stcpCmd = &cobra.Command{
prefix = user + "." prefix = user + "."
} }
if role == "server" { switch role {
cfg := &config.StcpProxyConf{} case "server":
cfg := &config.STCPProxyConf{}
cfg.ProxyName = prefix + proxyName cfg.ProxyName = prefix + proxyName
cfg.ProxyType = consts.StcpProxy cfg.ProxyType = consts.STCPProxy
cfg.UseEncryption = useEncryption cfg.UseEncryption = useEncryption
cfg.UseCompression = useCompression cfg.UseCompression = useCompression
cfg.Role = role cfg.Role = role
cfg.Sk = sk cfg.Sk = sk
cfg.LocalIp = localIp cfg.LocalIP = localIP
cfg.LocalPort = localPort cfg.LocalPort = localPort
err = cfg.CheckForCli() err = cfg.CheckForCli()
if err != nil { if err != nil {
@@ -82,10 +76,10 @@ var stcpCmd = &cobra.Command{
os.Exit(1) os.Exit(1)
} }
proxyConfs[cfg.ProxyName] = cfg proxyConfs[cfg.ProxyName] = cfg
} else if role == "visitor" { case "visitor":
cfg := &config.StcpVisitorConf{} cfg := &config.STCPVisitorConf{}
cfg.ProxyName = prefix + proxyName cfg.ProxyName = prefix + proxyName
cfg.ProxyType = consts.StcpProxy cfg.ProxyType = consts.STCPProxy
cfg.UseEncryption = useEncryption cfg.UseEncryption = useEncryption
cfg.UseCompression = useCompression cfg.UseCompression = useCompression
cfg.Role = role cfg.Role = role
@@ -99,7 +93,7 @@ var stcpCmd = &cobra.Command{
os.Exit(1) os.Exit(1)
} }
visitorConfs[cfg.ProxyName] = cfg visitorConfs[cfg.ProxyName] = cfg
} else { default:
fmt.Println("invalid role") fmt.Println("invalid role")
os.Exit(1) os.Exit(1)
} }

107
cmd/frpc/sub/sudp.go Normal file
View File

@@ -0,0 +1,107 @@
// Copyright 2018 fatedier, fatedier@gmail.com
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package sub
import (
"fmt"
"os"
"github.com/spf13/cobra"
"github.com/fatedier/frp/pkg/config"
"github.com/fatedier/frp/pkg/consts"
)
func init() {
RegisterCommonFlags(sudpCmd)
sudpCmd.PersistentFlags().StringVarP(&proxyName, "proxy_name", "n", "", "proxy name")
sudpCmd.PersistentFlags().StringVarP(&role, "role", "", "server", "role")
sudpCmd.PersistentFlags().StringVarP(&sk, "sk", "", "", "secret key")
sudpCmd.PersistentFlags().StringVarP(&serverName, "server_name", "", "", "server name")
sudpCmd.PersistentFlags().StringVarP(&localIP, "local_ip", "i", "127.0.0.1", "local ip")
sudpCmd.PersistentFlags().IntVarP(&localPort, "local_port", "l", 0, "local port")
sudpCmd.PersistentFlags().StringVarP(&bindAddr, "bind_addr", "", "", "bind addr")
sudpCmd.PersistentFlags().IntVarP(&bindPort, "bind_port", "", 0, "bind port")
sudpCmd.PersistentFlags().BoolVarP(&useEncryption, "ue", "", false, "use encryption")
sudpCmd.PersistentFlags().BoolVarP(&useCompression, "uc", "", false, "use compression")
rootCmd.AddCommand(sudpCmd)
}
var sudpCmd = &cobra.Command{
Use: "sudp",
Short: "Run frpc with a single sudp proxy",
RunE: func(cmd *cobra.Command, args []string) error {
clientCfg, err := parseClientCommonCfgFromCmd()
if err != nil {
fmt.Println(err)
os.Exit(1)
}
proxyConfs := make(map[string]config.ProxyConf)
visitorConfs := make(map[string]config.VisitorConf)
var prefix string
if user != "" {
prefix = user + "."
}
switch role {
case "server":
cfg := &config.SUDPProxyConf{}
cfg.ProxyName = prefix + proxyName
cfg.ProxyType = consts.SUDPProxy
cfg.UseEncryption = useEncryption
cfg.UseCompression = useCompression
cfg.Role = role
cfg.Sk = sk
cfg.LocalIP = localIP
cfg.LocalPort = localPort
err = cfg.CheckForCli()
if err != nil {
fmt.Println(err)
os.Exit(1)
}
proxyConfs[cfg.ProxyName] = cfg
case "visitor":
cfg := &config.SUDPVisitorConf{}
cfg.ProxyName = prefix + proxyName
cfg.ProxyType = consts.SUDPProxy
cfg.UseEncryption = useEncryption
cfg.UseCompression = useCompression
cfg.Role = role
cfg.Sk = sk
cfg.ServerName = serverName
cfg.BindAddr = bindAddr
cfg.BindPort = bindPort
err = cfg.Check()
if err != nil {
fmt.Println(err)
os.Exit(1)
}
visitorConfs[cfg.ProxyName] = cfg
default:
fmt.Println("invalid role")
os.Exit(1)
}
err = startService(clientCfg, proxyConfs, visitorConfs, "")
if err != nil {
os.Exit(1)
}
return nil
},
}

View File

@@ -20,22 +20,15 @@ import (
"github.com/spf13/cobra" "github.com/spf13/cobra"
"github.com/fatedier/frp/models/config" "github.com/fatedier/frp/pkg/config"
"github.com/fatedier/frp/models/consts" "github.com/fatedier/frp/pkg/consts"
) )
func init() { func init() {
tcpCmd.PersistentFlags().StringVarP(&serverAddr, "server_addr", "s", "127.0.0.1:7000", "frp server's address") RegisterCommonFlags(tcpCmd)
tcpCmd.PersistentFlags().StringVarP(&user, "user", "u", "", "user")
tcpCmd.PersistentFlags().StringVarP(&protocol, "protocol", "p", "tcp", "tcp or kcp")
tcpCmd.PersistentFlags().StringVarP(&token, "token", "t", "", "auth token")
tcpCmd.PersistentFlags().StringVarP(&logLevel, "log_level", "", "info", "log level")
tcpCmd.PersistentFlags().StringVarP(&logFile, "log_file", "", "console", "console or file path")
tcpCmd.PersistentFlags().IntVarP(&logMaxDays, "log_max_days", "", 3, "log file reversed days")
tcpCmd.PersistentFlags().BoolVarP(&disableLogColor, "disable_log_color", "", false, "disable log color in console")
tcpCmd.PersistentFlags().StringVarP(&proxyName, "proxy_name", "n", "", "proxy name") tcpCmd.PersistentFlags().StringVarP(&proxyName, "proxy_name", "n", "", "proxy name")
tcpCmd.PersistentFlags().StringVarP(&localIp, "local_ip", "i", "127.0.0.1", "local ip") tcpCmd.PersistentFlags().StringVarP(&localIP, "local_ip", "i", "127.0.0.1", "local ip")
tcpCmd.PersistentFlags().IntVarP(&localPort, "local_port", "l", 0, "local port") tcpCmd.PersistentFlags().IntVarP(&localPort, "local_port", "l", 0, "local port")
tcpCmd.PersistentFlags().IntVarP(&remotePort, "remote_port", "r", 0, "remote port") tcpCmd.PersistentFlags().IntVarP(&remotePort, "remote_port", "r", 0, "remote port")
tcpCmd.PersistentFlags().BoolVarP(&useEncryption, "ue", "", false, "use encryption") tcpCmd.PersistentFlags().BoolVarP(&useEncryption, "ue", "", false, "use encryption")
@@ -48,20 +41,20 @@ var tcpCmd = &cobra.Command{
Use: "tcp", Use: "tcp",
Short: "Run frpc with a single tcp proxy", Short: "Run frpc with a single tcp proxy",
RunE: func(cmd *cobra.Command, args []string) error { RunE: func(cmd *cobra.Command, args []string) error {
clientCfg, err := parseClientCommonCfg(CfgFileTypeCmd, "") clientCfg, err := parseClientCommonCfgFromCmd()
if err != nil { if err != nil {
fmt.Println(err) fmt.Println(err)
os.Exit(1) os.Exit(1)
} }
cfg := &config.TcpProxyConf{} cfg := &config.TCPProxyConf{}
var prefix string var prefix string
if user != "" { if user != "" {
prefix = user + "." prefix = user + "."
} }
cfg.ProxyName = prefix + proxyName cfg.ProxyName = prefix + proxyName
cfg.ProxyType = consts.TcpProxy cfg.ProxyType = consts.TCPProxy
cfg.LocalIp = localIp cfg.LocalIP = localIP
cfg.LocalPort = localPort cfg.LocalPort = localPort
cfg.RemotePort = remotePort cfg.RemotePort = remotePort
cfg.UseEncryption = useEncryption cfg.UseEncryption = useEncryption

View File

@@ -21,22 +21,15 @@ import (
"github.com/spf13/cobra" "github.com/spf13/cobra"
"github.com/fatedier/frp/models/config" "github.com/fatedier/frp/pkg/config"
"github.com/fatedier/frp/models/consts" "github.com/fatedier/frp/pkg/consts"
) )
func init() { func init() {
tcpMuxCmd.PersistentFlags().StringVarP(&serverAddr, "server_addr", "s", "127.0.0.1:7000", "frp server's address") RegisterCommonFlags(tcpMuxCmd)
tcpMuxCmd.PersistentFlags().StringVarP(&user, "user", "u", "", "user")
tcpMuxCmd.PersistentFlags().StringVarP(&protocol, "protocol", "p", "tcp", "tcp or kcp or websocket")
tcpMuxCmd.PersistentFlags().StringVarP(&token, "token", "t", "", "auth token")
tcpMuxCmd.PersistentFlags().StringVarP(&logLevel, "log_level", "", "info", "log level")
tcpMuxCmd.PersistentFlags().StringVarP(&logFile, "log_file", "", "console", "console or file path")
tcpMuxCmd.PersistentFlags().IntVarP(&logMaxDays, "log_max_days", "", 3, "log file reversed days")
tcpMuxCmd.PersistentFlags().BoolVarP(&disableLogColor, "disable_log_color", "", false, "disable log color in console")
tcpMuxCmd.PersistentFlags().StringVarP(&proxyName, "proxy_name", "n", "", "proxy name") tcpMuxCmd.PersistentFlags().StringVarP(&proxyName, "proxy_name", "n", "", "proxy name")
tcpMuxCmd.PersistentFlags().StringVarP(&localIp, "local_ip", "i", "127.0.0.1", "local ip") tcpMuxCmd.PersistentFlags().StringVarP(&localIP, "local_ip", "i", "127.0.0.1", "local ip")
tcpMuxCmd.PersistentFlags().IntVarP(&localPort, "local_port", "l", 0, "local port") tcpMuxCmd.PersistentFlags().IntVarP(&localPort, "local_port", "l", 0, "local port")
tcpMuxCmd.PersistentFlags().StringVarP(&customDomains, "custom_domain", "d", "", "custom domain") tcpMuxCmd.PersistentFlags().StringVarP(&customDomains, "custom_domain", "d", "", "custom domain")
tcpMuxCmd.PersistentFlags().StringVarP(&subDomain, "sd", "", "", "sub domain") tcpMuxCmd.PersistentFlags().StringVarP(&subDomain, "sd", "", "", "sub domain")
@@ -51,20 +44,20 @@ var tcpMuxCmd = &cobra.Command{
Use: "tcpmux", Use: "tcpmux",
Short: "Run frpc with a single tcpmux proxy", Short: "Run frpc with a single tcpmux proxy",
RunE: func(cmd *cobra.Command, args []string) error { RunE: func(cmd *cobra.Command, args []string) error {
clientCfg, err := parseClientCommonCfg(CfgFileTypeCmd, "") clientCfg, err := parseClientCommonCfgFromCmd()
if err != nil { if err != nil {
fmt.Println(err) fmt.Println(err)
os.Exit(1) os.Exit(1)
} }
cfg := &config.TcpMuxProxyConf{} cfg := &config.TCPMuxProxyConf{}
var prefix string var prefix string
if user != "" { if user != "" {
prefix = user + "." prefix = user + "."
} }
cfg.ProxyName = prefix + proxyName cfg.ProxyName = prefix + proxyName
cfg.ProxyType = consts.TcpMuxProxy cfg.ProxyType = consts.TCPMuxProxy
cfg.LocalIp = localIp cfg.LocalIP = localIP
cfg.LocalPort = localPort cfg.LocalPort = localPort
cfg.CustomDomains = strings.Split(customDomains, ",") cfg.CustomDomains = strings.Split(customDomains, ",")
cfg.SubDomain = subDomain cfg.SubDomain = subDomain

View File

@@ -20,22 +20,15 @@ import (
"github.com/spf13/cobra" "github.com/spf13/cobra"
"github.com/fatedier/frp/models/config" "github.com/fatedier/frp/pkg/config"
"github.com/fatedier/frp/models/consts" "github.com/fatedier/frp/pkg/consts"
) )
func init() { func init() {
udpCmd.PersistentFlags().StringVarP(&serverAddr, "server_addr", "s", "127.0.0.1:7000", "frp server's address") RegisterCommonFlags(udpCmd)
udpCmd.PersistentFlags().StringVarP(&user, "user", "u", "", "user")
udpCmd.PersistentFlags().StringVarP(&protocol, "protocol", "p", "tcp", "tcp or kcp or websocket")
udpCmd.PersistentFlags().StringVarP(&token, "token", "t", "", "auth token")
udpCmd.PersistentFlags().StringVarP(&logLevel, "log_level", "", "info", "log level")
udpCmd.PersistentFlags().StringVarP(&logFile, "log_file", "", "console", "console or file path")
udpCmd.PersistentFlags().IntVarP(&logMaxDays, "log_max_days", "", 3, "log file reversed days")
udpCmd.PersistentFlags().BoolVarP(&disableLogColor, "disable_log_color", "", false, "disable log color in console")
udpCmd.PersistentFlags().StringVarP(&proxyName, "proxy_name", "n", "", "proxy name") udpCmd.PersistentFlags().StringVarP(&proxyName, "proxy_name", "n", "", "proxy name")
udpCmd.PersistentFlags().StringVarP(&localIp, "local_ip", "i", "127.0.0.1", "local ip") udpCmd.PersistentFlags().StringVarP(&localIP, "local_ip", "i", "127.0.0.1", "local ip")
udpCmd.PersistentFlags().IntVarP(&localPort, "local_port", "l", 0, "local port") udpCmd.PersistentFlags().IntVarP(&localPort, "local_port", "l", 0, "local port")
udpCmd.PersistentFlags().IntVarP(&remotePort, "remote_port", "r", 0, "remote port") udpCmd.PersistentFlags().IntVarP(&remotePort, "remote_port", "r", 0, "remote port")
udpCmd.PersistentFlags().BoolVarP(&useEncryption, "ue", "", false, "use encryption") udpCmd.PersistentFlags().BoolVarP(&useEncryption, "ue", "", false, "use encryption")
@@ -48,20 +41,20 @@ var udpCmd = &cobra.Command{
Use: "udp", Use: "udp",
Short: "Run frpc with a single udp proxy", Short: "Run frpc with a single udp proxy",
RunE: func(cmd *cobra.Command, args []string) error { RunE: func(cmd *cobra.Command, args []string) error {
clientCfg, err := parseClientCommonCfg(CfgFileTypeCmd, "") clientCfg, err := parseClientCommonCfgFromCmd()
if err != nil { if err != nil {
fmt.Println(err) fmt.Println(err)
os.Exit(1) os.Exit(1)
} }
cfg := &config.UdpProxyConf{} cfg := &config.UDPProxyConf{}
var prefix string var prefix string
if user != "" { if user != "" {
prefix = user + "." prefix = user + "."
} }
cfg.ProxyName = prefix + proxyName cfg.ProxyName = prefix + proxyName
cfg.ProxyType = consts.UdpProxy cfg.ProxyType = consts.UDPProxy
cfg.LocalIp = localIp cfg.LocalIP = localIP
cfg.LocalPort = localPort cfg.LocalPort = localPort
cfg.RemotePort = remotePort cfg.RemotePort = remotePort
cfg.UseEncryption = useEncryption cfg.UseEncryption = useEncryption

View File

@@ -1,4 +1,4 @@
// Copyright 2020 guylewin, guy@lewin.co.il // Copyright 2021 The frp Authors
// //
// Licensed under the Apache License, Version 2.0 (the "License"); // Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License. // you may not use this file except in compliance with the License.
@@ -12,33 +12,32 @@
// See the License for the specific language governing permissions and // See the License for the specific language governing permissions and
// limitations under the License. // limitations under the License.
package util package sub
import ( import (
"net/http" "fmt"
"strings" "os"
"github.com/spf13/cobra"
"github.com/fatedier/frp/pkg/config"
) )
func OkResponse() *http.Response { func init() {
header := make(http.Header) rootCmd.AddCommand(verifyCmd)
res := &http.Response{
Status: "OK",
StatusCode: 200,
Proto: "HTTP/1.1",
ProtoMajor: 1,
ProtoMinor: 1,
Header: header,
}
return res
} }
func GetHostFromAddr(addr string) (host string) { var verifyCmd = &cobra.Command{
strs := strings.Split(addr, ":") Use: "verify",
if len(strs) > 1 { Short: "Verify that the configures is valid",
host = strs[0] RunE: func(cmd *cobra.Command, args []string) error {
} else { _, _, _, err := config.ParseClientConfig(cfgFile)
host = addr if err != nil {
} fmt.Println(err)
return os.Exit(1)
}
fmt.Printf("frpc: the configuration file %s syntax is ok\n", cfgFile)
return nil
},
} }

View File

@@ -20,25 +20,18 @@ import (
"github.com/spf13/cobra" "github.com/spf13/cobra"
"github.com/fatedier/frp/models/config" "github.com/fatedier/frp/pkg/config"
"github.com/fatedier/frp/models/consts" "github.com/fatedier/frp/pkg/consts"
) )
func init() { func init() {
xtcpCmd.PersistentFlags().StringVarP(&serverAddr, "server_addr", "s", "127.0.0.1:7000", "frp server's address") RegisterCommonFlags(xtcpCmd)
xtcpCmd.PersistentFlags().StringVarP(&user, "user", "u", "", "user")
xtcpCmd.PersistentFlags().StringVarP(&protocol, "protocol", "p", "tcp", "tcp or kcp or websocket")
xtcpCmd.PersistentFlags().StringVarP(&token, "token", "t", "", "auth token")
xtcpCmd.PersistentFlags().StringVarP(&logLevel, "log_level", "", "info", "log level")
xtcpCmd.PersistentFlags().StringVarP(&logFile, "log_file", "", "console", "console or file path")
xtcpCmd.PersistentFlags().IntVarP(&logMaxDays, "log_max_days", "", 3, "log file reversed days")
xtcpCmd.PersistentFlags().BoolVarP(&disableLogColor, "disable_log_color", "", false, "disable log color in console")
xtcpCmd.PersistentFlags().StringVarP(&proxyName, "proxy_name", "n", "", "proxy name") xtcpCmd.PersistentFlags().StringVarP(&proxyName, "proxy_name", "n", "", "proxy name")
xtcpCmd.PersistentFlags().StringVarP(&role, "role", "", "server", "role") xtcpCmd.PersistentFlags().StringVarP(&role, "role", "", "server", "role")
xtcpCmd.PersistentFlags().StringVarP(&sk, "sk", "", "", "secret key") xtcpCmd.PersistentFlags().StringVarP(&sk, "sk", "", "", "secret key")
xtcpCmd.PersistentFlags().StringVarP(&serverName, "server_name", "", "", "server name") xtcpCmd.PersistentFlags().StringVarP(&serverName, "server_name", "", "", "server name")
xtcpCmd.PersistentFlags().StringVarP(&localIp, "local_ip", "i", "127.0.0.1", "local ip") xtcpCmd.PersistentFlags().StringVarP(&localIP, "local_ip", "i", "127.0.0.1", "local ip")
xtcpCmd.PersistentFlags().IntVarP(&localPort, "local_port", "l", 0, "local port") xtcpCmd.PersistentFlags().IntVarP(&localPort, "local_port", "l", 0, "local port")
xtcpCmd.PersistentFlags().StringVarP(&bindAddr, "bind_addr", "", "", "bind addr") xtcpCmd.PersistentFlags().StringVarP(&bindAddr, "bind_addr", "", "", "bind addr")
xtcpCmd.PersistentFlags().IntVarP(&bindPort, "bind_port", "", 0, "bind port") xtcpCmd.PersistentFlags().IntVarP(&bindPort, "bind_port", "", 0, "bind port")
@@ -52,7 +45,7 @@ var xtcpCmd = &cobra.Command{
Use: "xtcp", Use: "xtcp",
Short: "Run frpc with a single xtcp proxy", Short: "Run frpc with a single xtcp proxy",
RunE: func(cmd *cobra.Command, args []string) error { RunE: func(cmd *cobra.Command, args []string) error {
clientCfg, err := parseClientCommonCfg(CfgFileTypeCmd, "") clientCfg, err := parseClientCommonCfgFromCmd()
if err != nil { if err != nil {
fmt.Println(err) fmt.Println(err)
os.Exit(1) os.Exit(1)
@@ -66,15 +59,16 @@ var xtcpCmd = &cobra.Command{
prefix = user + "." prefix = user + "."
} }
if role == "server" { switch role {
cfg := &config.XtcpProxyConf{} case "server":
cfg := &config.XTCPProxyConf{}
cfg.ProxyName = prefix + proxyName cfg.ProxyName = prefix + proxyName
cfg.ProxyType = consts.XtcpProxy cfg.ProxyType = consts.XTCPProxy
cfg.UseEncryption = useEncryption cfg.UseEncryption = useEncryption
cfg.UseCompression = useCompression cfg.UseCompression = useCompression
cfg.Role = role cfg.Role = role
cfg.Sk = sk cfg.Sk = sk
cfg.LocalIp = localIp cfg.LocalIP = localIP
cfg.LocalPort = localPort cfg.LocalPort = localPort
err = cfg.CheckForCli() err = cfg.CheckForCli()
if err != nil { if err != nil {
@@ -82,10 +76,10 @@ var xtcpCmd = &cobra.Command{
os.Exit(1) os.Exit(1)
} }
proxyConfs[cfg.ProxyName] = cfg proxyConfs[cfg.ProxyName] = cfg
} else if role == "visitor" { case "visitor":
cfg := &config.XtcpVisitorConf{} cfg := &config.XTCPVisitorConf{}
cfg.ProxyName = prefix + proxyName cfg.ProxyName = prefix + proxyName
cfg.ProxyType = consts.XtcpProxy cfg.ProxyType = consts.XTCPProxy
cfg.UseEncryption = useEncryption cfg.UseEncryption = useEncryption
cfg.UseCompression = useCompression cfg.UseCompression = useCompression
cfg.Role = role cfg.Role = role
@@ -99,7 +93,7 @@ var xtcpCmd = &cobra.Command{
os.Exit(1) os.Exit(1)
} }
visitorConfs[cfg.ProxyName] = cfg visitorConfs[cfg.ProxyName] = cfg
} else { default:
fmt.Println("invalid role") fmt.Println("invalid role")
os.Exit(1) os.Exit(1)
} }

View File

@@ -20,8 +20,8 @@ import (
"github.com/fatedier/golib/crypto" "github.com/fatedier/golib/crypto"
_ "github.com/fatedier/frp/assets/frps/statik" _ "github.com/fatedier/frp/assets/frps"
_ "github.com/fatedier/frp/models/metrics" _ "github.com/fatedier/frp/pkg/metrics"
) )
func main() { func main() {

View File

@@ -20,12 +20,12 @@ import (
"github.com/spf13/cobra" "github.com/spf13/cobra"
"github.com/fatedier/frp/models/auth" "github.com/fatedier/frp/pkg/auth"
"github.com/fatedier/frp/models/config" "github.com/fatedier/frp/pkg/config"
"github.com/fatedier/frp/pkg/util/log"
"github.com/fatedier/frp/pkg/util/util"
"github.com/fatedier/frp/pkg/util/version"
"github.com/fatedier/frp/server" "github.com/fatedier/frp/server"
"github.com/fatedier/frp/utils/log"
"github.com/fatedier/frp/utils/util"
"github.com/fatedier/frp/utils/version"
) )
const ( const (
@@ -37,47 +37,50 @@ var (
cfgFile string cfgFile string
showVersion bool showVersion bool
bindAddr string bindAddr string
bindPort int bindPort int
bindUdpPort int bindUDPPort int
kcpBindPort int kcpBindPort int
proxyBindAddr string proxyBindAddr string
vhostHttpPort int vhostHTTPPort int
vhostHttpsPort int vhostHTTPSPort int
vhostHttpTimeout int64 vhostHTTPTimeout int64
dashboardAddr string dashboardAddr string
dashboardPort int dashboardPort int
dashboardUser string dashboardUser string
dashboardPwd string dashboardPwd string
assetsDir string enablePrometheus bool
logFile string logFile string
logLevel string logLevel string
logMaxDays int64 logMaxDays int64
disableLogColor bool disableLogColor bool
token string token string
subDomainHost string subDomainHost string
tcpMux bool allowPorts string
allowPorts string maxPortsPerClient int64
maxPoolCount int64 tlsOnly bool
maxPortsPerClient int64 dashboardTLSMode bool
dashboardTLSCertFile string
dashboardTLSKeyFile string
) )
func init() { func init() {
rootCmd.PersistentFlags().StringVarP(&cfgFile, "config", "c", "", "config file of frps") rootCmd.PersistentFlags().StringVarP(&cfgFile, "config", "c", "", "config file of frps")
rootCmd.PersistentFlags().BoolVarP(&showVersion, "version", "v", false, "version of frpc") rootCmd.PersistentFlags().BoolVarP(&showVersion, "version", "v", false, "version of frps")
rootCmd.PersistentFlags().StringVarP(&bindAddr, "bind_addr", "", "0.0.0.0", "bind address") rootCmd.PersistentFlags().StringVarP(&bindAddr, "bind_addr", "", "0.0.0.0", "bind address")
rootCmd.PersistentFlags().IntVarP(&bindPort, "bind_port", "p", 7000, "bind port") rootCmd.PersistentFlags().IntVarP(&bindPort, "bind_port", "p", 7000, "bind port")
rootCmd.PersistentFlags().IntVarP(&bindUdpPort, "bind_udp_port", "", 0, "bind udp port") rootCmd.PersistentFlags().IntVarP(&bindUDPPort, "bind_udp_port", "", 0, "bind udp port")
rootCmd.PersistentFlags().IntVarP(&kcpBindPort, "kcp_bind_port", "", 0, "kcp bind udp port") rootCmd.PersistentFlags().IntVarP(&kcpBindPort, "kcp_bind_port", "", 0, "kcp bind udp port")
rootCmd.PersistentFlags().StringVarP(&proxyBindAddr, "proxy_bind_addr", "", "0.0.0.0", "proxy bind address") rootCmd.PersistentFlags().StringVarP(&proxyBindAddr, "proxy_bind_addr", "", "0.0.0.0", "proxy bind address")
rootCmd.PersistentFlags().IntVarP(&vhostHttpPort, "vhost_http_port", "", 0, "vhost http port") rootCmd.PersistentFlags().IntVarP(&vhostHTTPPort, "vhost_http_port", "", 0, "vhost http port")
rootCmd.PersistentFlags().IntVarP(&vhostHttpsPort, "vhost_https_port", "", 0, "vhost https port") rootCmd.PersistentFlags().IntVarP(&vhostHTTPSPort, "vhost_https_port", "", 0, "vhost https port")
rootCmd.PersistentFlags().Int64VarP(&vhostHttpTimeout, "vhost_http_timeout", "", 60, "vhost http response header timeout") rootCmd.PersistentFlags().Int64VarP(&vhostHTTPTimeout, "vhost_http_timeout", "", 60, "vhost http response header timeout")
rootCmd.PersistentFlags().StringVarP(&dashboardAddr, "dashboard_addr", "", "0.0.0.0", "dasboard address") rootCmd.PersistentFlags().StringVarP(&dashboardAddr, "dashboard_addr", "", "0.0.0.0", "dasboard address")
rootCmd.PersistentFlags().IntVarP(&dashboardPort, "dashboard_port", "", 0, "dashboard port") rootCmd.PersistentFlags().IntVarP(&dashboardPort, "dashboard_port", "", 0, "dashboard port")
rootCmd.PersistentFlags().StringVarP(&dashboardUser, "dashboard_user", "", "admin", "dashboard user") rootCmd.PersistentFlags().StringVarP(&dashboardUser, "dashboard_user", "", "admin", "dashboard user")
rootCmd.PersistentFlags().StringVarP(&dashboardPwd, "dashboard_pwd", "", "admin", "dashboard password") rootCmd.PersistentFlags().StringVarP(&dashboardPwd, "dashboard_pwd", "", "admin", "dashboard password")
rootCmd.PersistentFlags().BoolVarP(&enablePrometheus, "enable_prometheus", "", false, "enable prometheus dashboard")
rootCmd.PersistentFlags().StringVarP(&logFile, "log_file", "", "console", "log file") rootCmd.PersistentFlags().StringVarP(&logFile, "log_file", "", "console", "log file")
rootCmd.PersistentFlags().StringVarP(&logLevel, "log_level", "", "info", "log level") rootCmd.PersistentFlags().StringVarP(&logLevel, "log_level", "", "info", "log level")
rootCmd.PersistentFlags().Int64VarP(&logMaxDays, "log_max_days", "", 3, "log max days") rootCmd.PersistentFlags().Int64VarP(&logMaxDays, "log_max_days", "", 3, "log max days")
@@ -87,6 +90,10 @@ func init() {
rootCmd.PersistentFlags().StringVarP(&subDomainHost, "subdomain_host", "", "", "subdomain host") rootCmd.PersistentFlags().StringVarP(&subDomainHost, "subdomain_host", "", "", "subdomain host")
rootCmd.PersistentFlags().StringVarP(&allowPorts, "allow_ports", "", "", "allow ports") rootCmd.PersistentFlags().StringVarP(&allowPorts, "allow_ports", "", "", "allow ports")
rootCmd.PersistentFlags().Int64VarP(&maxPortsPerClient, "max_ports_per_client", "", 0, "max ports per client") rootCmd.PersistentFlags().Int64VarP(&maxPortsPerClient, "max_ports_per_client", "", 0, "max ports per client")
rootCmd.PersistentFlags().BoolVarP(&tlsOnly, "tls_only", "", false, "frps tls only")
rootCmd.PersistentFlags().BoolVarP(&dashboardTLSMode, "dashboard_tls_mode", "", false, "dashboard tls mode")
rootCmd.PersistentFlags().StringVarP(&dashboardTLSCertFile, "dashboard_tls_cert_file", "", "", "dashboard tls cert file")
rootCmd.PersistentFlags().StringVarP(&dashboardTLSKeyFile, "dashboard_tls_key_file", "", "", "dashboard tls key file")
} }
var rootCmd = &cobra.Command{ var rootCmd = &cobra.Command{
@@ -101,14 +108,14 @@ var rootCmd = &cobra.Command{
var cfg config.ServerCommonConf var cfg config.ServerCommonConf
var err error var err error
if cfgFile != "" { if cfgFile != "" {
var content string var content []byte
content, err = config.GetRenderedConfFromFile(cfgFile) content, err = config.GetRenderedConfFromFile(cfgFile)
if err != nil { if err != nil {
return err return err
} }
cfg, err = parseServerCommonCfg(CfgFileTypeIni, content) cfg, err = parseServerCommonCfg(CfgFileTypeIni, content)
} else { } else {
cfg, err = parseServerCommonCfg(CfgFileTypeCmd, "") cfg, err = parseServerCommonCfg(CfgFileTypeCmd, nil)
} }
if err != nil { if err != nil {
return err return err
@@ -129,59 +136,57 @@ func Execute() {
} }
} }
func parseServerCommonCfg(fileType int, content string) (cfg config.ServerCommonConf, err error) { func parseServerCommonCfg(fileType int, source []byte) (cfg config.ServerCommonConf, err error) {
if fileType == CfgFileTypeIni { if fileType == CfgFileTypeIni {
cfg, err = parseServerCommonCfgFromIni(content) cfg, err = config.UnmarshalServerConfFromIni(source)
} else if fileType == CfgFileTypeCmd { } else if fileType == CfgFileTypeCmd {
cfg, err = parseServerCommonCfgFromCmd() cfg, err = parseServerCommonCfgFromCmd()
} }
if err != nil { if err != nil {
return return
} }
cfg.Complete()
err = cfg.Check() err = cfg.Validate()
if err != nil { if err != nil {
err = fmt.Errorf("parse config error: %v", err)
return return
} }
return return
} }
func parseServerCommonCfgFromIni(content string) (config.ServerCommonConf, error) {
cfg, err := config.UnmarshalServerConfFromIni(content)
if err != nil {
return config.ServerCommonConf{}, err
}
return cfg, nil
}
func parseServerCommonCfgFromCmd() (cfg config.ServerCommonConf, err error) { func parseServerCommonCfgFromCmd() (cfg config.ServerCommonConf, err error) {
cfg = config.GetDefaultServerConf() cfg = config.GetDefaultServerConf()
cfg.BindAddr = bindAddr cfg.BindAddr = bindAddr
cfg.BindPort = bindPort cfg.BindPort = bindPort
cfg.BindUdpPort = bindUdpPort cfg.BindUDPPort = bindUDPPort
cfg.KcpBindPort = kcpBindPort cfg.KCPBindPort = kcpBindPort
cfg.ProxyBindAddr = proxyBindAddr cfg.ProxyBindAddr = proxyBindAddr
cfg.VhostHttpPort = vhostHttpPort cfg.VhostHTTPPort = vhostHTTPPort
cfg.VhostHttpsPort = vhostHttpsPort cfg.VhostHTTPSPort = vhostHTTPSPort
cfg.VhostHttpTimeout = vhostHttpTimeout cfg.VhostHTTPTimeout = vhostHTTPTimeout
cfg.DashboardAddr = dashboardAddr cfg.DashboardAddr = dashboardAddr
cfg.DashboardPort = dashboardPort cfg.DashboardPort = dashboardPort
cfg.DashboardUser = dashboardUser cfg.DashboardUser = dashboardUser
cfg.DashboardPwd = dashboardPwd cfg.DashboardPwd = dashboardPwd
cfg.EnablePrometheus = enablePrometheus
cfg.DashboardTLSCertFile = dashboardTLSCertFile
cfg.DashboardTLSKeyFile = dashboardTLSKeyFile
cfg.DashboardTLSMode = dashboardTLSMode
cfg.LogFile = logFile cfg.LogFile = logFile
cfg.LogLevel = logLevel cfg.LogLevel = logLevel
cfg.LogMaxDays = logMaxDays cfg.LogMaxDays = logMaxDays
cfg.SubDomainHost = subDomainHost cfg.SubDomainHost = subDomainHost
cfg.TLSOnly = tlsOnly
// Only token authentication is supported in cmd mode // Only token authentication is supported in cmd mode
cfg.AuthServerConfig = auth.GetDefaultAuthServerConf() cfg.ServerConfig = auth.GetDefaultServerConf()
cfg.Token = token cfg.Token = token
if len(allowPorts) > 0 { if len(allowPorts) > 0 {
// e.g. 1000-2000,2001,2002,3000-4000 // e.g. 1000-2000,2001,2002,3000-4000
ports, errRet := util.ParseRangeNumbers(allowPorts) ports, errRet := util.ParseRangeNumbers(allowPorts)
if errRet != nil { if errRet != nil {
err = fmt.Errorf("Parse conf error: allow_ports: %v", errRet) err = fmt.Errorf("parse conf error: allow_ports: %v", errRet)
return return
} }
@@ -190,23 +195,24 @@ func parseServerCommonCfgFromCmd() (cfg config.ServerCommonConf, err error) {
} }
} }
cfg.MaxPortsPerClient = maxPortsPerClient cfg.MaxPortsPerClient = maxPortsPerClient
if logFile == "console" {
cfg.LogWay = "console"
} else {
cfg.LogWay = "file"
}
cfg.DisableLogColor = disableLogColor cfg.DisableLogColor = disableLogColor
return return
} }
func runServer(cfg config.ServerCommonConf) (err error) { func runServer(cfg config.ServerCommonConf) (err error) {
log.InitLog(cfg.LogWay, cfg.LogFile, cfg.LogLevel, cfg.LogMaxDays, cfg.DisableLogColor) log.InitLog(cfg.LogWay, cfg.LogFile, cfg.LogLevel, cfg.LogMaxDays, cfg.DisableLogColor)
if cfgFile != "" {
log.Info("frps uses config file: %s", cfgFile)
} else {
log.Info("frps uses command line arguments for config")
}
svr, err := server.NewService(cfg) svr, err := server.NewService(cfg)
if err != nil { if err != nil {
return err return err
} }
log.Info("start frps success") log.Info("frps started successfully")
svr.Run() svr.Run()
return return
} }

53
cmd/frps/verify.go Normal file
View File

@@ -0,0 +1,53 @@
// Copyright 2021 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 main
import (
"fmt"
"os"
"github.com/spf13/cobra"
"github.com/fatedier/frp/pkg/config"
)
func init() {
rootCmd.AddCommand(verifyCmd)
}
var verifyCmd = &cobra.Command{
Use: "verify",
Short: "Verify that the configures is valid",
RunE: func(cmd *cobra.Command, args []string) error {
if cfgFile == "" {
fmt.Println("no config file is specified")
return nil
}
iniContent, err := config.GetRenderedConfFromFile(cfgFile)
if err != nil {
fmt.Println(err)
os.Exit(1)
}
_, err = parseServerCommonCfg(CfgFileTypeIni, iniContent)
if err != nil {
fmt.Println(err)
os.Exit(1)
}
fmt.Printf("frps: the configuration file %s syntax is ok\n", cfgFile)
return nil
},
}

View File

@@ -2,13 +2,22 @@
[common] [common]
# A literal address or host name for IPv6 must be enclosed # A literal address or host name for IPv6 must be enclosed
# in square brackets, as in "[::1]:80", "[ipv6-host]:http" or "[ipv6-host%zone]:80" # in square brackets, as in "[::1]:80", "[ipv6-host]:http" or "[ipv6-host%zone]:80"
# For single "server_addr" field, no need square brackets, like "server_addr = ::".
server_addr = 0.0.0.0 server_addr = 0.0.0.0
server_port = 7000 server_port = 7000
# if you want to connect frps by http proxy or socks5 proxy, you can set http_proxy here or in global environment variables # The maximum amount of time a dial to server will wait for a connect to complete. Default value is 10 seconds.
# dial_server_timeout = 10
# dial_server_keepalive specifies the interval between keep-alive probes for an active network connection between frpc and frps.
# If negative, keep-alive probes are disabled.
# dial_server_keepalive = 7200
# if you want to connect frps by http proxy or socks5 proxy or ntlm proxy, you can set http_proxy here or in global environment variables
# it only works when protocol is tcp # it only works when protocol is tcp
# http_proxy = http://user:passwd@192.168.1.128:8080 # http_proxy = http://user:passwd@192.168.1.128:8080
# http_proxy = socks5://user:passwd@192.168.1.128:1080 # http_proxy = socks5://user:passwd@192.168.1.128:1080
# http_proxy = ntlm://user:passwd@192.168.1.128:2080
# console or real logFile path like ./frpc.log # console or real logFile path like ./frpc.log
log_file = ./frpc.log log_file = ./frpc.log
@@ -21,9 +30,42 @@ log_max_days = 3
# disable log colors when log_file is console, default is false # disable log colors when log_file is console, default is false
disable_log_color = false disable_log_color = false
# for authentication # for authentication, should be same as your frps.ini
# authenticate_heartbeats specifies whether to include authentication token in heartbeats sent to frps. By default, this value is false.
authenticate_heartbeats = false
# authenticate_new_work_conns specifies whether to include authentication token in new work connections sent to frps. By default, this value is false.
authenticate_new_work_conns = false
# auth token
token = 12345678 token = 12345678
authentication_method =
# oidc_client_id specifies the client ID to use to get a token in OIDC authentication if AuthenticationMethod == "oidc".
# By default, this value is "".
oidc_client_id =
# oidc_client_secret specifies the client secret to use to get a token in OIDC authentication if AuthenticationMethod == "oidc".
# By default, this value is "".
oidc_client_secret =
# oidc_audience specifies the audience of the token in OIDC authentication if AuthenticationMethod == "oidc". By default, this value is "".
oidc_audience =
# oidc_scope specifies the permisssions of the token in OIDC authentication if AuthenticationMethod == "oidc". By default, this value is "".
oidc_scope =
# oidc_token_endpoint_url specifies the URL which implements OIDC Token Endpoint.
# It will be used to get an OIDC token if AuthenticationMethod == "oidc". By default, this value is "".
oidc_token_endpoint_url =
# oidc_additional_xxx specifies additional parameters to be sent to the OIDC Token Endpoint.
# For example, if you want to specify the "audience" parameter, you can set as follow.
# frp will add "audience=<value>" "var1=<value>" to the additional parameters.
# oidc_additional_audience = https://dev.auth.com/api/v2/
# oidc_additional_var1 = foobar
# set admin address for control frpc's action by http api such as reload # set admin address for control frpc's action by http api such as reload
admin_addr = 127.0.0.1 admin_addr = 127.0.0.1
admin_port = 7400 admin_port = 7400
@@ -36,7 +78,11 @@ admin_pwd = admin
pool_count = 5 pool_count = 5
# if tcp stream multiplexing is used, default is true, it must be same with frps # if tcp stream multiplexing is used, default is true, it must be same with frps
tcp_mux = true # tcp_mux = true
# specify keep alive interval for tcp mux.
# only valid if tcp_mux is true.
# tcp_mux_keepalive_interval = 60
# your proxy name will be changed to {user}.{proxy} # your proxy name will be changed to {user}.{proxy}
user = your_name user = your_name
@@ -46,21 +92,36 @@ user = your_name
login_fail_exit = true login_fail_exit = true
# communication protocol used to connect to server # communication protocol used to connect to server
# now it supports tcp and kcp and websocket, default is tcp # supports tcp, kcp, quic and websocket now, default is tcp
protocol = tcp protocol = tcp
# set client binding ip when connect server, default is empty.
# only when protocol = tcp or websocket, the value will be used.
connect_server_local_ip = 0.0.0.0
# quic protocol options
# quic_keepalive_period = 10
# 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
tls_enable = true tls_enable = true
# tls_cert_file = client.crt
# tls_key_file = client.key
# tls_trusted_ca_file = ca.crt
# tls_server_name = example.com
# specify a dns server, so frpc will use this instead of default one # specify a dns server, so frpc will use this instead of default one
# dns_server = 8.8.8.8 # dns_server = 8.8.8.8
# proxy names you want to start seperated by ',' # proxy names you want to start separated by ','
# default is empty, means all proxies # default is empty, means all proxies
# start = ssh,dns # start = ssh,dns
# heartbeat configure, it's not recommended to modify the default value # heartbeat configure, it's not recommended to modify the default value
# the default value of heartbeat_interval is 10 and heartbeat_timeout is 90 # The default value of heartbeat_interval is 10 and heartbeat_timeout is 90. Set negative value
# to disable it.
# heartbeat_interval = 30 # heartbeat_interval = 30
# heartbeat_timeout = 90 # heartbeat_timeout = 90
@@ -68,6 +129,22 @@ tls_enable = true
meta_var1 = 123 meta_var1 = 123
meta_var2 = 234 meta_var2 = 234
# specify udp packet size, unit is byte. If not set, the default value is 1500.
# This parameter should be same between client and server.
# It affects the udp and sudp proxy.
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
# Enable golang pprof handlers in admin listener.
# Admin port must be set first.
pprof_enable = false
# 'ssh' is the unique proxy name # 'ssh' is the unique proxy name
# if user in [common] section is not empty, it will be changed to {user}.{proxy} such as 'your_name.ssh' # if user in [common] section is not empty, it will be changed to {user}.{proxy} such as 'your_name.ssh'
[ssh] [ssh]
@@ -144,11 +221,13 @@ use_compression = true
# if not set, you can access this custom_domains without certification # if not set, you can access this custom_domains without certification
http_user = admin http_user = admin
http_pwd = admin http_pwd = admin
# if domain for frps is frps.com, then you can access [web01] proxy by URL http://test.frps.com # if domain for frps is frps.com, then you can access [web01] proxy by URL http://web01.frps.com
subdomain = web01 subdomain = web01
custom_domains = web02.yourdomain.com custom_domains = web01.yourdomain.com
# locations is only available for http type # locations is only available for http type
locations = /,/pic locations = /,/pic
# route requests to this service if http basic auto user is abc
# route_by_http_user = abc
host_header_rewrite = example.com host_header_rewrite = example.com
# params with prefix "header_" will be used to update http request headers # params with prefix "header_" will be used to update http request headers
header_X-From-Where = frp header_X-From-Where = frp
@@ -214,6 +293,16 @@ plugin_key_path = ./server.key
plugin_host_header_rewrite = 127.0.0.1 plugin_host_header_rewrite = 127.0.0.1
plugin_header_X-From-Where = frp plugin_header_X-From-Where = frp
[plugin_https2https]
type = https
custom_domains = test.yourdomain.com
plugin = https2https
plugin_local_addr = 127.0.0.1:443
plugin_crt_path = ./server.crt
plugin_key_path = ./server.key
plugin_host_header_rewrite = 127.0.0.1
plugin_header_X-From-Where = frp
[plugin_http2https] [plugin_http2https]
type = http type = http
custom_domains = test.yourdomain.com custom_domains = test.yourdomain.com
@@ -271,3 +360,4 @@ multiplexer = httpconnect
local_ip = 127.0.0.1 local_ip = 127.0.0.1
local_port = 10701 local_port = 10701
custom_domains = tunnel1 custom_domains = tunnel1
# route_by_http_user = user1

View File

@@ -2,16 +2,25 @@
[common] [common]
# A literal address or host name for IPv6 must be enclosed # A literal address or host name for IPv6 must be enclosed
# in square brackets, as in "[::1]:80", "[ipv6-host]:http" or "[ipv6-host%zone]:80" # in square brackets, as in "[::1]:80", "[ipv6-host]:http" or "[ipv6-host%zone]:80"
# For single "bind_addr" field, no need square brackets, like "bind_addr = ::".
bind_addr = 0.0.0.0 bind_addr = 0.0.0.0
bind_port = 7000 bind_port = 7000
# udp port to help make udp hole to penetrate nat # udp port to help make udp hole to penetrate nat
bind_udp_port = 7001 bind_udp_port = 7001
# udp port used for kcp protocol, it can be same with 'bind_port' # udp port used for kcp protocol, it can be same with 'bind_port'.
# if not set, kcp is disabled in frps # if not set, kcp is disabled in frps.
kcp_bind_port = 7000 kcp_bind_port = 7000
# udp port used for quic protocol.
# if not set, quic is disabled in frps.
# quic_bind_port = 7002
# quic protocol options
# quic_keepalive_period = 10
# quic_max_idle_timeout = 30
# quic_max_incoming_streams = 100000
# specify which address proxy will listen for, default value is same with bind_addr # specify which address proxy will listen for, default value is same with bind_addr
# proxy_bind_addr = 127.0.0.1 # proxy_bind_addr = 127.0.0.1
@@ -23,27 +32,36 @@ vhost_https_port = 443
# response header timeout(seconds) for vhost http server, default is 60s # response header timeout(seconds) for vhost http server, default is 60s
# vhost_http_timeout = 60 # vhost_http_timeout = 60
# TcpMuxHttpConnectPort specifies the port that the server listens for TCP # tcpmux_httpconnect_port specifies the port that the server listens for TCP
# HTTP CONNECT requests. If the value is 0, the server will not multiplex TCP # HTTP CONNECT requests. If the value is 0, the server will not multiplex TCP
# requests on one single port. If it's not - it will listen on this value for # requests on one single port. If it's not - it will listen on this value for
# HTTP CONNECT requests. By default, this value is 0. # HTTP CONNECT requests. By default, this value is 0.
# tcpmux_httpconnect_port = 1337 # tcpmux_httpconnect_port = 1337
# If tcpmux_passthrough is true, frps won't do any update on traffic.
# tcpmux_passthrough = false
# set dashboard_addr and dashboard_port to view dashboard of frps # set dashboard_addr and dashboard_port to view dashboard of frps
# dashboard_addr's default value is same with bind_addr # dashboard_addr's default value is same with bind_addr
# dashboard is available only if dashboard_port is set # dashboard is available only if dashboard_port is set
dashboard_addr = 0.0.0.0 dashboard_addr = 0.0.0.0
dashboard_port = 7500 dashboard_port = 7500
# dashboard user and passwd for basic auth protect, if not set, both default value is admin # dashboard user and passwd for basic auth protect
dashboard_user = admin dashboard_user = admin
dashboard_pwd = admin dashboard_pwd = admin
# dashboard TLS mode
dashboard_tls_mode = false
# dashboard_tls_cert_file = server.crt
# dashboard_tls_key_file = server.key
# enable_prometheus will export prometheus metrics on {dashboard_addr}:{dashboard_port} in /metrics api. # enable_prometheus will export prometheus metrics on {dashboard_addr}:{dashboard_port} in /metrics api.
enable_prometheus = true enable_prometheus = true
# dashboard assets directory(only for debug mode) # dashboard assets directory(only for debug mode)
# assets_dir = ./static # assets_dir = ./static
# console or real logFile path like ./frps.log # console or real logFile path like ./frps.log
log_file = ./frps.log log_file = ./frps.log
@@ -58,12 +76,12 @@ disable_log_color = false
# DetailedErrorsToClient defines whether to send the specific error (with debug info) to frpc. By default, this value is true. # DetailedErrorsToClient defines whether to send the specific error (with debug info) to frpc. By default, this value is true.
detailed_errors_to_client = true detailed_errors_to_client = true
# AuthenticationMethod specifies what authentication method to use authenticate frpc with frps. # authentication_method specifies what authentication method to use authenticate frpc with frps.
# If "token" is specified - token will be read into login message. # If "token" is specified - token will be read into login message.
# If "oidc" is specified - OIDC (Open ID Connect) token will be issued using OIDC settings. By default, this value is "token". # If "oidc" is specified - OIDC (Open ID Connect) token will be issued using OIDC settings. By default, this value is "token".
authentication_method = token authentication_method = token
# AuthenticateHeartBeats specifies whether to include authentication token in heartbeats sent to frps. By default, this value is false. # authenticate_heartbeats specifies whether to include authentication token in heartbeats sent to frps. By default, this value is false.
authenticate_heartbeats = false authenticate_heartbeats = false
# AuthenticateNewWorkConns specifies whether to include authentication token in new work connections sent to frps. By default, this value is false. # AuthenticateNewWorkConns specifies whether to include authentication token in new work connections sent to frps. By default, this value is false.
@@ -72,25 +90,30 @@ authenticate_new_work_conns = false
# auth token # auth token
token = 12345678 token = 12345678
# OidcClientId specifies the client ID to use to get a token in OIDC authentication if AuthenticationMethod == "oidc". # oidc_issuer specifies the issuer to verify OIDC tokens with.
# By default, this value is "". # By default, this value is "".
oidc_client_id = oidc_issuer =
# OidcClientSecret specifies the client secret to use to get a token in OIDC authentication if AuthenticationMethod == "oidc". # oidc_audience specifies the audience OIDC tokens should contain when validated.
# By default, this value is "". # By default, this value is "".
oidc_client_secret = oidc_audience =
# OidcAudience specifies the audience of the token in OIDC authentication if AuthenticationMethod == "oidc". By default, this value is "". # oidc_skip_expiry_check specifies whether to skip checking if the OIDC token is expired.
oidc_audience = # By default, this value is false.
oidc_skip_expiry_check = false
# OidcTokenEndpointUrl specifies the URL which implements OIDC Token Endpoint. # oidc_skip_issuer_check specifies whether to skip checking if the OIDC token's issuer claim matches the issuer specified in OidcIssuer.
# It will be used to get an OIDC token if AuthenticationMethod == "oidc". By default, this value is "". # By default, this value is false.
oidc_token_endpoint_url = oidc_skip_issuer_check = false
# heartbeat configure, it's not recommended to modify the default value # heartbeat configure, it's not recommended to modify the default value
# the default value of heartbeat_timeout is 90 # the default value of heartbeat_timeout is 90. Set negative value to disable it.
# heartbeat_timeout = 90 # heartbeat_timeout = 90
# user_conn_timeout configure, it's not recommended to modify the default value
# the default value of user_conn_timeout is 10
# user_conn_timeout = 10
# only allow frpc to bind ports you list, if you set nothing, there won't be any limit # only allow frpc to bind ports you list, if you set nothing, there won't be any limit
allow_ports = 2000-3000,3001,3003,4000-50000 allow_ports = 2000-3000,3001,3003,4000-50000
@@ -100,19 +123,40 @@ max_pool_count = 5
# max ports can be used for each client, default value is 0 means no limit # max ports can be used for each client, default value is 0 means no limit
max_ports_per_client = 0 max_ports_per_client = 0
# TlsOnly specifies whether to only accept TLS-encrypted connections. By default, the value is false. # tls_only specifies whether to only accept TLS-encrypted connections. By default, the value is false.
tls_only = false tls_only = false
# tls_cert_file = server.crt
# tls_key_file = server.key
# tls_trusted_ca_file = ca.crt
# if subdomain_host is not empty, you can set subdomain when type is http or https in frpc's configure file # if subdomain_host is not empty, you can set subdomain when type is http or https in frpc's configure file
# when subdomain is test, the host used by routing is test.frps.com # when subdomain is test, the host used by routing is test.frps.com
subdomain_host = frps.com subdomain_host = frps.com
# if tcp stream multiplexing is used, default is true # if tcp stream multiplexing is used, default is true
tcp_mux = true # tcp_mux = true
# specify keep alive interval for tcp mux.
# only valid if tcp_mux is true.
# tcp_mux_keepalive_interval = 60
# tcp_keepalive specifies the interval between keep-alive probes for an active network connection between frpc and frps.
# If negative, keep-alive probes are disabled.
# tcp_keepalive = 7200
# custom 404 page for HTTP requests # custom 404 page for HTTP requests
# custom_404_page = /path/to/404.html # custom_404_page = /path/to/404.html
# specify udp packet size, unit is byte. If not set, the default value is 1500.
# This parameter should be same between client and server.
# It affects the udp and sudp proxy.
udp_packet_size = 1500
# Enable golang pprof handlers in dashboard listener.
# Dashboard port must be set first
pprof_enable = false
[plugin.user-manager] [plugin.user-manager]
addr = 127.0.0.1:9000 addr = 127.0.0.1:9000
path = /handler path = /handler

View File

@@ -1,14 +0,0 @@
[Unit]
Description=Frp Client Service
After=network.target
[Service]
Type=simple
User=nobody
Restart=on-failure
RestartSec=5s
ExecStart=/usr/bin/frpc -c /etc/frp/frpc.ini
ExecReload=/usr/bin/frpc reload -c /etc/frp/frpc.ini
[Install]
WantedBy=multi-user.target

View File

@@ -1,14 +0,0 @@
[Unit]
Description=Frp Client Service
After=network.target
[Service]
Type=idle
User=nobody
Restart=on-failure
RestartSec=5s
ExecStart=/usr/bin/frpc -c /etc/frp/%i.ini
ExecReload=/usr/bin/frpc reload -c /etc/frp/%i.ini
[Install]
WantedBy=multi-user.target

View File

@@ -1,13 +0,0 @@
[Unit]
Description=Frp Server Service
After=network.target
[Service]
Type=simple
User=nobody
Restart=on-failure
RestartSec=5s
ExecStart=/usr/bin/frps -c /etc/frp/frps.ini
[Install]
WantedBy=multi-user.target

View File

@@ -1,13 +0,0 @@
[Unit]
Description=Frp Server Service
After=network.target
[Service]
Type=simple
User=nobody
Restart=on-failure
RestartSec=5s
ExecStart=/usr/bin/frps -c /etc/frp/%i.ini
[Install]
WantedBy=multi-user.target

BIN
doc/pic/sponsor_doppler.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 41 KiB

BIN
doc/pic/sponsor_workos.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 37 KiB

View File

@@ -1,27 +1,28 @@
### Manage Plugin ### Server Plugin
frp manage plugin is aim to extend frp's ability without modifing self code. frp server plugin is aimed to extend frp's ability without modifying the Golang code.
It runs as a process and listen on a port to provide RPC interface. Before frps doing some operations, frps will send RPC requests to manage plugin and do operations by it's response. An external server should run in a different process receiving RPC calls from frps.
Before frps is doing some operations, it will send RPC requests to notify the external RPC server and act according to its response.
### RPC request ### RPC request
Support HTTP first. RPC requests are based on JSON over HTTP.
When manage plugin accept the operation request, it can give three different responses. When a server plugin accepts an operation request, it can respond with three different responses:
* Reject operation and return the reason. * Reject operation and return a reason.
* Allow operation and keep original content. * Allow operation and keep original content.
* Allow operation and return modified content. * Allow operation and return modified content.
### Interface ### Interface
HTTP path can be configured for each manage plugin in frps. Assume here is `/handler`. HTTP path can be configured for each manage plugin in frps. We'll assume for this example that it's `/handler`.
Request A request to the RPC server will look like:
``` ```
POST /handler POST /handler?version=0.1.0&op=Login
{ {
"version": "0.1.0", "version": "0.1.0",
"op": "Login", "op": "Login",
@@ -30,15 +31,15 @@ POST /handler
} }
} }
Request Header Request Header:
X-Frp-Reqid: for tracing X-Frp-Reqid: for tracing
``` ```
Response The response can look like any of the following:
Error if not return 200 http code. * Non-200 HTTP response status code (this will automatically tell frps that the request should fail)
Reject opeartion * Reject operation:
``` ```
{ {
@@ -47,7 +48,7 @@ Reject opeartion
} }
``` ```
Allow operation and keep original content * Allow operation and keep original content:
``` ```
{ {
@@ -56,7 +57,7 @@ Allow operation and keep original content
} }
``` ```
Allow opeartion and modify content * Allow operation and modify content
``` ```
{ {
@@ -69,7 +70,7 @@ Allow opeartion and modify content
### Operation ### Operation
Now it supports `Login` and `NewProxy`. Currently `Login`, `NewProxy`, `CloseProxy`, `Ping`, `NewWorkConn` and `NewUserConn` operations are supported.
#### Login #### Login
@@ -87,7 +88,8 @@ Client login operation
"privilege_key": <string>, "privilege_key": <string>,
"run_id": <string>, "run_id": <string>,
"pool_count": <int>, "pool_count": <int>,
"metas": map<string>string "metas": map<string>string,
"client_address": <string>
} }
} }
``` ```
@@ -102,6 +104,7 @@ Create new proxy
"user": { "user": {
"user": <string>, "user": <string>,
"metas": map<string>string "metas": map<string>string
"run_id": <string>
}, },
"proxy_name": <string>, "proxy_name": <string>,
"proxy_type": <string>, "proxy_type": <string>,
@@ -122,14 +125,97 @@ Create new proxy
"host_header_rewrite": <string>, "host_header_rewrite": <string>,
"headers": map<string>string, "headers": map<string>string,
// stcp only
"sk": <string>,
// tcpmux only
"multiplexer": <string>
"metas": map<string>string "metas": map<string>string
} }
} }
``` ```
### manage plugin configure #### CloseProxy
A previously created proxy is closed.
Please note that one request will be sent for every proxy that is closed, do **NOT** use this
if you have too many proxies bound to a single client, as this may exhaust the server's resources.
```
{
"content": {
"user": {
"user": <string>,
"metas": map<string>string
"run_id": <string>
},
"proxy_name": <string>
}
}
```
#### Ping
Heartbeat from frpc
```
{
"content": {
"user": {
"user": <string>,
"metas": map<string>string
"run_id": <string>
},
"timestamp": <int64>,
"privilege_key": <string>
}
}
```
#### NewWorkConn
New work connection received from frpc (RPC sent after `run_id` is matched with an existing frp connection)
```
{
"content": {
"user": {
"user": <string>,
"metas": map<string>string
"run_id": <string>
},
"run_id": <string>
"timestamp": <int64>,
"privilege_key": <string>
}
}
```
#### NewUserConn
New user connection received from proxy (support `tcp`, `stcp`, `https` and `tcpmux`) .
```
{
"content": {
"user": {
"user": <string>,
"metas": map<string>string
"run_id": <string>
},
"proxy_name": <string>,
"proxy_type": <string>,
"remote_addr": <string>
}
}
```
### Server Plugin Configuration
```ini ```ini
# frps.ini
[common] [common]
bind_port = 7000 bind_port = 7000
@@ -144,15 +230,20 @@ path = /handler
ops = NewProxy ops = NewProxy
``` ```
addr: plugin listen on. - addr: the address where the external RPC service listens. Defaults to http. For https, specify the schema: `addr = https://127.0.0.1:9001`.
path: http request url path. - path: http request url path for the POST request.
ops: opeartions plugin needs handle. - ops: operations plugin needs to handle (e.g. "Login", "NewProxy", ...).
- tls_verify: When the schema is https, we verify by default. Set this value to false if you want to skip verification.
### meta data ### Metadata
Meta data will be sent to manage plugin in each RCP request. Metadata will be sent to the server plugin in each RPC request.
Meta data start with `meta_`. It can be configured in `common` and each proxy. There are 2 types of metadata entries - 1 under `[common]` and the other under each proxy configuration.
Metadata entries under `[common]` will be sent in `Login` under the key `metas`, and in any other RPC request under `user.metas`.
Metadata entries under each proxy configuration will be sent in `NewProxy` op only, under `metas`.
Metadata entries start with `meta_`. This is an example of metadata entries in `[common]` and under the proxy named `[ssh]`:
``` ```
# frpc.ini # frpc.ini

View File

@@ -1,171 +0,0 @@
### 服务端管理插件
frp 管理插件的作用是在不侵入自身代码的前提下,扩展 frp 服务端的能力。
frp 管理插件会以单独进程的形式运行,并且监听在一个端口上,对外提供 RPC 接口,响应 frps 的请求。
frps 在执行某些操作前,会根据配置向管理插件发送 RPC 请求,根据管理插件的响应来执行相应的操作。
### RPC 请求
管理插件接收到操作请求后,可以给出三种回应。
* 拒绝操作,需要返回拒绝操作的原因。
* 允许操作,不需要修改操作内容。
* 允许操作,对操作请求进行修改后,返回修改后的内容。
### 接口
接口路径可以在 frps 配置中为每个插件单独配置,这里以 `/handler` 为例。
Request
```
POST /handler
{
"version": "0.1.0",
"op": "Login",
"content": {
... // 具体的操作信息
}
}
请求 Header
X-Frp-Reqid: 用于追踪请求
```
Response
非 200 的返回都认为是请求异常。
拒绝执行操作
```
{
"reject": true,
"reject_reason": "invalid user"
}
```
允许且内容不需要变动
```
{
"reject": false,
"unchange": true
}
```
允许且需要替换操作内容
```
{
"unchange": "false",
"content": {
... // 替换后的操作信息,格式必须和请求时的一致
}
}
```
### 操作类型
目前插件支持管理的操作类型有 `Login``NewProxy`
#### Login
用户登录操作信息
```
{
"content": {
"version": <string>,
"hostname": <string>,
"os": <string>,
"arch": <string>,
"user": <string>,
"timestamp": <int64>,
"privilege_key": <string>,
"run_id": <string>,
"pool_count": <int>,
"metas": map<string>string
}
}
```
#### NewProxy
创建代理的相关信息
```
{
"content": {
"user": {
"user": <string>,
"metas": map<string>string
},
"proxy_name": <string>,
"proxy_type": <string>,
"use_encryption": <bool>,
"use_compression": <bool>,
"group": <string>,
"group_key": <string>,
// tcp and udp only
"remote_port": <int>,
// http and https only
"custom_domains": []<string>,
"subdomain": <string>,
"locations": <string>,
"http_user": <string>,
"http_pwd": <string>,
"host_header_rewrite": <string>,
"headers": map<string>string,
"metas": map<string>string
}
}
```
### frps 中插件配置
```ini
[common]
bind_port = 7000
[plugin.user-manager]
addr = 127.0.0.1:9000
path = /handler
ops = Login
[plugin.port-manager]
addr = 127.0.0.1:9001
path = /handler
ops = NewProxy
```
addr: 插件监听的网络地址。
path: 插件监听的 HTTP 请求路径。
ops: 插件需要处理的操作列表,多个 op 以英文逗号分隔。
### 元数据
为了减少 frps 的代码修改,同时提高管理插件的扩展能力,在 frpc 的配置文件中引入自定义元数据的概念。元数据会在调用 RPC 请求时发送给插件。
元数据以 `meta_` 开头,可以配置多个,元数据分为两种,一种配置在 `common` 下,一种配置在各个 proxy 中。
```
# frpc.ini
[common]
server_addr = 127.0.0.1
server_port = 7000
user = fake
meta_token = fake
meta_version = 1.0.0
[ssh]
type = tcp
local_port = 22
remote_port = 6000
meta_id = 123
```

View File

@@ -0,0 +1,12 @@
FROM golang:1.19 AS building
COPY . /building
WORKDIR /building
RUN make frpc
FROM alpine:3
COPY --from=building /building/bin/frpc /usr/bin/frpc
ENTRYPOINT ["/usr/bin/frpc"]

View File

@@ -0,0 +1,12 @@
FROM golang:1.19 AS building
COPY . /building
WORKDIR /building
RUN make frps
FROM alpine:3
COPY --from=building /building/bin/frps /usr/bin/frps
ENTRYPOINT ["/usr/bin/frps"]

97
go.mod
View File

@@ -1,37 +1,76 @@
module github.com/fatedier/frp module github.com/fatedier/frp
go 1.12 go 1.19
require ( require (
github.com/armon/go-socks5 v0.0.0-20160902184237-e75332964ef5 github.com/armon/go-socks5 v0.0.0-20160902184237-e75332964ef5
github.com/coreos/go-oidc v2.2.1+incompatible github.com/coreos/go-oidc/v3 v3.4.0
github.com/fatedier/beego v0.0.0-20171024143340-6c6a4f5bd5eb github.com/fatedier/beego v0.0.0-20171024143340-6c6a4f5bd5eb
github.com/fatedier/golib v0.0.0-20181107124048-ff8cd814b049 github.com/fatedier/golib v0.1.1-0.20220321042308-c306138b83ac
github.com/fatedier/kcp-go v2.0.4-0.20190803094908-fe8645b0a904+incompatible github.com/fatedier/kcp-go v2.0.4-0.20190803094908-fe8645b0a904+incompatible
github.com/golang/snappy v0.0.0-20170215233205-553a64147049 // indirect github.com/go-playground/validator/v10 v10.11.0
github.com/gorilla/mux v1.7.3 github.com/google/uuid v1.3.0
github.com/gorilla/websocket v1.4.0 github.com/gorilla/mux v1.8.0
github.com/hashicorp/yamux v0.0.0-20181012175058-2f1d1f20f75d github.com/gorilla/websocket v1.5.0
github.com/inconshreveable/mousetrap v1.0.0 // indirect github.com/hashicorp/yamux v0.1.1
github.com/klauspost/cpuid v1.2.0 // indirect github.com/lucas-clemente/quic-go v0.31.0
github.com/klauspost/reedsolomon v1.9.1 // indirect github.com/onsi/ginkgo v1.16.4
github.com/mattn/go-runewidth v0.0.4 // indirect github.com/onsi/gomega v1.20.2
github.com/pires/go-proxyproto v0.0.0-20190111085350-4d51b51e3bfc github.com/pires/go-proxyproto v0.6.2
github.com/pquerna/cachecontrol v0.0.0-20180517163645-1555304b9b35 // indirect github.com/prometheus/client_golang v1.13.0
github.com/prometheus/client_golang v1.4.1 github.com/rodaine/table v1.0.1
github.com/rakyll/statik v0.1.1 github.com/spf13/cobra v1.1.3
github.com/rodaine/table v1.0.0 github.com/stretchr/testify v1.7.0
github.com/spf13/cobra v0.0.3 golang.org/x/net v0.4.0
github.com/spf13/pflag v1.0.1 // indirect golang.org/x/oauth2 v0.3.0
github.com/stretchr/testify v1.4.0 golang.org/x/time v0.0.0-20220210224613-90d013bbcef8
github.com/templexxx/cpufeat v0.0.0-20170927014610-3794dfbfb047 // indirect gopkg.in/ini.v1 v1.67.0
github.com/templexxx/xor v0.0.0-20170926022130-0af8e873c554 // indirect k8s.io/apimachinery v0.25.0
github.com/tjfoc/gmsm v0.0.0-20171124023159-98aa888b79d8 // indirect k8s.io/client-go v0.25.0
github.com/vaughan0/go-ini v0.0.0-20130923145212-a98ad7ee00ec )
github.com/xtaci/lossyconn v0.0.0-20190602105132-8df528c0c9ae // indirect
golang.org/x/net v0.0.0-20190724013045-ca1201d0de80 require (
golang.org/x/oauth2 v0.0.0-20200107190931-bf48bf16ab8d github.com/Azure/go-ntlmssp v0.0.0-20200615164410-66371956d46c // indirect
golang.org/x/text v0.3.2 // indirect github.com/beorn7/perks v1.0.1 // indirect
golang.org/x/time v0.0.0-20191024005414-555d28b269f0 github.com/cespare/xxhash/v2 v2.1.2 // indirect
gopkg.in/square/go-jose.v2 v2.4.1 // indirect github.com/davecgh/go-spew v1.1.1 // indirect
github.com/fsnotify/fsnotify v1.4.9 // 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/golang/mock v1.6.0 // indirect
github.com/golang/protobuf v1.5.2 // indirect
github.com/golang/snappy v0.0.3 // indirect
github.com/google/go-cmp v0.5.8 // indirect
github.com/google/pprof v0.0.0-20210720184732-4bb14d4b1be1 // indirect
github.com/inconshreveable/mousetrap v1.0.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/marten-seemann/qtls-go1-18 v0.1.3 // indirect
github.com/marten-seemann/qtls-go1-19 v0.1.1 // indirect
github.com/matttproud/golang_protobuf_extensions v1.0.1 // indirect
github.com/nxadm/tail v1.4.8 // indirect
github.com/onsi/ginkgo/v2 v2.2.0 // 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/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/exp v0.0.0-20220722155223-a9213eeb770e // indirect
golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4 // indirect
golang.org/x/sys v0.3.0 // indirect
golang.org/x/text v0.5.0 // indirect
golang.org/x/tools v0.1.12 // 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
gopkg.in/tomb.v1 v1.0.0-20141024135613-dd632973f1e7 // indirect
gopkg.in/yaml.v3 v3.0.1 // indirect
k8s.io/utils v0.0.0-20220728103510-ee6ede2d64ed // indirect
) )

934
go.sum

File diff suppressed because it is too large Load Diff

20
hack/run-e2e.sh Executable file
View File

@@ -0,0 +1,20 @@
#!/usr/bin/env bash
ROOT=$(unset CDPATH && cd $(dirname "${BASH_SOURCE[0]}")/.. && pwd)
which ginkgo &> /dev/null
if [ $? -ne 0 ]; then
echo "ginkgo not found, try to install..."
go install github.com/onsi/ginkgo/ginkgo@v1.16.5
fi
debug=false
if [ x${DEBUG} == x"true" ]; then
debug=true
fi
logLevel=debug
if [ x${LOG_LEVEL} != x"" ]; then
logLevel=${LOG_LEVEL}
fi
ginkgo -nodes=8 -slowSpecThreshold=20 ${ROOT}/test/e2e -- -frpc-path=${ROOT}/bin/frpc -frps-path=${ROOT}/bin/frps -log-level=${logLevel} -debug=${debug}

View File

@@ -1,151 +0,0 @@
// Copyright 2020 guylewin, guy@lewin.co.il
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package auth
import (
"fmt"
"github.com/fatedier/frp/models/consts"
"github.com/fatedier/frp/models/msg"
"github.com/vaughan0/go-ini"
)
type baseConfig struct {
// AuthenticationMethod specifies what authentication method to use to
// authenticate frpc with frps. If "token" is specified - token will be
// read into login message. If "oidc" is specified - OIDC (Open ID Connect)
// token will be issued using OIDC settings. By default, this value is "token".
AuthenticationMethod string `json:"authentication_method"`
// AuthenticateHeartBeats specifies whether to include authentication token in
// heartbeats sent to frps. By default, this value is false.
AuthenticateHeartBeats bool `json:"authenticate_heartbeats"`
// AuthenticateNewWorkConns specifies whether to include authentication token in
// new work connections sent to frps. By default, this value is false.
AuthenticateNewWorkConns bool `json:"authenticate_new_work_conns"`
}
func getDefaultBaseConf() baseConfig {
return baseConfig{
AuthenticationMethod: "token",
AuthenticateHeartBeats: false,
AuthenticateNewWorkConns: false,
}
}
func unmarshalBaseConfFromIni(conf ini.File) baseConfig {
var (
tmpStr string
ok bool
)
cfg := getDefaultBaseConf()
if tmpStr, ok = conf.Get("common", "authentication_method"); ok {
cfg.AuthenticationMethod = tmpStr
}
if tmpStr, ok = conf.Get("common", "authenticate_heartbeats"); ok && tmpStr == "true" {
cfg.AuthenticateHeartBeats = true
} else {
cfg.AuthenticateHeartBeats = false
}
if tmpStr, ok = conf.Get("common", "authenticate_new_work_conns"); ok && tmpStr == "true" {
cfg.AuthenticateNewWorkConns = true
} else {
cfg.AuthenticateNewWorkConns = false
}
return cfg
}
type AuthClientConfig struct {
baseConfig
oidcClientConfig
tokenConfig
}
func GetDefaultAuthClientConf() AuthClientConfig {
return AuthClientConfig{
baseConfig: getDefaultBaseConf(),
oidcClientConfig: getDefaultOidcClientConf(),
tokenConfig: getDefaultTokenConf(),
}
}
func UnmarshalAuthClientConfFromIni(conf ini.File) (cfg AuthClientConfig) {
cfg.baseConfig = unmarshalBaseConfFromIni(conf)
cfg.oidcClientConfig = unmarshalOidcClientConfFromIni(conf)
cfg.tokenConfig = unmarshalTokenConfFromIni(conf)
return cfg
}
type AuthServerConfig struct {
baseConfig
oidcServerConfig
tokenConfig
}
func GetDefaultAuthServerConf() AuthServerConfig {
return AuthServerConfig{
baseConfig: getDefaultBaseConf(),
oidcServerConfig: getDefaultOidcServerConf(),
tokenConfig: getDefaultTokenConf(),
}
}
func UnmarshalAuthServerConfFromIni(conf ini.File) (cfg AuthServerConfig) {
cfg.baseConfig = unmarshalBaseConfFromIni(conf)
cfg.oidcServerConfig = unmarshalOidcServerConfFromIni(conf)
cfg.tokenConfig = unmarshalTokenConfFromIni(conf)
return cfg
}
type Setter interface {
SetLogin(*msg.Login) error
SetPing(*msg.Ping) error
SetNewWorkConn(*msg.NewWorkConn) error
}
func NewAuthSetter(cfg AuthClientConfig) (authProvider Setter) {
switch cfg.AuthenticationMethod {
case consts.TokenAuthMethod:
authProvider = NewTokenAuth(cfg.baseConfig, cfg.tokenConfig)
case consts.OidcAuthMethod:
authProvider = NewOidcAuthSetter(cfg.baseConfig, cfg.oidcClientConfig)
default:
panic(fmt.Sprintf("wrong authentication method: '%s'", cfg.AuthenticationMethod))
}
return authProvider
}
type Verifier interface {
VerifyLogin(*msg.Login) error
VerifyPing(*msg.Ping) error
VerifyNewWorkConn(*msg.NewWorkConn) error
}
func NewAuthVerifier(cfg AuthServerConfig) (authVerifier Verifier) {
switch cfg.AuthenticationMethod {
case consts.TokenAuthMethod:
authVerifier = NewTokenAuth(cfg.baseConfig, cfg.tokenConfig)
case consts.OidcAuthMethod:
authVerifier = NewOidcAuthVerifier(cfg.baseConfig, cfg.oidcServerConfig)
}
return authVerifier
}

View File

@@ -1,315 +0,0 @@
// Copyright 2016 fatedier, fatedier@gmail.com
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package config
import (
"fmt"
"os"
"strconv"
"strings"
ini "github.com/vaughan0/go-ini"
"github.com/fatedier/frp/models/auth"
)
// ClientCommonConf contains information for a client service. It is
// recommended to use GetDefaultClientConf instead of creating this object
// directly, so that all unspecified fields have reasonable default values.
type ClientCommonConf struct {
auth.AuthClientConfig
// ServerAddr specifies the address of the server to connect to. By
// default, this value is "0.0.0.0".
ServerAddr string `json:"server_addr"`
// ServerPort specifies the port to connect to the server on. By default,
// this value is 7000.
ServerPort int `json:"server_port"`
// HttpProxy specifies a proxy address to connect to the server through. If
// this value is "", the server will be connected to directly. By default,
// this value is read from the "http_proxy" environment variable.
HttpProxy string `json:"http_proxy"`
// LogFile specifies a file where logs will be written to. This value will
// only be used if LogWay is set appropriately. By default, this value is
// "console".
LogFile string `json:"log_file"`
// LogWay specifies the way logging is managed. Valid values are "console"
// or "file". If "console" is used, logs will be printed to stdout. If
// "file" is used, logs will be printed to LogFile. By default, this value
// is "console".
LogWay string `json:"log_way"`
// LogLevel specifies the minimum log level. Valid values are "trace",
// "debug", "info", "warn", and "error". By default, this value is "info".
LogLevel string `json:"log_level"`
// LogMaxDays specifies the maximum number of days to store log information
// before deletion. This is only used if LogWay == "file". By default, this
// value is 0.
LogMaxDays int64 `json:"log_max_days"`
// DisableLogColor disables log colors when LogWay == "console" when set to
// true. By default, this value is false.
DisableLogColor bool `json:"disable_log_color"`
// AdminAddr specifies the address that the admin server binds to. By
// default, this value is "127.0.0.1".
AdminAddr string `json:"admin_addr"`
// AdminPort specifies the port for the admin server to listen on. If this
// value is 0, the admin server will not be started. By default, this value
// is 0.
AdminPort int `json:"admin_port"`
// AdminUser specifies the username that the admin server will use for
// login. By default, this value is "admin".
AdminUser string `json:"admin_user"`
// AdminPwd specifies the password that the admin server will use for
// login. By default, this value is "admin".
AdminPwd string `json:"admin_pwd"`
// AssetsDir specifies the local directory that the admin server will load
// resources from. If this value is "", assets will be loaded from the
// bundled executable using statik. By default, this value is "".
AssetsDir string `json:"assets_dir"`
// PoolCount specifies the number of connections the client will make to
// the server in advance. By default, this value is 0.
PoolCount int `json:"pool_count"`
// TcpMux toggles TCP stream multiplexing. This allows multiple requests
// from a client to share a single TCP connection. If this value is true,
// the server must have TCP multiplexing enabled as well. By default, this
// value is true.
TcpMux bool `json:"tcp_mux"`
// User specifies a prefix for proxy names to distinguish them from other
// clients. If this value is not "", proxy names will automatically be
// changed to "{user}.{proxy_name}". By default, this value is "".
User string `json:"user"`
// DnsServer specifies a DNS server address for FRPC to use. If this value
// is "", the default DNS will be used. By default, this value is "".
DnsServer string `json:"dns_server"`
// LoginFailExit controls whether or not the client should exit after a
// failed login attempt. If false, the client will retry until a login
// attempt succeeds. By default, this value is true.
LoginFailExit bool `json:"login_fail_exit"`
// Start specifies a set of enabled proxies by name. If this set is empty,
// all supplied proxies are enabled. By default, this value is an empty
// set.
Start map[string]struct{} `json:"start"`
// Protocol specifies the protocol to use when interacting with the server.
// Valid values are "tcp", "kcp", and "websocket". By default, this value
// is "tcp".
Protocol string `json:"protocol"`
// TLSEnable specifies whether or not TLS should be used when communicating
// with the server.
TLSEnable bool `json:"tls_enable"`
// HeartBeatInterval specifies at what interval heartbeats are sent to the
// server, in seconds. It is not recommended to change this value. By
// default, this value is 30.
HeartBeatInterval int64 `json:"heartbeat_interval"`
// HeartBeatTimeout specifies the maximum allowed heartbeat response delay
// before the connection is terminated, in seconds. It is not recommended
// to change this value. By default, this value is 90.
HeartBeatTimeout int64 `json:"heartbeat_timeout"`
// Client meta info
Metas map[string]string `json:"metas"`
}
// GetDefaultClientConf returns a client configuration with default values.
func GetDefaultClientConf() ClientCommonConf {
return ClientCommonConf{
ServerAddr: "0.0.0.0",
ServerPort: 7000,
HttpProxy: os.Getenv("http_proxy"),
LogFile: "console",
LogWay: "console",
LogLevel: "info",
LogMaxDays: 3,
DisableLogColor: false,
AdminAddr: "127.0.0.1",
AdminPort: 0,
AdminUser: "",
AdminPwd: "",
AssetsDir: "",
PoolCount: 1,
TcpMux: true,
User: "",
DnsServer: "",
LoginFailExit: true,
Start: make(map[string]struct{}),
Protocol: "tcp",
TLSEnable: false,
HeartBeatInterval: 30,
HeartBeatTimeout: 90,
Metas: make(map[string]string),
}
}
func UnmarshalClientConfFromIni(content string) (cfg ClientCommonConf, err error) {
cfg = GetDefaultClientConf()
conf, err := ini.Load(strings.NewReader(content))
if err != nil {
return ClientCommonConf{}, fmt.Errorf("parse ini conf file error: %v", err)
}
cfg.AuthClientConfig = auth.UnmarshalAuthClientConfFromIni(conf)
var (
tmpStr string
ok bool
v int64
)
if tmpStr, ok = conf.Get("common", "server_addr"); ok {
cfg.ServerAddr = tmpStr
}
if tmpStr, ok = conf.Get("common", "server_port"); ok {
v, err = strconv.ParseInt(tmpStr, 10, 64)
if err != nil {
err = fmt.Errorf("Parse conf error: invalid server_port")
return
}
cfg.ServerPort = int(v)
}
if tmpStr, ok = conf.Get("common", "disable_log_color"); ok && tmpStr == "true" {
cfg.DisableLogColor = true
}
if tmpStr, ok = conf.Get("common", "http_proxy"); ok {
cfg.HttpProxy = tmpStr
}
if tmpStr, ok = conf.Get("common", "log_file"); ok {
cfg.LogFile = tmpStr
if cfg.LogFile == "console" {
cfg.LogWay = "console"
} else {
cfg.LogWay = "file"
}
}
if tmpStr, ok = conf.Get("common", "log_level"); ok {
cfg.LogLevel = tmpStr
}
if tmpStr, ok = conf.Get("common", "log_max_days"); ok {
if v, err = strconv.ParseInt(tmpStr, 10, 64); err == nil {
cfg.LogMaxDays = v
}
}
if tmpStr, ok = conf.Get("common", "admin_addr"); ok {
cfg.AdminAddr = tmpStr
}
if tmpStr, ok = conf.Get("common", "admin_port"); ok {
if v, err = strconv.ParseInt(tmpStr, 10, 64); err == nil {
cfg.AdminPort = int(v)
} else {
err = fmt.Errorf("Parse conf error: invalid admin_port")
return
}
}
if tmpStr, ok = conf.Get("common", "admin_user"); ok {
cfg.AdminUser = tmpStr
}
if tmpStr, ok = conf.Get("common", "admin_pwd"); ok {
cfg.AdminPwd = tmpStr
}
if tmpStr, ok = conf.Get("common", "assets_dir"); ok {
cfg.AssetsDir = tmpStr
}
if tmpStr, ok = conf.Get("common", "pool_count"); ok {
if v, err = strconv.ParseInt(tmpStr, 10, 64); err == nil {
cfg.PoolCount = int(v)
}
}
if tmpStr, ok = conf.Get("common", "tcp_mux"); ok && tmpStr == "false" {
cfg.TcpMux = false
} else {
cfg.TcpMux = true
}
if tmpStr, ok = conf.Get("common", "user"); ok {
cfg.User = tmpStr
}
if tmpStr, ok = conf.Get("common", "dns_server"); ok {
cfg.DnsServer = tmpStr
}
if tmpStr, ok = conf.Get("common", "start"); ok {
proxyNames := strings.Split(tmpStr, ",")
for _, name := range proxyNames {
cfg.Start[strings.TrimSpace(name)] = struct{}{}
}
}
if tmpStr, ok = conf.Get("common", "login_fail_exit"); ok && tmpStr == "false" {
cfg.LoginFailExit = false
} else {
cfg.LoginFailExit = true
}
if tmpStr, ok = conf.Get("common", "protocol"); ok {
// Now it only support tcp and kcp and websocket.
if tmpStr != "tcp" && tmpStr != "kcp" && tmpStr != "websocket" {
err = fmt.Errorf("Parse conf error: invalid protocol")
return
}
cfg.Protocol = tmpStr
}
if tmpStr, ok = conf.Get("common", "tls_enable"); ok && tmpStr == "true" {
cfg.TLSEnable = true
} else {
cfg.TLSEnable = false
}
if tmpStr, ok = conf.Get("common", "heartbeat_timeout"); ok {
if v, err = strconv.ParseInt(tmpStr, 10, 64); err != nil {
err = fmt.Errorf("Parse conf error: invalid heartbeat_timeout")
return
} else {
cfg.HeartBeatTimeout = v
}
}
if tmpStr, ok = conf.Get("common", "heartbeat_interval"); ok {
if v, err = strconv.ParseInt(tmpStr, 10, 64); err != nil {
err = fmt.Errorf("Parse conf error: invalid heartbeat_interval")
return
} else {
cfg.HeartBeatInterval = v
}
}
for k, v := range conf.Section("common") {
if strings.HasPrefix(k, "meta_") {
cfg.Metas[strings.TrimPrefix(k, "meta_")] = v
}
}
return
}
func (cfg *ClientCommonConf) Check() (err error) {
if cfg.HeartBeatInterval <= 0 {
err = fmt.Errorf("Parse conf error: invalid heartbeat_interval")
return
}
if cfg.HeartBeatTimeout < cfg.HeartBeatInterval {
err = fmt.Errorf("Parse conf error: invalid heartbeat_timeout, heartbeat_timeout is less than heartbeat_interval")
return
}
return
}

File diff suppressed because it is too large Load Diff

View File

@@ -1,442 +0,0 @@
// Copyright 2016 fatedier, fatedier@gmail.com
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package config
import (
"fmt"
"strconv"
"strings"
ini "github.com/vaughan0/go-ini"
"github.com/fatedier/frp/models/auth"
plugin "github.com/fatedier/frp/models/plugin/server"
"github.com/fatedier/frp/utils/util"
)
// ServerCommonConf contains information for a server service. It is
// recommended to use GetDefaultServerConf instead of creating this object
// directly, so that all unspecified fields have reasonable default values.
type ServerCommonConf struct {
auth.AuthServerConfig
// BindAddr specifies the address that the server binds to. By default,
// this value is "0.0.0.0".
BindAddr string `json:"bind_addr"`
// BindPort specifies the port that the server listens on. By default, this
// value is 7000.
BindPort int `json:"bind_port"`
// BindUdpPort specifies the UDP port that the server listens on. If this
// value is 0, the server will not listen for UDP connections. By default,
// this value is 0
BindUdpPort int `json:"bind_udp_port"`
// BindKcpPort specifies the KCP port that the server listens on. If this
// value is 0, the server will not listen for KCP connections. By default,
// this value is 0.
KcpBindPort int `json:"kcp_bind_port"`
// ProxyBindAddr specifies the address that the proxy binds to. This value
// may be the same as BindAddr. By default, this value is "0.0.0.0".
ProxyBindAddr string `json:"proxy_bind_addr"`
// VhostHttpPort specifies the port that the server listens for HTTP Vhost
// requests. If this value is 0, the server will not listen for HTTP
// requests. By default, this value is 0.
VhostHttpPort int `json:"vhost_http_port"`
// VhostHttpsPort specifies the port that the server listens for HTTPS
// Vhost requests. If this value is 0, the server will not listen for HTTPS
// requests. By default, this value is 0.
VhostHttpsPort int `json:"vhost_https_port"`
// TcpMuxHttpConnectPort specifies the port that the server listens for TCP
// HTTP CONNECT requests. If the value is 0, the server will not multiplex TCP
// requests on one single port. If it's not - it will listen on this value for
// HTTP CONNECT requests. By default, this value is 0.
TcpMuxHttpConnectPort int `json:"tcpmux_httpconnect_port"`
// VhostHttpTimeout specifies the response header timeout for the Vhost
// HTTP server, in seconds. By default, this value is 60.
VhostHttpTimeout int64 `json:"vhost_http_timeout"`
// DashboardAddr specifies the address that the dashboard binds to. By
// default, this value is "0.0.0.0".
DashboardAddr string `json:"dashboard_addr"`
// DashboardPort specifies the port that the dashboard listens on. If this
// value is 0, the dashboard will not be started. By default, this value is
// 0.
DashboardPort int `json:"dashboard_port"`
// DashboardUser specifies the username that the dashboard will use for
// login. By default, this value is "admin".
DashboardUser string `json:"dashboard_user"`
// DashboardUser specifies the password that the dashboard will use for
// login. By default, this value is "admin".
DashboardPwd string `json:"dashboard_pwd"`
// EnablePrometheus will export prometheus metrics on {dashboard_addr}:{dashboard_port}
// in /metrics api.
EnablePrometheus bool `json:"enable_prometheus"`
// AssetsDir specifies the local directory that the dashboard will load
// resources from. If this value is "", assets will be loaded from the
// bundled executable using statik. By default, this value is "".
AssetsDir string `json:"asserts_dir"`
// LogFile specifies a file where logs will be written to. This value will
// only be used if LogWay is set appropriately. By default, this value is
// "console".
LogFile string `json:"log_file"`
// LogWay specifies the way logging is managed. Valid values are "console"
// or "file". If "console" is used, logs will be printed to stdout. If
// "file" is used, logs will be printed to LogFile. By default, this value
// is "console".
LogWay string `json:"log_way"`
// LogLevel specifies the minimum log level. Valid values are "trace",
// "debug", "info", "warn", and "error". By default, this value is "info".
LogLevel string `json:"log_level"`
// LogMaxDays specifies the maximum number of days to store log information
// before deletion. This is only used if LogWay == "file". By default, this
// value is 0.
LogMaxDays int64 `json:"log_max_days"`
// DisableLogColor disables log colors when LogWay == "console" when set to
// true. By default, this value is false.
DisableLogColor bool `json:"disable_log_color"`
// DetailedErrorsToClient defines whether to send the specific error (with
// debug info) to frpc. By default, this value is true.
DetailedErrorsToClient bool `json:"detailed_errors_to_client"`
// SubDomainHost specifies the domain that will be attached to sub-domains
// requested by the client when using Vhost proxying. For example, if this
// value is set to "frps.com" and the client requested the subdomain
// "test", the resulting URL would be "test.frps.com". By default, this
// value is "".
SubDomainHost string `json:"subdomain_host"`
// TcpMux toggles TCP stream multiplexing. This allows multiple requests
// from a client to share a single TCP connection. By default, this value
// is true.
TcpMux bool `json:"tcp_mux"`
// Custom404Page specifies a path to a custom 404 page to display. If this
// value is "", a default page will be displayed. By default, this value is
// "".
Custom404Page string `json:"custom_404_page"`
// AllowPorts specifies a set of ports that clients are able to proxy to.
// If the length of this value is 0, all ports are allowed. By default,
// this value is an empty set.
AllowPorts map[int]struct{}
// MaxPoolCount specifies the maximum pool size for each proxy. By default,
// this value is 5.
MaxPoolCount int64 `json:"max_pool_count"`
// MaxPortsPerClient specifies the maximum number of ports a single client
// may proxy to. If this value is 0, no limit will be applied. By default,
// this value is 0.
MaxPortsPerClient int64 `json:"max_ports_per_client"`
// TlsOnly specifies whether to only accept TLS-encrypted connections. By
// default, the value is false.
TlsOnly bool `json:"tls_only"`
// HeartBeatTimeout specifies the maximum time to wait for a heartbeat
// before terminating the connection. It is not recommended to change this
// value. By default, this value is 90.
HeartBeatTimeout int64 `json:"heart_beat_timeout"`
// UserConnTimeout specifies the maximum time to wait for a work
// connection. By default, this value is 10.
UserConnTimeout int64 `json:"user_conn_timeout"`
// HTTPPlugins specify the server plugins support HTTP protocol.
HTTPPlugins map[string]plugin.HTTPPluginOptions `json:"http_plugins"`
}
// GetDefaultServerConf returns a server configuration with reasonable
// defaults.
func GetDefaultServerConf() ServerCommonConf {
return ServerCommonConf{
BindAddr: "0.0.0.0",
BindPort: 7000,
BindUdpPort: 0,
KcpBindPort: 0,
ProxyBindAddr: "0.0.0.0",
VhostHttpPort: 0,
VhostHttpsPort: 0,
TcpMuxHttpConnectPort: 0,
VhostHttpTimeout: 60,
DashboardAddr: "0.0.0.0",
DashboardPort: 0,
DashboardUser: "admin",
DashboardPwd: "admin",
EnablePrometheus: false,
AssetsDir: "",
LogFile: "console",
LogWay: "console",
LogLevel: "info",
LogMaxDays: 3,
DisableLogColor: false,
DetailedErrorsToClient: true,
SubDomainHost: "",
TcpMux: true,
AllowPorts: make(map[int]struct{}),
MaxPoolCount: 5,
MaxPortsPerClient: 0,
TlsOnly: false,
HeartBeatTimeout: 90,
UserConnTimeout: 10,
Custom404Page: "",
HTTPPlugins: make(map[string]plugin.HTTPPluginOptions),
}
}
// UnmarshalServerConfFromIni parses the contents of a server configuration ini
// file and returns the resulting server configuration.
func UnmarshalServerConfFromIni(content string) (cfg ServerCommonConf, err error) {
cfg = GetDefaultServerConf()
conf, err := ini.Load(strings.NewReader(content))
if err != nil {
err = fmt.Errorf("parse ini conf file error: %v", err)
return ServerCommonConf{}, err
}
UnmarshalPluginsFromIni(conf, &cfg)
cfg.AuthServerConfig = auth.UnmarshalAuthServerConfFromIni(conf)
var (
tmpStr string
ok bool
v int64
)
if tmpStr, ok = conf.Get("common", "bind_addr"); ok {
cfg.BindAddr = tmpStr
}
if tmpStr, ok = conf.Get("common", "bind_port"); ok {
if v, err = strconv.ParseInt(tmpStr, 10, 64); err != nil {
err = fmt.Errorf("Parse conf error: invalid bind_port")
return
} else {
cfg.BindPort = int(v)
}
}
if tmpStr, ok = conf.Get("common", "bind_udp_port"); ok {
if v, err = strconv.ParseInt(tmpStr, 10, 64); err != nil {
err = fmt.Errorf("Parse conf error: invalid bind_udp_port")
return
} else {
cfg.BindUdpPort = int(v)
}
}
if tmpStr, ok = conf.Get("common", "kcp_bind_port"); ok {
if v, err = strconv.ParseInt(tmpStr, 10, 64); err != nil {
err = fmt.Errorf("Parse conf error: invalid kcp_bind_port")
return
} else {
cfg.KcpBindPort = int(v)
}
}
if tmpStr, ok = conf.Get("common", "proxy_bind_addr"); ok {
cfg.ProxyBindAddr = tmpStr
} else {
cfg.ProxyBindAddr = cfg.BindAddr
}
if tmpStr, ok = conf.Get("common", "vhost_http_port"); ok {
if v, err = strconv.ParseInt(tmpStr, 10, 64); err != nil {
err = fmt.Errorf("Parse conf error: invalid vhost_http_port")
return
} else {
cfg.VhostHttpPort = int(v)
}
} else {
cfg.VhostHttpPort = 0
}
if tmpStr, ok = conf.Get("common", "vhost_https_port"); ok {
if v, err = strconv.ParseInt(tmpStr, 10, 64); err != nil {
err = fmt.Errorf("Parse conf error: invalid vhost_https_port")
return
} else {
cfg.VhostHttpsPort = int(v)
}
} else {
cfg.VhostHttpsPort = 0
}
if tmpStr, ok = conf.Get("common", "tcpmux_httpconnect_port"); ok {
if v, err = strconv.ParseInt(tmpStr, 10, 64); err != nil {
err = fmt.Errorf("Parse conf error: invalid tcpmux_httpconnect_port")
return
} else {
cfg.TcpMuxHttpConnectPort = int(v)
}
} else {
cfg.TcpMuxHttpConnectPort = 0
}
if tmpStr, ok = conf.Get("common", "vhost_http_timeout"); ok {
v, errRet := strconv.ParseInt(tmpStr, 10, 64)
if errRet != nil || v < 0 {
err = fmt.Errorf("Parse conf error: invalid vhost_http_timeout")
return
} else {
cfg.VhostHttpTimeout = v
}
}
if tmpStr, ok = conf.Get("common", "dashboard_addr"); ok {
cfg.DashboardAddr = tmpStr
} else {
cfg.DashboardAddr = cfg.BindAddr
}
if tmpStr, ok = conf.Get("common", "dashboard_port"); ok {
if v, err = strconv.ParseInt(tmpStr, 10, 64); err != nil {
err = fmt.Errorf("Parse conf error: invalid dashboard_port")
return
} else {
cfg.DashboardPort = int(v)
}
} else {
cfg.DashboardPort = 0
}
if tmpStr, ok = conf.Get("common", "dashboard_user"); ok {
cfg.DashboardUser = tmpStr
}
if tmpStr, ok = conf.Get("common", "dashboard_pwd"); ok {
cfg.DashboardPwd = tmpStr
}
if tmpStr, ok = conf.Get("common", "enable_prometheus"); ok && tmpStr == "true" {
cfg.EnablePrometheus = true
}
if tmpStr, ok = conf.Get("common", "assets_dir"); ok {
cfg.AssetsDir = tmpStr
}
if tmpStr, ok = conf.Get("common", "log_file"); ok {
cfg.LogFile = tmpStr
if cfg.LogFile == "console" {
cfg.LogWay = "console"
} else {
cfg.LogWay = "file"
}
}
if tmpStr, ok = conf.Get("common", "log_level"); ok {
cfg.LogLevel = tmpStr
}
if tmpStr, ok = conf.Get("common", "log_max_days"); ok {
v, err = strconv.ParseInt(tmpStr, 10, 64)
if err == nil {
cfg.LogMaxDays = v
}
}
if tmpStr, ok = conf.Get("common", "disable_log_color"); ok && tmpStr == "true" {
cfg.DisableLogColor = true
}
if tmpStr, ok = conf.Get("common", "detailed_errors_to_client"); ok && tmpStr == "false" {
cfg.DetailedErrorsToClient = false
} else {
cfg.DetailedErrorsToClient = true
}
if allowPortsStr, ok := conf.Get("common", "allow_ports"); ok {
// e.g. 1000-2000,2001,2002,3000-4000
ports, errRet := util.ParseRangeNumbers(allowPortsStr)
if errRet != nil {
err = fmt.Errorf("Parse conf error: allow_ports: %v", errRet)
return
}
for _, port := range ports {
cfg.AllowPorts[int(port)] = struct{}{}
}
}
if tmpStr, ok = conf.Get("common", "max_pool_count"); ok {
if v, err = strconv.ParseInt(tmpStr, 10, 64); err != nil {
err = fmt.Errorf("Parse conf error: invalid max_pool_count")
return
} else {
if v < 0 {
err = fmt.Errorf("Parse conf error: invalid max_pool_count")
return
}
cfg.MaxPoolCount = v
}
}
if tmpStr, ok = conf.Get("common", "max_ports_per_client"); ok {
if v, err = strconv.ParseInt(tmpStr, 10, 64); err != nil {
err = fmt.Errorf("Parse conf error: invalid max_ports_per_client")
return
} else {
if v < 0 {
err = fmt.Errorf("Parse conf error: invalid max_ports_per_client")
return
}
cfg.MaxPortsPerClient = v
}
}
if tmpStr, ok = conf.Get("common", "subdomain_host"); ok {
cfg.SubDomainHost = strings.ToLower(strings.TrimSpace(tmpStr))
}
if tmpStr, ok = conf.Get("common", "tcp_mux"); ok && tmpStr == "false" {
cfg.TcpMux = false
} else {
cfg.TcpMux = true
}
if tmpStr, ok = conf.Get("common", "custom_404_page"); ok {
cfg.Custom404Page = tmpStr
}
if tmpStr, ok = conf.Get("common", "heartbeat_timeout"); ok {
v, errRet := strconv.ParseInt(tmpStr, 10, 64)
if errRet != nil {
err = fmt.Errorf("Parse conf error: heartbeat_timeout is incorrect")
return
} else {
cfg.HeartBeatTimeout = v
}
}
if tmpStr, ok = conf.Get("common", "tls_only"); ok && tmpStr == "true" {
cfg.TlsOnly = true
} else {
cfg.TlsOnly = false
}
return
}
func UnmarshalPluginsFromIni(sections ini.File, cfg *ServerCommonConf) {
for name, section := range sections {
if strings.HasPrefix(name, "plugin.") {
name = strings.TrimSpace(strings.TrimPrefix(name, "plugin."))
options := plugin.HTTPPluginOptions{
Name: name,
Addr: section["addr"],
Path: section["path"],
Ops: strings.Split(section["ops"], ","),
}
for i, _ := range options.Ops {
options.Ops[i] = strings.TrimSpace(options.Ops[i])
}
cfg.HTTPPlugins[name] = options
}
}
}
func (cfg *ServerCommonConf) Check() (err error) {
return
}

View File

@@ -1,64 +0,0 @@
package config
import (
"bytes"
"io/ioutil"
"os"
"strings"
"text/template"
)
var (
glbEnvs map[string]string
)
func init() {
glbEnvs = make(map[string]string)
envs := os.Environ()
for _, env := range envs {
kv := strings.Split(env, "=")
if len(kv) != 2 {
continue
}
glbEnvs[kv[0]] = kv[1]
}
}
type Values struct {
Envs map[string]string // environment vars
}
func GetValues() *Values {
return &Values{
Envs: glbEnvs,
}
}
func RenderContent(in string) (out string, err error) {
tmpl, errRet := template.New("frp").Parse(in)
if errRet != nil {
err = errRet
return
}
buffer := bytes.NewBufferString("")
v := GetValues()
err = tmpl.Execute(buffer, v)
if err != nil {
return
}
out = buffer.String()
return
}
func GetRenderedConfFromFile(path string) (out string, err error) {
var b []byte
b, err = ioutil.ReadFile(path)
if err != nil {
return
}
content := string(b)
out, err = RenderContent(content)
return
}

View File

@@ -1,213 +0,0 @@
// Copyright 2018 fatedier, fatedier@gmail.com
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package config
import (
"fmt"
"reflect"
"strconv"
"github.com/fatedier/frp/models/consts"
ini "github.com/vaughan0/go-ini"
)
var (
visitorConfTypeMap map[string]reflect.Type
)
func init() {
visitorConfTypeMap = make(map[string]reflect.Type)
visitorConfTypeMap[consts.StcpProxy] = reflect.TypeOf(StcpVisitorConf{})
visitorConfTypeMap[consts.XtcpProxy] = reflect.TypeOf(XtcpVisitorConf{})
}
type VisitorConf interface {
GetBaseInfo() *BaseVisitorConf
Compare(cmp VisitorConf) bool
UnmarshalFromIni(prefix string, name string, section ini.Section) error
Check() error
}
func NewVisitorConfByType(cfgType string) VisitorConf {
v, ok := visitorConfTypeMap[cfgType]
if !ok {
return nil
}
cfg := reflect.New(v).Interface().(VisitorConf)
return cfg
}
func NewVisitorConfFromIni(prefix string, name string, section ini.Section) (cfg VisitorConf, err error) {
cfgType := section["type"]
if cfgType == "" {
err = fmt.Errorf("visitor [%s] type shouldn't be empty", name)
return
}
cfg = NewVisitorConfByType(cfgType)
if cfg == nil {
err = fmt.Errorf("visitor [%s] type [%s] error", name, cfgType)
return
}
if err = cfg.UnmarshalFromIni(prefix, name, section); err != nil {
return
}
if err = cfg.Check(); err != nil {
return
}
return
}
type BaseVisitorConf struct {
ProxyName string `json:"proxy_name"`
ProxyType string `json:"proxy_type"`
UseEncryption bool `json:"use_encryption"`
UseCompression bool `json:"use_compression"`
Role string `json:"role"`
Sk string `json:"sk"`
ServerName string `json:"server_name"`
BindAddr string `json:"bind_addr"`
BindPort int `json:"bind_port"`
}
func (cfg *BaseVisitorConf) GetBaseInfo() *BaseVisitorConf {
return cfg
}
func (cfg *BaseVisitorConf) compare(cmp *BaseVisitorConf) bool {
if cfg.ProxyName != cmp.ProxyName ||
cfg.ProxyType != cmp.ProxyType ||
cfg.UseEncryption != cmp.UseEncryption ||
cfg.UseCompression != cmp.UseCompression ||
cfg.Role != cmp.Role ||
cfg.Sk != cmp.Sk ||
cfg.ServerName != cmp.ServerName ||
cfg.BindAddr != cmp.BindAddr ||
cfg.BindPort != cmp.BindPort {
return false
}
return true
}
func (cfg *BaseVisitorConf) check() (err error) {
if cfg.Role != "visitor" {
err = fmt.Errorf("invalid role")
return
}
if cfg.BindAddr == "" {
err = fmt.Errorf("bind_addr shouldn't be empty")
return
}
if cfg.BindPort <= 0 {
err = fmt.Errorf("bind_port is required")
return
}
return
}
func (cfg *BaseVisitorConf) UnmarshalFromIni(prefix string, name string, section ini.Section) (err error) {
var (
tmpStr string
ok bool
)
cfg.ProxyName = prefix + name
cfg.ProxyType = section["type"]
if tmpStr, ok = section["use_encryption"]; ok && tmpStr == "true" {
cfg.UseEncryption = true
}
if tmpStr, ok = section["use_compression"]; ok && tmpStr == "true" {
cfg.UseCompression = true
}
cfg.Role = section["role"]
if cfg.Role != "visitor" {
return fmt.Errorf("Parse conf error: proxy [%s] incorrect role [%s]", name, cfg.Role)
}
cfg.Sk = section["sk"]
cfg.ServerName = prefix + section["server_name"]
if cfg.BindAddr = section["bind_addr"]; cfg.BindAddr == "" {
cfg.BindAddr = "127.0.0.1"
}
if tmpStr, ok = section["bind_port"]; ok {
if cfg.BindPort, err = strconv.Atoi(tmpStr); err != nil {
return fmt.Errorf("Parse conf error: proxy [%s] bind_port incorrect", name)
}
} else {
return fmt.Errorf("Parse conf error: proxy [%s] bind_port not found", name)
}
return nil
}
type StcpVisitorConf struct {
BaseVisitorConf
}
func (cfg *StcpVisitorConf) Compare(cmp VisitorConf) bool {
cmpConf, ok := cmp.(*StcpVisitorConf)
if !ok {
return false
}
if !cfg.BaseVisitorConf.compare(&cmpConf.BaseVisitorConf) {
return false
}
return true
}
func (cfg *StcpVisitorConf) UnmarshalFromIni(prefix string, name string, section ini.Section) (err error) {
if err = cfg.BaseVisitorConf.UnmarshalFromIni(prefix, name, section); err != nil {
return
}
return
}
func (cfg *StcpVisitorConf) Check() (err error) {
if err = cfg.BaseVisitorConf.check(); err != nil {
return
}
return
}
type XtcpVisitorConf struct {
BaseVisitorConf
}
func (cfg *XtcpVisitorConf) Compare(cmp VisitorConf) bool {
cmpConf, ok := cmp.(*XtcpVisitorConf)
if !ok {
return false
}
if !cfg.BaseVisitorConf.compare(&cmpConf.BaseVisitorConf) {
return false
}
return true
}
func (cfg *XtcpVisitorConf) UnmarshalFromIni(prefix string, name string, section ini.Section) (err error) {
if err = cfg.BaseVisitorConf.UnmarshalFromIni(prefix, name, section); err != nil {
return
}
return
}
func (cfg *XtcpVisitorConf) Check() (err error) {
if err = cfg.BaseVisitorConf.check(); err != nil {
return
}
return
}

View File

@@ -1,8 +0,0 @@
package metrics
import (
"github.com/fatedier/frp/models/metrics/aggregate"
)
var EnableMem = aggregate.EnableMem
var EnablePrometheus = aggregate.EnablePrometheus

View File

@@ -1,194 +0,0 @@
// Copyright 2016 fatedier, fatedier@gmail.com
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package msg
import "net"
const (
TypeLogin = 'o'
TypeLoginResp = '1'
TypeNewProxy = 'p'
TypeNewProxyResp = '2'
TypeCloseProxy = 'c'
TypeNewWorkConn = 'w'
TypeReqWorkConn = 'r'
TypeStartWorkConn = 's'
TypeNewVisitorConn = 'v'
TypeNewVisitorConnResp = '3'
TypePing = 'h'
TypePong = '4'
TypeUdpPacket = 'u'
TypeNatHoleVisitor = 'i'
TypeNatHoleClient = 'n'
TypeNatHoleResp = 'm'
TypeNatHoleClientDetectOK = 'd'
TypeNatHoleSid = '5'
)
var (
msgTypeMap = map[byte]interface{}{
TypeLogin: Login{},
TypeLoginResp: LoginResp{},
TypeNewProxy: NewProxy{},
TypeNewProxyResp: NewProxyResp{},
TypeCloseProxy: CloseProxy{},
TypeNewWorkConn: NewWorkConn{},
TypeReqWorkConn: ReqWorkConn{},
TypeStartWorkConn: StartWorkConn{},
TypeNewVisitorConn: NewVisitorConn{},
TypeNewVisitorConnResp: NewVisitorConnResp{},
TypePing: Ping{},
TypePong: Pong{},
TypeUdpPacket: UdpPacket{},
TypeNatHoleVisitor: NatHoleVisitor{},
TypeNatHoleClient: NatHoleClient{},
TypeNatHoleResp: NatHoleResp{},
TypeNatHoleClientDetectOK: NatHoleClientDetectOK{},
TypeNatHoleSid: NatHoleSid{},
}
)
// When frpc start, client send this message to login to server.
type Login struct {
Version string `json:"version"`
Hostname string `json:"hostname"`
Os string `json:"os"`
Arch string `json:"arch"`
User string `json:"user"`
PrivilegeKey string `json:"privilege_key"`
Timestamp int64 `json:"timestamp"`
RunId string `json:"run_id"`
Metas map[string]string `json:"metas"`
// Some global configures.
PoolCount int `json:"pool_count"`
}
type LoginResp struct {
Version string `json:"version"`
RunId string `json:"run_id"`
ServerUdpPort int `json:"server_udp_port"`
Error string `json:"error"`
}
// When frpc login success, send this message to frps for running a new proxy.
type NewProxy struct {
ProxyName string `json:"proxy_name"`
ProxyType string `json:"proxy_type"`
UseEncryption bool `json:"use_encryption"`
UseCompression bool `json:"use_compression"`
Group string `json:"group"`
GroupKey string `json:"group_key"`
Metas map[string]string `json:"metas"`
// tcp and udp only
RemotePort int `json:"remote_port"`
// http and https only
CustomDomains []string `json:"custom_domains"`
SubDomain string `json:"subdomain"`
Locations []string `json:"locations"`
HttpUser string `json:"http_user"`
HttpPwd string `json:"http_pwd"`
HostHeaderRewrite string `json:"host_header_rewrite"`
Headers map[string]string `json:"headers"`
// stcp
Sk string `json:"sk"`
// tcpmux
Multiplexer string `json:"multiplexer"`
}
type NewProxyResp struct {
ProxyName string `json:"proxy_name"`
RemoteAddr string `json:"remote_addr"`
Error string `json:"error"`
}
type CloseProxy struct {
ProxyName string `json:"proxy_name"`
}
type NewWorkConn struct {
RunId string `json:"run_id"`
PrivilegeKey string `json:"privilege_key"`
Timestamp int64 `json:"timestamp"`
}
type ReqWorkConn struct {
}
type StartWorkConn struct {
ProxyName string `json:"proxy_name"`
SrcAddr string `json:"src_addr"`
DstAddr string `json:"dst_addr"`
SrcPort uint16 `json:"src_port"`
DstPort uint16 `json:"dst_port"`
Error string `json:"error"`
}
type NewVisitorConn struct {
ProxyName string `json:"proxy_name"`
SignKey string `json:"sign_key"`
Timestamp int64 `json:"timestamp"`
UseEncryption bool `json:"use_encryption"`
UseCompression bool `json:"use_compression"`
}
type NewVisitorConnResp struct {
ProxyName string `json:"proxy_name"`
Error string `json:"error"`
}
type Ping struct {
PrivilegeKey string `json:"privilege_key"`
Timestamp int64 `json:"timestamp"`
}
type Pong struct {
Error string `json:"error"`
}
type UdpPacket struct {
Content string `json:"c"`
LocalAddr *net.UDPAddr `json:"l"`
RemoteAddr *net.UDPAddr `json:"r"`
}
type NatHoleVisitor struct {
ProxyName string `json:"proxy_name"`
SignKey string `json:"sign_key"`
Timestamp int64 `json:"timestamp"`
}
type NatHoleClient struct {
ProxyName string `json:"proxy_name"`
Sid string `json:"sid"`
}
type NatHoleResp struct {
Sid string `json:"sid"`
VisitorAddr string `json:"visitor_addr"`
ClientAddr string `json:"client_addr"`
Error string `json:"error"`
}
type NatHoleClientDetectOK struct {
}
type NatHoleSid struct {
Sid string `json:"sid"`
}

View File

@@ -1,105 +0,0 @@
// Copyright 2019 fatedier, fatedier@gmail.com
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package plugin
import (
"context"
"errors"
"fmt"
"github.com/fatedier/frp/utils/util"
"github.com/fatedier/frp/utils/xlog"
)
type Manager struct {
loginPlugins []Plugin
newProxyPlugins []Plugin
}
func NewManager() *Manager {
return &Manager{
loginPlugins: make([]Plugin, 0),
newProxyPlugins: make([]Plugin, 0),
}
}
func (m *Manager) Register(p Plugin) {
if p.IsSupport(OpLogin) {
m.loginPlugins = append(m.loginPlugins, p)
}
if p.IsSupport(OpNewProxy) {
m.newProxyPlugins = append(m.newProxyPlugins, p)
}
}
func (m *Manager) Login(content *LoginContent) (*LoginContent, error) {
var (
res = &Response{
Reject: false,
Unchange: true,
}
retContent interface{}
err error
)
reqid, _ := util.RandId()
xl := xlog.New().AppendPrefix("reqid: " + reqid)
ctx := xlog.NewContext(context.Background(), xl)
ctx = NewReqidContext(ctx, reqid)
for _, p := range m.loginPlugins {
res, retContent, err = p.Handle(ctx, OpLogin, *content)
if err != nil {
xl.Warn("send Login request to plugin [%s] error: %v", p.Name(), err)
return nil, errors.New("send Login request to plugin error")
}
if res.Reject {
return nil, fmt.Errorf("%s", res.RejectReason)
}
if !res.Unchange {
content = retContent.(*LoginContent)
}
}
return content, nil
}
func (m *Manager) NewProxy(content *NewProxyContent) (*NewProxyContent, error) {
var (
res = &Response{
Reject: false,
Unchange: true,
}
retContent interface{}
err error
)
reqid, _ := util.RandId()
xl := xlog.New().AppendPrefix("reqid: " + reqid)
ctx := xlog.NewContext(context.Background(), xl)
ctx = NewReqidContext(ctx, reqid)
for _, p := range m.newProxyPlugins {
res, retContent, err = p.Handle(ctx, OpNewProxy, *content)
if err != nil {
xl.Warn("send NewProxy request to plugin [%s] error: %v", p.Name(), err)
return nil, errors.New("send NewProxy request to plugin error")
}
if res.Reject {
return nil, fmt.Errorf("%s", res.RejectReason)
}
if !res.Unchange {
content = retContent.(*NewProxyContent)
}
}
return content, nil
}

View File

@@ -11,11 +11,13 @@ echo "build version: $frp_version"
# cross_compiles # cross_compiles
make -f ./Makefile.cross-compiles make -f ./Makefile.cross-compiles
rm -rf ./packages rm -rf ./release/packages
mkdir ./packages mkdir -p ./release/packages
os_all='linux windows darwin freebsd' os_all='linux windows darwin freebsd'
arch_all='386 amd64 arm arm64 mips64 mips64le mips mipsle' arch_all='386 amd64 arm arm64 mips64 mips64le mips mipsle riscv64'
cd ./release
for os in $os_all; do for os in $os_all; do
for arch in $arch_all; do for arch in $arch_all; do
@@ -43,8 +45,8 @@ for os in $os_all; do
mv ./frpc_${os}_${arch} ${frp_path}/frpc mv ./frpc_${os}_${arch} ${frp_path}/frpc
mv ./frps_${os}_${arch} ${frp_path}/frps mv ./frps_${os}_${arch} ${frp_path}/frps
fi fi
cp ./LICENSE ${frp_path} cp ../LICENSE ${frp_path}
cp -rf ./conf/* ${frp_path} cp -rf ../conf/* ${frp_path}
# packages # packages
cd ./packages cd ./packages
@@ -57,3 +59,5 @@ for os in $os_all; do
rm -rf ${frp_path} rm -rf ${frp_path}
done done
done done
cd -

108
pkg/auth/auth.go Normal file
View File

@@ -0,0 +1,108 @@
// Copyright 2020 guylewin, guy@lewin.co.il
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package auth
import (
"fmt"
"github.com/fatedier/frp/pkg/consts"
"github.com/fatedier/frp/pkg/msg"
)
type BaseConfig struct {
// AuthenticationMethod specifies what authentication method to use to
// authenticate frpc with frps. If "token" is specified - token will be
// read into login message. If "oidc" is specified - OIDC (Open ID Connect)
// token will be issued using OIDC settings. By default, this value is "token".
AuthenticationMethod string `ini:"authentication_method" json:"authentication_method"`
// AuthenticateHeartBeats specifies whether to include authentication token in
// heartbeats sent to frps. By default, this value is false.
AuthenticateHeartBeats bool `ini:"authenticate_heartbeats" json:"authenticate_heartbeats"`
// AuthenticateNewWorkConns specifies whether to include authentication token in
// new work connections sent to frps. By default, this value is false.
AuthenticateNewWorkConns bool `ini:"authenticate_new_work_conns" json:"authenticate_new_work_conns"`
}
func getDefaultBaseConf() BaseConfig {
return BaseConfig{
AuthenticationMethod: "token",
AuthenticateHeartBeats: false,
AuthenticateNewWorkConns: false,
}
}
type ClientConfig struct {
BaseConfig `ini:",extends"`
OidcClientConfig `ini:",extends"`
TokenConfig `ini:",extends"`
}
func GetDefaultClientConf() ClientConfig {
return ClientConfig{
BaseConfig: getDefaultBaseConf(),
OidcClientConfig: getDefaultOidcClientConf(),
TokenConfig: getDefaultTokenConf(),
}
}
type ServerConfig struct {
BaseConfig `ini:",extends"`
OidcServerConfig `ini:",extends"`
TokenConfig `ini:",extends"`
}
func GetDefaultServerConf() ServerConfig {
return ServerConfig{
BaseConfig: getDefaultBaseConf(),
OidcServerConfig: getDefaultOidcServerConf(),
TokenConfig: getDefaultTokenConf(),
}
}
type Setter interface {
SetLogin(*msg.Login) error
SetPing(*msg.Ping) error
SetNewWorkConn(*msg.NewWorkConn) error
}
func NewAuthSetter(cfg ClientConfig) (authProvider Setter) {
switch cfg.AuthenticationMethod {
case consts.TokenAuthMethod:
authProvider = NewTokenAuth(cfg.BaseConfig, cfg.TokenConfig)
case consts.OidcAuthMethod:
authProvider = NewOidcAuthSetter(cfg.BaseConfig, cfg.OidcClientConfig)
default:
panic(fmt.Sprintf("wrong authentication method: '%s'", cfg.AuthenticationMethod))
}
return authProvider
}
type Verifier interface {
VerifyLogin(*msg.Login) error
VerifyPing(*msg.Ping) error
VerifyNewWorkConn(*msg.NewWorkConn) error
}
func NewAuthVerifier(cfg ServerConfig) (authVerifier Verifier) {
switch cfg.AuthenticationMethod {
case consts.TokenAuthMethod:
authVerifier = NewTokenAuth(cfg.BaseConfig, cfg.TokenConfig)
case consts.OidcAuthMethod:
authVerifier = NewOidcAuthVerifier(cfg.BaseConfig, cfg.OidcServerConfig)
}
return authVerifier
}

View File

@@ -18,90 +18,72 @@ import (
"context" "context"
"fmt" "fmt"
"github.com/fatedier/frp/models/msg" "github.com/coreos/go-oidc/v3/oidc"
"github.com/coreos/go-oidc"
"github.com/vaughan0/go-ini"
"golang.org/x/oauth2/clientcredentials" "golang.org/x/oauth2/clientcredentials"
"github.com/fatedier/frp/pkg/msg"
) )
type oidcClientConfig struct { type OidcClientConfig struct {
// OidcClientId specifies the client ID to use to get a token in OIDC // OidcClientID specifies the client ID to use to get a token in OIDC
// authentication if AuthenticationMethod == "oidc". By default, this value // authentication if AuthenticationMethod == "oidc". By default, this value
// is "". // is "".
OidcClientId string `json:"oidc_client_id"` OidcClientID string `ini:"oidc_client_id" json:"oidc_client_id"`
// OidcClientSecret specifies the client secret to use to get a token in OIDC // OidcClientSecret specifies the client secret to use to get a token in OIDC
// authentication if AuthenticationMethod == "oidc". By default, this value // authentication if AuthenticationMethod == "oidc". By default, this value
// is "". // is "".
OidcClientSecret string `json:"oidc_client_secret"` OidcClientSecret string `ini:"oidc_client_secret" json:"oidc_client_secret"`
// OidcAudience specifies the audience of the token in OIDC authentication // OidcAudience specifies the audience of the token in OIDC authentication
//if AuthenticationMethod == "oidc". By default, this value is "". // if AuthenticationMethod == "oidc". By default, this value is "".
OidcAudience string `json:"oidc_audience"` OidcAudience string `ini:"oidc_audience" json:"oidc_audience"`
// OidcTokenEndpointUrl specifies the URL which implements OIDC Token Endpoint. // OidcScope specifies the scope of the token in OIDC authentication
// if AuthenticationMethod == "oidc". By default, this value is "".
OidcScope string `ini:"oidc_scope" json:"oidc_scope"`
// OidcTokenEndpointURL specifies the URL which implements OIDC Token Endpoint.
// It will be used to get an OIDC token if AuthenticationMethod == "oidc". // It will be used to get an OIDC token if AuthenticationMethod == "oidc".
// By default, this value is "". // By default, this value is "".
OidcTokenEndpointUrl string `json:"oidc_token_endpoint_url"` OidcTokenEndpointURL string `ini:"oidc_token_endpoint_url" json:"oidc_token_endpoint_url"`
// OidcAdditionalEndpointParams specifies additional parameters to be sent
// this field will be transfer to map[string][]string in OIDC token generator
// The field will be set by prefix "oidc_additional_"
OidcAdditionalEndpointParams map[string]string `ini:"-" json:"oidc_additional_endpoint_params"`
} }
func getDefaultOidcClientConf() oidcClientConfig { func getDefaultOidcClientConf() OidcClientConfig {
return oidcClientConfig{ return OidcClientConfig{
OidcClientId: "", OidcClientID: "",
OidcClientSecret: "", OidcClientSecret: "",
OidcAudience: "", OidcAudience: "",
OidcTokenEndpointUrl: "", OidcScope: "",
OidcTokenEndpointURL: "",
OidcAdditionalEndpointParams: make(map[string]string),
} }
} }
func unmarshalOidcClientConfFromIni(conf ini.File) oidcClientConfig { type OidcServerConfig struct {
var (
tmpStr string
ok bool
)
cfg := getDefaultOidcClientConf()
if tmpStr, ok = conf.Get("common", "oidc_client_id"); ok {
cfg.OidcClientId = tmpStr
}
if tmpStr, ok = conf.Get("common", "oidc_client_secret"); ok {
cfg.OidcClientSecret = tmpStr
}
if tmpStr, ok = conf.Get("common", "oidc_audience"); ok {
cfg.OidcAudience = tmpStr
}
if tmpStr, ok = conf.Get("common", "oidc_token_endpoint_url"); ok {
cfg.OidcTokenEndpointUrl = tmpStr
}
return cfg
}
type oidcServerConfig struct {
// OidcIssuer specifies the issuer to verify OIDC tokens with. This issuer // OidcIssuer specifies the issuer to verify OIDC tokens with. This issuer
// will be used to load public keys to verify signature and will be compared // will be used to load public keys to verify signature and will be compared
// with the issuer claim in the OIDC token. It will be used if // with the issuer claim in the OIDC token. It will be used if
// AuthenticationMethod == "oidc". By default, this value is "". // AuthenticationMethod == "oidc". By default, this value is "".
OidcIssuer string `json:"oidc_issuer"` OidcIssuer string `ini:"oidc_issuer" json:"oidc_issuer"`
// OidcAudience specifies the audience OIDC tokens should contain when validated. // OidcAudience specifies the audience OIDC tokens should contain when validated.
// If this value is empty, audience ("client ID") verification will be skipped. // If this value is empty, audience ("client ID") verification will be skipped.
// It will be used when AuthenticationMethod == "oidc". By default, this // It will be used when AuthenticationMethod == "oidc". By default, this
// value is "". // value is "".
OidcAudience string `json:"oidc_audience"` OidcAudience string `ini:"oidc_audience" json:"oidc_audience"`
// OidcSkipExpiryCheck specifies whether to skip checking if the OIDC token is // OidcSkipExpiryCheck specifies whether to skip checking if the OIDC token is
// expired. It will be used when AuthenticationMethod == "oidc". By default, this // expired. It will be used when AuthenticationMethod == "oidc". By default, this
// value is false. // value is false.
OidcSkipExpiryCheck bool `json:"oidc_skip_expiry_check"` OidcSkipExpiryCheck bool `ini:"oidc_skip_expiry_check" json:"oidc_skip_expiry_check"`
// OidcSkipIssuerCheck specifies whether to skip checking if the OIDC token's // OidcSkipIssuerCheck specifies whether to skip checking if the OIDC token's
// issuer claim matches the issuer specified in OidcIssuer. It will be used when // issuer claim matches the issuer specified in OidcIssuer. It will be used when
// AuthenticationMethod == "oidc". By default, this value is false. // AuthenticationMethod == "oidc". By default, this value is false.
OidcSkipIssuerCheck bool `json:"oidc_skip_issuer_check"` OidcSkipIssuerCheck bool `ini:"oidc_skip_issuer_check" json:"oidc_skip_issuer_check"`
} }
func getDefaultOidcServerConf() oidcServerConfig { func getDefaultOidcServerConf() OidcServerConfig {
return oidcServerConfig{ return OidcServerConfig{
OidcIssuer: "", OidcIssuer: "",
OidcAudience: "", OidcAudience: "",
OidcSkipExpiryCheck: false, OidcSkipExpiryCheck: false,
@@ -109,53 +91,32 @@ func getDefaultOidcServerConf() oidcServerConfig {
} }
} }
func unmarshalOidcServerConfFromIni(conf ini.File) oidcServerConfig {
var (
tmpStr string
ok bool
)
cfg := getDefaultOidcServerConf()
if tmpStr, ok = conf.Get("common", "oidc_issuer"); ok {
cfg.OidcIssuer = tmpStr
}
if tmpStr, ok = conf.Get("common", "oidc_audience"); ok {
cfg.OidcAudience = tmpStr
}
if tmpStr, ok = conf.Get("common", "oidc_skip_expiry_check"); ok && tmpStr == "true" {
cfg.OidcSkipExpiryCheck = true
} else {
cfg.OidcSkipExpiryCheck = false
}
if tmpStr, ok = conf.Get("common", "oidc_skip_issuer_check"); ok && tmpStr == "true" {
cfg.OidcSkipIssuerCheck = true
} else {
cfg.OidcSkipIssuerCheck = false
}
return cfg
}
type OidcAuthProvider struct { type OidcAuthProvider struct {
baseConfig BaseConfig
tokenGenerator *clientcredentials.Config tokenGenerator *clientcredentials.Config
} }
func NewOidcAuthSetter(baseCfg baseConfig, cfg oidcClientConfig) *OidcAuthProvider { func NewOidcAuthSetter(baseCfg BaseConfig, cfg OidcClientConfig) *OidcAuthProvider {
eps := make(map[string][]string)
for k, v := range cfg.OidcAdditionalEndpointParams {
eps[k] = []string{v}
}
if cfg.OidcAudience != "" {
eps["audience"] = []string{cfg.OidcAudience}
}
tokenGenerator := &clientcredentials.Config{ tokenGenerator := &clientcredentials.Config{
ClientID: cfg.OidcClientId, ClientID: cfg.OidcClientID,
ClientSecret: cfg.OidcClientSecret, ClientSecret: cfg.OidcClientSecret,
Scopes: []string{cfg.OidcAudience}, Scopes: []string{cfg.OidcScope},
TokenURL: cfg.OidcTokenEndpointUrl, TokenURL: cfg.OidcTokenEndpointURL,
EndpointParams: eps,
} }
return &OidcAuthProvider{ return &OidcAuthProvider{
baseConfig: baseCfg, BaseConfig: baseCfg,
tokenGenerator: tokenGenerator, tokenGenerator: tokenGenerator,
} }
} }
@@ -192,13 +153,13 @@ func (auth *OidcAuthProvider) SetNewWorkConn(newWorkConnMsg *msg.NewWorkConn) (e
} }
type OidcAuthConsumer struct { type OidcAuthConsumer struct {
baseConfig BaseConfig
verifier *oidc.IDTokenVerifier verifier *oidc.IDTokenVerifier
subjectFromLogin string subjectFromLogin string
} }
func NewOidcAuthVerifier(baseCfg baseConfig, cfg oidcServerConfig) *OidcAuthConsumer { func NewOidcAuthVerifier(baseCfg BaseConfig, cfg OidcServerConfig) *OidcAuthConsumer {
provider, err := oidc.NewProvider(context.Background(), cfg.OidcIssuer) provider, err := oidc.NewProvider(context.Background(), cfg.OidcIssuer)
if err != nil { if err != nil {
panic(err) panic(err)
@@ -210,7 +171,7 @@ func NewOidcAuthVerifier(baseCfg baseConfig, cfg oidcServerConfig) *OidcAuthCons
SkipIssuerCheck: cfg.OidcSkipIssuerCheck, SkipIssuerCheck: cfg.OidcSkipIssuerCheck,
} }
return &OidcAuthConsumer{ return &OidcAuthConsumer{
baseConfig: baseCfg, BaseConfig: baseCfg,
verifier: provider.Verifier(&verifierConf), verifier: provider.Verifier(&verifierConf),
} }
} }

View File

@@ -18,49 +18,32 @@ import (
"fmt" "fmt"
"time" "time"
"github.com/fatedier/frp/models/msg" "github.com/fatedier/frp/pkg/msg"
"github.com/fatedier/frp/utils/util" "github.com/fatedier/frp/pkg/util/util"
"github.com/vaughan0/go-ini"
) )
type tokenConfig struct { type TokenConfig struct {
// Token specifies the authorization token used to create keys to be sent // Token specifies the authorization token used to create keys to be sent
// to the server. The server must have a matching token for authorization // to the server. The server must have a matching token for authorization
// to succeed. By default, this value is "". // to succeed. By default, this value is "".
Token string `json:"token"` Token string `ini:"token" json:"token"`
} }
func getDefaultTokenConf() tokenConfig { func getDefaultTokenConf() TokenConfig {
return tokenConfig{ return TokenConfig{
Token: "", Token: "",
} }
} }
func unmarshalTokenConfFromIni(conf ini.File) tokenConfig {
var (
tmpStr string
ok bool
)
cfg := getDefaultTokenConf()
if tmpStr, ok = conf.Get("common", "token"); ok {
cfg.Token = tmpStr
}
return cfg
}
type TokenAuthSetterVerifier struct { type TokenAuthSetterVerifier struct {
baseConfig BaseConfig
token string token string
} }
func NewTokenAuth(baseCfg baseConfig, cfg tokenConfig) *TokenAuthSetterVerifier { func NewTokenAuth(baseCfg BaseConfig, cfg TokenConfig) *TokenAuthSetterVerifier {
return &TokenAuthSetterVerifier{ return &TokenAuthSetterVerifier{
baseConfig: baseCfg, BaseConfig: baseCfg,
token: cfg.Token, token: cfg.Token,
} }
} }
@@ -81,7 +64,7 @@ func (auth *TokenAuthSetterVerifier) SetPing(pingMsg *msg.Ping) error {
} }
func (auth *TokenAuthSetterVerifier) SetNewWorkConn(newWorkConnMsg *msg.NewWorkConn) error { func (auth *TokenAuthSetterVerifier) SetNewWorkConn(newWorkConnMsg *msg.NewWorkConn) error {
if !auth.AuthenticateHeartBeats { if !auth.AuthenticateNewWorkConns {
return nil return nil
} }

12
pkg/config/README.md Normal file
View File

@@ -0,0 +1,12 @@
So far, there is no mature Go project that does well in parsing `*.ini` files.
By comparison, we have selected an open source project: `https://github.com/go-ini/ini`.
This library helped us solve most of the key-value matching, but there are still some problems, such as not supporting parsing `map`.
We add our own logic on the basis of this library. In the current situationwhich, we need to complete the entire `Unmarshal` in two steps:
* Step#1, use `go-ini` to complete the basic parameter matching;
* Step#2, parse our custom parameters to realize parsing special structure, like `map`, `array`.
Some of the keywords in `tag`(like inline, extends, etc.) may be different from standard libraries such as `json` and `protobuf` in Go. For details, please refer to the library documentation: https://ini.unknwon.io/docs/intro.

415
pkg/config/client.go Normal file
View File

@@ -0,0 +1,415 @@
// Copyright 2020 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 config
import (
"fmt"
"os"
"path/filepath"
"strings"
"gopkg.in/ini.v1"
"github.com/fatedier/frp/pkg/auth"
"github.com/fatedier/frp/pkg/util/util"
)
// ClientCommonConf contains information for a client service. It is
// recommended to use GetDefaultClientConf instead of creating this object
// directly, so that all unspecified fields have reasonable default values.
type ClientCommonConf struct {
auth.ClientConfig `ini:",extends"`
// ServerAddr specifies the address of the server to connect to. By
// default, this value is "0.0.0.0".
ServerAddr string `ini:"server_addr" json:"server_addr"`
// ServerPort specifies the port to connect to the server on. By default,
// this value is 7000.
ServerPort int `ini:"server_port" json:"server_port"`
// The maximum amount of time a dial to server will wait for a connect to complete.
DialServerTimeout int64 `ini:"dial_server_timeout" json:"dial_server_timeout"`
// DialServerKeepAlive specifies the interval between keep-alive probes for an active network connection between frpc and frps.
// If negative, keep-alive probes are disabled.
DialServerKeepAlive int64 `ini:"dial_server_keepalive" json:"dial_server_keepalive"`
// ConnectServerLocalIP specifies the address of the client bind when it connect to server.
// By default, this value is empty.
// this value only use in TCP/Websocket protocol. Not support in KCP protocol.
ConnectServerLocalIP string `ini:"connect_server_local_ip" json:"connect_server_local_ip"`
// HTTPProxy specifies a proxy address to connect to the server through. If
// this value is "", the server will be connected to directly. By default,
// this value is read from the "http_proxy" environment variable.
HTTPProxy string `ini:"http_proxy" json:"http_proxy"`
// LogFile specifies a file where logs will be written to. This value will
// only be used if LogWay is set appropriately. By default, this value is
// "console".
LogFile string `ini:"log_file" json:"log_file"`
// LogWay specifies the way logging is managed. Valid values are "console"
// or "file". If "console" is used, logs will be printed to stdout. If
// "file" is used, logs will be printed to LogFile. By default, this value
// is "console".
LogWay string `ini:"log_way" json:"log_way"`
// LogLevel specifies the minimum log level. Valid values are "trace",
// "debug", "info", "warn", and "error". By default, this value is "info".
LogLevel string `ini:"log_level" json:"log_level"`
// LogMaxDays specifies the maximum number of days to store log information
// before deletion. This is only used if LogWay == "file". By default, this
// value is 0.
LogMaxDays int64 `ini:"log_max_days" json:"log_max_days"`
// DisableLogColor disables log colors when LogWay == "console" when set to
// true. By default, this value is false.
DisableLogColor bool `ini:"disable_log_color" json:"disable_log_color"`
// AdminAddr specifies the address that the admin server binds to. By
// default, this value is "127.0.0.1".
AdminAddr string `ini:"admin_addr" json:"admin_addr"`
// AdminPort specifies the port for the admin server to listen on. If this
// value is 0, the admin server will not be started. By default, this value
// is 0.
AdminPort int `ini:"admin_port" json:"admin_port"`
// AdminUser specifies the username that the admin server will use for
// login.
AdminUser string `ini:"admin_user" json:"admin_user"`
// AdminPwd specifies the password that the admin server will use for
// login.
AdminPwd string `ini:"admin_pwd" json:"admin_pwd"`
// AssetsDir specifies the local directory that the admin server will load
// resources from. If this value is "", assets will be loaded from the
// bundled executable using statik. By default, this value is "".
AssetsDir string `ini:"assets_dir" json:"assets_dir"`
// PoolCount specifies the number of connections the client will make to
// the server in advance. By default, this value is 0.
PoolCount int `ini:"pool_count" json:"pool_count"`
// TCPMux toggles TCP stream multiplexing. This allows multiple requests
// from a client to share a single TCP connection. If this value is true,
// the server must have TCP multiplexing enabled as well. By default, this
// value is true.
TCPMux bool `ini:"tcp_mux" json:"tcp_mux"`
// TCPMuxKeepaliveInterval specifies the keep alive interval for TCP stream multipler.
// If TCPMux is true, heartbeat of application layer is unnecessary because it can only rely on heartbeat in TCPMux.
TCPMuxKeepaliveInterval int64 `ini:"tcp_mux_keepalive_interval" json:"tcp_mux_keepalive_interval"`
// User specifies a prefix for proxy names to distinguish them from other
// clients. If this value is not "", proxy names will automatically be
// changed to "{user}.{proxy_name}". By default, this value is "".
User string `ini:"user" json:"user"`
// DNSServer specifies a DNS server address for FRPC to use. If this value
// is "", the default DNS will be used. By default, this value is "".
DNSServer string `ini:"dns_server" json:"dns_server"`
// LoginFailExit controls whether or not the client should exit after a
// failed login attempt. If false, the client will retry until a login
// attempt succeeds. By default, this value is true.
LoginFailExit bool `ini:"login_fail_exit" json:"login_fail_exit"`
// Start specifies a set of enabled proxies by name. If this set is empty,
// all supplied proxies are enabled. By default, this value is an empty
// set.
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
// is "tcp".
Protocol string `ini:"protocol" json:"protocol"`
// QUIC protocol options
QUICKeepalivePeriod int `ini:"quic_keepalive_period" json:"quic_keepalive_period" validate:"gte=0"`
QUICMaxIdleTimeout int `ini:"quic_max_idle_timeout" json:"quic_max_idle_timeout" validate:"gte=0"`
QUICMaxIncomingStreams int `ini:"quic_max_incoming_streams" json:"quic_max_incoming_streams" validate:"gte=0"`
// 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.
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.
TLSCertFile string `ini:"tls_cert_file" json:"tls_cert_file"`
// TLSKeyPath specifies the path of the secret key file that client
// will load. It only works when "tls_enable" is true and "tls_cert_file"
// are valid.
TLSKeyFile string `ini:"tls_key_file" json:"tls_key_file"`
// TLSTrustedCaFile specifies the path of the trusted ca file that will load.
// It only works when "tls_enable" is valid and tls configuration of server
// has been specified.
TLSTrustedCaFile string `ini:"tls_trusted_ca_file" json:"tls_trusted_ca_file"`
// 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.
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
// default, this value is 30. Set negative value to disable it.
HeartbeatInterval int64 `ini:"heartbeat_interval" json:"heartbeat_interval"`
// HeartBeatTimeout specifies the maximum allowed heartbeat response delay
// before the connection is terminated, in seconds. It is not recommended
// to change this value. By default, this value is 90. Set negative value to disable it.
HeartbeatTimeout int64 `ini:"heartbeat_timeout" json:"heartbeat_timeout"`
// Client meta info
Metas map[string]string `ini:"-" json:"metas"`
// UDPPacketSize specifies the udp packet size
// By default, this value is 1500
UDPPacketSize int64 `ini:"udp_packet_size" json:"udp_packet_size"`
// Include other config files for proxies.
IncludeConfigFiles []string `ini:"includes" json:"includes"`
// Enable golang pprof handlers in admin listener.
// Admin port must be set first.
PprofEnable bool `ini:"pprof_enable" json:"pprof_enable"`
}
// GetDefaultClientConf returns a client configuration with default values.
func GetDefaultClientConf() ClientCommonConf {
return ClientCommonConf{
ClientConfig: auth.GetDefaultClientConf(),
ServerAddr: "0.0.0.0",
ServerPort: 7000,
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),
}
}
func (cfg *ClientCommonConf) Complete() {
if cfg.LogFile == "console" {
cfg.LogWay = "console"
} else {
cfg.LogWay = "file"
}
}
func (cfg *ClientCommonConf) Validate() error {
if cfg.HeartbeatTimeout > 0 && cfg.HeartbeatInterval > 0 {
if cfg.HeartbeatTimeout < cfg.HeartbeatInterval {
return fmt.Errorf("invalid heartbeat_timeout, heartbeat_timeout is less than heartbeat_interval")
}
}
if !cfg.TLSEnable {
if cfg.TLSCertFile != "" {
fmt.Println("WARNING! tls_cert_file is invalid when tls_enable is false")
}
if cfg.TLSKeyFile != "" {
fmt.Println("WARNING! tls_key_file is invalid when tls_enable is false")
}
if cfg.TLSTrustedCaFile != "" {
fmt.Println("WARNING! tls_trusted_ca_file is invalid when tls_enable is false")
}
}
if cfg.Protocol != "tcp" && cfg.Protocol != "kcp" && cfg.Protocol != "websocket" && cfg.Protocol != "quic" {
return fmt.Errorf("invalid protocol")
}
for _, f := range cfg.IncludeConfigFiles {
absDir, err := filepath.Abs(filepath.Dir(f))
if err != nil {
return fmt.Errorf("include: parse directory of %s failed: %v", f, absDir)
}
if _, err := os.Stat(absDir); os.IsNotExist(err) {
return fmt.Errorf("include: directory of %s not exist", f)
}
}
return nil
}
// Supported sources including: string(file path), []byte, Reader interface.
func UnmarshalClientConfFromIni(source interface{}) (ClientCommonConf, error) {
f, err := ini.LoadSources(ini.LoadOptions{
Insensitive: false,
InsensitiveSections: false,
InsensitiveKeys: false,
IgnoreInlineComment: true,
AllowBooleanKeys: true,
}, source)
if err != nil {
return ClientCommonConf{}, err
}
s, err := f.GetSection("common")
if err != nil {
return ClientCommonConf{}, fmt.Errorf("invalid configuration file, not found [common] section")
}
common := GetDefaultClientConf()
err = s.MapTo(&common)
if err != nil {
return ClientCommonConf{}, err
}
common.Metas = GetMapWithoutPrefix(s.KeysHash(), "meta_")
common.ClientConfig.OidcAdditionalEndpointParams = GetMapWithoutPrefix(s.KeysHash(), "oidc_additional_")
return common, nil
}
// if len(startProxy) is 0, start all
// otherwise just start proxies in startProxy map
func LoadAllProxyConfsFromIni(
prefix string,
source interface{},
start []string,
) (map[string]ProxyConf, map[string]VisitorConf, error) {
f, err := ini.LoadSources(ini.LoadOptions{
Insensitive: false,
InsensitiveSections: false,
InsensitiveKeys: false,
IgnoreInlineComment: true,
AllowBooleanKeys: true,
}, source)
if err != nil {
return nil, nil, err
}
proxyConfs := make(map[string]ProxyConf)
visitorConfs := make(map[string]VisitorConf)
if prefix != "" {
prefix += "."
}
startProxy := make(map[string]struct{})
for _, s := range start {
startProxy[s] = struct{}{}
}
startAll := true
if len(startProxy) > 0 {
startAll = false
}
// Build template sections from range section And append to ini.File.
rangeSections := make([]*ini.Section, 0)
for _, section := range f.Sections() {
if !strings.HasPrefix(section.Name(), "range:") {
continue
}
rangeSections = append(rangeSections, section)
}
for _, section := range rangeSections {
err = renderRangeProxyTemplates(f, section)
if err != nil {
return nil, nil, fmt.Errorf("failed to render template for proxy %s: %v", section.Name(), err)
}
}
for _, section := range f.Sections() {
name := section.Name()
if name == ini.DefaultSection || name == "common" || strings.HasPrefix(name, "range:") {
continue
}
_, shouldStart := startProxy[name]
if !startAll && !shouldStart {
continue
}
roleType := section.Key("role").String()
if roleType == "" {
roleType = "server"
}
switch roleType {
case "server":
newConf, newErr := NewProxyConfFromIni(prefix, name, section)
if newErr != nil {
return nil, nil, fmt.Errorf("failed to parse proxy %s, err: %v", name, newErr)
}
proxyConfs[prefix+name] = newConf
case "visitor":
newConf, newErr := NewVisitorConfFromIni(prefix, name, section)
if newErr != nil {
return nil, nil, newErr
}
visitorConfs[prefix+name] = newConf
default:
return nil, nil, fmt.Errorf("proxy %s role should be 'server' or 'visitor'", name)
}
}
return proxyConfs, visitorConfs, nil
}
func renderRangeProxyTemplates(f *ini.File, section *ini.Section) error {
// Validation
localPortStr := section.Key("local_port").String()
remotePortStr := section.Key("remote_port").String()
if localPortStr == "" || remotePortStr == "" {
return fmt.Errorf("local_port or remote_port is empty")
}
localPorts, err := util.ParseRangeNumbers(localPortStr)
if err != nil {
return err
}
remotePorts, err := util.ParseRangeNumbers(remotePortStr)
if err != nil {
return err
}
if len(localPorts) != len(remotePorts) {
return fmt.Errorf("local ports number should be same with remote ports number")
}
if len(localPorts) == 0 {
return fmt.Errorf("local_port and remote_port is necessary")
}
// Templates
prefix := strings.TrimSpace(strings.TrimPrefix(section.Name(), "range:"))
for i := range localPorts {
tmpname := fmt.Sprintf("%s_%d", prefix, i)
tmpsection, err := f.NewSection(tmpname)
if err != nil {
return err
}
copySection(section, tmpsection)
if _, err := tmpsection.NewKey("local_port", fmt.Sprintf("%d", localPorts[i])); err != nil {
return fmt.Errorf("local_port new key in section error: %v", err)
}
if _, err := tmpsection.NewKey("remote_port", fmt.Sprintf("%d", remotePorts[i])); err != nil {
return fmt.Errorf("remote_port new key in section error: %v", err)
}
}
return nil
}
func copySection(source, target *ini.Section) {
for key, value := range source.KeysHash() {
_, _ = target.NewKey(key, value)
}
}

649
pkg/config/client_test.go Normal file
View File

@@ -0,0 +1,649 @@
// Copyright 2020 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 config
import (
"testing"
"github.com/stretchr/testify/assert"
"github.com/fatedier/frp/pkg/auth"
"github.com/fatedier/frp/pkg/consts"
)
const (
testUser = "test"
)
var testClientBytesWithFull = []byte(`
# [common] is integral section
[common]
server_addr = 0.0.0.9
server_port = 7009
http_proxy = http://user:passwd@192.168.1.128:8080
log_file = ./frpc.log9
log_way = file
log_level = info9
log_max_days = 39
disable_log_color = false
authenticate_heartbeats = false
authenticate_new_work_conns = false
token = 12345678
oidc_client_id = client-id
oidc_client_secret = client-secret
oidc_audience = audience
oidc_token_endpoint_url = endpoint_url
admin_addr = 127.0.0.9
admin_port = 7409
admin_user = admin9
admin_pwd = admin9
assets_dir = ./static9
pool_count = 59
tcp_mux
user = your_name
login_fail_exit
protocol = tcp
tls_enable = true
tls_cert_file = client.crt
tls_key_file = client.key
tls_trusted_ca_file = ca.crt
tls_server_name = example.com
dns_server = 8.8.8.9
start = ssh,dns
heartbeat_interval = 39
heartbeat_timeout = 99
meta_var1 = 123
meta_var2 = 234
udp_packet_size = 1509
# all proxy
[ssh]
type = tcp
local_ip = 127.0.0.9
local_port = 29
bandwidth_limit = 19MB
use_encryption
use_compression
remote_port = 6009
group = test_group
group_key = 123456
health_check_type = tcp
health_check_timeout_s = 3
health_check_max_failed = 3
health_check_interval_s = 19
meta_var1 = 123
meta_var2 = 234
[ssh_random]
type = tcp
local_ip = 127.0.0.9
local_port = 29
remote_port = 9
[range:tcp_port]
type = tcp
local_ip = 127.0.0.9
local_port = 6010-6011,6019
remote_port = 6010-6011,6019
use_encryption = false
use_compression = false
[dns]
type = udp
local_ip = 114.114.114.114
local_port = 59
remote_port = 6009
use_encryption
use_compression
[range:udp_port]
type = udp
local_ip = 114.114.114.114
local_port = 6000,6010-6011
remote_port = 6000,6010-6011
use_encryption
use_compression
[web01]
type = http
local_ip = 127.0.0.9
local_port = 89
use_encryption
use_compression
http_user = admin
http_pwd = admin
subdomain = web01
custom_domains = web02.yourdomain.com
locations = /,/pic
host_header_rewrite = example.com
header_X-From-Where = frp
health_check_type = http
health_check_url = /status
health_check_interval_s = 19
health_check_max_failed = 3
health_check_timeout_s = 3
[web02]
type = https
local_ip = 127.0.0.9
local_port = 8009
use_encryption
use_compression
subdomain = web01
custom_domains = web02.yourdomain.com
proxy_protocol_version = v2
[secret_tcp]
type = stcp
sk = abcdefg
local_ip = 127.0.0.1
local_port = 22
use_encryption = false
use_compression = false
[p2p_tcp]
type = xtcp
sk = abcdefg
local_ip = 127.0.0.1
local_port = 22
use_encryption = false
use_compression = false
[tcpmuxhttpconnect]
type = tcpmux
multiplexer = httpconnect
local_ip = 127.0.0.1
local_port = 10701
custom_domains = tunnel1
[plugin_unix_domain_socket]
type = tcp
remote_port = 6003
plugin = unix_domain_socket
plugin_unix_path = /var/run/docker.sock
[plugin_http_proxy]
type = tcp
remote_port = 6004
plugin = http_proxy
plugin_http_user = abc
plugin_http_passwd = abc
[plugin_socks5]
type = tcp
remote_port = 6005
plugin = socks5
plugin_user = abc
plugin_passwd = abc
[plugin_static_file]
type = tcp
remote_port = 6006
plugin = static_file
plugin_local_path = /var/www/blog
plugin_strip_prefix = static
plugin_http_user = abc
plugin_http_passwd = abc
[plugin_https2http]
type = https
custom_domains = test.yourdomain.com
plugin = https2http
plugin_local_addr = 127.0.0.1:80
plugin_crt_path = ./server.crt
plugin_key_path = ./server.key
plugin_host_header_rewrite = 127.0.0.1
plugin_header_X-From-Where = frp
[plugin_http2https]
type = http
custom_domains = test.yourdomain.com
plugin = http2https
plugin_local_addr = 127.0.0.1:443
plugin_host_header_rewrite = 127.0.0.1
plugin_header_X-From-Where = frp
# visitor
[secret_tcp_visitor]
role = visitor
type = stcp
server_name = secret_tcp
sk = abcdefg
bind_addr = 127.0.0.1
bind_port = 9000
use_encryption = false
use_compression = false
[p2p_tcp_visitor]
role = visitor
type = xtcp
server_name = p2p_tcp
sk = abcdefg
bind_addr = 127.0.0.1
bind_port = 9001
use_encryption = false
use_compression = false
`)
func Test_LoadClientCommonConf(t *testing.T) {
assert := assert.New(t)
expected := ClientCommonConf{
ClientConfig: auth.ClientConfig{
BaseConfig: auth.BaseConfig{
AuthenticationMethod: "token",
AuthenticateHeartBeats: false,
AuthenticateNewWorkConns: false,
},
TokenConfig: auth.TokenConfig{
Token: "12345678",
},
OidcClientConfig: auth.OidcClientConfig{
OidcClientID: "client-id",
OidcClientSecret: "client-secret",
OidcAudience: "audience",
OidcTokenEndpointURL: "endpoint_url",
},
},
ServerAddr: "0.0.0.9",
ServerPort: 7009,
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,
Metas: map[string]string{
"var1": "123",
"var2": "234",
},
UDPPacketSize: 1509,
IncludeConfigFiles: []string{},
}
common, err := UnmarshalClientConfFromIni(testClientBytesWithFull)
assert.NoError(err)
assert.EqualValues(expected, common)
}
func Test_LoadClientBasicConf(t *testing.T) {
assert := assert.New(t)
proxyExpected := map[string]ProxyConf{
testUser + ".ssh": &TCPProxyConf{
BaseProxyConf: BaseProxyConf{
ProxyName: testUser + ".ssh",
ProxyType: consts.TCPProxy,
UseCompression: true,
UseEncryption: true,
Group: "test_group",
GroupKey: "123456",
BandwidthLimit: MustBandwidthQuantity("19MB"),
Metas: map[string]string{
"var1": "123",
"var2": "234",
},
LocalSvrConf: LocalSvrConf{
LocalIP: "127.0.0.9",
LocalPort: 29,
},
HealthCheckConf: HealthCheckConf{
HealthCheckType: consts.TCPProxy,
HealthCheckTimeoutS: 3,
HealthCheckMaxFailed: 3,
HealthCheckIntervalS: 19,
HealthCheckAddr: "127.0.0.9:29",
},
},
RemotePort: 6009,
},
testUser + ".ssh_random": &TCPProxyConf{
BaseProxyConf: BaseProxyConf{
ProxyName: testUser + ".ssh_random",
ProxyType: consts.TCPProxy,
LocalSvrConf: LocalSvrConf{
LocalIP: "127.0.0.9",
LocalPort: 29,
},
},
RemotePort: 9,
},
testUser + ".tcp_port_0": &TCPProxyConf{
BaseProxyConf: BaseProxyConf{
ProxyName: testUser + ".tcp_port_0",
ProxyType: consts.TCPProxy,
LocalSvrConf: LocalSvrConf{
LocalIP: "127.0.0.9",
LocalPort: 6010,
},
},
RemotePort: 6010,
},
testUser + ".tcp_port_1": &TCPProxyConf{
BaseProxyConf: BaseProxyConf{
ProxyName: testUser + ".tcp_port_1",
ProxyType: consts.TCPProxy,
LocalSvrConf: LocalSvrConf{
LocalIP: "127.0.0.9",
LocalPort: 6011,
},
},
RemotePort: 6011,
},
testUser + ".tcp_port_2": &TCPProxyConf{
BaseProxyConf: BaseProxyConf{
ProxyName: testUser + ".tcp_port_2",
ProxyType: consts.TCPProxy,
LocalSvrConf: LocalSvrConf{
LocalIP: "127.0.0.9",
LocalPort: 6019,
},
},
RemotePort: 6019,
},
testUser + ".dns": &UDPProxyConf{
BaseProxyConf: BaseProxyConf{
ProxyName: testUser + ".dns",
ProxyType: consts.UDPProxy,
UseEncryption: true,
UseCompression: true,
LocalSvrConf: LocalSvrConf{
LocalIP: "114.114.114.114",
LocalPort: 59,
},
},
RemotePort: 6009,
},
testUser + ".udp_port_0": &UDPProxyConf{
BaseProxyConf: BaseProxyConf{
ProxyName: testUser + ".udp_port_0",
ProxyType: consts.UDPProxy,
UseEncryption: true,
UseCompression: true,
LocalSvrConf: LocalSvrConf{
LocalIP: "114.114.114.114",
LocalPort: 6000,
},
},
RemotePort: 6000,
},
testUser + ".udp_port_1": &UDPProxyConf{
BaseProxyConf: BaseProxyConf{
ProxyName: testUser + ".udp_port_1",
ProxyType: consts.UDPProxy,
UseEncryption: true,
UseCompression: true,
LocalSvrConf: LocalSvrConf{
LocalIP: "114.114.114.114",
LocalPort: 6010,
},
},
RemotePort: 6010,
},
testUser + ".udp_port_2": &UDPProxyConf{
BaseProxyConf: BaseProxyConf{
ProxyName: testUser + ".udp_port_2",
ProxyType: consts.UDPProxy,
UseEncryption: true,
UseCompression: true,
LocalSvrConf: LocalSvrConf{
LocalIP: "114.114.114.114",
LocalPort: 6011,
},
},
RemotePort: 6011,
},
testUser + ".web01": &HTTPProxyConf{
BaseProxyConf: BaseProxyConf{
ProxyName: testUser + ".web01",
ProxyType: consts.HTTPProxy,
UseCompression: true,
UseEncryption: true,
LocalSvrConf: LocalSvrConf{
LocalIP: "127.0.0.9",
LocalPort: 89,
},
HealthCheckConf: HealthCheckConf{
HealthCheckType: consts.HTTPProxy,
HealthCheckTimeoutS: 3,
HealthCheckMaxFailed: 3,
HealthCheckIntervalS: 19,
HealthCheckURL: "http://127.0.0.9:89/status",
},
},
DomainConf: DomainConf{
CustomDomains: []string{"web02.yourdomain.com"},
SubDomain: "web01",
},
Locations: []string{"/", "/pic"},
HTTPUser: "admin",
HTTPPwd: "admin",
HostHeaderRewrite: "example.com",
Headers: map[string]string{
"X-From-Where": "frp",
},
},
testUser + ".web02": &HTTPSProxyConf{
BaseProxyConf: BaseProxyConf{
ProxyName: testUser + ".web02",
ProxyType: consts.HTTPSProxy,
UseCompression: true,
UseEncryption: true,
LocalSvrConf: LocalSvrConf{
LocalIP: "127.0.0.9",
LocalPort: 8009,
},
ProxyProtocolVersion: "v2",
},
DomainConf: DomainConf{
CustomDomains: []string{"web02.yourdomain.com"},
SubDomain: "web01",
},
},
testUser + ".secret_tcp": &STCPProxyConf{
BaseProxyConf: BaseProxyConf{
ProxyName: testUser + ".secret_tcp",
ProxyType: consts.STCPProxy,
LocalSvrConf: LocalSvrConf{
LocalIP: "127.0.0.1",
LocalPort: 22,
},
},
Role: "server",
Sk: "abcdefg",
},
testUser + ".p2p_tcp": &XTCPProxyConf{
BaseProxyConf: BaseProxyConf{
ProxyName: testUser + ".p2p_tcp",
ProxyType: consts.XTCPProxy,
LocalSvrConf: LocalSvrConf{
LocalIP: "127.0.0.1",
LocalPort: 22,
},
},
Role: "server",
Sk: "abcdefg",
},
testUser + ".tcpmuxhttpconnect": &TCPMuxProxyConf{
BaseProxyConf: BaseProxyConf{
ProxyName: testUser + ".tcpmuxhttpconnect",
ProxyType: consts.TCPMuxProxy,
LocalSvrConf: LocalSvrConf{
LocalIP: "127.0.0.1",
LocalPort: 10701,
},
},
DomainConf: DomainConf{
CustomDomains: []string{"tunnel1"},
SubDomain: "",
},
Multiplexer: "httpconnect",
},
testUser + ".plugin_unix_domain_socket": &TCPProxyConf{
BaseProxyConf: BaseProxyConf{
ProxyName: testUser + ".plugin_unix_domain_socket",
ProxyType: consts.TCPProxy,
LocalSvrConf: LocalSvrConf{
LocalIP: "127.0.0.1",
Plugin: "unix_domain_socket",
PluginParams: map[string]string{
"plugin_unix_path": "/var/run/docker.sock",
},
},
},
RemotePort: 6003,
},
testUser + ".plugin_http_proxy": &TCPProxyConf{
BaseProxyConf: BaseProxyConf{
ProxyName: testUser + ".plugin_http_proxy",
ProxyType: consts.TCPProxy,
LocalSvrConf: LocalSvrConf{
LocalIP: "127.0.0.1",
Plugin: "http_proxy",
PluginParams: map[string]string{
"plugin_http_user": "abc",
"plugin_http_passwd": "abc",
},
},
},
RemotePort: 6004,
},
testUser + ".plugin_socks5": &TCPProxyConf{
BaseProxyConf: BaseProxyConf{
ProxyName: testUser + ".plugin_socks5",
ProxyType: consts.TCPProxy,
LocalSvrConf: LocalSvrConf{
LocalIP: "127.0.0.1",
Plugin: "socks5",
PluginParams: map[string]string{
"plugin_user": "abc",
"plugin_passwd": "abc",
},
},
},
RemotePort: 6005,
},
testUser + ".plugin_static_file": &TCPProxyConf{
BaseProxyConf: BaseProxyConf{
ProxyName: testUser + ".plugin_static_file",
ProxyType: consts.TCPProxy,
LocalSvrConf: LocalSvrConf{
LocalIP: "127.0.0.1",
Plugin: "static_file",
PluginParams: map[string]string{
"plugin_local_path": "/var/www/blog",
"plugin_strip_prefix": "static",
"plugin_http_user": "abc",
"plugin_http_passwd": "abc",
},
},
},
RemotePort: 6006,
},
testUser + ".plugin_https2http": &HTTPSProxyConf{
BaseProxyConf: BaseProxyConf{
ProxyName: testUser + ".plugin_https2http",
ProxyType: consts.HTTPSProxy,
LocalSvrConf: LocalSvrConf{
LocalIP: "127.0.0.1",
Plugin: "https2http",
PluginParams: map[string]string{
"plugin_local_addr": "127.0.0.1:80",
"plugin_crt_path": "./server.crt",
"plugin_key_path": "./server.key",
"plugin_host_header_rewrite": "127.0.0.1",
"plugin_header_X-From-Where": "frp",
},
},
},
DomainConf: DomainConf{
CustomDomains: []string{"test.yourdomain.com"},
},
},
testUser + ".plugin_http2https": &HTTPProxyConf{
BaseProxyConf: BaseProxyConf{
ProxyName: testUser + ".plugin_http2https",
ProxyType: consts.HTTPProxy,
LocalSvrConf: LocalSvrConf{
LocalIP: "127.0.0.1",
Plugin: "http2https",
PluginParams: map[string]string{
"plugin_local_addr": "127.0.0.1:443",
"plugin_host_header_rewrite": "127.0.0.1",
"plugin_header_X-From-Where": "frp",
},
},
},
DomainConf: DomainConf{
CustomDomains: []string{"test.yourdomain.com"},
},
},
}
visitorExpected := map[string]VisitorConf{
testUser + ".secret_tcp_visitor": &STCPVisitorConf{
BaseVisitorConf: BaseVisitorConf{
ProxyName: testUser + ".secret_tcp_visitor",
ProxyType: consts.STCPProxy,
Role: "visitor",
Sk: "abcdefg",
ServerName: testVisitorPrefix + "secret_tcp",
BindAddr: "127.0.0.1",
BindPort: 9000,
},
},
testUser + ".p2p_tcp_visitor": &XTCPVisitorConf{
BaseVisitorConf: BaseVisitorConf{
ProxyName: testUser + ".p2p_tcp_visitor",
ProxyType: consts.XTCPProxy,
Role: "visitor",
Sk: "abcdefg",
ServerName: testProxyPrefix + "p2p_tcp",
BindAddr: "127.0.0.1",
BindPort: 9001,
},
},
}
proxyActual, visitorActual, err := LoadAllProxyConfsFromIni(testUser, testClientBytesWithFull, nil)
assert.NoError(err)
assert.Equal(proxyExpected, proxyActual)
assert.Equal(visitorExpected, visitorActual)
}

99
pkg/config/parse.go Normal file
View File

@@ -0,0 +1,99 @@
// Copyright 2021 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 config
import (
"bytes"
"fmt"
"os"
"path/filepath"
)
func ParseClientConfig(filePath string) (
cfg ClientCommonConf,
pxyCfgs map[string]ProxyConf,
visitorCfgs map[string]VisitorConf,
err error,
) {
var content []byte
content, err = GetRenderedConfFromFile(filePath)
if err != nil {
return
}
configBuffer := bytes.NewBuffer(nil)
configBuffer.Write(content)
// Parse common section.
cfg, err = UnmarshalClientConfFromIni(content)
if err != nil {
return
}
cfg.Complete()
if err = cfg.Validate(); err != nil {
err = fmt.Errorf("parse config error: %v", err)
return
}
// Aggregate proxy configs from include files.
var buf []byte
buf, err = getIncludeContents(cfg.IncludeConfigFiles)
if err != nil {
err = fmt.Errorf("getIncludeContents error: %v", err)
return
}
configBuffer.WriteString("\n")
configBuffer.Write(buf)
// Parse all proxy and visitor configs.
pxyCfgs, visitorCfgs, err = LoadAllProxyConfsFromIni(cfg.User, configBuffer.Bytes(), cfg.Start)
if err != nil {
return
}
return
}
// getIncludeContents renders all configs from paths.
// files format can be a single file path or directory or regex path.
func getIncludeContents(paths []string) ([]byte, error) {
out := bytes.NewBuffer(nil)
for _, path := range paths {
absDir, err := filepath.Abs(filepath.Dir(path))
if err != nil {
return nil, err
}
if _, err := os.Stat(absDir); os.IsNotExist(err) {
return nil, err
}
files, err := os.ReadDir(absDir)
if err != nil {
return nil, err
}
for _, fi := range files {
if fi.IsDir() {
continue
}
absFile := filepath.Join(absDir, fi.Name())
if matched, _ := filepath.Match(filepath.Join(absDir, filepath.Base(path)), absFile); matched {
tmpContent, err := GetRenderedConfFromFile(absFile)
if err != nil {
return nil, fmt.Errorf("render extra config %s error: %v", absFile, err)
}
out.Write(tmpContent)
out.WriteString("\n")
}
}
}
return out.Bytes(), nil
}

1068
pkg/config/proxy.go Normal file

File diff suppressed because it is too large Load Diff

459
pkg/config/proxy_test.go Normal file
View File

@@ -0,0 +1,459 @@
// Copyright 2020 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 config
import (
"testing"
"github.com/stretchr/testify/assert"
"gopkg.in/ini.v1"
"github.com/fatedier/frp/pkg/consts"
)
var (
testLoadOptions = ini.LoadOptions{
Insensitive: false,
InsensitiveSections: false,
InsensitiveKeys: false,
IgnoreInlineComment: true,
AllowBooleanKeys: true,
}
testProxyPrefix = "test."
)
func Test_Proxy_Interface(t *testing.T) {
for name := range proxyConfTypeMap {
NewConfByType(name)
}
}
func Test_Proxy_UnmarshalFromIni(t *testing.T) {
assert := assert.New(t)
testcases := []struct {
sname string
source []byte
expected ProxyConf
}{
{
sname: "ssh",
source: []byte(`
[ssh]
# tcp | udp | http | https | stcp | xtcp, default is tcp
type = tcp
local_ip = 127.0.0.9
local_port = 29
bandwidth_limit = 19MB
use_encryption
use_compression
remote_port = 6009
group = test_group
group_key = 123456
health_check_type = tcp
health_check_timeout_s = 3
health_check_max_failed = 3
health_check_interval_s = 19
meta_var1 = 123
meta_var2 = 234`),
expected: &TCPProxyConf{
BaseProxyConf: BaseProxyConf{
ProxyName: testProxyPrefix + "ssh",
ProxyType: consts.TCPProxy,
UseCompression: true,
UseEncryption: true,
Group: "test_group",
GroupKey: "123456",
BandwidthLimit: MustBandwidthQuantity("19MB"),
Metas: map[string]string{
"var1": "123",
"var2": "234",
},
LocalSvrConf: LocalSvrConf{
LocalIP: "127.0.0.9",
LocalPort: 29,
},
HealthCheckConf: HealthCheckConf{
HealthCheckType: consts.TCPProxy,
HealthCheckTimeoutS: 3,
HealthCheckMaxFailed: 3,
HealthCheckIntervalS: 19,
HealthCheckAddr: "127.0.0.9:29",
},
},
RemotePort: 6009,
},
},
{
sname: "ssh_random",
source: []byte(`
[ssh_random]
type = tcp
local_ip = 127.0.0.9
local_port = 29
remote_port = 9
`),
expected: &TCPProxyConf{
BaseProxyConf: BaseProxyConf{
ProxyName: testProxyPrefix + "ssh_random",
ProxyType: consts.TCPProxy,
LocalSvrConf: LocalSvrConf{
LocalIP: "127.0.0.9",
LocalPort: 29,
},
},
RemotePort: 9,
},
},
{
sname: "dns",
source: []byte(`
[dns]
type = udp
local_ip = 114.114.114.114
local_port = 59
remote_port = 6009
use_encryption
use_compression
`),
expected: &UDPProxyConf{
BaseProxyConf: BaseProxyConf{
ProxyName: testProxyPrefix + "dns",
ProxyType: consts.UDPProxy,
UseEncryption: true,
UseCompression: true,
LocalSvrConf: LocalSvrConf{
LocalIP: "114.114.114.114",
LocalPort: 59,
},
},
RemotePort: 6009,
},
},
{
sname: "web01",
source: []byte(`
[web01]
type = http
local_ip = 127.0.0.9
local_port = 89
use_encryption
use_compression
http_user = admin
http_pwd = admin
subdomain = web01
custom_domains = web02.yourdomain.com
locations = /,/pic
host_header_rewrite = example.com
header_X-From-Where = frp
health_check_type = http
health_check_url = /status
health_check_interval_s = 19
health_check_max_failed = 3
health_check_timeout_s = 3
`),
expected: &HTTPProxyConf{
BaseProxyConf: BaseProxyConf{
ProxyName: testProxyPrefix + "web01",
ProxyType: consts.HTTPProxy,
UseCompression: true,
UseEncryption: true,
LocalSvrConf: LocalSvrConf{
LocalIP: "127.0.0.9",
LocalPort: 89,
},
HealthCheckConf: HealthCheckConf{
HealthCheckType: consts.HTTPProxy,
HealthCheckTimeoutS: 3,
HealthCheckMaxFailed: 3,
HealthCheckIntervalS: 19,
HealthCheckURL: "http://127.0.0.9:89/status",
},
},
DomainConf: DomainConf{
CustomDomains: []string{"web02.yourdomain.com"},
SubDomain: "web01",
},
Locations: []string{"/", "/pic"},
HTTPUser: "admin",
HTTPPwd: "admin",
HostHeaderRewrite: "example.com",
Headers: map[string]string{
"X-From-Where": "frp",
},
},
},
{
sname: "web02",
source: []byte(`
[web02]
type = https
local_ip = 127.0.0.9
local_port = 8009
use_encryption
use_compression
subdomain = web01
custom_domains = web02.yourdomain.com
proxy_protocol_version = v2
`),
expected: &HTTPSProxyConf{
BaseProxyConf: BaseProxyConf{
ProxyName: testProxyPrefix + "web02",
ProxyType: consts.HTTPSProxy,
UseCompression: true,
UseEncryption: true,
LocalSvrConf: LocalSvrConf{
LocalIP: "127.0.0.9",
LocalPort: 8009,
},
ProxyProtocolVersion: "v2",
},
DomainConf: DomainConf{
CustomDomains: []string{"web02.yourdomain.com"},
SubDomain: "web01",
},
},
},
{
sname: "secret_tcp",
source: []byte(`
[secret_tcp]
type = stcp
sk = abcdefg
local_ip = 127.0.0.1
local_port = 22
use_encryption = false
use_compression = false
`),
expected: &STCPProxyConf{
BaseProxyConf: BaseProxyConf{
ProxyName: testProxyPrefix + "secret_tcp",
ProxyType: consts.STCPProxy,
LocalSvrConf: LocalSvrConf{
LocalIP: "127.0.0.1",
LocalPort: 22,
},
},
Role: "server",
Sk: "abcdefg",
},
},
{
sname: "p2p_tcp",
source: []byte(`
[p2p_tcp]
type = xtcp
sk = abcdefg
local_ip = 127.0.0.1
local_port = 22
use_encryption = false
use_compression = false
`),
expected: &XTCPProxyConf{
BaseProxyConf: BaseProxyConf{
ProxyName: testProxyPrefix + "p2p_tcp",
ProxyType: consts.XTCPProxy,
LocalSvrConf: LocalSvrConf{
LocalIP: "127.0.0.1",
LocalPort: 22,
},
},
Role: "server",
Sk: "abcdefg",
},
},
{
sname: "tcpmuxhttpconnect",
source: []byte(`
[tcpmuxhttpconnect]
type = tcpmux
multiplexer = httpconnect
local_ip = 127.0.0.1
local_port = 10701
custom_domains = tunnel1
`),
expected: &TCPMuxProxyConf{
BaseProxyConf: BaseProxyConf{
ProxyName: testProxyPrefix + "tcpmuxhttpconnect",
ProxyType: consts.TCPMuxProxy,
LocalSvrConf: LocalSvrConf{
LocalIP: "127.0.0.1",
LocalPort: 10701,
},
},
DomainConf: DomainConf{
CustomDomains: []string{"tunnel1"},
SubDomain: "",
},
Multiplexer: "httpconnect",
},
},
}
for _, c := range testcases {
f, err := ini.LoadSources(testLoadOptions, c.source)
assert.NoError(err)
proxyType := f.Section(c.sname).Key("type").String()
assert.NotEmpty(proxyType)
actual := DefaultProxyConf(proxyType)
assert.NotNil(actual)
err = actual.UnmarshalFromIni(testProxyPrefix, c.sname, f.Section(c.sname))
assert.NoError(err)
assert.Equal(c.expected, actual)
}
}
func Test_RangeProxy_UnmarshalFromIni(t *testing.T) {
assert := assert.New(t)
testcases := []struct {
sname string
source []byte
expected map[string]ProxyConf
}{
{
sname: "range:tcp_port",
source: []byte(`
[range:tcp_port]
type = tcp
local_ip = 127.0.0.9
local_port = 6010-6011,6019
remote_port = 6010-6011,6019
use_encryption = false
use_compression = false
`),
expected: map[string]ProxyConf{
"tcp_port_0": &TCPProxyConf{
BaseProxyConf: BaseProxyConf{
ProxyName: testProxyPrefix + "tcp_port_0",
ProxyType: consts.TCPProxy,
LocalSvrConf: LocalSvrConf{
LocalIP: "127.0.0.9",
LocalPort: 6010,
},
},
RemotePort: 6010,
},
"tcp_port_1": &TCPProxyConf{
BaseProxyConf: BaseProxyConf{
ProxyName: testProxyPrefix + "tcp_port_1",
ProxyType: consts.TCPProxy,
LocalSvrConf: LocalSvrConf{
LocalIP: "127.0.0.9",
LocalPort: 6011,
},
},
RemotePort: 6011,
},
"tcp_port_2": &TCPProxyConf{
BaseProxyConf: BaseProxyConf{
ProxyName: testProxyPrefix + "tcp_port_2",
ProxyType: consts.TCPProxy,
LocalSvrConf: LocalSvrConf{
LocalIP: "127.0.0.9",
LocalPort: 6019,
},
},
RemotePort: 6019,
},
},
},
{
sname: "range:udp_port",
source: []byte(`
[range:udp_port]
type = udp
local_ip = 114.114.114.114
local_port = 6000,6010-6011
remote_port = 6000,6010-6011
use_encryption
use_compression
`),
expected: map[string]ProxyConf{
"udp_port_0": &UDPProxyConf{
BaseProxyConf: BaseProxyConf{
ProxyName: testProxyPrefix + "udp_port_0",
ProxyType: consts.UDPProxy,
UseEncryption: true,
UseCompression: true,
LocalSvrConf: LocalSvrConf{
LocalIP: "114.114.114.114",
LocalPort: 6000,
},
},
RemotePort: 6000,
},
"udp_port_1": &UDPProxyConf{
BaseProxyConf: BaseProxyConf{
ProxyName: testProxyPrefix + "udp_port_1",
ProxyType: consts.UDPProxy,
UseEncryption: true,
UseCompression: true,
LocalSvrConf: LocalSvrConf{
LocalIP: "114.114.114.114",
LocalPort: 6010,
},
},
RemotePort: 6010,
},
"udp_port_2": &UDPProxyConf{
BaseProxyConf: BaseProxyConf{
ProxyName: testProxyPrefix + "udp_port_2",
ProxyType: consts.UDPProxy,
UseEncryption: true,
UseCompression: true,
LocalSvrConf: LocalSvrConf{
LocalIP: "114.114.114.114",
LocalPort: 6011,
},
},
RemotePort: 6011,
},
},
},
}
for _, c := range testcases {
f, err := ini.LoadSources(testLoadOptions, c.source)
assert.NoError(err)
actual := make(map[string]ProxyConf)
s := f.Section(c.sname)
err = renderRangeProxyTemplates(f, s)
assert.NoError(err)
f.DeleteSection(ini.DefaultSection)
f.DeleteSection(c.sname)
for _, section := range f.Sections() {
proxyType := section.Key("type").String()
newsname := section.Name()
tmp := DefaultProxyConf(proxyType)
err = tmp.UnmarshalFromIni(testProxyPrefix, newsname, section)
assert.NoError(err)
actual[newsname] = tmp
}
assert.Equal(c.expected, actual)
}
}

333
pkg/config/server.go Normal file
View File

@@ -0,0 +1,333 @@
// Copyright 2020 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 config
import (
"fmt"
"strings"
"github.com/go-playground/validator/v10"
"gopkg.in/ini.v1"
"github.com/fatedier/frp/pkg/auth"
plugin "github.com/fatedier/frp/pkg/plugin/server"
"github.com/fatedier/frp/pkg/util/util"
)
// ServerCommonConf contains information for a server service. It is
// recommended to use GetDefaultServerConf instead of creating this object
// directly, so that all unspecified fields have reasonable default values.
type ServerCommonConf struct {
auth.ServerConfig `ini:",extends"`
// BindAddr specifies the address that the server binds to. By default,
// this value is "0.0.0.0".
BindAddr string `ini:"bind_addr" json:"bind_addr"`
// BindPort specifies the port that the server listens on. By default, this
// value is 7000.
BindPort int `ini:"bind_port" json:"bind_port" validate:"gte=0,lte=65535"`
// BindUDPPort specifies the UDP port that the server listens on. If this
// value is 0, the server will not listen for UDP connections. By default,
// this value is 0
BindUDPPort int `ini:"bind_udp_port" json:"bind_udp_port" validate:"gte=0,lte=65535"`
// KCPBindPort specifies the KCP port that the server listens on. If this
// value is 0, the server will not listen for KCP connections. By default,
// this value is 0.
KCPBindPort int `ini:"kcp_bind_port" json:"kcp_bind_port" validate:"gte=0,lte=65535"`
// QUICBindPort specifies the QUIC port that the server listens on.
// Set this value to 0 will disable this feature.
// By default, the value is 0.
QUICBindPort int `ini:"quic_bind_port" json:"quic_bind_port" validate:"gte=0,lte=65535"`
// QUIC protocol options
QUICKeepalivePeriod int `ini:"quic_keepalive_period" json:"quic_keepalive_period" validate:"gte=0"`
QUICMaxIdleTimeout int `ini:"quic_max_idle_timeout" json:"quic_max_idle_timeout" validate:"gte=0"`
QUICMaxIncomingStreams int `ini:"quic_max_incoming_streams" json:"quic_max_incoming_streams" validate:"gte=0"`
// ProxyBindAddr specifies the address that the proxy binds to. This value
// may be the same as BindAddr.
ProxyBindAddr string `ini:"proxy_bind_addr" json:"proxy_bind_addr"`
// VhostHTTPPort specifies the port that the server listens for HTTP Vhost
// requests. If this value is 0, the server will not listen for HTTP
// requests. By default, this value is 0.
VhostHTTPPort int `ini:"vhost_http_port" json:"vhost_http_port" validate:"gte=0,lte=65535"`
// VhostHTTPSPort specifies the port that the server listens for HTTPS
// Vhost requests. If this value is 0, the server will not listen for HTTPS
// requests. By default, this value is 0.
VhostHTTPSPort int `ini:"vhost_https_port" json:"vhost_https_port" validate:"gte=0,lte=65535"`
// TCPMuxHTTPConnectPort specifies the port that the server listens for TCP
// HTTP CONNECT requests. If the value is 0, the server will not multiplex TCP
// requests on one single port. If it's not - it will listen on this value for
// HTTP CONNECT requests. By default, this value is 0.
TCPMuxHTTPConnectPort int `ini:"tcpmux_httpconnect_port" json:"tcpmux_httpconnect_port" validate:"gte=0,lte=65535"`
// If TCPMuxPassthrough is true, frps won't do any update on traffic.
TCPMuxPassthrough bool `ini:"tcpmux_passthrough" json:"tcpmux_passthrough"`
// VhostHTTPTimeout specifies the response header timeout for the Vhost
// HTTP server, in seconds. By default, this value is 60.
VhostHTTPTimeout int64 `ini:"vhost_http_timeout" json:"vhost_http_timeout"`
// DashboardAddr specifies the address that the dashboard binds to. By
// default, this value is "0.0.0.0".
DashboardAddr string `ini:"dashboard_addr" json:"dashboard_addr"`
// DashboardPort specifies the port that the dashboard listens on. If this
// value is 0, the dashboard will not be started. By default, this value is
// 0.
DashboardPort int `ini:"dashboard_port" json:"dashboard_port" validate:"gte=0,lte=65535"`
// DashboardTLSCertFile specifies the path of the cert file that the server will
// load. If "dashboard_tls_cert_file", "dashboard_tls_key_file" are valid, the server will use this
// supplied tls configuration.
DashboardTLSCertFile string `ini:"dashboard_tls_cert_file" json:"dashboard_tls_cert_file"`
// DashboardTLSKeyFile specifies the path of the secret key that the server will
// load. If "dashboard_tls_cert_file", "dashboard_tls_key_file" are valid, the server will use this
// supplied tls configuration.
DashboardTLSKeyFile string `ini:"dashboard_tls_key_file" json:"dashboard_tls_key_file"`
// DashboardTLSMode specifies the mode of the dashboard between HTTP or HTTPS modes. By
// default, this value is false, which is HTTP mode.
DashboardTLSMode bool `ini:"dashboard_tls_mode" json:"dashboard_tls_mode"`
// DashboardUser specifies the username that the dashboard will use for
// login.
DashboardUser string `ini:"dashboard_user" json:"dashboard_user"`
// DashboardPwd specifies the password that the dashboard will use for
// login.
DashboardPwd string `ini:"dashboard_pwd" json:"dashboard_pwd"`
// EnablePrometheus will export prometheus metrics on {dashboard_addr}:{dashboard_port}
// in /metrics api.
EnablePrometheus bool `ini:"enable_prometheus" json:"enable_prometheus"`
// AssetsDir specifies the local directory that the dashboard will load
// resources from. If this value is "", assets will be loaded from the
// bundled executable using statik. By default, this value is "".
AssetsDir string `ini:"assets_dir" json:"assets_dir"`
// LogFile specifies a file where logs will be written to. This value will
// only be used if LogWay is set appropriately. By default, this value is
// "console".
LogFile string `ini:"log_file" json:"log_file"`
// LogWay specifies the way logging is managed. Valid values are "console"
// or "file". If "console" is used, logs will be printed to stdout. If
// "file" is used, logs will be printed to LogFile. By default, this value
// is "console".
LogWay string `ini:"log_way" json:"log_way"`
// LogLevel specifies the minimum log level. Valid values are "trace",
// "debug", "info", "warn", and "error". By default, this value is "info".
LogLevel string `ini:"log_level" json:"log_level"`
// LogMaxDays specifies the maximum number of days to store log information
// before deletion. This is only used if LogWay == "file". By default, this
// value is 0.
LogMaxDays int64 `ini:"log_max_days" json:"log_max_days"`
// DisableLogColor disables log colors when LogWay == "console" when set to
// true. By default, this value is false.
DisableLogColor bool `ini:"disable_log_color" json:"disable_log_color"`
// DetailedErrorsToClient defines whether to send the specific error (with
// debug info) to frpc. By default, this value is true.
DetailedErrorsToClient bool `ini:"detailed_errors_to_client" json:"detailed_errors_to_client"`
// SubDomainHost specifies the domain that will be attached to sub-domains
// requested by the client when using Vhost proxying. For example, if this
// value is set to "frps.com" and the client requested the subdomain
// "test", the resulting URL would be "test.frps.com". By default, this
// value is "".
SubDomainHost string `ini:"subdomain_host" json:"subdomain_host"`
// TCPMux toggles TCP stream multiplexing. This allows multiple requests
// from a client to share a single TCP connection. By default, this value
// is true.
TCPMux bool `ini:"tcp_mux" json:"tcp_mux"`
// TCPMuxKeepaliveInterval specifies the keep alive interval for TCP stream multipler.
// If TCPMux is true, heartbeat of application layer is unnecessary because it can only rely on heartbeat in TCPMux.
TCPMuxKeepaliveInterval int64 `ini:"tcp_mux_keepalive_interval" json:"tcp_mux_keepalive_interval"`
// TCPKeepAlive specifies the interval between keep-alive probes for an active network connection between frpc and frps.
// If negative, keep-alive probes are disabled.
TCPKeepAlive int64 `ini:"tcp_keepalive" json:"tcp_keepalive"`
// Custom404Page specifies a path to a custom 404 page to display. If this
// value is "", a default page will be displayed. By default, this value is
// "".
Custom404Page string `ini:"custom_404_page" json:"custom_404_page"`
// AllowPorts specifies a set of ports that clients are able to proxy to.
// If the length of this value is 0, all ports are allowed. By default,
// this value is an empty set.
AllowPorts map[int]struct{} `ini:"-" json:"-"`
// MaxPoolCount specifies the maximum pool size for each proxy. By default,
// this value is 5.
MaxPoolCount int64 `ini:"max_pool_count" json:"max_pool_count"`
// MaxPortsPerClient specifies the maximum number of ports a single client
// may proxy to. If this value is 0, no limit will be applied. By default,
// this value is 0.
MaxPortsPerClient int64 `ini:"max_ports_per_client" json:"max_ports_per_client"`
// TLSOnly specifies whether to only accept TLS-encrypted connections.
// By default, the value is false.
TLSOnly bool `ini:"tls_only" json:"tls_only"`
// TLSCertFile specifies the path of the cert file that the server will
// load. If "tls_cert_file", "tls_key_file" are valid, the server will use this
// supplied tls configuration. Otherwise, the server will use the tls
// configuration generated by itself.
TLSCertFile string `ini:"tls_cert_file" json:"tls_cert_file"`
// TLSKeyFile specifies the path of the secret key that the server will
// load. If "tls_cert_file", "tls_key_file" are valid, the server will use this
// supplied tls configuration. Otherwise, the server will use the tls
// configuration generated by itself.
TLSKeyFile string `ini:"tls_key_file" json:"tls_key_file"`
// TLSTrustedCaFile specifies the paths of the client cert files that the
// server will load. It only works when "tls_only" is true. If
// "tls_trusted_ca_file" is valid, the server will verify each client's
// certificate.
TLSTrustedCaFile string `ini:"tls_trusted_ca_file" json:"tls_trusted_ca_file"`
// HeartBeatTimeout specifies the maximum time to wait for a heartbeat
// before terminating the connection. It is not recommended to change this
// value. By default, this value is 90. Set negative value to disable it.
HeartbeatTimeout int64 `ini:"heartbeat_timeout" json:"heartbeat_timeout"`
// UserConnTimeout specifies the maximum time to wait for a work
// connection. By default, this value is 10.
UserConnTimeout int64 `ini:"user_conn_timeout" json:"user_conn_timeout"`
// HTTPPlugins specify the server plugins support HTTP protocol.
HTTPPlugins map[string]plugin.HTTPPluginOptions `ini:"-" json:"http_plugins"`
// UDPPacketSize specifies the UDP packet size
// By default, this value is 1500
UDPPacketSize int64 `ini:"udp_packet_size" json:"udp_packet_size"`
// Enable golang pprof handlers in dashboard listener.
// Dashboard port must be set first.
PprofEnable bool `ini:"pprof_enable" json:"pprof_enable"`
}
// GetDefaultServerConf returns a server configuration with reasonable
// defaults.
func GetDefaultServerConf() ServerCommonConf {
return ServerCommonConf{
ServerConfig: auth.GetDefaultServerConf(),
BindAddr: "0.0.0.0",
BindPort: 7000,
QUICKeepalivePeriod: 10,
QUICMaxIdleTimeout: 30,
QUICMaxIncomingStreams: 100000,
VhostHTTPTimeout: 60,
DashboardAddr: "0.0.0.0",
LogFile: "console",
LogWay: "console",
LogLevel: "info",
LogMaxDays: 3,
DetailedErrorsToClient: true,
TCPMux: true,
TCPMuxKeepaliveInterval: 60,
TCPKeepAlive: 7200,
AllowPorts: make(map[int]struct{}),
MaxPoolCount: 5,
MaxPortsPerClient: 0,
HeartbeatTimeout: 90,
UserConnTimeout: 10,
HTTPPlugins: make(map[string]plugin.HTTPPluginOptions),
UDPPacketSize: 1500,
}
}
func UnmarshalServerConfFromIni(source interface{}) (ServerCommonConf, error) {
f, err := ini.LoadSources(ini.LoadOptions{
Insensitive: false,
InsensitiveSections: false,
InsensitiveKeys: false,
IgnoreInlineComment: true,
AllowBooleanKeys: true,
}, source)
if err != nil {
return ServerCommonConf{}, err
}
s, err := f.GetSection("common")
if err != nil {
return ServerCommonConf{}, err
}
common := GetDefaultServerConf()
err = s.MapTo(&common)
if err != nil {
return ServerCommonConf{}, err
}
// allow_ports
allowPortStr := s.Key("allow_ports").String()
if allowPortStr != "" {
allowPorts, err := util.ParseRangeNumbers(allowPortStr)
if err != nil {
return ServerCommonConf{}, fmt.Errorf("invalid allow_ports: %v", err)
}
for _, port := range allowPorts {
common.AllowPorts[int(port)] = struct{}{}
}
}
// plugin.xxx
pluginOpts := make(map[string]plugin.HTTPPluginOptions)
for _, section := range f.Sections() {
name := section.Name()
if !strings.HasPrefix(name, "plugin.") {
continue
}
opt, err := loadHTTPPluginOpt(section)
if err != nil {
return ServerCommonConf{}, err
}
pluginOpts[opt.Name] = *opt
}
common.HTTPPlugins = pluginOpts
return common, nil
}
func (cfg *ServerCommonConf) Complete() {
if cfg.LogFile == "console" {
cfg.LogWay = "console"
} else {
cfg.LogWay = "file"
}
if cfg.ProxyBindAddr == "" {
cfg.ProxyBindAddr = cfg.BindAddr
}
if cfg.TLSTrustedCaFile != "" {
cfg.TLSOnly = true
}
}
func (cfg *ServerCommonConf) Validate() error {
if !cfg.DashboardTLSMode {
if cfg.DashboardTLSCertFile != "" {
fmt.Println("WARNING! dashboard_tls_cert_file is invalid when dashboard_tls_mode is false")
}
if cfg.DashboardTLSKeyFile != "" {
fmt.Println("WARNING! dashboard_tls_key_file is invalid when dashboard_tls_mode is false")
}
} else {
if cfg.DashboardTLSCertFile == "" {
return fmt.Errorf("ERROR! dashboard_tls_cert_file must be specified when dashboard_tls_mode is true")
}
if cfg.DashboardTLSKeyFile == "" {
return fmt.Errorf("ERROR! dashboard_tls_cert_file must be specified when dashboard_tls_mode is true")
}
}
return validator.New().Struct(cfg)
}
func loadHTTPPluginOpt(section *ini.Section) (*plugin.HTTPPluginOptions, error) {
name := strings.TrimSpace(strings.TrimPrefix(section.Name(), "plugin."))
opt := new(plugin.HTTPPluginOptions)
err := section.MapTo(opt)
if err != nil {
return nil, err
}
opt.Name = name
return opt, nil
}

218
pkg/config/server_test.go Normal file
View File

@@ -0,0 +1,218 @@
// Copyright 2020 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 config
import (
"testing"
"github.com/stretchr/testify/assert"
"github.com/fatedier/frp/pkg/auth"
plugin "github.com/fatedier/frp/pkg/plugin/server"
)
func Test_LoadServerCommonConf(t *testing.T) {
assert := assert.New(t)
testcases := []struct {
source []byte
expected ServerCommonConf
}{
{
source: []byte(`
# [common] is integral section
[common]
bind_addr = 0.0.0.9
bind_port = 7009
bind_udp_port = 7008
kcp_bind_port = 7007
proxy_bind_addr = 127.0.0.9
vhost_http_port = 89
vhost_https_port = 449
vhost_http_timeout = 69
tcpmux_httpconnect_port = 1339
dashboard_addr = 0.0.0.9
dashboard_port = 7509
dashboard_user = admin9
dashboard_pwd = admin9
enable_prometheus
assets_dir = ./static9
log_file = ./frps.log9
log_way = file
log_level = info9
log_max_days = 39
disable_log_color = false
detailed_errors_to_client
authentication_method = token
authenticate_heartbeats = false
authenticate_new_work_conns = false
token = 123456789
oidc_issuer = test9
oidc_audience = test9
oidc_skip_expiry_check
oidc_skip_issuer_check
heartbeat_timeout = 99
user_conn_timeout = 9
allow_ports = 10-12,99
max_pool_count = 59
max_ports_per_client = 9
tls_only = false
tls_cert_file = server.crt
tls_key_file = server.key
tls_trusted_ca_file = ca.crt
subdomain_host = frps.com
tcp_mux
udp_packet_size = 1509
[plugin.user-manager]
addr = 127.0.0.1:9009
path = /handler
ops = Login
[plugin.port-manager]
addr = 127.0.0.1:9009
path = /handler
ops = NewProxy
tls_verify
`),
expected: ServerCommonConf{
ServerConfig: auth.ServerConfig{
BaseConfig: auth.BaseConfig{
AuthenticationMethod: "token",
AuthenticateHeartBeats: false,
AuthenticateNewWorkConns: false,
},
TokenConfig: auth.TokenConfig{
Token: "123456789",
},
OidcServerConfig: auth.OidcServerConfig{
OidcIssuer: "test9",
OidcAudience: "test9",
OidcSkipExpiryCheck: true,
OidcSkipIssuerCheck: true,
},
},
BindAddr: "0.0.0.9",
BindPort: 7009,
BindUDPPort: 7008,
KCPBindPort: 7007,
QUICKeepalivePeriod: 10,
QUICMaxIdleTimeout: 30,
QUICMaxIncomingStreams: 100000,
ProxyBindAddr: "127.0.0.9",
VhostHTTPPort: 89,
VhostHTTPSPort: 449,
VhostHTTPTimeout: 69,
TCPMuxHTTPConnectPort: 1339,
DashboardAddr: "0.0.0.9",
DashboardPort: 7509,
DashboardUser: "admin9",
DashboardPwd: "admin9",
EnablePrometheus: true,
AssetsDir: "./static9",
LogFile: "./frps.log9",
LogWay: "file",
LogLevel: "info9",
LogMaxDays: 39,
DisableLogColor: false,
DetailedErrorsToClient: true,
HeartbeatTimeout: 99,
UserConnTimeout: 9,
AllowPorts: map[int]struct{}{
10: {},
11: {},
12: {},
99: {},
},
MaxPoolCount: 59,
MaxPortsPerClient: 9,
TLSOnly: true,
TLSCertFile: "server.crt",
TLSKeyFile: "server.key",
TLSTrustedCaFile: "ca.crt",
SubDomainHost: "frps.com",
TCPMux: true,
TCPMuxKeepaliveInterval: 60,
TCPKeepAlive: 7200,
UDPPacketSize: 1509,
HTTPPlugins: map[string]plugin.HTTPPluginOptions{
"user-manager": {
Name: "user-manager",
Addr: "127.0.0.1:9009",
Path: "/handler",
Ops: []string{"Login"},
},
"port-manager": {
Name: "port-manager",
Addr: "127.0.0.1:9009",
Path: "/handler",
Ops: []string{"NewProxy"},
TLSVerify: true,
},
},
},
},
{
source: []byte(`
# [common] is integral section
[common]
bind_addr = 0.0.0.9
bind_port = 7009
bind_udp_port = 7008
`),
expected: ServerCommonConf{
ServerConfig: auth.ServerConfig{
BaseConfig: auth.BaseConfig{
AuthenticationMethod: "token",
AuthenticateHeartBeats: false,
AuthenticateNewWorkConns: false,
},
},
BindAddr: "0.0.0.9",
BindPort: 7009,
BindUDPPort: 7008,
QUICKeepalivePeriod: 10,
QUICMaxIdleTimeout: 30,
QUICMaxIncomingStreams: 100000,
ProxyBindAddr: "0.0.0.9",
VhostHTTPTimeout: 60,
DashboardAddr: "0.0.0.0",
DashboardUser: "",
DashboardPwd: "",
EnablePrometheus: false,
LogFile: "console",
LogWay: "console",
LogLevel: "info",
LogMaxDays: 3,
DetailedErrorsToClient: true,
TCPMux: true,
TCPMuxKeepaliveInterval: 60,
TCPKeepAlive: 7200,
AllowPorts: make(map[int]struct{}),
MaxPoolCount: 5,
HeartbeatTimeout: 90,
UserConnTimeout: 10,
HTTPPlugins: make(map[string]plugin.HTTPPluginOptions),
UDPPacketSize: 1500,
},
},
}
for _, c := range testcases {
actual, err := UnmarshalServerConfFromIni(c.source)
assert.NoError(err)
actual.Complete()
assert.Equal(c.expected, actual)
}
}

View File

@@ -41,6 +41,15 @@ func NewBandwidthQuantity(s string) (BandwidthQuantity, error) {
return q, nil return q, nil
} }
func MustBandwidthQuantity(s string) BandwidthQuantity {
q := BandwidthQuantity{}
err := q.UnmarshalString(s)
if err != nil {
panic(err)
}
return q
}
func (q *BandwidthQuantity) Equal(u *BandwidthQuantity) bool { func (q *BandwidthQuantity) Equal(u *BandwidthQuantity) bool {
if q == nil && u == nil { if q == nil && u == nil {
return true return true
@@ -66,21 +75,22 @@ func (q *BandwidthQuantity) UnmarshalString(s string) error {
f float64 f float64
err error err error
) )
if strings.HasSuffix(s, "MB") { switch {
case strings.HasSuffix(s, "MB"):
base = MB base = MB
fstr := strings.TrimSuffix(s, "MB") fstr := strings.TrimSuffix(s, "MB")
f, err = strconv.ParseFloat(fstr, 64) f, err = strconv.ParseFloat(fstr, 64)
if err != nil { if err != nil {
return err return err
} }
} else if strings.HasSuffix(s, "KB") { case strings.HasSuffix(s, "KB"):
base = KB base = KB
fstr := strings.TrimSuffix(s, "KB") fstr := strings.TrimSuffix(s, "KB")
f, err = strconv.ParseFloat(fstr, 64) f, err = strconv.ParseFloat(fstr, 64)
if err != nil { if err != nil {
return err return err
} }
} else { default:
return errors.New("unit not support") return errors.New("unit not support")
} }

Some files were not shown because too many files have changed in this diff Show More