mirror of
https://github.com/fatedier/frp.git
synced 2025-07-27 15:45:39 +00:00
Compare commits
76 Commits
Author | SHA1 | Date | |
---|---|---|---|
|
649a2f2457 | ||
|
54916793f9 | ||
|
0b06c1c821 | ||
|
bbc6f1687d | ||
|
b250342e27 | ||
|
f76deb8898 | ||
|
611d063e1f | ||
|
0c7d778896 | ||
|
7c21906884 | ||
|
a4106ec4b7 | ||
|
655c52f9ce | ||
|
25cfda5768 | ||
|
b61cb14c8f | ||
|
d5ce4d4916 | ||
|
4f0ee5980d | ||
|
146956ac6e | ||
|
35278ad17f | ||
|
aea9f9fbcc | ||
|
08c17c3247 | ||
|
6934a18f95 | ||
|
5165b0821f | ||
|
0aec869513 | ||
|
826b9db5f2 | ||
|
89d1a1fb2b | ||
|
450e0b7148 | ||
|
a1ac002694 | ||
|
951d33d47c | ||
|
b33ea9274c | ||
|
3b3f3dc2b5 | ||
|
ec0b59732c | ||
|
bae1ecdc69 | ||
|
5c2ab5a749 | ||
|
1a8ac148ca | ||
|
698219b621 | ||
|
229740524e | ||
|
cbeeac06a5 | ||
|
66a69f873f | ||
|
fb13774457 | ||
|
f14ed87b29 | ||
|
07623027bc | ||
|
941ac25648 | ||
|
f645082d72 | ||
|
7793f55545 | ||
|
ca88b07ecf | ||
|
6e305db4be | ||
|
9bb08396c7 | ||
|
64136a3b3e | ||
|
b8037475ed | ||
|
082447f517 | ||
|
cc6486addb | ||
|
57417c83ae | ||
|
d74b45be5d | ||
|
0d02f291e3 | ||
|
42ee536dae | ||
|
c33b5152e7 | ||
|
b6c219aa97 | ||
|
bbc36be052 | ||
|
f5778349d5 | ||
|
71603c6d0b | ||
|
e64fcce417 | ||
|
629f2856b1 | ||
|
aeb9f2b64d | ||
|
85dd41c17b | ||
|
102408d37f | ||
|
495b577819 | ||
|
f56b49ad3b | ||
|
cb1bf71bef | ||
|
b9f062bef2 | ||
|
490019fb51 | ||
|
2e497274ba | ||
|
cf4136fe99 | ||
|
b1e9cff622 | ||
|
db2d1fce76 | ||
|
8579de9d3f | ||
|
0c35273759 | ||
|
6eb8146334 |
@@ -1,5 +0,0 @@
|
||||
Dockerfile
|
||||
.git
|
||||
*~
|
||||
*#
|
||||
.#*
|
@@ -3,6 +3,7 @@ language: go
|
||||
|
||||
go:
|
||||
- 1.10.x
|
||||
- 1.11.x
|
||||
|
||||
install:
|
||||
- make
|
||||
|
17
Dockerfile
17
Dockerfile
@@ -1,17 +0,0 @@
|
||||
FROM golang:1.10
|
||||
|
||||
COPY . /go/src/github.com/fatedier/frp
|
||||
|
||||
RUN cd /go/src/github.com/fatedier/frp \
|
||||
&& make \
|
||||
&& mv bin/frpc /frpc \
|
||||
&& mv bin/frps /frps \
|
||||
&& mv conf/frpc.ini /frpc.ini \
|
||||
&& mv conf/frps.ini /frps.ini \
|
||||
&& make clean
|
||||
|
||||
WORKDIR /
|
||||
|
||||
EXPOSE 80 443 6000 7000 7500
|
||||
|
||||
ENTRYPOINT ["/frps"]
|
@@ -1,12 +0,0 @@
|
||||
FROM alpine:3.5
|
||||
|
||||
COPY tmp/frpc /frpc
|
||||
COPY tmp/frps /frps
|
||||
COPY conf/frpc_min.ini /frpc.ini
|
||||
COPY conf/frps_min.ini /frps.ini
|
||||
|
||||
WORKDIR /
|
||||
|
||||
EXPOSE 80 443 6000 7000 7500
|
||||
|
||||
ENTRYPOINT ["/frps"]
|
@@ -1,21 +0,0 @@
|
||||
FROM golang:1.8 as frpBuild
|
||||
|
||||
COPY . /go/src/github.com/fatedier/frp
|
||||
|
||||
ENV CGO_ENABLED=0
|
||||
|
||||
RUN cd /go/src/github.com/fatedier/frp \
|
||||
&& make
|
||||
|
||||
FROM alpine:3.6
|
||||
|
||||
COPY --from=frpBuild /go/src/github.com/fatedier/frp/bin/frpc /
|
||||
COPY --from=frpBuild /go/src/github.com/fatedier/frp/conf/frpc.ini /
|
||||
COPY --from=frpBuild /go/src/github.com/fatedier/frp/bin/frps /
|
||||
COPY --from=frpBuild /go/src/github.com/fatedier/frp/conf/frps.ini /
|
||||
|
||||
EXPOSE 80 443 6000 7000 7500
|
||||
|
||||
WORKDIR /
|
||||
|
||||
CMD ["/frps","-c","frps.ini"]
|
108
Gopkg.lock
generated
108
Gopkg.lock
generated
@@ -2,23 +2,29 @@
|
||||
|
||||
|
||||
[[projects]]
|
||||
digest = "1:5a91fc342af1f94bce8b760a80d5b709fe53ea10c870a5daf1dc7e9fada8525f"
|
||||
name = "github.com/armon/go-socks5"
|
||||
packages = ["."]
|
||||
pruneopts = "UT"
|
||||
revision = "e75332964ef517daa070d7c38a9466a0d687e0a5"
|
||||
|
||||
[[projects]]
|
||||
digest = "1:a2c1d0e43bd3baaa071d1b9ed72c27d78169b2b269f71c105ac4ba34b1be4a39"
|
||||
name = "github.com/davecgh/go-spew"
|
||||
packages = ["spew"]
|
||||
pruneopts = "UT"
|
||||
revision = "346938d642f2ec3594ed81d874461961cd0faa76"
|
||||
version = "v1.1.0"
|
||||
|
||||
[[projects]]
|
||||
digest = "1:0f8ca5fa815e8058bfbf5d0e4ad0c2f8334d68cac86e3bfee94b4e3031e9f69f"
|
||||
name = "github.com/fatedier/beego"
|
||||
packages = ["logs"]
|
||||
pruneopts = "UT"
|
||||
revision = "6c6a4f5bd5eb5a39f7e289b8f345b55f75e7e3e8"
|
||||
|
||||
[[projects]]
|
||||
branch = "master"
|
||||
digest = "1:edb90bd03be19aa95d375ed6eb5d681538e0a3f7d2a057b69bc2ca6e5217477a"
|
||||
name = "github.com/fatedier/golib"
|
||||
packages = [
|
||||
"control/shutdown",
|
||||
@@ -28,116 +34,162 @@
|
||||
"msg/json",
|
||||
"net",
|
||||
"net/mux",
|
||||
"pool"
|
||||
"pool",
|
||||
]
|
||||
revision = "354693cdd7fd9fa4f207c2f91ec2534615d3e5e5"
|
||||
pruneopts = "UT"
|
||||
revision = "ff8cd814b04901d617b7fffaca6fedb81067821d"
|
||||
|
||||
[[projects]]
|
||||
branch = "frp"
|
||||
digest = "1:6621826f49b587c0d6f868e1c56d2bbbc1d75597347d97419b3b027e8a753bdb"
|
||||
name = "github.com/fatedier/kcp-go"
|
||||
packages = ["."]
|
||||
pruneopts = "UT"
|
||||
revision = "cd167d2f15f451b0f33780ce862fca97adc0331e"
|
||||
|
||||
[[projects]]
|
||||
digest = "1:29a5ab9fa9e845fd8e8726f31b187d710afd271ef1eb32085fe3d604b7e06382"
|
||||
name = "github.com/golang/snappy"
|
||||
packages = ["."]
|
||||
pruneopts = "UT"
|
||||
revision = "553a641470496b2327abcac10b36396bd98e45c9"
|
||||
|
||||
[[projects]]
|
||||
digest = "1:c79fb010be38a59d657c48c6ba1d003a8aa651fa56b579d959d74573b7dff8e1"
|
||||
name = "github.com/gorilla/context"
|
||||
packages = ["."]
|
||||
pruneopts = "UT"
|
||||
revision = "08b5f424b9271eedf6f9f0ce86cb9396ed337a42"
|
||||
version = "v1.1.1"
|
||||
|
||||
[[projects]]
|
||||
digest = "1:e73f5b0152105f18bc131fba127d9949305c8693f8a762588a82a48f61756f5f"
|
||||
name = "github.com/gorilla/mux"
|
||||
packages = ["."]
|
||||
pruneopts = "UT"
|
||||
revision = "e3702bed27f0d39777b0b37b664b6280e8ef8fbf"
|
||||
version = "v1.6.2"
|
||||
|
||||
[[projects]]
|
||||
digest = "1:43dd08a10854b2056e615d1b1d22ac94559d822e1f8b6fcc92c1a1057e85188e"
|
||||
name = "github.com/gorilla/websocket"
|
||||
packages = ["."]
|
||||
pruneopts = "UT"
|
||||
revision = "ea4d1f681babbce9545c9c5f3d5194a789c89f5b"
|
||||
version = "v1.2.0"
|
||||
|
||||
[[projects]]
|
||||
digest = "1:6074024c54115955afc83ee5064367523bbc55e4eb0e9cf145e43c9c0371918c"
|
||||
name = "github.com/hashicorp/yamux"
|
||||
packages = ["."]
|
||||
pruneopts = "UT"
|
||||
revision = "2658be15c5f05e76244154714161f17e3e77de2e"
|
||||
|
||||
[[projects]]
|
||||
digest = "1:870d441fe217b8e689d7949fef6e43efbc787e50f200cb1e70dbca9204a1d6be"
|
||||
name = "github.com/inconshreveable/mousetrap"
|
||||
packages = ["."]
|
||||
pruneopts = "UT"
|
||||
revision = "76626ae9c91c4f2a10f34cad8ce83ea42c93bb75"
|
||||
version = "v1.0"
|
||||
|
||||
[[projects]]
|
||||
name = "github.com/julienschmidt/httprouter"
|
||||
packages = ["."]
|
||||
revision = "8c199fb6259ffc1af525cc3ad52ee60ba8359669"
|
||||
version = "v1.1"
|
||||
|
||||
[[projects]]
|
||||
digest = "1:40e195917a951a8bf867cd05de2a46aaf1806c50cf92eebf4c16f78cd196f747"
|
||||
name = "github.com/pkg/errors"
|
||||
packages = ["."]
|
||||
pruneopts = "UT"
|
||||
revision = "645ef00459ed84a119197bfb8d8205042c6df63d"
|
||||
version = "v0.8.0"
|
||||
|
||||
[[projects]]
|
||||
digest = "1:0028cb19b2e4c3112225cd871870f2d9cf49b9b4276531f03438a88e94be86fe"
|
||||
name = "github.com/pmezard/go-difflib"
|
||||
packages = ["difflib"]
|
||||
pruneopts = "UT"
|
||||
revision = "792786c7400a136282c1664665ae0a8db921c6c2"
|
||||
version = "v1.0.0"
|
||||
|
||||
[[projects]]
|
||||
digest = "1:bc91590d3e20673d5e33267fc140e7dadddde0b84f2e9030547ba86859d2d13e"
|
||||
name = "github.com/rakyll/statik"
|
||||
packages = ["fs"]
|
||||
pruneopts = "UT"
|
||||
revision = "fd36b3595eb2ec8da4b8153b107f7ea08504899d"
|
||||
version = "v0.1.1"
|
||||
|
||||
[[projects]]
|
||||
digest = "1:4c01929c0b1665523b469482fc8241a04519bd5bfc97a1c113367cfadebab07b"
|
||||
name = "github.com/rodaine/table"
|
||||
packages = ["."]
|
||||
pruneopts = "UT"
|
||||
revision = "212a2ad1c462ed4d5b5511ea2b480a573281dbbd"
|
||||
version = "v1.0.0"
|
||||
|
||||
[[projects]]
|
||||
digest = "1:645cabccbb4fa8aab25a956cbcbdf6a6845ca736b2c64e197ca7cbb9d210b939"
|
||||
name = "github.com/spf13/cobra"
|
||||
packages = ["."]
|
||||
revision = "a1f051bc3eba734da4772d60e2d677f47cf93ef4"
|
||||
version = "v0.0.2"
|
||||
pruneopts = "UT"
|
||||
revision = "ef82de70bb3f60c65fb8eebacbb2d122ef517385"
|
||||
version = "v0.0.3"
|
||||
|
||||
[[projects]]
|
||||
digest = "1:9424f440bba8f7508b69414634aef3b2b3a877e522d8a4624692412805407bb7"
|
||||
name = "github.com/spf13/pflag"
|
||||
packages = ["."]
|
||||
pruneopts = "UT"
|
||||
revision = "583c0c0531f06d5278b7d917446061adc344b5cd"
|
||||
version = "v1.0.1"
|
||||
|
||||
[[projects]]
|
||||
digest = "1:f85e109eda8f6080877185d1c39e98dd8795e1780c08beca28304b87fd855a1c"
|
||||
name = "github.com/stretchr/testify"
|
||||
packages = ["assert"]
|
||||
pruneopts = "UT"
|
||||
revision = "12b6f73e6084dad08a7c6e575284b177ecafbc71"
|
||||
version = "v1.2.1"
|
||||
|
||||
[[projects]]
|
||||
branch = "master"
|
||||
digest = "1:710ccf83337a9ca27abe968c3e58fdf16bd69d76b9870dadafc511e94fc33d7f"
|
||||
name = "github.com/templexxx/cpufeat"
|
||||
packages = ["."]
|
||||
pruneopts = "UT"
|
||||
revision = "3794dfbfb04749f896b521032f69383f24c3687e"
|
||||
|
||||
[[projects]]
|
||||
digest = "1:7bf0e709c5dd92c937e6f59a76056fe0a89cfe2f52ce25493c6337d23781af0a"
|
||||
name = "github.com/templexxx/reedsolomon"
|
||||
packages = ["."]
|
||||
pruneopts = "UT"
|
||||
revision = "5e06b81a1c7628d9c8d4fb7c3c4e401e37db39b4"
|
||||
version = "0.1.1"
|
||||
|
||||
[[projects]]
|
||||
digest = "1:a0a269bea865974fc4d583373c984a5aa60cf98b5aa4f3e1b5de527891d37845"
|
||||
name = "github.com/templexxx/xor"
|
||||
packages = ["."]
|
||||
pruneopts = "UT"
|
||||
revision = "0af8e873c554da75f37f2049cdffda804533d44c"
|
||||
version = "0.1.2"
|
||||
|
||||
[[projects]]
|
||||
digest = "1:97293f3bd0b9f81484da18dba66a20de340307b43835a91157aaaee484c80e9b"
|
||||
name = "github.com/tjfoc/gmsm"
|
||||
packages = ["sm4"]
|
||||
pruneopts = "UT"
|
||||
revision = "98aa888b79d8de04afe0fccf45ed10594efc858b"
|
||||
version = "v1.1"
|
||||
|
||||
[[projects]]
|
||||
digest = "1:8f70510b21fd07eba5bd4e0f84d49d932ea74c8b0ea20a5807e9492cc819928c"
|
||||
name = "github.com/vaughan0/go-ini"
|
||||
packages = ["."]
|
||||
pruneopts = "UT"
|
||||
revision = "a98ad7ee00ec53921f08832bc06ecf7fd600e6a1"
|
||||
|
||||
[[projects]]
|
||||
digest = "1:a14b2b0fb9cc2d9ed073aac9834ff93ded673b94fedee4eead3cd9a65e80a40b"
|
||||
name = "golang.org/x/crypto"
|
||||
packages = [
|
||||
"blowfish",
|
||||
@@ -147,12 +199,14 @@
|
||||
"salsa20/salsa",
|
||||
"tea",
|
||||
"twofish",
|
||||
"xtea"
|
||||
"xtea",
|
||||
]
|
||||
pruneopts = "UT"
|
||||
revision = "4ec37c66abab2c7e02ae775328b2ff001c3f025a"
|
||||
|
||||
[[projects]]
|
||||
branch = "master"
|
||||
digest = "1:4781de952463c8e97ab707c03c73f5f53296be672d1bceac9323393a7b6e7e0a"
|
||||
name = "golang.org/x/net"
|
||||
packages = [
|
||||
"bpf",
|
||||
@@ -161,13 +215,37 @@
|
||||
"internal/socket",
|
||||
"internal/socks",
|
||||
"ipv4",
|
||||
"proxy"
|
||||
"proxy",
|
||||
"websocket",
|
||||
]
|
||||
revision = "d11bb6cd8e3c4e60239c9cb20ef68586d74500d0"
|
||||
pruneopts = "UT"
|
||||
revision = "dfa909b99c79129e1100513e5cd36307665e5723"
|
||||
|
||||
[solve-meta]
|
||||
analyzer-name = "dep"
|
||||
analyzer-version = 1
|
||||
inputs-digest = "d934d16928772cfb22c55a39964c7ca364d02fe1ab680a90cdb5c3c8be256273"
|
||||
input-imports = [
|
||||
"github.com/armon/go-socks5",
|
||||
"github.com/fatedier/beego/logs",
|
||||
"github.com/fatedier/golib/control/shutdown",
|
||||
"github.com/fatedier/golib/crypto",
|
||||
"github.com/fatedier/golib/errors",
|
||||
"github.com/fatedier/golib/io",
|
||||
"github.com/fatedier/golib/msg/json",
|
||||
"github.com/fatedier/golib/net",
|
||||
"github.com/fatedier/golib/net/mux",
|
||||
"github.com/fatedier/golib/pool",
|
||||
"github.com/fatedier/kcp-go",
|
||||
"github.com/gorilla/mux",
|
||||
"github.com/gorilla/websocket",
|
||||
"github.com/hashicorp/yamux",
|
||||
"github.com/rakyll/statik/fs",
|
||||
"github.com/rodaine/table",
|
||||
"github.com/spf13/cobra",
|
||||
"github.com/stretchr/testify/assert",
|
||||
"github.com/vaughan0/go-ini",
|
||||
"golang.org/x/net/ipv4",
|
||||
"golang.org/x/net/websocket",
|
||||
]
|
||||
solver-name = "gps-cdcl"
|
||||
solver-version = 1
|
||||
|
12
Gopkg.toml
12
Gopkg.toml
@@ -35,7 +35,7 @@
|
||||
|
||||
[[constraint]]
|
||||
name = "github.com/fatedier/golib"
|
||||
branch = "master"
|
||||
revision = "ff8cd814b04901d617b7fffaca6fedb81067821d"
|
||||
|
||||
[[constraint]]
|
||||
branch = "frp"
|
||||
@@ -49,6 +49,10 @@
|
||||
name = "github.com/hashicorp/yamux"
|
||||
revision = "2658be15c5f05e76244154714161f17e3e77de2e"
|
||||
|
||||
[[constraint]]
|
||||
name = "github.com/gorilla/mux"
|
||||
version = "1.6.2"
|
||||
|
||||
[[constraint]]
|
||||
name = "github.com/rakyll/statik"
|
||||
version = "0.1.0"
|
||||
@@ -59,12 +63,16 @@
|
||||
|
||||
[[constraint]]
|
||||
name = "github.com/spf13/cobra"
|
||||
version = "0.0.2"
|
||||
version = "0.0.3"
|
||||
|
||||
[[constraint]]
|
||||
name = "github.com/vaughan0/go-ini"
|
||||
revision = "a98ad7ee00ec53921f08832bc06ecf7fd600e6a1"
|
||||
|
||||
[[override]]
|
||||
name = "github.com/templexxx/reedsolomon"
|
||||
version = "0.1.1"
|
||||
|
||||
[prune]
|
||||
go-tests = true
|
||||
unused-packages = true
|
||||
|
20
Makefile
20
Makefile
@@ -26,24 +26,18 @@ frpc:
|
||||
test: gotest
|
||||
|
||||
gotest:
|
||||
go test -v ./assets/...
|
||||
go test -v ./client/...
|
||||
go test -v ./cmd/...
|
||||
go test -v ./models/...
|
||||
go test -v ./server/...
|
||||
go test -v ./utils/...
|
||||
go test -v --cover ./assets/...
|
||||
go test -v --cover ./client/...
|
||||
go test -v --cover ./cmd/...
|
||||
go test -v --cover ./models/...
|
||||
go test -v --cover ./server/...
|
||||
go test -v --cover ./utils/...
|
||||
|
||||
ci:
|
||||
cd ./tests && ./run_test.sh && cd -
|
||||
go test -v ./tests/...
|
||||
cd ./tests && ./clean_test.sh && cd -
|
||||
|
||||
cic:
|
||||
cd ./tests && ./clean_test.sh && cd -
|
||||
go test -count=1 -p=1 -v ./tests/...
|
||||
|
||||
alltest: gotest ci
|
||||
|
||||
clean:
|
||||
rm -f ./bin/frpc
|
||||
rm -f ./bin/frps
|
||||
cd ./tests && ./clean_test.sh && cd -
|
||||
|
@@ -18,6 +18,8 @@ app:
|
||||
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
|
||||
env CGO_ENABLED=0 GOOS=linux GOARCH=arm go build -ldflags "$(LDFLAGS)" -o ./frps_linux_arm ./cmd/frps
|
||||
env CGO_ENABLED=0 GOOS=linux GOARCH=arm64 go build -ldflags "$(LDFLAGS)" -o ./frpc_linux_arm64 ./cmd/frpc
|
||||
env CGO_ENABLED=0 GOOS=linux GOARCH=arm64 go build -ldflags "$(LDFLAGS)" -o ./frps_linux_arm64 ./cmd/frps
|
||||
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
|
||||
|
148
README.md
148
README.md
@@ -6,13 +6,14 @@
|
||||
|
||||
## What is frp?
|
||||
|
||||
frp is a fast reverse proxy to help you expose a local server behind a NAT or firewall to the internet. Now, it supports tcp, udp, http and https protocol when requests can be forwarded by domains to backward web services.
|
||||
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 & udp, as well as http and https protocols, where requests can be forwarded to internal services by domain name.
|
||||
|
||||
Now it also try to support p2p connect.
|
||||
|
||||
## Table of Contents
|
||||
|
||||
<!-- vim-markdown-toc GFM -->
|
||||
|
||||
* [What can I do with frp?](#what-can-i-do-with-frp)
|
||||
* [Status](#status)
|
||||
* [Architecture](#architecture)
|
||||
* [Example Usage](#example-usage)
|
||||
@@ -25,6 +26,7 @@ frp is a fast reverse proxy to help you expose a local server behind a NAT or fi
|
||||
* [P2P Mode](#p2p-mode)
|
||||
* [Features](#features)
|
||||
* [Configuration File](#configuration-file)
|
||||
* [Configuration file template](#configuration-file-template)
|
||||
* [Dashboard](#dashboard)
|
||||
* [Authentication](#authentication)
|
||||
* [Encryption and Compression](#encryption-and-compression)
|
||||
@@ -35,7 +37,10 @@ frp is a fast reverse proxy to help you expose a local server behind a NAT or fi
|
||||
* [TCP Stream Multiplexing](#tcp-stream-multiplexing)
|
||||
* [Support KCP Protocol](#support-kcp-protocol)
|
||||
* [Connection Pool](#connection-pool)
|
||||
* [Load balancing](#load-balancing)
|
||||
* [Health Check](#health-check)
|
||||
* [Rewriting the Host Header](#rewriting-the-host-header)
|
||||
* [Set Headers In HTTP Request](#set-headers-in-http-request)
|
||||
* [Get Real IP](#get-real-ip)
|
||||
* [Password protecting your web service](#password-protecting-your-web-service)
|
||||
* [Custom subdomain names](#custom-subdomain-names)
|
||||
@@ -52,11 +57,6 @@ frp is a fast reverse proxy to help you expose a local server behind a NAT or fi
|
||||
|
||||
<!-- vim-markdown-toc -->
|
||||
|
||||
## What can I do with frp?
|
||||
|
||||
* Expose any http and https service behind a NAT or firewall to the internet by a server with public IP address(Name-based Virtual Host Support).
|
||||
* Expose any tcp or udp service behind a NAT or firewall to the internet by a server with public IP address.
|
||||
|
||||
## Status
|
||||
|
||||
frp is under development and you can try it with latest release version. Master branch for releasing stable version when dev branch for developing.
|
||||
@@ -343,6 +343,34 @@ You can find features which this document not metioned from full example configu
|
||||
|
||||
[frpc full configuration file](./conf/frpc_full.ini)
|
||||
|
||||
### Configuration file template
|
||||
|
||||
Configuration file tempalte can be rendered using os environments. Template uses Go's standard format.
|
||||
|
||||
```ini
|
||||
# frpc.ini
|
||||
[common]
|
||||
server_addr = {{ .Envs.FRP_SERVER_ADDR }}
|
||||
server_port = 7000
|
||||
|
||||
[ssh]
|
||||
type = tcp
|
||||
local_ip = 127.0.0.1
|
||||
local_port = 22
|
||||
remote_port = {{ .Envs.FRP_SSH_REMOTE_PORT }}
|
||||
```
|
||||
|
||||
Start frpc program:
|
||||
|
||||
```
|
||||
export FRP_SERVER_ADDR="x.x.x.x"
|
||||
export FRP_SSH_REMOTE_PORT="6000"
|
||||
./frpc -c ./frpc.ini
|
||||
```
|
||||
|
||||
frpc will auto render configuration file template using os environments.
|
||||
All environments has prefix `.Envs`.
|
||||
|
||||
### Dashboard
|
||||
|
||||
Check frp's status and proxies's statistics information by Dashboard.
|
||||
@@ -363,11 +391,7 @@ Then visit `http://[server_addr]:7500` to see dashboard, default username and pa
|
||||
|
||||
### Authentication
|
||||
|
||||
Since v0.10.0, you only need to set `token` in frps.ini and frpc.ini.
|
||||
|
||||
Note that time duration between server of frpc and frps mustn't exceed 15 minutes because timestamp is used for authentication.
|
||||
|
||||
Howerver, this timeout duration can be modified by setting `authentication_timeout` in frps's configure file. It's defalut value is 900, means 15 minutes. If it is equals 0, then frps will not check authentication timeout.
|
||||
`token` in frps.ini and frpc.ini should be same.
|
||||
|
||||
### Encryption and Compression
|
||||
|
||||
@@ -483,9 +507,81 @@ This feature is fit for a large number of short connections.
|
||||
pool_count = 1
|
||||
```
|
||||
|
||||
### Load balancing
|
||||
|
||||
Load balancing is supported by `group`.
|
||||
This feature is available only for type `tcp` now.
|
||||
|
||||
```ini
|
||||
# frpc.ini
|
||||
[test1]
|
||||
type = tcp
|
||||
local_port = 8080
|
||||
remote_port = 80
|
||||
group = web
|
||||
group_key = 123
|
||||
|
||||
[test2]
|
||||
type = tcp
|
||||
local_port = 8081
|
||||
remote_port = 80
|
||||
group = web
|
||||
group_key = 123
|
||||
```
|
||||
|
||||
`group_key` is used for authentication.
|
||||
|
||||
Proxies in same group will accept connections from port 80 randomly.
|
||||
|
||||
### Health Check
|
||||
|
||||
Health check feature can help you achieve high availability with load balancing.
|
||||
|
||||
Add `health_check_type = {type}` to enable health check.
|
||||
|
||||
**type** can be tcp or http.
|
||||
|
||||
Type tcp will dial the service port and type http will send a http rquest to service and require a 200 response.
|
||||
|
||||
Type tcp configuration:
|
||||
|
||||
```ini
|
||||
# frpc.ini
|
||||
[test1]
|
||||
type = tcp
|
||||
local_port = 22
|
||||
remote_port = 6000
|
||||
# enable tcp health check
|
||||
health_check_type = tcp
|
||||
# dial timeout seconds
|
||||
health_check_timeout_s = 3
|
||||
# if continuous failed in 3 times, the proxy will be removed from frps
|
||||
health_check_max_failed = 3
|
||||
# every 10 seconds will do a health check
|
||||
health_check_interval_s = 10
|
||||
```
|
||||
|
||||
Type http configuration:
|
||||
```ini
|
||||
# frpc.ini
|
||||
[web]
|
||||
type = http
|
||||
local_ip = 127.0.0.1
|
||||
local_port = 80
|
||||
custom_domains = test.yourdomain.com
|
||||
# enable http health check
|
||||
health_check_type = http
|
||||
# frpc will send a GET http request '/status' to local http service
|
||||
# http service is alive when it return 2xx http response code
|
||||
health_check_url = /status
|
||||
health_check_interval_s = 10
|
||||
health_check_max_failed = 3
|
||||
health_check_timeout_s = 3
|
||||
```
|
||||
|
||||
### Rewriting the Host Header
|
||||
|
||||
When forwarding to a local port, frp does not modify the tunneled HTTP requests at all, they are copied to your server byte-for-byte as they are received. Some application servers use the Host header for determining which development site to display. For this reason, frp can rewrite your requests with a modified Host header. Use the `host_header_rewrite` switch to rewrite incoming HTTP requests.
|
||||
When forwarding to a local port, frp does not modify the tunneled HTTP requests at all, they are copied to your server byte-for-byte as they are received. Some application servers use the Host header for determining which development site to display. For this reason, frp can rewrite your requests with a modified host header. Use the `host_header_rewrite` switch to rewrite incoming HTTP requests.
|
||||
|
||||
```ini
|
||||
# frpc.ini
|
||||
@@ -496,7 +592,24 @@ custom_domains = test.yourdomain.com
|
||||
host_header_rewrite = dev.yourdomain.com
|
||||
```
|
||||
|
||||
If `host_header_rewrite` is specified, the Host header will be rewritten to match the hostname portion of the forwarding address.
|
||||
If `host_header_rewrite` is specified, the host header will be rewritten to match the hostname portion of the forwarding address.
|
||||
|
||||
### Set Headers In HTTP Request
|
||||
|
||||
You can set headers for proxy which type is `http`.
|
||||
|
||||
```ini
|
||||
# frpc.ini
|
||||
[web]
|
||||
type = http
|
||||
local_port = 80
|
||||
custom_domains = test.yourdomain.com
|
||||
host_header_rewrite = dev.yourdomain.com
|
||||
header_X-From-Where = frp
|
||||
```
|
||||
|
||||
Note that params which have prefix `header_` will be added to http request headers.
|
||||
In this example, it will set header `X-From-Where: frp` to http request.
|
||||
|
||||
### Get Real IP
|
||||
|
||||
@@ -504,8 +617,6 @@ Features for http proxy only.
|
||||
|
||||
You can get user's real IP from http request header `X-Forwarded-For` and `X-Real-IP`.
|
||||
|
||||
**Note that now you can only get these two headers in first request of each user connection.**
|
||||
|
||||
### Password protecting your web service
|
||||
|
||||
Anyone who can guess your tunnel URL can access your local web server unless you protect it with a password.
|
||||
@@ -521,7 +632,7 @@ type = http
|
||||
local_port = 80
|
||||
custom_domains = test.yourdomain.com
|
||||
http_user = abc
|
||||
http_passwd = abc
|
||||
http_pwd = abc
|
||||
```
|
||||
|
||||
Visit `http://test.yourdomain.com` and now you need to input username and password.
|
||||
@@ -598,7 +709,7 @@ local_port = 6000-6006,6007
|
||||
remote_port = 6000-6006,6007
|
||||
```
|
||||
|
||||
frpc will generate 6 proxies like `test_tcp_0, test_tcp_1 ... test_tcp_5`.
|
||||
frpc will generate 8 proxies like `test_tcp_0, test_tcp_1 ... test_tcp_7`.
|
||||
|
||||
### Plugin
|
||||
|
||||
@@ -626,7 +737,6 @@ plugin_http_passwd = abc
|
||||
|
||||
* Log http request information in frps.
|
||||
* Direct reverse proxy, like haproxy.
|
||||
* Load balance to different service in frpc.
|
||||
* kubernetes ingress support.
|
||||
|
||||
## Contributing
|
||||
|
157
README_zh.md
157
README_zh.md
@@ -4,13 +4,12 @@
|
||||
|
||||
[README](README.md) | [中文文档](README_zh.md)
|
||||
|
||||
frp 是一个可用于内网穿透的高性能的反向代理应用,支持 tcp, udp, http, https 协议。
|
||||
frp 是一个可用于内网穿透的高性能的反向代理应用,支持 tcp, udp 协议,为 http 和 https 应用协议提供了额外的能力,且尝试性支持了点对点穿透。
|
||||
|
||||
## 目录
|
||||
|
||||
<!-- vim-markdown-toc GFM -->
|
||||
|
||||
* [frp 的作用](#frp-的作用)
|
||||
* [开发状态](#开发状态)
|
||||
* [架构](#架构)
|
||||
* [使用示例](#使用示例)
|
||||
@@ -23,6 +22,7 @@ frp 是一个可用于内网穿透的高性能的反向代理应用,支持 tcp
|
||||
* [点对点内网穿透](#点对点内网穿透)
|
||||
* [功能说明](#功能说明)
|
||||
* [配置文件](#配置文件)
|
||||
* [配置文件模版渲染](#配置文件模版渲染)
|
||||
* [Dashboard](#dashboard)
|
||||
* [身份验证](#身份验证)
|
||||
* [加密与压缩](#加密与压缩)
|
||||
@@ -33,7 +33,10 @@ frp 是一个可用于内网穿透的高性能的反向代理应用,支持 tcp
|
||||
* [TCP 多路复用](#tcp-多路复用)
|
||||
* [底层通信可选 kcp 协议](#底层通信可选-kcp-协议)
|
||||
* [连接池](#连接池)
|
||||
* [负载均衡](#负载均衡)
|
||||
* [健康检查](#健康检查)
|
||||
* [修改 Host Header](#修改-host-header)
|
||||
* [设置 HTTP 请求的 header](#设置-http-请求的-header)
|
||||
* [获取用户真实 IP](#获取用户真实-ip)
|
||||
* [通过密码保护你的 web 服务](#通过密码保护你的-web-服务)
|
||||
* [自定义二级域名](#自定义二级域名)
|
||||
@@ -50,15 +53,9 @@ frp 是一个可用于内网穿透的高性能的反向代理应用,支持 tcp
|
||||
|
||||
<!-- vim-markdown-toc -->
|
||||
|
||||
## frp 的作用
|
||||
|
||||
* 利用处于内网或防火墙后的机器,对外网环境提供 http 或 https 服务。
|
||||
* 对于 http, https 服务支持基于域名的虚拟主机,支持自定义域名绑定,使多个域名可以共用一个80端口。
|
||||
* 利用处于内网或防火墙后的机器,对外网环境提供 tcp 和 udp 服务,例如在家里通过 ssh 访问处于公司内网环境内的主机。
|
||||
|
||||
## 开发状态
|
||||
|
||||
frp 仍然处于前期开发阶段,未经充分测试与验证,不推荐用于生产环境。
|
||||
frp 仍然处于开发阶段,未经充分测试与验证,不推荐用于生产环境。
|
||||
|
||||
master 分支用于发布稳定版本,dev 分支用于开发,您可以尝试下载最新的 release 版本进行测试。
|
||||
|
||||
@@ -358,10 +355,41 @@ frp 提供了一种新的代理类型 **xtcp** 用于应对在希望传输大量
|
||||
|
||||
[frpc 完整配置文件](./conf/frpc_full.ini)
|
||||
|
||||
### 配置文件模版渲染
|
||||
|
||||
配置文件支持使用系统环境变量进行模版渲染,模版格式采用 Go 的标准格式。
|
||||
|
||||
示例配置如下:
|
||||
|
||||
```ini
|
||||
# frpc.ini
|
||||
[common]
|
||||
server_addr = {{ .Envs.FRP_SERVER_ADDR }}
|
||||
server_port = 7000
|
||||
|
||||
[ssh]
|
||||
type = tcp
|
||||
local_ip = 127.0.0.1
|
||||
local_port = 22
|
||||
remote_port = {{ .Envs.FRP_SSH_REMOTE_PORT }}
|
||||
```
|
||||
|
||||
启动 frpc 程序:
|
||||
|
||||
```
|
||||
export FRP_SERVER_ADDR="x.x.x.x"
|
||||
export FRP_SSH_REMOTE_PORT="6000"
|
||||
./frpc -c ./frpc.ini
|
||||
```
|
||||
|
||||
frpc 会自动使用环境变量渲染配置文件模版,所有环境变量需要以 `.Envs` 为前缀。
|
||||
|
||||
### Dashboard
|
||||
|
||||
通过浏览器查看 frp 的状态以及代理统计信息展示。
|
||||
|
||||
**注:Dashboard 尚未针对大量的 proxy 数据展示做优化,如果出现 Dashboard 访问较慢的情况,请不要启用此功能。**
|
||||
|
||||
需要在 frps.ini 中指定 dashboard 服务使用的端口,即可开启此功能:
|
||||
|
||||
```ini
|
||||
@@ -378,11 +406,7 @@ dashboard_pwd = admin
|
||||
|
||||
### 身份验证
|
||||
|
||||
从 v0.10.0 版本开始,所有 proxy 配置全部放在客户端(也就是之前版本的特权模式),服务端和客户端的 common 配置中的 `token` 参数一致则身份验证通过。
|
||||
|
||||
需要注意的是 frpc 所在机器和 frps 所在机器的时间相差不能超过 15 分钟,因为时间戳会被用于加密验证中,防止报文被劫持后被其他人利用。
|
||||
|
||||
这个超时时间可以在配置文件中通过 `authentication_timeout` 这个参数来修改,单位为秒,默认值为 900,即 15 分钟。如果修改为 0,则 frps 将不对身份验证报文的时间戳进行超时校验。
|
||||
服务端和客户端的 common 配置中的 `token` 参数一致则身份验证通过。
|
||||
|
||||
### 加密与压缩
|
||||
|
||||
@@ -510,6 +534,78 @@ tcp_mux = false
|
||||
pool_count = 1
|
||||
```
|
||||
|
||||
### 负载均衡
|
||||
|
||||
可以将多个相同类型的 proxy 加入到同一个 group 中,从而实现负载均衡的功能。
|
||||
目前只支持 tcp 类型的 proxy。
|
||||
|
||||
```ini
|
||||
# frpc.ini
|
||||
[test1]
|
||||
type = tcp
|
||||
local_port = 8080
|
||||
remote_port = 80
|
||||
group = web
|
||||
group_key = 123
|
||||
|
||||
[test2]
|
||||
type = tcp
|
||||
local_port = 8081
|
||||
remote_port = 80
|
||||
group = web
|
||||
group_key = 123
|
||||
```
|
||||
|
||||
用户连接 frps 服务器的 80 端口,frps 会将接收到的用户连接随机分发给其中一个存活的 proxy。这样可以在一台 frpc 机器挂掉后仍然有其他节点能够提供服务。
|
||||
|
||||
要求 `group_key` 相同,做权限验证,且 `remote_port` 相同。
|
||||
|
||||
### 健康检查
|
||||
|
||||
通过给 proxy 加上健康检查的功能,可以在要反向代理的服务出现故障时,将这个服务从 frps 中摘除,搭配负载均衡的功能,可以用来实现高可用的架构,避免服务单点故障。
|
||||
|
||||
在每一个 proxy 的配置下加上 `health_check_type = {type}` 来启用健康检查功能。
|
||||
|
||||
**type** 目前可选 tcp 和 http。
|
||||
|
||||
tcp 只要能够建立连接则认为服务正常,http 会发送一个 http 请求,服务需要返回 2xx 的状态码才会被认为正常。
|
||||
|
||||
tcp 示例配置如下:
|
||||
|
||||
```ini
|
||||
# frpc.ini
|
||||
[test1]
|
||||
type = tcp
|
||||
local_port = 22
|
||||
remote_port = 6000
|
||||
# 启用健康检查,类型为 tcp
|
||||
health_check_type = tcp
|
||||
# 建立连接超时时间为 3 秒
|
||||
health_check_timeout_s = 3
|
||||
# 连续 3 次检查失败,此 proxy 会被摘除
|
||||
health_check_max_failed = 3
|
||||
# 每隔 10 秒进行一次健康检查
|
||||
health_check_interval_s = 10
|
||||
```
|
||||
|
||||
http 示例配置如下:
|
||||
|
||||
```ini
|
||||
# frpc.ini
|
||||
[web]
|
||||
type = http
|
||||
local_ip = 127.0.0.1
|
||||
local_port = 80
|
||||
custom_domains = test.yourdomain.com
|
||||
# 启用健康检查,类型为 http
|
||||
health_check_type = http
|
||||
# 健康检查发送 http 请求的 url,后端服务需要返回 2xx 的 http 状态码
|
||||
health_check_url = /status
|
||||
health_check_interval_s = 10
|
||||
health_check_max_failed = 3
|
||||
health_check_timeout_s = 3
|
||||
```
|
||||
|
||||
### 修改 Host Header
|
||||
|
||||
通常情况下 frp 不会修改转发的任何数据。但有一些后端服务会根据 http 请求 header 中的 host 字段来展现不同的网站,例如 nginx 的虚拟主机服务,启用 host-header 的修改功能可以动态修改 http 请求中的 host 字段。该功能仅限于 http 类型的代理。
|
||||
@@ -525,12 +621,26 @@ host_header_rewrite = dev.yourdomain.com
|
||||
|
||||
原来 http 请求中的 host 字段 `test.yourdomain.com` 转发到后端服务时会被替换为 `dev.yourdomain.com`。
|
||||
|
||||
### 设置 HTTP 请求的 header
|
||||
|
||||
对于 `type = http` 的代理,可以设置在转发中动态添加的 header 参数。
|
||||
|
||||
```ini
|
||||
# frpc.ini
|
||||
[web]
|
||||
type = http
|
||||
local_port = 80
|
||||
custom_domains = test.yourdomain.com
|
||||
host_header_rewrite = dev.yourdomain.com
|
||||
header_X-From-Where = frp
|
||||
```
|
||||
|
||||
对于参数配置中所有以 `header_` 开头的参数(支持同时配置多个),都会被添加到 http 请求的 header 中,根据如上的配置,会在请求的 header 中加上 `X-From-Where: frp`。
|
||||
|
||||
### 获取用户真实 IP
|
||||
|
||||
目前只有 **http** 类型的代理支持这一功能,可以通过用户请求的 header 中的 `X-Forwarded-For` 和 `X-Real-IP` 来获取用户真实 IP。
|
||||
|
||||
**需要注意的是,目前只在每一个用户连接的第一个 HTTP 请求中添加了这两个 header。**
|
||||
|
||||
### 通过密码保护你的 web 服务
|
||||
|
||||
由于所有客户端共用一个 frps 的 http 服务端口,任何知道你的域名和 url 的人都能访问到你部署在内网的 web 服务,但是在某些场景下需要确保只有限定的用户才能访问。
|
||||
@@ -575,9 +685,9 @@ local_port = 80
|
||||
subdomain = test
|
||||
```
|
||||
|
||||
frps 和 fprc 都启动成功后,通过 `test.frps.com` 就可以访问到内网的 web 服务。
|
||||
frps 和 frpc 都启动成功后,通过 `test.frps.com` 就可以访问到内网的 web 服务。
|
||||
|
||||
需要注意的是如果 frps 配置了 `subdomain_host`,则 `custom_domains` 中不能是属于 `subdomain_host` 的子域名或者泛域名。
|
||||
**注:如果 frps 配置了 `subdomain_host`,则 `custom_domains` 中不能是属于 `subdomain_host` 的子域名或者泛域名。**
|
||||
|
||||
同一个 http 或 https 类型的代理中 `custom_domains` 和 `subdomain` 可以同时配置。
|
||||
|
||||
@@ -637,7 +747,7 @@ local_port = 6000-6006,6007
|
||||
remote_port = 6000-6006,6007
|
||||
```
|
||||
|
||||
实际连接成功后会创建 6 个 proxy,命名为 `test_tcp_0, test_tcp_1 ... test_tcp_5`。
|
||||
实际连接成功后会创建 8 个 proxy,命名为 `test_tcp_0, test_tcp_1 ... test_tcp_7`。
|
||||
|
||||
### 插件
|
||||
|
||||
@@ -666,9 +776,6 @@ plugin_http_passwd = abc
|
||||
计划在后续版本中加入的功能与优化,排名不分先后,如果有其他功能建议欢迎在 [issues](https://github.com/fatedier/frp/issues) 中反馈。
|
||||
|
||||
* frps 记录 http 请求日志。
|
||||
* frps 支持直接反向代理,类似 haproxy。
|
||||
* frpc 支持负载均衡到后端不同服务。
|
||||
* 集成对 k8s 等平台的支持。
|
||||
|
||||
## 为 frp 做贡献
|
||||
|
||||
@@ -689,6 +796,12 @@ frp 是一个免费且开源的项目,我们欢迎任何人为其开发和进
|
||||
|
||||
frp 交流群:606194980 (QQ 群号)
|
||||
|
||||
### 知识星球
|
||||
|
||||
如果您想学习 frp 相关的知识和技术,或者寻求任何帮助,都可以通过微信扫描下方的二维码付费加入知识星球的官方社群:
|
||||
|
||||

|
||||
|
||||
### 支付宝扫码捐赠
|
||||
|
||||

|
||||
|
@@ -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?b90a32ccfb87def61aaa"></script><script type="text/javascript" src="vendor.js?f04985ef00f520142368"></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?14bea8276eef86cc7c61"></script><script type="text/javascript" src="vendor.js?51925ec1a77936b64d61"></script></body> </html>
|
@@ -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,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:"f04985ef00f520142368"}[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}}([]);
|
||||
!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}}([]);
|
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
@@ -23,7 +23,7 @@ import (
|
||||
"github.com/fatedier/frp/g"
|
||||
frpNet "github.com/fatedier/frp/utils/net"
|
||||
|
||||
"github.com/julienschmidt/httprouter"
|
||||
"github.com/gorilla/mux"
|
||||
)
|
||||
|
||||
var (
|
||||
@@ -33,13 +33,14 @@ var (
|
||||
|
||||
func (svr *Service) RunAdminServer(addr string, port int) (err error) {
|
||||
// url router
|
||||
router := httprouter.New()
|
||||
router := mux.NewRouter()
|
||||
|
||||
user, passwd := g.GlbClientCfg.AdminUser, g.GlbClientCfg.AdminPwd
|
||||
router.Use(frpNet.NewHttpAuthMiddleware(user, passwd).Middleware)
|
||||
|
||||
// api, see dashboard_api.go
|
||||
router.GET("/api/reload", frpNet.HttprouterBasicAuth(svr.apiReload, user, passwd))
|
||||
router.GET("/api/status", frpNet.HttprouterBasicAuth(svr.apiStatus, user, passwd))
|
||||
router.HandleFunc("/api/reload", svr.apiReload).Methods("GET")
|
||||
router.HandleFunc("/api/status", svr.apiStatus).Methods("GET")
|
||||
|
||||
address := fmt.Sprintf("%s:%d", addr, port)
|
||||
server := &http.Server{
|
||||
|
@@ -17,14 +17,11 @@ package client
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io/ioutil"
|
||||
"net/http"
|
||||
"sort"
|
||||
"strings"
|
||||
|
||||
"github.com/julienschmidt/httprouter"
|
||||
ini "github.com/vaughan0/go-ini"
|
||||
|
||||
"github.com/fatedier/frp/client/proxy"
|
||||
"github.com/fatedier/frp/g"
|
||||
"github.com/fatedier/frp/models/config"
|
||||
"github.com/fatedier/frp/utils/log"
|
||||
@@ -40,7 +37,7 @@ type ReloadResp struct {
|
||||
GeneralResponse
|
||||
}
|
||||
|
||||
func (svr *Service) apiReload(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {
|
||||
func (svr *Service) apiReload(w http.ResponseWriter, r *http.Request) {
|
||||
var (
|
||||
buf []byte
|
||||
res ReloadResp
|
||||
@@ -53,14 +50,13 @@ func (svr *Service) apiReload(w http.ResponseWriter, r *http.Request, _ httprout
|
||||
|
||||
log.Info("Http request: [/api/reload]")
|
||||
|
||||
b, err := ioutil.ReadFile(g.GlbClientCfg.CfgFile)
|
||||
content, err := config.GetRenderedConfFromFile(g.GlbClientCfg.CfgFile)
|
||||
if err != nil {
|
||||
res.Code = 1
|
||||
res.Msg = err.Error()
|
||||
log.Error("reload frpc config file error: %v", err)
|
||||
return
|
||||
}
|
||||
content := string(b)
|
||||
|
||||
newCommonCfg, err := config.UnmarshalClientConfFromIni(nil, content)
|
||||
if err != nil {
|
||||
@@ -70,15 +66,7 @@ func (svr *Service) apiReload(w http.ResponseWriter, r *http.Request, _ httprout
|
||||
return
|
||||
}
|
||||
|
||||
conf, err := ini.LoadFile(g.GlbClientCfg.CfgFile)
|
||||
if err != nil {
|
||||
res.Code = 1
|
||||
res.Msg = err.Error()
|
||||
log.Error("reload frpc config file error: %v", err)
|
||||
return
|
||||
}
|
||||
|
||||
pxyCfgs, visitorCfgs, err := config.LoadProxyConfFromIni(g.GlbClientCfg.User, conf, newCommonCfg.Start)
|
||||
pxyCfgs, visitorCfgs, err := config.LoadAllConfFromIni(g.GlbClientCfg.User, content, newCommonCfg.Start)
|
||||
if err != nil {
|
||||
res.Code = 3
|
||||
res.Msg = err.Error()
|
||||
@@ -86,7 +74,7 @@ func (svr *Service) apiReload(w http.ResponseWriter, r *http.Request, _ httprout
|
||||
return
|
||||
}
|
||||
|
||||
err = svr.ctl.reloadConf(pxyCfgs, visitorCfgs)
|
||||
err = svr.ctl.ReloadConf(pxyCfgs, visitorCfgs)
|
||||
if err != nil {
|
||||
res.Code = 4
|
||||
res.Msg = err.Error()
|
||||
@@ -122,7 +110,7 @@ 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) Less(i, j int) bool { return strings.Compare(a[i].Name, a[j].Name) < 0 }
|
||||
|
||||
func NewProxyStatusResp(status *ProxyStatus) ProxyStatusResp {
|
||||
func NewProxyStatusResp(status *proxy.ProxyStatus) ProxyStatusResp {
|
||||
psr := ProxyStatusResp{
|
||||
Name: status.Name,
|
||||
Type: status.Type,
|
||||
@@ -176,7 +164,7 @@ func NewProxyStatusResp(status *ProxyStatus) ProxyStatusResp {
|
||||
}
|
||||
|
||||
// api/status
|
||||
func (svr *Service) apiStatus(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {
|
||||
func (svr *Service) apiStatus(w http.ResponseWriter, r *http.Request) {
|
||||
var (
|
||||
buf []byte
|
||||
res StatusResp
|
||||
|
@@ -17,37 +17,32 @@ package client
|
||||
import (
|
||||
"fmt"
|
||||
"io"
|
||||
"io/ioutil"
|
||||
"runtime"
|
||||
"runtime/debug"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/fatedier/frp/client/proxy"
|
||||
"github.com/fatedier/frp/g"
|
||||
"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/util"
|
||||
"github.com/fatedier/frp/utils/version"
|
||||
|
||||
"github.com/fatedier/golib/control/shutdown"
|
||||
"github.com/fatedier/golib/crypto"
|
||||
fmux "github.com/hashicorp/yamux"
|
||||
)
|
||||
|
||||
const (
|
||||
connReadTimeout time.Duration = 10 * time.Second
|
||||
)
|
||||
|
||||
type Control struct {
|
||||
// frpc service
|
||||
svr *Service
|
||||
// uniq id got from frps, attach it in loginMsg
|
||||
runId string
|
||||
|
||||
// login message to server, only used
|
||||
loginMsg *msg.Login
|
||||
// manage all proxies
|
||||
pxyCfgs map[string]config.ProxyConf
|
||||
pm *proxy.ProxyManager
|
||||
|
||||
pm *ProxyManager
|
||||
// manage all visitors
|
||||
vm *VisitorManager
|
||||
|
||||
// control connection
|
||||
conn frpNet.Conn
|
||||
@@ -61,14 +56,10 @@ type Control struct {
|
||||
// read from this channel to get the next message sent by server
|
||||
readCh chan (msg.Message)
|
||||
|
||||
// run id got from server
|
||||
runId string
|
||||
|
||||
// if we call close() in control, do not reconnect to server
|
||||
exit bool
|
||||
|
||||
// goroutines can block by reading from this channel, it will be closed only in reader() when control connection is closed
|
||||
closedCh chan int
|
||||
closedCh chan struct{}
|
||||
|
||||
closedDoneCh chan struct{}
|
||||
|
||||
// last time got the Pong message
|
||||
lastPong time.Time
|
||||
@@ -82,54 +73,37 @@ type Control struct {
|
||||
log.Logger
|
||||
}
|
||||
|
||||
func NewControl(svr *Service, pxyCfgs map[string]config.ProxyConf, visitorCfgs map[string]config.ProxyConf) *Control {
|
||||
loginMsg := &msg.Login{
|
||||
Arch: runtime.GOARCH,
|
||||
Os: runtime.GOOS,
|
||||
PoolCount: g.GlbClientCfg.PoolCount,
|
||||
User: g.GlbClientCfg.User,
|
||||
Version: version.Full(),
|
||||
}
|
||||
func NewControl(runId string, conn frpNet.Conn, session *fmux.Session, pxyCfgs map[string]config.ProxyConf, visitorCfgs map[string]config.VisitorConf) *Control {
|
||||
ctl := &Control{
|
||||
svr: svr,
|
||||
loginMsg: loginMsg,
|
||||
runId: runId,
|
||||
conn: conn,
|
||||
session: session,
|
||||
pxyCfgs: pxyCfgs,
|
||||
sendCh: make(chan msg.Message, 100),
|
||||
readCh: make(chan msg.Message, 100),
|
||||
closedCh: make(chan int),
|
||||
closedCh: make(chan struct{}),
|
||||
closedDoneCh: make(chan struct{}),
|
||||
readerShutdown: shutdown.New(),
|
||||
writerShutdown: shutdown.New(),
|
||||
msgHandlerShutdown: shutdown.New(),
|
||||
Logger: log.NewPrefixLogger(""),
|
||||
}
|
||||
ctl.pm = NewProxyManager(ctl, ctl.sendCh, "")
|
||||
ctl.pm.Reload(pxyCfgs, visitorCfgs, false)
|
||||
ctl.pm = proxy.NewProxyManager(ctl.sendCh, runId)
|
||||
|
||||
ctl.vm = NewVisitorManager(ctl)
|
||||
ctl.vm.Reload(visitorCfgs)
|
||||
return ctl
|
||||
}
|
||||
|
||||
func (ctl *Control) Run() (err error) {
|
||||
for {
|
||||
err = ctl.login()
|
||||
if err != nil {
|
||||
ctl.Warn("login to server failed: %v", err)
|
||||
|
||||
// if login_fail_exit is true, just exit this program
|
||||
// otherwise sleep a while and continues relogin to server
|
||||
if g.GlbClientCfg.LoginFailExit {
|
||||
return
|
||||
} else {
|
||||
time.Sleep(10 * time.Second)
|
||||
}
|
||||
} else {
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
func (ctl *Control) Run() {
|
||||
go ctl.worker()
|
||||
|
||||
// start all local visitors and send NewProxy message for all configured proxies
|
||||
ctl.pm.Reset(ctl.sendCh, ctl.runId)
|
||||
ctl.pm.CheckAndStartProxy([]string{ProxyStatusNew})
|
||||
return nil
|
||||
// start all proxies
|
||||
ctl.pm.Reload(ctl.pxyCfgs)
|
||||
|
||||
// start all visitors
|
||||
go ctl.vm.Run()
|
||||
return
|
||||
}
|
||||
|
||||
func (ctl *Control) HandleReqWorkConn(inMsg *msg.ReqWorkConn) {
|
||||
@@ -171,82 +145,17 @@ func (ctl *Control) HandleNewProxyResp(inMsg *msg.NewProxyResp) {
|
||||
}
|
||||
|
||||
func (ctl *Control) Close() error {
|
||||
ctl.mu.Lock()
|
||||
defer ctl.mu.Unlock()
|
||||
ctl.exit = true
|
||||
ctl.pm.CloseProxies()
|
||||
ctl.pm.Close()
|
||||
ctl.conn.Close()
|
||||
return nil
|
||||
}
|
||||
|
||||
// login send a login message to server and wait for a loginResp message.
|
||||
func (ctl *Control) login() (err error) {
|
||||
if ctl.conn != nil {
|
||||
ctl.conn.Close()
|
||||
}
|
||||
if ctl.session != nil {
|
||||
ctl.session.Close()
|
||||
}
|
||||
|
||||
conn, err := frpNet.ConnectServerByProxy(g.GlbClientCfg.HttpProxy, g.GlbClientCfg.Protocol,
|
||||
fmt.Sprintf("%s:%d", g.GlbClientCfg.ServerAddr, g.GlbClientCfg.ServerPort))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
defer func() {
|
||||
if err != nil {
|
||||
conn.Close()
|
||||
}
|
||||
}()
|
||||
|
||||
if g.GlbClientCfg.TcpMux {
|
||||
fmuxCfg := fmux.DefaultConfig()
|
||||
fmuxCfg.LogOutput = ioutil.Discard
|
||||
session, errRet := fmux.Client(conn, fmuxCfg)
|
||||
if errRet != nil {
|
||||
return errRet
|
||||
}
|
||||
stream, errRet := session.OpenStream()
|
||||
if errRet != nil {
|
||||
session.Close()
|
||||
return errRet
|
||||
}
|
||||
conn = frpNet.WrapConn(stream)
|
||||
ctl.session = session
|
||||
}
|
||||
|
||||
now := time.Now().Unix()
|
||||
ctl.loginMsg.PrivilegeKey = util.GetAuthKey(g.GlbClientCfg.Token, now)
|
||||
ctl.loginMsg.Timestamp = now
|
||||
ctl.loginMsg.RunId = ctl.runId
|
||||
|
||||
if err = msg.WriteMsg(conn, ctl.loginMsg); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
var loginRespMsg msg.LoginResp
|
||||
conn.SetReadDeadline(time.Now().Add(connReadTimeout))
|
||||
if err = msg.ReadMsgInto(conn, &loginRespMsg); err != nil {
|
||||
return err
|
||||
}
|
||||
conn.SetReadDeadline(time.Time{})
|
||||
|
||||
if loginRespMsg.Error != "" {
|
||||
err = fmt.Errorf("%s", loginRespMsg.Error)
|
||||
ctl.Error("%s", loginRespMsg.Error)
|
||||
return err
|
||||
}
|
||||
|
||||
ctl.conn = conn
|
||||
// update runId got from server
|
||||
ctl.runId = loginRespMsg.RunId
|
||||
g.GlbClientCfg.ServerUdpPort = loginRespMsg.ServerUdpPort
|
||||
ctl.ClearLogPrefix()
|
||||
ctl.AddLogPrefix(loginRespMsg.RunId)
|
||||
ctl.Info("login to server success, get run id [%s], server udp port [%d]", loginRespMsg.RunId, loginRespMsg.ServerUdpPort)
|
||||
return nil
|
||||
// ClosedDoneCh returns a channel which will be closed after all resources are released
|
||||
func (ctl *Control) ClosedDoneCh() <-chan struct{} {
|
||||
return ctl.closedDoneCh
|
||||
}
|
||||
|
||||
// connectServer return a new connection to frps
|
||||
func (ctl *Control) connectServer() (conn frpNet.Conn, err error) {
|
||||
if g.GlbClientCfg.TcpMux {
|
||||
stream, errRet := ctl.session.OpenStream()
|
||||
@@ -364,87 +273,32 @@ func (ctl *Control) msgHandler() {
|
||||
}
|
||||
}
|
||||
|
||||
// controler keep watching closedCh, start a new connection if previous control connection is closed.
|
||||
// If controler is notified by closedCh, reader and writer and handler will exit, then recall these functions.
|
||||
// If controler is notified by closedCh, reader and writer and handler will exit
|
||||
func (ctl *Control) worker() {
|
||||
go ctl.msgHandler()
|
||||
go ctl.reader()
|
||||
go ctl.writer()
|
||||
|
||||
var err error
|
||||
maxDelayTime := 20 * time.Second
|
||||
delayTime := time.Second
|
||||
select {
|
||||
case <-ctl.closedCh:
|
||||
// close related channels and wait until other goroutines done
|
||||
close(ctl.readCh)
|
||||
ctl.readerShutdown.WaitDone()
|
||||
ctl.msgHandlerShutdown.WaitDone()
|
||||
|
||||
checkInterval := 60 * time.Second
|
||||
checkProxyTicker := time.NewTicker(checkInterval)
|
||||
for {
|
||||
select {
|
||||
case <-checkProxyTicker.C:
|
||||
// check which proxy registered failed and reregister it to server
|
||||
ctl.pm.CheckAndStartProxy([]string{ProxyStatusStartErr, ProxyStatusClosed})
|
||||
case _, ok := <-ctl.closedCh:
|
||||
// we won't get any variable from this channel
|
||||
if !ok {
|
||||
// close related channels and wait until other goroutines done
|
||||
close(ctl.readCh)
|
||||
ctl.readerShutdown.WaitDone()
|
||||
ctl.msgHandlerShutdown.WaitDone()
|
||||
close(ctl.sendCh)
|
||||
ctl.writerShutdown.WaitDone()
|
||||
|
||||
close(ctl.sendCh)
|
||||
ctl.writerShutdown.WaitDone()
|
||||
ctl.pm.Close()
|
||||
ctl.vm.Close()
|
||||
|
||||
ctl.pm.CloseProxies()
|
||||
// if ctl.exit is true, just exit
|
||||
ctl.mu.RLock()
|
||||
exit := ctl.exit
|
||||
ctl.mu.RUnlock()
|
||||
if exit {
|
||||
return
|
||||
}
|
||||
|
||||
// loop util reconnecting to server success
|
||||
for {
|
||||
ctl.Info("try to reconnect to server...")
|
||||
err = ctl.login()
|
||||
if err != nil {
|
||||
ctl.Warn("reconnect to server error: %v", err)
|
||||
time.Sleep(delayTime)
|
||||
delayTime = delayTime * 2
|
||||
if delayTime > maxDelayTime {
|
||||
delayTime = maxDelayTime
|
||||
}
|
||||
continue
|
||||
}
|
||||
// reconnect success, init delayTime
|
||||
delayTime = time.Second
|
||||
break
|
||||
}
|
||||
|
||||
// init related channels and variables
|
||||
ctl.sendCh = make(chan msg.Message, 100)
|
||||
ctl.readCh = make(chan msg.Message, 100)
|
||||
ctl.closedCh = make(chan int)
|
||||
ctl.readerShutdown = shutdown.New()
|
||||
ctl.writerShutdown = shutdown.New()
|
||||
ctl.msgHandlerShutdown = shutdown.New()
|
||||
ctl.pm.Reset(ctl.sendCh, ctl.runId)
|
||||
|
||||
// previous work goroutines should be closed and start them here
|
||||
go ctl.msgHandler()
|
||||
go ctl.writer()
|
||||
go ctl.reader()
|
||||
|
||||
// start all configured proxies
|
||||
ctl.pm.CheckAndStartProxy([]string{ProxyStatusNew, ProxyStatusClosed})
|
||||
|
||||
checkProxyTicker.Stop()
|
||||
checkProxyTicker = time.NewTicker(checkInterval)
|
||||
}
|
||||
}
|
||||
close(ctl.closedDoneCh)
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
func (ctl *Control) reloadConf(pxyCfgs map[string]config.ProxyConf, visitorCfgs map[string]config.ProxyConf) error {
|
||||
err := ctl.pm.Reload(pxyCfgs, visitorCfgs, true)
|
||||
return err
|
||||
func (ctl *Control) ReloadConf(pxyCfgs map[string]config.ProxyConf, visitorCfgs map[string]config.VisitorConf) error {
|
||||
ctl.vm.Reload(visitorCfgs)
|
||||
ctl.pm.Reload(pxyCfgs)
|
||||
return nil
|
||||
}
|
||||
|
28
client/event/event.go
Normal file
28
client/event/event.go
Normal file
@@ -0,0 +1,28 @@
|
||||
package event
|
||||
|
||||
import (
|
||||
"errors"
|
||||
|
||||
"github.com/fatedier/frp/models/msg"
|
||||
)
|
||||
|
||||
type EventType int
|
||||
|
||||
const (
|
||||
EvStartProxy EventType = iota
|
||||
EvCloseProxy
|
||||
)
|
||||
|
||||
var (
|
||||
ErrPayloadType = errors.New("error payload type")
|
||||
)
|
||||
|
||||
type EventHandler func(evType EventType, payload interface{}) error
|
||||
|
||||
type StartProxyPayload struct {
|
||||
NewProxyMsg *msg.NewProxy
|
||||
}
|
||||
|
||||
type CloseProxyPayload struct {
|
||||
CloseProxyMsg *msg.CloseProxy
|
||||
}
|
178
client/health/health.go
Normal file
178
client/health/health.go
Normal file
@@ -0,0 +1,178 @@
|
||||
// Copyright 2018 fatedier, fatedier@gmail.com
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
package health
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net"
|
||||
"net/http"
|
||||
"time"
|
||||
|
||||
"github.com/fatedier/frp/utils/log"
|
||||
)
|
||||
|
||||
var (
|
||||
ErrHealthCheckType = errors.New("error health check type")
|
||||
)
|
||||
|
||||
type HealthCheckMonitor struct {
|
||||
checkType string
|
||||
interval time.Duration
|
||||
timeout time.Duration
|
||||
maxFailedTimes int
|
||||
|
||||
// For tcp
|
||||
addr string
|
||||
|
||||
// For http
|
||||
url string
|
||||
|
||||
failedTimes uint64
|
||||
statusOK bool
|
||||
statusNormalFn func()
|
||||
statusFailedFn func()
|
||||
|
||||
ctx context.Context
|
||||
cancel context.CancelFunc
|
||||
|
||||
l log.Logger
|
||||
}
|
||||
|
||||
func NewHealthCheckMonitor(checkType string, intervalS int, timeoutS int, maxFailedTimes int, addr string, url string,
|
||||
statusNormalFn func(), statusFailedFn func()) *HealthCheckMonitor {
|
||||
|
||||
if intervalS <= 0 {
|
||||
intervalS = 10
|
||||
}
|
||||
if timeoutS <= 0 {
|
||||
timeoutS = 3
|
||||
}
|
||||
if maxFailedTimes <= 0 {
|
||||
maxFailedTimes = 1
|
||||
}
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
return &HealthCheckMonitor{
|
||||
checkType: checkType,
|
||||
interval: time.Duration(intervalS) * time.Second,
|
||||
timeout: time.Duration(timeoutS) * time.Second,
|
||||
maxFailedTimes: maxFailedTimes,
|
||||
addr: addr,
|
||||
url: url,
|
||||
statusOK: false,
|
||||
statusNormalFn: statusNormalFn,
|
||||
statusFailedFn: statusFailedFn,
|
||||
ctx: ctx,
|
||||
cancel: cancel,
|
||||
}
|
||||
}
|
||||
|
||||
func (monitor *HealthCheckMonitor) SetLogger(l log.Logger) {
|
||||
monitor.l = l
|
||||
}
|
||||
|
||||
func (monitor *HealthCheckMonitor) Start() {
|
||||
go monitor.checkWorker()
|
||||
}
|
||||
|
||||
func (monitor *HealthCheckMonitor) Stop() {
|
||||
monitor.cancel()
|
||||
}
|
||||
|
||||
func (monitor *HealthCheckMonitor) checkWorker() {
|
||||
for {
|
||||
ctx, cancel := context.WithDeadline(monitor.ctx, time.Now().Add(monitor.timeout))
|
||||
err := monitor.doCheck(ctx)
|
||||
|
||||
// check if this monitor has been closed
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
cancel()
|
||||
return
|
||||
default:
|
||||
cancel()
|
||||
}
|
||||
|
||||
if err == nil {
|
||||
if monitor.l != nil {
|
||||
monitor.l.Trace("do one health check success")
|
||||
}
|
||||
if !monitor.statusOK && monitor.statusNormalFn != nil {
|
||||
if monitor.l != nil {
|
||||
monitor.l.Info("health check status change to success")
|
||||
}
|
||||
monitor.statusOK = true
|
||||
monitor.statusNormalFn()
|
||||
}
|
||||
} else {
|
||||
if monitor.l != nil {
|
||||
monitor.l.Warn("do one health check failed: %v", err)
|
||||
}
|
||||
monitor.failedTimes++
|
||||
if monitor.statusOK && int(monitor.failedTimes) >= monitor.maxFailedTimes && monitor.statusFailedFn != nil {
|
||||
if monitor.l != nil {
|
||||
monitor.l.Warn("health check status change to failed")
|
||||
}
|
||||
monitor.statusOK = false
|
||||
monitor.statusFailedFn()
|
||||
}
|
||||
}
|
||||
|
||||
time.Sleep(monitor.interval)
|
||||
}
|
||||
}
|
||||
|
||||
func (monitor *HealthCheckMonitor) doCheck(ctx context.Context) error {
|
||||
switch monitor.checkType {
|
||||
case "tcp":
|
||||
return monitor.doTcpCheck(ctx)
|
||||
case "http":
|
||||
return monitor.doHttpCheck(ctx)
|
||||
default:
|
||||
return ErrHealthCheckType
|
||||
}
|
||||
}
|
||||
|
||||
func (monitor *HealthCheckMonitor) doTcpCheck(ctx context.Context) error {
|
||||
// if tcp address is not specified, always return nil
|
||||
if monitor.addr == "" {
|
||||
return nil
|
||||
}
|
||||
|
||||
var d net.Dialer
|
||||
conn, err := d.DialContext(ctx, "tcp", monitor.addr)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
conn.Close()
|
||||
return nil
|
||||
}
|
||||
|
||||
func (monitor *HealthCheckMonitor) doHttpCheck(ctx context.Context) error {
|
||||
req, err := http.NewRequest("GET", monitor.url, nil)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
resp, err := http.DefaultClient.Do(req)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if resp.StatusCode/100 != 2 {
|
||||
return fmt.Errorf("do http health check, StatusCode is [%d] not 2xx", resp.StatusCode)
|
||||
}
|
||||
return nil
|
||||
}
|
@@ -12,7 +12,7 @@
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
package client
|
||||
package proxy
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
@@ -35,7 +35,7 @@ import (
|
||||
"github.com/fatedier/golib/pool"
|
||||
)
|
||||
|
||||
// Proxy defines how to deal with work connections for different proxy type.
|
||||
// Proxy defines how to handle work connections for different proxy type.
|
||||
type Proxy interface {
|
||||
Run() error
|
||||
|
139
client/proxy/proxy_manager.go
Normal file
139
client/proxy/proxy_manager.go
Normal file
@@ -0,0 +1,139 @@
|
||||
package proxy
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"sync"
|
||||
|
||||
"github.com/fatedier/frp/client/event"
|
||||
"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/golib/errors"
|
||||
)
|
||||
|
||||
type ProxyManager struct {
|
||||
sendCh chan (msg.Message)
|
||||
proxies map[string]*ProxyWrapper
|
||||
|
||||
closed bool
|
||||
mu sync.RWMutex
|
||||
|
||||
logPrefix string
|
||||
log.Logger
|
||||
}
|
||||
|
||||
func NewProxyManager(msgSendCh chan (msg.Message), logPrefix string) *ProxyManager {
|
||||
return &ProxyManager{
|
||||
proxies: make(map[string]*ProxyWrapper),
|
||||
sendCh: msgSendCh,
|
||||
closed: false,
|
||||
logPrefix: logPrefix,
|
||||
Logger: log.NewPrefixLogger(logPrefix),
|
||||
}
|
||||
}
|
||||
|
||||
func (pm *ProxyManager) StartProxy(name string, remoteAddr string, serverRespErr string) error {
|
||||
pm.mu.RLock()
|
||||
pxy, ok := pm.proxies[name]
|
||||
pm.mu.RUnlock()
|
||||
if !ok {
|
||||
return fmt.Errorf("proxy [%s] not found", name)
|
||||
}
|
||||
|
||||
err := pxy.SetRunningStatus(remoteAddr, serverRespErr)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (pm *ProxyManager) Close() {
|
||||
pm.mu.Lock()
|
||||
defer pm.mu.Unlock()
|
||||
for _, pxy := range pm.proxies {
|
||||
pxy.Stop()
|
||||
}
|
||||
pm.proxies = make(map[string]*ProxyWrapper)
|
||||
}
|
||||
|
||||
func (pm *ProxyManager) HandleWorkConn(name string, workConn frpNet.Conn) {
|
||||
pm.mu.RLock()
|
||||
pw, ok := pm.proxies[name]
|
||||
pm.mu.RUnlock()
|
||||
if ok {
|
||||
pw.InWorkConn(workConn)
|
||||
} else {
|
||||
workConn.Close()
|
||||
}
|
||||
}
|
||||
|
||||
func (pm *ProxyManager) HandleEvent(evType event.EventType, payload interface{}) error {
|
||||
var m msg.Message
|
||||
switch e := payload.(type) {
|
||||
case *event.StartProxyPayload:
|
||||
m = e.NewProxyMsg
|
||||
case *event.CloseProxyPayload:
|
||||
m = e.CloseProxyMsg
|
||||
default:
|
||||
return event.ErrPayloadType
|
||||
}
|
||||
|
||||
err := errors.PanicToError(func() {
|
||||
pm.sendCh <- m
|
||||
})
|
||||
return err
|
||||
}
|
||||
|
||||
func (pm *ProxyManager) GetAllProxyStatus() []*ProxyStatus {
|
||||
ps := make([]*ProxyStatus, 0)
|
||||
pm.mu.RLock()
|
||||
defer pm.mu.RUnlock()
|
||||
for _, pxy := range pm.proxies {
|
||||
ps = append(ps, pxy.GetStatus())
|
||||
}
|
||||
return ps
|
||||
}
|
||||
|
||||
func (pm *ProxyManager) Reload(pxyCfgs map[string]config.ProxyConf) {
|
||||
pm.mu.Lock()
|
||||
defer pm.mu.Unlock()
|
||||
|
||||
delPxyNames := make([]string, 0)
|
||||
for name, pxy := range pm.proxies {
|
||||
del := false
|
||||
cfg, ok := pxyCfgs[name]
|
||||
if !ok {
|
||||
del = true
|
||||
} else {
|
||||
if !pxy.Cfg.Compare(cfg) {
|
||||
del = true
|
||||
}
|
||||
}
|
||||
|
||||
if del {
|
||||
delPxyNames = append(delPxyNames, name)
|
||||
delete(pm.proxies, name)
|
||||
|
||||
pxy.Stop()
|
||||
}
|
||||
}
|
||||
if len(delPxyNames) > 0 {
|
||||
pm.Info("proxy removed: %v", delPxyNames)
|
||||
}
|
||||
|
||||
addPxyNames := make([]string, 0)
|
||||
for name, cfg := range pxyCfgs {
|
||||
if _, ok := pm.proxies[name]; !ok {
|
||||
pxy := NewProxyWrapper(cfg, pm.HandleEvent, pm.logPrefix)
|
||||
pm.proxies[name] = pxy
|
||||
addPxyNames = append(addPxyNames, name)
|
||||
|
||||
pxy.Start()
|
||||
}
|
||||
}
|
||||
if len(addPxyNames) > 0 {
|
||||
pm.Info("proxy added: %v", addPxyNames)
|
||||
}
|
||||
}
|
244
client/proxy/proxy_wrapper.go
Normal file
244
client/proxy/proxy_wrapper.go
Normal file
@@ -0,0 +1,244 @@
|
||||
package proxy
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
|
||||
"github.com/fatedier/frp/client/event"
|
||||
"github.com/fatedier/frp/client/health"
|
||||
"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/golib/errors"
|
||||
)
|
||||
|
||||
const (
|
||||
ProxyStatusNew = "new"
|
||||
ProxyStatusWaitStart = "wait start"
|
||||
ProxyStatusStartErr = "start error"
|
||||
ProxyStatusRunning = "running"
|
||||
ProxyStatusCheckFailed = "check failed"
|
||||
ProxyStatusClosed = "closed"
|
||||
)
|
||||
|
||||
var (
|
||||
statusCheckInterval time.Duration = 3 * time.Second
|
||||
waitResponseTimeout = 20 * time.Second
|
||||
startErrTimeout = 30 * time.Second
|
||||
)
|
||||
|
||||
type ProxyStatus struct {
|
||||
Name string `json:"name"`
|
||||
Type string `json:"type"`
|
||||
Status string `json:"status"`
|
||||
Err string `json:"err"`
|
||||
Cfg config.ProxyConf `json:"cfg"`
|
||||
|
||||
// Got from server.
|
||||
RemoteAddr string `json:"remote_addr"`
|
||||
}
|
||||
|
||||
type ProxyWrapper struct {
|
||||
ProxyStatus
|
||||
|
||||
// underlying proxy
|
||||
pxy Proxy
|
||||
|
||||
// if ProxyConf has healcheck config
|
||||
// monitor will watch if it is alive
|
||||
monitor *health.HealthCheckMonitor
|
||||
|
||||
// event handler
|
||||
handler event.EventHandler
|
||||
|
||||
health uint32
|
||||
lastSendStartMsg time.Time
|
||||
lastStartErr time.Time
|
||||
closeCh chan struct{}
|
||||
healthNotifyCh chan struct{}
|
||||
mu sync.RWMutex
|
||||
|
||||
log.Logger
|
||||
}
|
||||
|
||||
func NewProxyWrapper(cfg config.ProxyConf, eventHandler event.EventHandler, logPrefix string) *ProxyWrapper {
|
||||
baseInfo := cfg.GetBaseInfo()
|
||||
pw := &ProxyWrapper{
|
||||
ProxyStatus: ProxyStatus{
|
||||
Name: baseInfo.ProxyName,
|
||||
Type: baseInfo.ProxyType,
|
||||
Status: ProxyStatusNew,
|
||||
Cfg: cfg,
|
||||
},
|
||||
closeCh: make(chan struct{}),
|
||||
healthNotifyCh: make(chan struct{}),
|
||||
handler: eventHandler,
|
||||
Logger: log.NewPrefixLogger(logPrefix),
|
||||
}
|
||||
pw.AddLogPrefix(pw.Name)
|
||||
|
||||
if baseInfo.HealthCheckType != "" {
|
||||
pw.health = 1 // means failed
|
||||
pw.monitor = health.NewHealthCheckMonitor(baseInfo.HealthCheckType, baseInfo.HealthCheckIntervalS,
|
||||
baseInfo.HealthCheckTimeoutS, baseInfo.HealthCheckMaxFailed, baseInfo.HealthCheckAddr,
|
||||
baseInfo.HealthCheckUrl, pw.statusNormalCallback, pw.statusFailedCallback)
|
||||
pw.monitor.SetLogger(pw.Logger)
|
||||
pw.Trace("enable health check monitor")
|
||||
}
|
||||
|
||||
pw.pxy = NewProxy(pw.Cfg)
|
||||
return pw
|
||||
}
|
||||
|
||||
func (pw *ProxyWrapper) SetRunningStatus(remoteAddr string, respErr string) error {
|
||||
pw.mu.Lock()
|
||||
defer pw.mu.Unlock()
|
||||
if pw.Status != ProxyStatusWaitStart {
|
||||
return fmt.Errorf("status not wait start, ignore start message")
|
||||
}
|
||||
|
||||
pw.RemoteAddr = remoteAddr
|
||||
if respErr != "" {
|
||||
pw.Status = ProxyStatusStartErr
|
||||
pw.Err = respErr
|
||||
pw.lastStartErr = time.Now()
|
||||
return fmt.Errorf(pw.Err)
|
||||
}
|
||||
|
||||
if err := pw.pxy.Run(); err != nil {
|
||||
pw.Status = ProxyStatusStartErr
|
||||
pw.Err = err.Error()
|
||||
pw.lastStartErr = time.Now()
|
||||
return err
|
||||
}
|
||||
|
||||
pw.Status = ProxyStatusRunning
|
||||
pw.Err = ""
|
||||
return nil
|
||||
}
|
||||
|
||||
func (pw *ProxyWrapper) Start() {
|
||||
go pw.checkWorker()
|
||||
if pw.monitor != nil {
|
||||
go pw.monitor.Start()
|
||||
}
|
||||
}
|
||||
|
||||
func (pw *ProxyWrapper) Stop() {
|
||||
pw.mu.Lock()
|
||||
defer pw.mu.Unlock()
|
||||
close(pw.closeCh)
|
||||
close(pw.healthNotifyCh)
|
||||
pw.pxy.Close()
|
||||
if pw.monitor != nil {
|
||||
pw.monitor.Stop()
|
||||
}
|
||||
pw.Status = ProxyStatusClosed
|
||||
|
||||
pw.handler(event.EvCloseProxy, &event.CloseProxyPayload{
|
||||
CloseProxyMsg: &msg.CloseProxy{
|
||||
ProxyName: pw.Name,
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
func (pw *ProxyWrapper) checkWorker() {
|
||||
if pw.monitor != nil {
|
||||
// let monitor do check request first
|
||||
time.Sleep(500 * time.Millisecond)
|
||||
}
|
||||
for {
|
||||
// check proxy status
|
||||
now := time.Now()
|
||||
if atomic.LoadUint32(&pw.health) == 0 {
|
||||
pw.mu.Lock()
|
||||
if pw.Status == ProxyStatusNew ||
|
||||
pw.Status == ProxyStatusCheckFailed ||
|
||||
(pw.Status == ProxyStatusWaitStart && now.After(pw.lastSendStartMsg.Add(waitResponseTimeout))) ||
|
||||
(pw.Status == ProxyStatusStartErr && now.After(pw.lastStartErr.Add(startErrTimeout))) {
|
||||
|
||||
pw.Trace("change status from [%s] to [%s]", pw.Status, ProxyStatusWaitStart)
|
||||
pw.Status = ProxyStatusWaitStart
|
||||
|
||||
var newProxyMsg msg.NewProxy
|
||||
pw.Cfg.MarshalToMsg(&newProxyMsg)
|
||||
pw.lastSendStartMsg = now
|
||||
pw.handler(event.EvStartProxy, &event.StartProxyPayload{
|
||||
NewProxyMsg: &newProxyMsg,
|
||||
})
|
||||
}
|
||||
pw.mu.Unlock()
|
||||
} else {
|
||||
pw.mu.Lock()
|
||||
if pw.Status == ProxyStatusRunning || pw.Status == ProxyStatusWaitStart {
|
||||
pw.handler(event.EvCloseProxy, &event.CloseProxyPayload{
|
||||
CloseProxyMsg: &msg.CloseProxy{
|
||||
ProxyName: pw.Name,
|
||||
},
|
||||
})
|
||||
pw.Trace("change status from [%s] to [%s]", pw.Status, ProxyStatusCheckFailed)
|
||||
pw.Status = ProxyStatusCheckFailed
|
||||
}
|
||||
pw.mu.Unlock()
|
||||
}
|
||||
|
||||
select {
|
||||
case <-pw.closeCh:
|
||||
return
|
||||
case <-time.After(statusCheckInterval):
|
||||
case <-pw.healthNotifyCh:
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (pw *ProxyWrapper) statusNormalCallback() {
|
||||
atomic.StoreUint32(&pw.health, 0)
|
||||
errors.PanicToError(func() {
|
||||
select {
|
||||
case pw.healthNotifyCh <- struct{}{}:
|
||||
default:
|
||||
}
|
||||
})
|
||||
pw.Info("health check success")
|
||||
}
|
||||
|
||||
func (pw *ProxyWrapper) statusFailedCallback() {
|
||||
atomic.StoreUint32(&pw.health, 1)
|
||||
errors.PanicToError(func() {
|
||||
select {
|
||||
case pw.healthNotifyCh <- struct{}{}:
|
||||
default:
|
||||
}
|
||||
})
|
||||
pw.Info("health check failed")
|
||||
}
|
||||
|
||||
func (pw *ProxyWrapper) InWorkConn(workConn frpNet.Conn) {
|
||||
pw.mu.RLock()
|
||||
pxy := pw.pxy
|
||||
pw.mu.RUnlock()
|
||||
if pxy != nil {
|
||||
workConn.Debug("start a new work connection, localAddr: %s remoteAddr: %s", workConn.LocalAddr().String(), workConn.RemoteAddr().String())
|
||||
go pxy.InWorkConn(workConn)
|
||||
} else {
|
||||
workConn.Close()
|
||||
}
|
||||
}
|
||||
|
||||
func (pw *ProxyWrapper) GetStatus() *ProxyStatus {
|
||||
pw.mu.RLock()
|
||||
defer pw.mu.RUnlock()
|
||||
ps := &ProxyStatus{
|
||||
Name: pw.Name,
|
||||
Type: pw.Type,
|
||||
Status: pw.Status,
|
||||
Err: pw.Err,
|
||||
Cfg: pw.Cfg,
|
||||
RemoteAddr: pw.RemoteAddr,
|
||||
}
|
||||
return ps
|
||||
}
|
@@ -1,365 +0,0 @@
|
||||
package client
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"sync"
|
||||
|
||||
"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/golib/errors"
|
||||
)
|
||||
|
||||
const (
|
||||
ProxyStatusNew = "new"
|
||||
ProxyStatusStartErr = "start error"
|
||||
ProxyStatusWaitStart = "wait start"
|
||||
ProxyStatusRunning = "running"
|
||||
ProxyStatusClosed = "closed"
|
||||
)
|
||||
|
||||
type ProxyManager struct {
|
||||
ctl *Control
|
||||
|
||||
proxies map[string]*ProxyWrapper
|
||||
|
||||
visitorCfgs map[string]config.ProxyConf
|
||||
visitors map[string]Visitor
|
||||
|
||||
sendCh chan (msg.Message)
|
||||
|
||||
closed bool
|
||||
mu sync.RWMutex
|
||||
|
||||
log.Logger
|
||||
}
|
||||
|
||||
type ProxyWrapper struct {
|
||||
Name string
|
||||
Type string
|
||||
Status string
|
||||
Err string
|
||||
Cfg config.ProxyConf
|
||||
|
||||
RemoteAddr string
|
||||
|
||||
pxy Proxy
|
||||
|
||||
mu sync.RWMutex
|
||||
}
|
||||
|
||||
type ProxyStatus struct {
|
||||
Name string `json:"name"`
|
||||
Type string `json:"type"`
|
||||
Status string `json:"status"`
|
||||
Err string `json:"err"`
|
||||
Cfg config.ProxyConf `json:"cfg"`
|
||||
|
||||
// Got from server.
|
||||
RemoteAddr string `json:"remote_addr"`
|
||||
}
|
||||
|
||||
func NewProxyWrapper(cfg config.ProxyConf) *ProxyWrapper {
|
||||
return &ProxyWrapper{
|
||||
Name: cfg.GetBaseInfo().ProxyName,
|
||||
Type: cfg.GetBaseInfo().ProxyType,
|
||||
Status: ProxyStatusNew,
|
||||
Cfg: cfg,
|
||||
pxy: nil,
|
||||
}
|
||||
}
|
||||
|
||||
func (pw *ProxyWrapper) GetStatusStr() string {
|
||||
pw.mu.RLock()
|
||||
defer pw.mu.RUnlock()
|
||||
return pw.Status
|
||||
}
|
||||
|
||||
func (pw *ProxyWrapper) GetStatus() *ProxyStatus {
|
||||
pw.mu.RLock()
|
||||
defer pw.mu.RUnlock()
|
||||
ps := &ProxyStatus{
|
||||
Name: pw.Name,
|
||||
Type: pw.Type,
|
||||
Status: pw.Status,
|
||||
Err: pw.Err,
|
||||
Cfg: pw.Cfg,
|
||||
RemoteAddr: pw.RemoteAddr,
|
||||
}
|
||||
return ps
|
||||
}
|
||||
|
||||
func (pw *ProxyWrapper) WaitStart() {
|
||||
pw.mu.Lock()
|
||||
defer pw.mu.Unlock()
|
||||
pw.Status = ProxyStatusWaitStart
|
||||
}
|
||||
|
||||
func (pw *ProxyWrapper) Start(remoteAddr string, serverRespErr string) error {
|
||||
if pw.pxy != nil {
|
||||
pw.pxy.Close()
|
||||
pw.pxy = nil
|
||||
}
|
||||
|
||||
if serverRespErr != "" {
|
||||
pw.mu.Lock()
|
||||
pw.Status = ProxyStatusStartErr
|
||||
pw.RemoteAddr = remoteAddr
|
||||
pw.Err = serverRespErr
|
||||
pw.mu.Unlock()
|
||||
return fmt.Errorf(serverRespErr)
|
||||
}
|
||||
|
||||
pxy := NewProxy(pw.Cfg)
|
||||
pw.mu.Lock()
|
||||
defer pw.mu.Unlock()
|
||||
pw.RemoteAddr = remoteAddr
|
||||
if err := pxy.Run(); err != nil {
|
||||
pw.Status = ProxyStatusStartErr
|
||||
pw.Err = err.Error()
|
||||
return err
|
||||
}
|
||||
pw.Status = ProxyStatusRunning
|
||||
pw.Err = ""
|
||||
pw.pxy = pxy
|
||||
return nil
|
||||
}
|
||||
|
||||
func (pw *ProxyWrapper) InWorkConn(workConn frpNet.Conn) {
|
||||
pw.mu.RLock()
|
||||
pxy := pw.pxy
|
||||
pw.mu.RUnlock()
|
||||
if pxy != nil {
|
||||
workConn.Debug("start a new work connection, localAddr: %s remoteAddr: %s", workConn.LocalAddr().String(), workConn.RemoteAddr().String())
|
||||
go pxy.InWorkConn(workConn)
|
||||
} else {
|
||||
workConn.Close()
|
||||
}
|
||||
}
|
||||
|
||||
func (pw *ProxyWrapper) Close() {
|
||||
pw.mu.Lock()
|
||||
defer pw.mu.Unlock()
|
||||
if pw.pxy != nil {
|
||||
pw.pxy.Close()
|
||||
pw.pxy = nil
|
||||
}
|
||||
pw.Status = ProxyStatusClosed
|
||||
}
|
||||
|
||||
func NewProxyManager(ctl *Control, msgSendCh chan (msg.Message), logPrefix string) *ProxyManager {
|
||||
return &ProxyManager{
|
||||
ctl: ctl,
|
||||
proxies: make(map[string]*ProxyWrapper),
|
||||
visitorCfgs: make(map[string]config.ProxyConf),
|
||||
visitors: make(map[string]Visitor),
|
||||
sendCh: msgSendCh,
|
||||
closed: false,
|
||||
Logger: log.NewPrefixLogger(logPrefix),
|
||||
}
|
||||
}
|
||||
|
||||
func (pm *ProxyManager) Reset(msgSendCh chan (msg.Message), logPrefix string) {
|
||||
pm.mu.Lock()
|
||||
defer pm.mu.Unlock()
|
||||
pm.closed = false
|
||||
pm.sendCh = msgSendCh
|
||||
pm.ClearLogPrefix()
|
||||
pm.AddLogPrefix(logPrefix)
|
||||
}
|
||||
|
||||
// Must hold the lock before calling this function.
|
||||
func (pm *ProxyManager) sendMsg(m msg.Message) error {
|
||||
err := errors.PanicToError(func() {
|
||||
pm.sendCh <- m
|
||||
})
|
||||
if err != nil {
|
||||
pm.closed = true
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
func (pm *ProxyManager) StartProxy(name string, remoteAddr string, serverRespErr string) error {
|
||||
pm.mu.Lock()
|
||||
defer pm.mu.Unlock()
|
||||
if pm.closed {
|
||||
return fmt.Errorf("ProxyManager is closed now")
|
||||
}
|
||||
|
||||
pxy, ok := pm.proxies[name]
|
||||
if !ok {
|
||||
return fmt.Errorf("no proxy found")
|
||||
}
|
||||
|
||||
if err := pxy.Start(remoteAddr, serverRespErr); err != nil {
|
||||
errRet := err
|
||||
err = pm.sendMsg(&msg.CloseProxy{
|
||||
ProxyName: name,
|
||||
})
|
||||
if err != nil {
|
||||
errRet = fmt.Errorf("send CloseProxy message error")
|
||||
}
|
||||
return errRet
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (pm *ProxyManager) CloseProxies() {
|
||||
pm.mu.RLock()
|
||||
defer pm.mu.RUnlock()
|
||||
for _, pxy := range pm.proxies {
|
||||
pxy.Close()
|
||||
}
|
||||
}
|
||||
|
||||
// pxyStatus: check and start proxies in which status
|
||||
func (pm *ProxyManager) CheckAndStartProxy(pxyStatus []string) {
|
||||
pm.mu.RLock()
|
||||
defer pm.mu.RUnlock()
|
||||
if pm.closed {
|
||||
pm.Warn("CheckAndStartProxy error: ProxyManager is closed now")
|
||||
return
|
||||
}
|
||||
|
||||
for _, pxy := range pm.proxies {
|
||||
status := pxy.GetStatusStr()
|
||||
for _, s := range pxyStatus {
|
||||
if status == s {
|
||||
var newProxyMsg msg.NewProxy
|
||||
pxy.Cfg.MarshalToMsg(&newProxyMsg)
|
||||
err := pm.sendMsg(&newProxyMsg)
|
||||
if err != nil {
|
||||
pm.Warn("[%s] proxy send NewProxy message error")
|
||||
return
|
||||
}
|
||||
pxy.WaitStart()
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
for _, cfg := range pm.visitorCfgs {
|
||||
name := cfg.GetBaseInfo().ProxyName
|
||||
if _, exist := pm.visitors[name]; !exist {
|
||||
pm.Info("try to start visitor [%s]", name)
|
||||
visitor := NewVisitor(pm.ctl, cfg)
|
||||
err := visitor.Run()
|
||||
if err != nil {
|
||||
visitor.Warn("start error: %v", err)
|
||||
continue
|
||||
}
|
||||
pm.visitors[name] = visitor
|
||||
visitor.Info("start visitor success")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (pm *ProxyManager) Reload(pxyCfgs map[string]config.ProxyConf, visitorCfgs map[string]config.ProxyConf, startNow bool) error {
|
||||
pm.mu.Lock()
|
||||
defer func() {
|
||||
pm.mu.Unlock()
|
||||
if startNow {
|
||||
go pm.CheckAndStartProxy([]string{ProxyStatusNew})
|
||||
}
|
||||
}()
|
||||
if pm.closed {
|
||||
err := fmt.Errorf("Reload error: ProxyManager is closed now")
|
||||
pm.Warn(err.Error())
|
||||
return err
|
||||
}
|
||||
|
||||
delPxyNames := make([]string, 0)
|
||||
for name, pxy := range pm.proxies {
|
||||
del := false
|
||||
cfg, ok := pxyCfgs[name]
|
||||
if !ok {
|
||||
del = true
|
||||
} else {
|
||||
if !pxy.Cfg.Compare(cfg) {
|
||||
del = true
|
||||
}
|
||||
}
|
||||
|
||||
if del {
|
||||
delPxyNames = append(delPxyNames, name)
|
||||
delete(pm.proxies, name)
|
||||
|
||||
pxy.Close()
|
||||
err := pm.sendMsg(&msg.CloseProxy{
|
||||
ProxyName: name,
|
||||
})
|
||||
if err != nil {
|
||||
err = fmt.Errorf("Reload error: ProxyManager is closed now")
|
||||
pm.Warn(err.Error())
|
||||
return err
|
||||
}
|
||||
}
|
||||
}
|
||||
pm.Info("proxy removed: %v", delPxyNames)
|
||||
|
||||
addPxyNames := make([]string, 0)
|
||||
for name, cfg := range pxyCfgs {
|
||||
if _, ok := pm.proxies[name]; !ok {
|
||||
pxy := NewProxyWrapper(cfg)
|
||||
pm.proxies[name] = pxy
|
||||
addPxyNames = append(addPxyNames, name)
|
||||
}
|
||||
}
|
||||
pm.Info("proxy added: %v", addPxyNames)
|
||||
|
||||
delVisitorName := make([]string, 0)
|
||||
for name, oldVisitorCfg := range pm.visitorCfgs {
|
||||
del := false
|
||||
cfg, ok := visitorCfgs[name]
|
||||
if !ok {
|
||||
del = true
|
||||
} else {
|
||||
if !oldVisitorCfg.Compare(cfg) {
|
||||
del = true
|
||||
}
|
||||
}
|
||||
|
||||
if del {
|
||||
delVisitorName = append(delVisitorName, name)
|
||||
delete(pm.visitorCfgs, name)
|
||||
if visitor, ok := pm.visitors[name]; ok {
|
||||
visitor.Close()
|
||||
}
|
||||
delete(pm.visitors, name)
|
||||
}
|
||||
}
|
||||
pm.Info("visitor removed: %v", delVisitorName)
|
||||
|
||||
addVisitorName := make([]string, 0)
|
||||
for name, visitorCfg := range visitorCfgs {
|
||||
if _, ok := pm.visitorCfgs[name]; !ok {
|
||||
pm.visitorCfgs[name] = visitorCfg
|
||||
addVisitorName = append(addVisitorName, name)
|
||||
}
|
||||
}
|
||||
pm.Info("visitor added: %v", addVisitorName)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (pm *ProxyManager) HandleWorkConn(name string, workConn frpNet.Conn) {
|
||||
pm.mu.RLock()
|
||||
pw, ok := pm.proxies[name]
|
||||
pm.mu.RUnlock()
|
||||
if ok {
|
||||
pw.InWorkConn(workConn)
|
||||
} else {
|
||||
workConn.Close()
|
||||
}
|
||||
}
|
||||
|
||||
func (pm *ProxyManager) GetAllProxyStatus() []*ProxyStatus {
|
||||
ps := make([]*ProxyStatus, 0)
|
||||
pm.mu.RLock()
|
||||
defer pm.mu.RUnlock()
|
||||
for _, pxy := range pm.proxies {
|
||||
ps = append(ps, pxy.GetStatus())
|
||||
}
|
||||
return ps
|
||||
}
|
@@ -15,35 +15,85 @@
|
||||
package client
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"io/ioutil"
|
||||
"runtime"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
|
||||
"github.com/fatedier/frp/g"
|
||||
"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/util"
|
||||
"github.com/fatedier/frp/utils/version"
|
||||
|
||||
fmux "github.com/hashicorp/yamux"
|
||||
)
|
||||
|
||||
type Service struct {
|
||||
// manager control connection with server
|
||||
ctl *Control
|
||||
// uniq id got from frps, attach it in loginMsg
|
||||
runId string
|
||||
|
||||
// manager control connection with server
|
||||
ctl *Control
|
||||
ctlMu sync.RWMutex
|
||||
|
||||
pxyCfgs map[string]config.ProxyConf
|
||||
visitorCfgs map[string]config.VisitorConf
|
||||
cfgMu sync.RWMutex
|
||||
|
||||
exit uint32 // 0 means not exit
|
||||
closedCh chan int
|
||||
}
|
||||
|
||||
func NewService(pxyCfgs map[string]config.ProxyConf, visitorCfgs map[string]config.ProxyConf) (svr *Service) {
|
||||
func NewService(pxyCfgs map[string]config.ProxyConf, visitorCfgs map[string]config.VisitorConf) (svr *Service) {
|
||||
svr = &Service{
|
||||
closedCh: make(chan int),
|
||||
pxyCfgs: pxyCfgs,
|
||||
visitorCfgs: visitorCfgs,
|
||||
exit: 0,
|
||||
closedCh: make(chan int),
|
||||
}
|
||||
ctl := NewControl(svr, pxyCfgs, visitorCfgs)
|
||||
svr.ctl = ctl
|
||||
return
|
||||
}
|
||||
|
||||
func (svr *Service) GetController() *Control {
|
||||
svr.ctlMu.RLock()
|
||||
defer svr.ctlMu.RUnlock()
|
||||
return svr.ctl
|
||||
}
|
||||
|
||||
func (svr *Service) Run() error {
|
||||
err := svr.ctl.Run()
|
||||
if err != nil {
|
||||
return err
|
||||
// first login
|
||||
for {
|
||||
conn, session, err := svr.login()
|
||||
if err != nil {
|
||||
log.Warn("login to server failed: %v", err)
|
||||
|
||||
// if login_fail_exit is true, just exit this program
|
||||
// otherwise sleep a while and try again to connect to server
|
||||
if g.GlbClientCfg.LoginFailExit {
|
||||
return err
|
||||
} else {
|
||||
time.Sleep(10 * time.Second)
|
||||
}
|
||||
} else {
|
||||
// login success
|
||||
ctl := NewControl(svr.runId, conn, session, svr.pxyCfgs, svr.visitorCfgs)
|
||||
ctl.Run()
|
||||
svr.ctlMu.Lock()
|
||||
svr.ctl = ctl
|
||||
svr.ctlMu.Unlock()
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
go svr.keepControllerWorking()
|
||||
|
||||
if g.GlbClientCfg.AdminPort != 0 {
|
||||
err = svr.RunAdminServer(g.GlbClientCfg.AdminAddr, g.GlbClientCfg.AdminPort)
|
||||
err := svr.RunAdminServer(g.GlbClientCfg.AdminAddr, g.GlbClientCfg.AdminPort)
|
||||
if err != nil {
|
||||
log.Warn("run admin server error: %v", err)
|
||||
}
|
||||
@@ -54,6 +104,120 @@ func (svr *Service) Run() error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (svr *Service) Close() {
|
||||
svr.ctl.Close()
|
||||
func (svr *Service) keepControllerWorking() {
|
||||
maxDelayTime := 20 * time.Second
|
||||
delayTime := time.Second
|
||||
|
||||
for {
|
||||
<-svr.ctl.ClosedDoneCh()
|
||||
if atomic.LoadUint32(&svr.exit) != 0 {
|
||||
return
|
||||
}
|
||||
|
||||
for {
|
||||
log.Info("try to reconnect to server...")
|
||||
conn, session, err := svr.login()
|
||||
if err != nil {
|
||||
log.Warn("reconnect to server error: %v", err)
|
||||
time.Sleep(delayTime)
|
||||
delayTime = delayTime * 2
|
||||
if delayTime > maxDelayTime {
|
||||
delayTime = maxDelayTime
|
||||
}
|
||||
continue
|
||||
}
|
||||
// reconnect success, init delayTime
|
||||
delayTime = time.Second
|
||||
|
||||
ctl := NewControl(svr.runId, conn, session, svr.pxyCfgs, svr.visitorCfgs)
|
||||
ctl.Run()
|
||||
svr.ctlMu.Lock()
|
||||
svr.ctl = ctl
|
||||
svr.ctlMu.Unlock()
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// login creates a connection to frps and registers it self as a client
|
||||
// conn: control connection
|
||||
// session: if it's not nil, using tcp mux
|
||||
func (svr *Service) login() (conn frpNet.Conn, session *fmux.Session, err error) {
|
||||
conn, err = frpNet.ConnectServerByProxy(g.GlbClientCfg.HttpProxy, g.GlbClientCfg.Protocol,
|
||||
fmt.Sprintf("%s:%d", g.GlbClientCfg.ServerAddr, g.GlbClientCfg.ServerPort))
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
defer func() {
|
||||
if err != nil {
|
||||
conn.Close()
|
||||
}
|
||||
}()
|
||||
|
||||
if g.GlbClientCfg.TcpMux {
|
||||
fmuxCfg := fmux.DefaultConfig()
|
||||
fmuxCfg.KeepAliveInterval = 20 * time.Second
|
||||
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 = frpNet.WrapConn(stream)
|
||||
}
|
||||
|
||||
now := time.Now().Unix()
|
||||
loginMsg := &msg.Login{
|
||||
Arch: runtime.GOARCH,
|
||||
Os: runtime.GOOS,
|
||||
PoolCount: g.GlbClientCfg.PoolCount,
|
||||
User: g.GlbClientCfg.User,
|
||||
Version: version.Full(),
|
||||
PrivilegeKey: util.GetAuthKey(g.GlbClientCfg.Token, now),
|
||||
Timestamp: now,
|
||||
RunId: svr.runId,
|
||||
}
|
||||
|
||||
if err = msg.WriteMsg(conn, loginMsg); err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
var loginRespMsg msg.LoginResp
|
||||
conn.SetReadDeadline(time.Now().Add(10 * time.Second))
|
||||
if err = msg.ReadMsgInto(conn, &loginRespMsg); err != nil {
|
||||
return
|
||||
}
|
||||
conn.SetReadDeadline(time.Time{})
|
||||
|
||||
if loginRespMsg.Error != "" {
|
||||
err = fmt.Errorf("%s", loginRespMsg.Error)
|
||||
log.Error("%s", loginRespMsg.Error)
|
||||
return
|
||||
}
|
||||
|
||||
svr.runId = loginRespMsg.RunId
|
||||
g.GlbClientCfg.ServerUdpPort = loginRespMsg.ServerUdpPort
|
||||
log.Info("login to server success, get run id [%s], server udp port [%d]", loginRespMsg.RunId, loginRespMsg.ServerUdpPort)
|
||||
return
|
||||
}
|
||||
|
||||
func (svr *Service) ReloadConf(pxyCfgs map[string]config.ProxyConf, visitorCfgs map[string]config.VisitorConf) error {
|
||||
svr.cfgMu.Lock()
|
||||
svr.pxyCfgs = pxyCfgs
|
||||
svr.visitorCfgs = visitorCfgs
|
||||
svr.cfgMu.Unlock()
|
||||
|
||||
return svr.ctl.ReloadConf(pxyCfgs, visitorCfgs)
|
||||
}
|
||||
|
||||
func (svr *Service) Close() {
|
||||
atomic.StoreUint32(&svr.exit, 1)
|
||||
svr.ctl.Close()
|
||||
close(svr.closedCh)
|
||||
}
|
||||
|
@@ -44,18 +44,18 @@ type Visitor interface {
|
||||
log.Logger
|
||||
}
|
||||
|
||||
func NewVisitor(ctl *Control, pxyConf config.ProxyConf) (visitor Visitor) {
|
||||
func NewVisitor(ctl *Control, cfg config.VisitorConf) (visitor Visitor) {
|
||||
baseVisitor := BaseVisitor{
|
||||
ctl: ctl,
|
||||
Logger: log.NewPrefixLogger(pxyConf.GetBaseInfo().ProxyName),
|
||||
Logger: log.NewPrefixLogger(cfg.GetBaseInfo().ProxyName),
|
||||
}
|
||||
switch cfg := pxyConf.(type) {
|
||||
case *config.StcpProxyConf:
|
||||
switch cfg := cfg.(type) {
|
||||
case *config.StcpVisitorConf:
|
||||
visitor = &StcpVisitor{
|
||||
BaseVisitor: baseVisitor,
|
||||
cfg: cfg,
|
||||
}
|
||||
case *config.XtcpProxyConf:
|
||||
case *config.XtcpVisitorConf:
|
||||
visitor = &XtcpVisitor{
|
||||
BaseVisitor: baseVisitor,
|
||||
cfg: cfg,
|
||||
@@ -75,7 +75,7 @@ type BaseVisitor struct {
|
||||
type StcpVisitor struct {
|
||||
BaseVisitor
|
||||
|
||||
cfg *config.StcpProxyConf
|
||||
cfg *config.StcpVisitorConf
|
||||
}
|
||||
|
||||
func (sv *StcpVisitor) Run() (err error) {
|
||||
@@ -162,7 +162,7 @@ func (sv *StcpVisitor) handleConn(userConn frpNet.Conn) {
|
||||
type XtcpVisitor struct {
|
||||
BaseVisitor
|
||||
|
||||
cfg *config.XtcpProxyConf
|
||||
cfg *config.XtcpVisitorConf
|
||||
}
|
||||
|
||||
func (sv *XtcpVisitor) Run() (err error) {
|
||||
@@ -183,7 +183,7 @@ func (sv *XtcpVisitor) worker() {
|
||||
for {
|
||||
conn, err := sv.l.Accept()
|
||||
if err != nil {
|
||||
sv.Warn("stcp local listener closed")
|
||||
sv.Warn("xtcp local listener closed")
|
||||
return
|
||||
}
|
||||
|
||||
@@ -202,7 +202,16 @@ func (sv *XtcpVisitor) handleConn(userConn frpNet.Conn) {
|
||||
|
||||
raddr, err := net.ResolveUDPAddr("udp",
|
||||
fmt.Sprintf("%s:%d", g.GlbClientCfg.ServerAddr, g.GlbClientCfg.ServerUdpPort))
|
||||
if err != nil {
|
||||
sv.Error("resolve server UDP addr error")
|
||||
return
|
||||
}
|
||||
|
||||
visitorConn, err := net.DialUDP("udp", nil, raddr)
|
||||
if err != nil {
|
||||
sv.Warn("dial server udp addr error: %v", err)
|
||||
return
|
||||
}
|
||||
defer visitorConn.Close()
|
||||
|
||||
now := time.Now().Unix()
|
||||
|
123
client/visitor_manager.go
Normal file
123
client/visitor_manager.go
Normal file
@@ -0,0 +1,123 @@
|
||||
// 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 client
|
||||
|
||||
import (
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/fatedier/frp/models/config"
|
||||
"github.com/fatedier/frp/utils/log"
|
||||
)
|
||||
|
||||
type VisitorManager struct {
|
||||
ctl *Control
|
||||
|
||||
cfgs map[string]config.VisitorConf
|
||||
visitors map[string]Visitor
|
||||
|
||||
checkInterval time.Duration
|
||||
|
||||
mu sync.Mutex
|
||||
}
|
||||
|
||||
func NewVisitorManager(ctl *Control) *VisitorManager {
|
||||
return &VisitorManager{
|
||||
ctl: ctl,
|
||||
cfgs: make(map[string]config.VisitorConf),
|
||||
visitors: make(map[string]Visitor),
|
||||
checkInterval: 10 * time.Second,
|
||||
}
|
||||
}
|
||||
|
||||
func (vm *VisitorManager) Run() {
|
||||
for {
|
||||
time.Sleep(vm.checkInterval)
|
||||
vm.mu.Lock()
|
||||
for _, cfg := range vm.cfgs {
|
||||
name := cfg.GetBaseInfo().ProxyName
|
||||
if _, exist := vm.visitors[name]; !exist {
|
||||
log.Info("try to start visitor [%s]", name)
|
||||
vm.startVisitor(cfg)
|
||||
}
|
||||
}
|
||||
vm.mu.Unlock()
|
||||
}
|
||||
}
|
||||
|
||||
// Hold lock before calling this function.
|
||||
func (vm *VisitorManager) startVisitor(cfg config.VisitorConf) (err error) {
|
||||
name := cfg.GetBaseInfo().ProxyName
|
||||
visitor := NewVisitor(vm.ctl, cfg)
|
||||
err = visitor.Run()
|
||||
if err != nil {
|
||||
visitor.Warn("start error: %v", err)
|
||||
} else {
|
||||
vm.visitors[name] = visitor
|
||||
visitor.Info("start visitor success")
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
func (vm *VisitorManager) Reload(cfgs map[string]config.VisitorConf) {
|
||||
vm.mu.Lock()
|
||||
defer vm.mu.Unlock()
|
||||
|
||||
delNames := make([]string, 0)
|
||||
for name, oldCfg := range vm.cfgs {
|
||||
del := false
|
||||
cfg, ok := cfgs[name]
|
||||
if !ok {
|
||||
del = true
|
||||
} else {
|
||||
if !oldCfg.Compare(cfg) {
|
||||
del = true
|
||||
}
|
||||
}
|
||||
|
||||
if del {
|
||||
delNames = append(delNames, name)
|
||||
delete(vm.cfgs, name)
|
||||
if visitor, ok := vm.visitors[name]; ok {
|
||||
visitor.Close()
|
||||
}
|
||||
delete(vm.visitors, name)
|
||||
}
|
||||
}
|
||||
if len(delNames) > 0 {
|
||||
log.Info("visitor removed: %v", delNames)
|
||||
}
|
||||
|
||||
addNames := make([]string, 0)
|
||||
for name, cfg := range cfgs {
|
||||
if _, ok := vm.cfgs[name]; !ok {
|
||||
vm.cfgs[name] = cfg
|
||||
addNames = append(addNames, name)
|
||||
vm.startVisitor(cfg)
|
||||
}
|
||||
}
|
||||
if len(addNames) > 0 {
|
||||
log.Info("visitor added: %v", addNames)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
func (vm *VisitorManager) Close() {
|
||||
vm.mu.Lock()
|
||||
defer vm.mu.Unlock()
|
||||
for _, v := range vm.visitors {
|
||||
v.Close()
|
||||
}
|
||||
}
|
@@ -12,7 +12,7 @@
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
package main
|
||||
package main // "github.com/fatedier/frp/cmd/frpc"
|
||||
|
||||
import (
|
||||
"github.com/fatedier/frp/cmd/frpc/sub"
|
||||
|
@@ -17,7 +17,6 @@ package sub
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"io/ioutil"
|
||||
"net"
|
||||
"os"
|
||||
"os/signal"
|
||||
@@ -27,7 +26,6 @@ import (
|
||||
"time"
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
ini "github.com/vaughan0/go-ini"
|
||||
|
||||
"github.com/fatedier/frp/client"
|
||||
"github.com/fatedier/frp/g"
|
||||
@@ -70,11 +68,15 @@ var (
|
||||
serverName string
|
||||
bindAddr string
|
||||
bindPort int
|
||||
|
||||
kcpDoneCh chan struct{}
|
||||
)
|
||||
|
||||
func init() {
|
||||
rootCmd.PersistentFlags().StringVarP(&cfgFile, "", "c", "./frpc.ini", "config file of frpc")
|
||||
rootCmd.PersistentFlags().BoolVarP(&showVersion, "version", "v", false, "version of frpc")
|
||||
|
||||
kcpDoneCh = make(chan struct{})
|
||||
}
|
||||
|
||||
var rootCmd = &cobra.Command{
|
||||
@@ -108,12 +110,12 @@ func handleSignal(svr *client.Service) {
|
||||
<-ch
|
||||
svr.Close()
|
||||
time.Sleep(250 * time.Millisecond)
|
||||
os.Exit(0)
|
||||
close(kcpDoneCh)
|
||||
}
|
||||
|
||||
func parseClientCommonCfg(fileType int, filePath string) (err error) {
|
||||
func parseClientCommonCfg(fileType int, content string) (err error) {
|
||||
if fileType == CfgFileTypeIni {
|
||||
err = parseClientCommonCfgFromIni(filePath)
|
||||
err = parseClientCommonCfgFromIni(content)
|
||||
} else if fileType == CfgFileTypeCmd {
|
||||
err = parseClientCommonCfgFromCmd()
|
||||
}
|
||||
@@ -121,8 +123,6 @@ func parseClientCommonCfg(fileType int, filePath string) (err error) {
|
||||
return
|
||||
}
|
||||
|
||||
g.GlbClientCfg.CfgFile = cfgFile
|
||||
|
||||
err = g.GlbClientCfg.ClientCommonConf.Check()
|
||||
if err != nil {
|
||||
return
|
||||
@@ -130,13 +130,7 @@ func parseClientCommonCfg(fileType int, filePath string) (err error) {
|
||||
return
|
||||
}
|
||||
|
||||
func parseClientCommonCfgFromIni(filePath string) (err error) {
|
||||
b, err := ioutil.ReadFile(filePath)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
content := string(b)
|
||||
|
||||
func parseClientCommonCfgFromIni(content string) (err error) {
|
||||
cfg, err := config.UnmarshalClientConfFromIni(&g.GlbClientCfg.ClientCommonConf, content)
|
||||
if err != nil {
|
||||
return err
|
||||
@@ -166,21 +160,28 @@ func parseClientCommonCfgFromCmd() (err error) {
|
||||
g.GlbClientCfg.LogLevel = logLevel
|
||||
g.GlbClientCfg.LogFile = logFile
|
||||
g.GlbClientCfg.LogMaxDays = int64(logMaxDays)
|
||||
if logFile == "console" {
|
||||
g.GlbClientCfg.LogWay = "console"
|
||||
} else {
|
||||
g.GlbClientCfg.LogWay = "file"
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func runClient(cfgFilePath string) (err error) {
|
||||
err = parseClientCommonCfg(CfgFileTypeIni, cfgFilePath)
|
||||
var content string
|
||||
content, err = config.GetRenderedConfFromFile(cfgFilePath)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
g.GlbClientCfg.CfgFile = cfgFilePath
|
||||
|
||||
err = parseClientCommonCfg(CfgFileTypeIni, content)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
conf, err := ini.LoadFile(cfgFilePath)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
pxyCfgs, visitorCfgs, err := config.LoadProxyConfFromIni(g.GlbClientCfg.User, conf, g.GlbClientCfg.Start)
|
||||
pxyCfgs, visitorCfgs, err := config.LoadAllConfFromIni(g.GlbClientCfg.User, content, g.GlbClientCfg.Start)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -189,7 +190,7 @@ func runClient(cfgFilePath string) (err error) {
|
||||
return
|
||||
}
|
||||
|
||||
func startService(pxyCfgs map[string]config.ProxyConf, visitorCfgs map[string]config.ProxyConf) (err error) {
|
||||
func startService(pxyCfgs map[string]config.ProxyConf, visitorCfgs map[string]config.VisitorConf) (err error) {
|
||||
log.InitLog(g.GlbClientCfg.LogWay, g.GlbClientCfg.LogFile, g.GlbClientCfg.LogLevel, g.GlbClientCfg.LogMaxDays)
|
||||
if g.GlbClientCfg.DnsServer != "" {
|
||||
s := g.GlbClientCfg.DnsServer
|
||||
@@ -212,5 +213,8 @@ func startService(pxyCfgs map[string]config.ProxyConf, visitorCfgs map[string]co
|
||||
}
|
||||
|
||||
err = svr.Run()
|
||||
if g.GlbClientCfg.Protocol == "kcp" {
|
||||
<-kcpDoneCh
|
||||
}
|
||||
return
|
||||
}
|
||||
|
@@ -57,48 +57,57 @@ var stcpCmd = &cobra.Command{
|
||||
os.Exit(1)
|
||||
}
|
||||
|
||||
cfg := &config.StcpProxyConf{}
|
||||
proxyConfs := make(map[string]config.ProxyConf)
|
||||
visitorConfs := make(map[string]config.VisitorConf)
|
||||
|
||||
var prefix string
|
||||
if user != "" {
|
||||
prefix = user + "."
|
||||
}
|
||||
cfg.ProxyName = prefix + proxyName
|
||||
cfg.ProxyType = consts.StcpProxy
|
||||
cfg.Role = role
|
||||
cfg.Sk = sk
|
||||
cfg.ServerName = serverName
|
||||
cfg.LocalIp = localIp
|
||||
cfg.LocalPort = localPort
|
||||
cfg.BindAddr = bindAddr
|
||||
cfg.BindPort = bindPort
|
||||
cfg.UseEncryption = useEncryption
|
||||
cfg.UseCompression = useCompression
|
||||
|
||||
err = cfg.CheckForCli()
|
||||
if role == "server" {
|
||||
cfg := &config.StcpProxyConf{}
|
||||
cfg.ProxyName = prefix + proxyName
|
||||
cfg.ProxyType = consts.StcpProxy
|
||||
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
|
||||
} else if role == "visitor" {
|
||||
cfg := &config.StcpVisitorConf{}
|
||||
cfg.ProxyName = prefix + proxyName
|
||||
cfg.ProxyType = consts.StcpProxy
|
||||
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
|
||||
} else {
|
||||
fmt.Println("invalid role")
|
||||
os.Exit(1)
|
||||
}
|
||||
|
||||
err = startService(proxyConfs, visitorConfs)
|
||||
if err != nil {
|
||||
fmt.Println(err)
|
||||
os.Exit(1)
|
||||
}
|
||||
|
||||
if cfg.Role == "server" {
|
||||
proxyConfs := map[string]config.ProxyConf{
|
||||
cfg.ProxyName: cfg,
|
||||
}
|
||||
err = startService(proxyConfs, nil)
|
||||
if err != nil {
|
||||
fmt.Println(err)
|
||||
os.Exit(1)
|
||||
}
|
||||
} else {
|
||||
visitorConfs := map[string]config.ProxyConf{
|
||||
cfg.ProxyName: cfg,
|
||||
}
|
||||
err = startService(nil, visitorConfs)
|
||||
if err != nil {
|
||||
fmt.Println(err)
|
||||
os.Exit(1)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
},
|
||||
}
|
||||
|
@@ -57,48 +57,57 @@ var xtcpCmd = &cobra.Command{
|
||||
os.Exit(1)
|
||||
}
|
||||
|
||||
cfg := &config.XtcpProxyConf{}
|
||||
proxyConfs := make(map[string]config.ProxyConf)
|
||||
visitorConfs := make(map[string]config.VisitorConf)
|
||||
|
||||
var prefix string
|
||||
if user != "" {
|
||||
prefix = user + "."
|
||||
}
|
||||
cfg.ProxyName = prefix + proxyName
|
||||
cfg.ProxyType = consts.XtcpProxy
|
||||
cfg.Role = role
|
||||
cfg.Sk = sk
|
||||
cfg.ServerName = serverName
|
||||
cfg.LocalIp = localIp
|
||||
cfg.LocalPort = localPort
|
||||
cfg.BindAddr = bindAddr
|
||||
cfg.BindPort = bindPort
|
||||
cfg.UseEncryption = useEncryption
|
||||
cfg.UseCompression = useCompression
|
||||
|
||||
err = cfg.CheckForCli()
|
||||
if role == "server" {
|
||||
cfg := &config.XtcpProxyConf{}
|
||||
cfg.ProxyName = prefix + proxyName
|
||||
cfg.ProxyType = consts.StcpProxy
|
||||
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
|
||||
} else if role == "visitor" {
|
||||
cfg := &config.XtcpVisitorConf{}
|
||||
cfg.ProxyName = prefix + proxyName
|
||||
cfg.ProxyType = consts.StcpProxy
|
||||
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
|
||||
} else {
|
||||
fmt.Println("invalid role")
|
||||
os.Exit(1)
|
||||
}
|
||||
|
||||
err = startService(proxyConfs, visitorConfs)
|
||||
if err != nil {
|
||||
fmt.Println(err)
|
||||
os.Exit(1)
|
||||
}
|
||||
|
||||
if cfg.Role == "server" {
|
||||
proxyConfs := map[string]config.ProxyConf{
|
||||
cfg.ProxyName: cfg,
|
||||
}
|
||||
err = startService(proxyConfs, nil)
|
||||
if err != nil {
|
||||
fmt.Println(err)
|
||||
os.Exit(1)
|
||||
}
|
||||
} else {
|
||||
visitorConfs := map[string]config.ProxyConf{
|
||||
cfg.ProxyName: cfg,
|
||||
}
|
||||
err = startService(nil, visitorConfs)
|
||||
if err != nil {
|
||||
fmt.Println(err)
|
||||
os.Exit(1)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
},
|
||||
}
|
||||
|
@@ -12,7 +12,7 @@
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
package main
|
||||
package main // "github.com/fatedier/frp/cmd/frps"
|
||||
|
||||
import (
|
||||
"github.com/fatedier/golib/crypto"
|
||||
|
@@ -16,7 +16,6 @@ package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"io/ioutil"
|
||||
"os"
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
@@ -25,6 +24,7 @@ import (
|
||||
"github.com/fatedier/frp/models/config"
|
||||
"github.com/fatedier/frp/server"
|
||||
"github.com/fatedier/frp/utils/log"
|
||||
"github.com/fatedier/frp/utils/util"
|
||||
"github.com/fatedier/frp/utils/version"
|
||||
)
|
||||
|
||||
@@ -44,17 +44,16 @@ var (
|
||||
proxyBindAddr string
|
||||
vhostHttpPort int
|
||||
vhostHttpsPort int
|
||||
vhostHttpTimeout int64
|
||||
dashboardAddr string
|
||||
dashboardPort int
|
||||
dashboardUser string
|
||||
dashboardPwd string
|
||||
assetsDir string
|
||||
logFile string
|
||||
logWay string
|
||||
logLevel string
|
||||
logMaxDays int64
|
||||
token string
|
||||
authTimeout int64
|
||||
subDomainHost string
|
||||
tcpMux bool
|
||||
allowPorts string
|
||||
@@ -73,17 +72,17 @@ func init() {
|
||||
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(&vhostHttpsPort, "vhost_https_port", "", 0, "vhost https port")
|
||||
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().IntVarP(&dashboardPort, "dashboard_port", "", 0, "dashboard port")
|
||||
rootCmd.PersistentFlags().StringVarP(&dashboardUser, "dashboard_user", "", "admin", "dashboard user")
|
||||
rootCmd.PersistentFlags().StringVarP(&dashboardPwd, "dashboard_pwd", "", "admin", "dashboard password")
|
||||
rootCmd.PersistentFlags().StringVarP(&logFile, "log_file", "", "console", "log file")
|
||||
rootCmd.PersistentFlags().StringVarP(&logWay, "log_way", "", "console", "log way")
|
||||
rootCmd.PersistentFlags().StringVarP(&logLevel, "log_level", "", "info", "log level")
|
||||
rootCmd.PersistentFlags().Int64VarP(&logMaxDays, "log_max_days", "", 3, "log_max_days")
|
||||
rootCmd.PersistentFlags().StringVarP(&token, "token", "t", "", "auth token")
|
||||
rootCmd.PersistentFlags().Int64VarP(&authTimeout, "auth_timeout", "", 900, "auth timeout")
|
||||
rootCmd.PersistentFlags().StringVarP(&subDomainHost, "subdomain_host", "", "", "subdomain host")
|
||||
rootCmd.PersistentFlags().StringVarP(&allowPorts, "allow_ports", "", "", "allow ports")
|
||||
rootCmd.PersistentFlags().Int64VarP(&maxPortsPerClient, "max_ports_per_client", "", 0, "max ports per client")
|
||||
}
|
||||
|
||||
@@ -98,7 +97,13 @@ var rootCmd = &cobra.Command{
|
||||
|
||||
var err error
|
||||
if cfgFile != "" {
|
||||
err = parseServerCommonCfg(CfgFileTypeIni, cfgFile)
|
||||
var content string
|
||||
content, err = config.GetRenderedConfFromFile(cfgFile)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
g.GlbServerCfg.CfgFile = cfgFile
|
||||
err = parseServerCommonCfg(CfgFileTypeIni, content)
|
||||
} else {
|
||||
err = parseServerCommonCfg(CfgFileTypeCmd, "")
|
||||
}
|
||||
@@ -121,9 +126,9 @@ func Execute() {
|
||||
}
|
||||
}
|
||||
|
||||
func parseServerCommonCfg(fileType int, filePath string) (err error) {
|
||||
func parseServerCommonCfg(fileType int, content string) (err error) {
|
||||
if fileType == CfgFileTypeIni {
|
||||
err = parseServerCommonCfgFromIni(filePath)
|
||||
err = parseServerCommonCfgFromIni(content)
|
||||
} else if fileType == CfgFileTypeCmd {
|
||||
err = parseServerCommonCfgFromCmd()
|
||||
}
|
||||
@@ -131,8 +136,6 @@ func parseServerCommonCfg(fileType int, filePath string) (err error) {
|
||||
return
|
||||
}
|
||||
|
||||
g.GlbServerCfg.CfgFile = filePath
|
||||
|
||||
err = g.GlbServerCfg.ServerCommonConf.Check()
|
||||
if err != nil {
|
||||
return
|
||||
@@ -142,13 +145,7 @@ func parseServerCommonCfg(fileType int, filePath string) (err error) {
|
||||
return
|
||||
}
|
||||
|
||||
func parseServerCommonCfgFromIni(filePath string) (err error) {
|
||||
b, err := ioutil.ReadFile(filePath)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
content := string(b)
|
||||
|
||||
func parseServerCommonCfgFromIni(content string) (err error) {
|
||||
cfg, err := config.UnmarshalServerConfFromIni(&g.GlbServerCfg.ServerCommonConf, content)
|
||||
if err != nil {
|
||||
return err
|
||||
@@ -165,18 +162,35 @@ func parseServerCommonCfgFromCmd() (err error) {
|
||||
g.GlbServerCfg.ProxyBindAddr = proxyBindAddr
|
||||
g.GlbServerCfg.VhostHttpPort = vhostHttpPort
|
||||
g.GlbServerCfg.VhostHttpsPort = vhostHttpsPort
|
||||
g.GlbServerCfg.VhostHttpTimeout = vhostHttpTimeout
|
||||
g.GlbServerCfg.DashboardAddr = dashboardAddr
|
||||
g.GlbServerCfg.DashboardPort = dashboardPort
|
||||
g.GlbServerCfg.DashboardUser = dashboardUser
|
||||
g.GlbServerCfg.DashboardPwd = dashboardPwd
|
||||
g.GlbServerCfg.LogFile = logFile
|
||||
g.GlbServerCfg.LogWay = logWay
|
||||
g.GlbServerCfg.LogLevel = logLevel
|
||||
g.GlbServerCfg.LogMaxDays = logMaxDays
|
||||
g.GlbServerCfg.Token = token
|
||||
g.GlbServerCfg.AuthTimeout = authTimeout
|
||||
g.GlbServerCfg.SubDomainHost = subDomainHost
|
||||
if len(allowPorts) > 0 {
|
||||
// e.g. 1000-2000,2001,2002,3000-4000
|
||||
ports, errRet := util.ParseRangeNumbers(allowPorts)
|
||||
if errRet != nil {
|
||||
err = fmt.Errorf("Parse conf error: allow_ports: %v", errRet)
|
||||
return
|
||||
}
|
||||
|
||||
for _, port := range ports {
|
||||
g.GlbServerCfg.AllowPorts[int(port)] = struct{}{}
|
||||
}
|
||||
}
|
||||
g.GlbServerCfg.MaxPortsPerClient = maxPortsPerClient
|
||||
|
||||
if logFile == "console" {
|
||||
g.GlbClientCfg.LogWay = "console"
|
||||
} else {
|
||||
g.GlbClientCfg.LogWay = "file"
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
|
@@ -25,7 +25,7 @@ token = 12345678
|
||||
admin_addr = 127.0.0.1
|
||||
admin_port = 7400
|
||||
admin_user = admin
|
||||
admin_passwd = admin
|
||||
admin_pwd = admin
|
||||
|
||||
# connections will be established in advance, default value is zero
|
||||
pool_count = 5
|
||||
@@ -41,11 +41,11 @@ user = your_name
|
||||
login_fail_exit = true
|
||||
|
||||
# communication protocol used to connect to server
|
||||
# now it supports tcp and kcp, default is tcp
|
||||
# now it supports tcp and kcp and websocket, default is tcp
|
||||
protocol = tcp
|
||||
|
||||
# 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 divided by ','
|
||||
# default is empty, means all proxies
|
||||
@@ -56,10 +56,10 @@ dns_server = 8.8.8.8
|
||||
# heartbeat_interval = 30
|
||||
# heartbeat_timeout = 90
|
||||
|
||||
# ssh is the proxy name same as server's configuration
|
||||
# if user in [common] section is not empty, it will be changed to {user}.{proxy} such as your_name.ssh
|
||||
# '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'
|
||||
[ssh]
|
||||
# tcp | udp | http | https, default is tcp
|
||||
# tcp | udp | http | https | stcp | xtcp, default is tcp
|
||||
type = tcp
|
||||
local_ip = 127.0.0.1
|
||||
local_port = 22
|
||||
@@ -69,6 +69,19 @@ use_encryption = false
|
||||
use_compression = false
|
||||
# remote port listen by frps
|
||||
remote_port = 6001
|
||||
# frps will load balancing connections for proxies in same group
|
||||
group = test_group
|
||||
# group should have same group key
|
||||
group_key = 123456
|
||||
# enable health check for the backend service, it support 'tcp' and 'http' now
|
||||
# frpc will connect local service's port to detect it's healthy status
|
||||
health_check_type = tcp
|
||||
# health check connection timeout
|
||||
health_check_timeout_s = 3
|
||||
# if continuous failed in 3 times, the proxy will be removed from frps
|
||||
health_check_max_failed = 3
|
||||
# every 10 seconds will do a health check
|
||||
health_check_interval_s = 10
|
||||
|
||||
[ssh_random]
|
||||
type = tcp
|
||||
@@ -120,6 +133,15 @@ custom_domains = web02.yourdomain.com
|
||||
# locations is only available for http type
|
||||
locations = /,/pic
|
||||
host_header_rewrite = example.com
|
||||
# params with prefix "header_" will be used to update http request headers
|
||||
header_X-From-Where = frp
|
||||
health_check_type = http
|
||||
# frpc will send a GET http request '/status' to local http service
|
||||
# http service is alive when it return 2xx http response code
|
||||
health_check_url = /status
|
||||
health_check_interval_s = 10
|
||||
health_check_max_failed = 3
|
||||
health_check_timeout_s = 3
|
||||
|
||||
[web02]
|
||||
type = https
|
||||
@@ -136,7 +158,7 @@ remote_port = 6003
|
||||
# if plugin is defined, local_ip and local_port is useless
|
||||
# plugin will handle connections got from frps
|
||||
plugin = unix_domain_socket
|
||||
# params set with prefix "plugin_" that plugin needed
|
||||
# params with prefix "plugin_" that plugin needed
|
||||
plugin_unix_path = /var/run/docker.sock
|
||||
|
||||
[plugin_http_proxy]
|
||||
|
@@ -20,6 +20,9 @@ kcp_bind_port = 7000
|
||||
vhost_http_port = 80
|
||||
vhost_https_port = 443
|
||||
|
||||
# response header timeout(seconds) for vhost http server, default is 60s
|
||||
# vhost_http_timeout = 60
|
||||
|
||||
# set dashboard_addr and dashboard_port to view dashboard of frps
|
||||
# dashboard_addr's default value is same with bind_addr
|
||||
# dashboard is available only if dashboard_port is set
|
||||
@@ -56,10 +59,6 @@ max_pool_count = 5
|
||||
# max ports can be used for each client, default value is 0 means no limit
|
||||
max_ports_per_client = 0
|
||||
|
||||
# authentication_timeout means the timeout interval (seconds) when the frpc connects frps
|
||||
# if authentication_timeout is zero, the time is not verified, default is 900s
|
||||
authentication_timeout = 900
|
||||
|
||||
# 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
|
||||
subdomain_host = frps.com
|
||||
|
BIN
doc/pic/zsxq.jpg
Normal file
BIN
doc/pic/zsxq.jpg
Normal file
Binary file not shown.
After Width: | Height: | Size: 12 KiB |
@@ -186,9 +186,10 @@ func UnmarshalClientConfFromIni(defaultCfg *ClientCommonConf, content string) (c
|
||||
}
|
||||
|
||||
if tmpStr, ok = conf.Get("common", "protocol"); ok {
|
||||
// Now it only support tcp and kcp.
|
||||
if tmpStr != "kcp" {
|
||||
tmpStr = "tcp"
|
||||
// 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
|
||||
}
|
||||
|
@@ -91,7 +91,9 @@ func NewProxyConfFromIni(prefix string, name string, section ini.Section) (cfg P
|
||||
if err = cfg.UnmarshalFromIni(prefix, name, section); err != nil {
|
||||
return
|
||||
}
|
||||
err = cfg.CheckForCli()
|
||||
if err = cfg.CheckForCli(); err != nil {
|
||||
return
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
@@ -100,8 +102,13 @@ type BaseProxyConf struct {
|
||||
ProxyName string `json:"proxy_name"`
|
||||
ProxyType string `json:"proxy_type"`
|
||||
|
||||
UseEncryption bool `json:"use_encryption"`
|
||||
UseCompression bool `json:"use_compression"`
|
||||
UseEncryption bool `json:"use_encryption"`
|
||||
UseCompression bool `json:"use_compression"`
|
||||
Group string `json:"group"`
|
||||
GroupKey string `json:"group_key"`
|
||||
|
||||
LocalSvrConf
|
||||
HealthCheckConf // only used for client
|
||||
}
|
||||
|
||||
func (cfg *BaseProxyConf) GetBaseInfo() *BaseProxyConf {
|
||||
@@ -112,7 +119,15 @@ func (cfg *BaseProxyConf) compare(cmp *BaseProxyConf) bool {
|
||||
if cfg.ProxyName != cmp.ProxyName ||
|
||||
cfg.ProxyType != cmp.ProxyType ||
|
||||
cfg.UseEncryption != cmp.UseEncryption ||
|
||||
cfg.UseCompression != cmp.UseCompression {
|
||||
cfg.UseCompression != cmp.UseCompression ||
|
||||
cfg.Group != cmp.Group ||
|
||||
cfg.GroupKey != cmp.GroupKey {
|
||||
return false
|
||||
}
|
||||
if !cfg.LocalSvrConf.compare(&cmp.LocalSvrConf) {
|
||||
return false
|
||||
}
|
||||
if !cfg.HealthCheckConf.compare(&cmp.HealthCheckConf) {
|
||||
return false
|
||||
}
|
||||
return true
|
||||
@@ -123,6 +138,8 @@ func (cfg *BaseProxyConf) UnmarshalFromMsg(pMsg *msg.NewProxy) {
|
||||
cfg.ProxyType = pMsg.ProxyType
|
||||
cfg.UseEncryption = pMsg.UseEncryption
|
||||
cfg.UseCompression = pMsg.UseCompression
|
||||
cfg.Group = pMsg.Group
|
||||
cfg.GroupKey = pMsg.GroupKey
|
||||
}
|
||||
|
||||
func (cfg *BaseProxyConf) UnmarshalFromIni(prefix string, name string, section ini.Section) error {
|
||||
@@ -142,6 +159,28 @@ func (cfg *BaseProxyConf) UnmarshalFromIni(prefix string, name string, section i
|
||||
if ok && tmpStr == "true" {
|
||||
cfg.UseCompression = true
|
||||
}
|
||||
|
||||
cfg.Group = section["group"]
|
||||
cfg.GroupKey = section["group_key"]
|
||||
|
||||
if err := cfg.LocalSvrConf.UnmarshalFromIni(prefix, name, section); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if err := cfg.HealthCheckConf.UnmarshalFromIni(prefix, name, section); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if cfg.HealthCheckType == "tcp" && cfg.Plugin == "" {
|
||||
cfg.HealthCheckAddr = cfg.LocalIp + fmt.Sprintf(":%d", cfg.LocalPort)
|
||||
}
|
||||
if cfg.HealthCheckType == "http" && cfg.Plugin == "" && cfg.HealthCheckUrl != "" {
|
||||
s := fmt.Sprintf("http://%s:%d", cfg.LocalIp, cfg.LocalPort)
|
||||
if !strings.HasPrefix(cfg.HealthCheckUrl, "/") {
|
||||
s += "/"
|
||||
}
|
||||
cfg.HealthCheckUrl = s + cfg.HealthCheckUrl
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -150,6 +189,18 @@ func (cfg *BaseProxyConf) MarshalToMsg(pMsg *msg.NewProxy) {
|
||||
pMsg.ProxyType = cfg.ProxyType
|
||||
pMsg.UseEncryption = cfg.UseEncryption
|
||||
pMsg.UseCompression = cfg.UseCompression
|
||||
pMsg.Group = cfg.Group
|
||||
pMsg.GroupKey = cfg.GroupKey
|
||||
}
|
||||
|
||||
func (cfg *BaseProxyConf) checkForCli() (err error) {
|
||||
if err = cfg.LocalSvrConf.checkForCli(); err != nil {
|
||||
return
|
||||
}
|
||||
if err = cfg.HealthCheckConf.checkForCli(); err != nil {
|
||||
return
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// Bind info
|
||||
@@ -324,12 +375,83 @@ func (cfg *LocalSvrConf) UnmarshalFromIni(prefix string, name string, section in
|
||||
return
|
||||
}
|
||||
|
||||
func (cfg *LocalSvrConf) checkForCli() (err error) {
|
||||
if cfg.Plugin == "" {
|
||||
if cfg.LocalIp == "" {
|
||||
err = fmt.Errorf("local ip or plugin is required")
|
||||
return
|
||||
}
|
||||
if cfg.LocalPort <= 0 {
|
||||
err = fmt.Errorf("error local_port")
|
||||
return
|
||||
}
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
// Health check info
|
||||
type HealthCheckConf struct {
|
||||
HealthCheckType string `json:"health_check_type"` // tcp | http
|
||||
HealthCheckTimeoutS int `json:"health_check_timeout_s"`
|
||||
HealthCheckMaxFailed int `json:"health_check_max_failed"`
|
||||
HealthCheckIntervalS int `json:"health_check_interval_s"`
|
||||
HealthCheckUrl string `json:"health_check_url"`
|
||||
|
||||
// local_ip + local_port
|
||||
HealthCheckAddr string `json:"-"`
|
||||
}
|
||||
|
||||
func (cfg *HealthCheckConf) compare(cmp *HealthCheckConf) bool {
|
||||
if cfg.HealthCheckType != cmp.HealthCheckType ||
|
||||
cfg.HealthCheckTimeoutS != cmp.HealthCheckTimeoutS ||
|
||||
cfg.HealthCheckMaxFailed != cmp.HealthCheckMaxFailed ||
|
||||
cfg.HealthCheckIntervalS != cmp.HealthCheckIntervalS ||
|
||||
cfg.HealthCheckUrl != cmp.HealthCheckUrl {
|
||||
return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
func (cfg *HealthCheckConf) UnmarshalFromIni(prefix string, name string, section ini.Section) (err error) {
|
||||
cfg.HealthCheckType = section["health_check_type"]
|
||||
cfg.HealthCheckUrl = section["health_check_url"]
|
||||
|
||||
if tmpStr, ok := section["health_check_timeout_s"]; ok {
|
||||
if cfg.HealthCheckTimeoutS, err = strconv.Atoi(tmpStr); err != nil {
|
||||
return fmt.Errorf("Parse conf error: proxy [%s] health_check_timeout_s error", name)
|
||||
}
|
||||
}
|
||||
|
||||
if tmpStr, ok := section["health_check_max_failed"]; ok {
|
||||
if cfg.HealthCheckMaxFailed, err = strconv.Atoi(tmpStr); err != nil {
|
||||
return fmt.Errorf("Parse conf error: proxy [%s] health_check_max_failed error", name)
|
||||
}
|
||||
}
|
||||
|
||||
if tmpStr, ok := section["health_check_interval_s"]; ok {
|
||||
if cfg.HealthCheckIntervalS, err = strconv.Atoi(tmpStr); err != nil {
|
||||
return fmt.Errorf("Parse conf error: proxy [%s] health_check_interval_s error", name)
|
||||
}
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
func (cfg *HealthCheckConf) checkForCli() error {
|
||||
if cfg.HealthCheckType != "" && cfg.HealthCheckType != "tcp" && cfg.HealthCheckType != "http" {
|
||||
return fmt.Errorf("unsupport health check type")
|
||||
}
|
||||
if cfg.HealthCheckType != "" {
|
||||
if cfg.HealthCheckType == "http" && cfg.HealthCheckUrl == "" {
|
||||
return fmt.Errorf("health_check_url is required for health check type 'http'")
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// TCP
|
||||
type TcpProxyConf struct {
|
||||
BaseProxyConf
|
||||
BindInfoConf
|
||||
|
||||
LocalSvrConf
|
||||
}
|
||||
|
||||
func (cfg *TcpProxyConf) Compare(cmp ProxyConf) bool {
|
||||
@@ -339,8 +461,7 @@ func (cfg *TcpProxyConf) Compare(cmp ProxyConf) bool {
|
||||
}
|
||||
|
||||
if !cfg.BaseProxyConf.compare(&cmpConf.BaseProxyConf) ||
|
||||
!cfg.BindInfoConf.compare(&cmpConf.BindInfoConf) ||
|
||||
!cfg.LocalSvrConf.compare(&cmpConf.LocalSvrConf) {
|
||||
!cfg.BindInfoConf.compare(&cmpConf.BindInfoConf) {
|
||||
return false
|
||||
}
|
||||
return true
|
||||
@@ -358,9 +479,6 @@ func (cfg *TcpProxyConf) UnmarshalFromIni(prefix string, name string, section in
|
||||
if err = cfg.BindInfoConf.UnmarshalFromIni(prefix, name, section); err != nil {
|
||||
return
|
||||
}
|
||||
if err = cfg.LocalSvrConf.UnmarshalFromIni(prefix, name, section); err != nil {
|
||||
return
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
@@ -369,7 +487,12 @@ func (cfg *TcpProxyConf) MarshalToMsg(pMsg *msg.NewProxy) {
|
||||
cfg.BindInfoConf.MarshalToMsg(pMsg)
|
||||
}
|
||||
|
||||
func (cfg *TcpProxyConf) CheckForCli() error { return nil }
|
||||
func (cfg *TcpProxyConf) CheckForCli() (err error) {
|
||||
if err = cfg.BaseProxyConf.checkForCli(); err != nil {
|
||||
return err
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
func (cfg *TcpProxyConf) CheckForSvr() error { return nil }
|
||||
|
||||
@@ -377,8 +500,6 @@ func (cfg *TcpProxyConf) CheckForSvr() error { return nil }
|
||||
type UdpProxyConf struct {
|
||||
BaseProxyConf
|
||||
BindInfoConf
|
||||
|
||||
LocalSvrConf
|
||||
}
|
||||
|
||||
func (cfg *UdpProxyConf) Compare(cmp ProxyConf) bool {
|
||||
@@ -388,8 +509,7 @@ func (cfg *UdpProxyConf) Compare(cmp ProxyConf) bool {
|
||||
}
|
||||
|
||||
if !cfg.BaseProxyConf.compare(&cmpConf.BaseProxyConf) ||
|
||||
!cfg.BindInfoConf.compare(&cmpConf.BindInfoConf) ||
|
||||
!cfg.LocalSvrConf.compare(&cmpConf.LocalSvrConf) {
|
||||
!cfg.BindInfoConf.compare(&cmpConf.BindInfoConf) {
|
||||
return false
|
||||
}
|
||||
return true
|
||||
@@ -407,9 +527,6 @@ func (cfg *UdpProxyConf) UnmarshalFromIni(prefix string, name string, section in
|
||||
if err = cfg.BindInfoConf.UnmarshalFromIni(prefix, name, section); err != nil {
|
||||
return
|
||||
}
|
||||
if err = cfg.LocalSvrConf.UnmarshalFromIni(prefix, name, section); err != nil {
|
||||
return
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
@@ -418,7 +535,12 @@ func (cfg *UdpProxyConf) MarshalToMsg(pMsg *msg.NewProxy) {
|
||||
cfg.BindInfoConf.MarshalToMsg(pMsg)
|
||||
}
|
||||
|
||||
func (cfg *UdpProxyConf) CheckForCli() error { return nil }
|
||||
func (cfg *UdpProxyConf) CheckForCli() (err error) {
|
||||
if err = cfg.BaseProxyConf.checkForCli(); err != nil {
|
||||
return
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
func (cfg *UdpProxyConf) CheckForSvr() error { return nil }
|
||||
|
||||
@@ -427,12 +549,11 @@ type HttpProxyConf struct {
|
||||
BaseProxyConf
|
||||
DomainConf
|
||||
|
||||
LocalSvrConf
|
||||
|
||||
Locations []string `json:"locations"`
|
||||
HostHeaderRewrite string `json:"host_header_rewrite"`
|
||||
HttpUser string `json:"http_user"`
|
||||
HttpPwd string `json:"http_pwd"`
|
||||
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"`
|
||||
}
|
||||
|
||||
func (cfg *HttpProxyConf) Compare(cmp ProxyConf) bool {
|
||||
@@ -443,13 +564,23 @@ func (cfg *HttpProxyConf) Compare(cmp ProxyConf) bool {
|
||||
|
||||
if !cfg.BaseProxyConf.compare(&cmpConf.BaseProxyConf) ||
|
||||
!cfg.DomainConf.compare(&cmpConf.DomainConf) ||
|
||||
!cfg.LocalSvrConf.compare(&cmpConf.LocalSvrConf) ||
|
||||
strings.Join(cfg.Locations, " ") != strings.Join(cmpConf.Locations, " ") ||
|
||||
cfg.HostHeaderRewrite != cmpConf.HostHeaderRewrite ||
|
||||
cfg.HttpUser != cmpConf.HttpUser ||
|
||||
cfg.HttpPwd != cmpConf.HttpPwd {
|
||||
cfg.HttpPwd != cmpConf.HttpPwd ||
|
||||
len(cfg.Headers) != len(cmpConf.Headers) {
|
||||
return false
|
||||
}
|
||||
|
||||
for k, v := range cfg.Headers {
|
||||
if v2, ok := cmpConf.Headers[k]; !ok {
|
||||
return false
|
||||
} else {
|
||||
if v != v2 {
|
||||
return false
|
||||
}
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
@@ -461,6 +592,7 @@ func (cfg *HttpProxyConf) UnmarshalFromMsg(pMsg *msg.NewProxy) {
|
||||
cfg.HostHeaderRewrite = pMsg.HostHeaderRewrite
|
||||
cfg.HttpUser = pMsg.HttpUser
|
||||
cfg.HttpPwd = pMsg.HttpPwd
|
||||
cfg.Headers = pMsg.Headers
|
||||
}
|
||||
|
||||
func (cfg *HttpProxyConf) UnmarshalFromIni(prefix string, name string, section ini.Section) (err error) {
|
||||
@@ -470,9 +602,6 @@ func (cfg *HttpProxyConf) UnmarshalFromIni(prefix string, name string, section i
|
||||
if err = cfg.DomainConf.UnmarshalFromIni(prefix, name, section); err != nil {
|
||||
return
|
||||
}
|
||||
if err = cfg.LocalSvrConf.UnmarshalFromIni(prefix, name, section); err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
var (
|
||||
tmpStr string
|
||||
@@ -487,6 +616,13 @@ func (cfg *HttpProxyConf) UnmarshalFromIni(prefix string, name string, section i
|
||||
cfg.HostHeaderRewrite = section["host_header_rewrite"]
|
||||
cfg.HttpUser = section["http_user"]
|
||||
cfg.HttpPwd = section["http_pwd"]
|
||||
cfg.Headers = make(map[string]string)
|
||||
|
||||
for k, v := range section {
|
||||
if strings.HasPrefix(k, "header_") {
|
||||
cfg.Headers[strings.TrimPrefix(k, "header_")] = v
|
||||
}
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
@@ -498,9 +634,13 @@ func (cfg *HttpProxyConf) MarshalToMsg(pMsg *msg.NewProxy) {
|
||||
pMsg.HostHeaderRewrite = cfg.HostHeaderRewrite
|
||||
pMsg.HttpUser = cfg.HttpUser
|
||||
pMsg.HttpPwd = cfg.HttpPwd
|
||||
pMsg.Headers = cfg.Headers
|
||||
}
|
||||
|
||||
func (cfg *HttpProxyConf) CheckForCli() (err error) {
|
||||
if err = cfg.BaseProxyConf.checkForCli(); err != nil {
|
||||
return
|
||||
}
|
||||
if err = cfg.DomainConf.checkForCli(); err != nil {
|
||||
return
|
||||
}
|
||||
@@ -522,8 +662,6 @@ func (cfg *HttpProxyConf) CheckForSvr() (err error) {
|
||||
type HttpsProxyConf struct {
|
||||
BaseProxyConf
|
||||
DomainConf
|
||||
|
||||
LocalSvrConf
|
||||
}
|
||||
|
||||
func (cfg *HttpsProxyConf) Compare(cmp ProxyConf) bool {
|
||||
@@ -533,8 +671,7 @@ func (cfg *HttpsProxyConf) Compare(cmp ProxyConf) bool {
|
||||
}
|
||||
|
||||
if !cfg.BaseProxyConf.compare(&cmpConf.BaseProxyConf) ||
|
||||
!cfg.DomainConf.compare(&cmpConf.DomainConf) ||
|
||||
!cfg.LocalSvrConf.compare(&cmpConf.LocalSvrConf) {
|
||||
!cfg.DomainConf.compare(&cmpConf.DomainConf) {
|
||||
return false
|
||||
}
|
||||
return true
|
||||
@@ -552,9 +689,6 @@ func (cfg *HttpsProxyConf) UnmarshalFromIni(prefix string, name string, section
|
||||
if err = cfg.DomainConf.UnmarshalFromIni(prefix, name, section); err != nil {
|
||||
return
|
||||
}
|
||||
if err = cfg.LocalSvrConf.UnmarshalFromIni(prefix, name, section); err != nil {
|
||||
return
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
@@ -564,6 +698,9 @@ func (cfg *HttpsProxyConf) MarshalToMsg(pMsg *msg.NewProxy) {
|
||||
}
|
||||
|
||||
func (cfg *HttpsProxyConf) CheckForCli() (err error) {
|
||||
if err = cfg.BaseProxyConf.checkForCli(); err != nil {
|
||||
return
|
||||
}
|
||||
if err = cfg.DomainConf.checkForCli(); err != nil {
|
||||
return
|
||||
}
|
||||
@@ -587,14 +724,6 @@ type StcpProxyConf struct {
|
||||
|
||||
Role string `json:"role"`
|
||||
Sk string `json:"sk"`
|
||||
|
||||
// used in role server
|
||||
LocalSvrConf
|
||||
|
||||
// used in role visitor
|
||||
ServerName string `json:"server_name"`
|
||||
BindAddr string `json:"bind_addr"`
|
||||
BindPort int `json:"bind_port"`
|
||||
}
|
||||
|
||||
func (cfg *StcpProxyConf) Compare(cmp ProxyConf) bool {
|
||||
@@ -604,12 +733,8 @@ func (cfg *StcpProxyConf) Compare(cmp ProxyConf) bool {
|
||||
}
|
||||
|
||||
if !cfg.BaseProxyConf.compare(&cmpConf.BaseProxyConf) ||
|
||||
!cfg.LocalSvrConf.compare(&cmpConf.LocalSvrConf) ||
|
||||
cfg.Role != cmpConf.Role ||
|
||||
cfg.Sk != cmpConf.Sk ||
|
||||
cfg.ServerName != cmpConf.ServerName ||
|
||||
cfg.BindAddr != cmpConf.BindAddr ||
|
||||
cfg.BindPort != cmpConf.BindPort {
|
||||
cfg.Sk != cmpConf.Sk {
|
||||
return false
|
||||
}
|
||||
return true
|
||||
@@ -626,36 +751,15 @@ func (cfg *StcpProxyConf) UnmarshalFromIni(prefix string, name string, section i
|
||||
return
|
||||
}
|
||||
|
||||
tmpStr := section["role"]
|
||||
if tmpStr == "" {
|
||||
tmpStr = "server"
|
||||
}
|
||||
if tmpStr == "server" || tmpStr == "visitor" {
|
||||
cfg.Role = tmpStr
|
||||
} else {
|
||||
return fmt.Errorf("Parse conf error: proxy [%s] incorrect role [%s]", name, tmpStr)
|
||||
cfg.Role = section["role"]
|
||||
if cfg.Role != "server" {
|
||||
return fmt.Errorf("Parse conf error: proxy [%s] incorrect role [%s]", name, cfg.Role)
|
||||
}
|
||||
|
||||
cfg.Sk = section["sk"]
|
||||
|
||||
if tmpStr == "visitor" {
|
||||
prefix := section["prefix"]
|
||||
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 error", name)
|
||||
}
|
||||
} else {
|
||||
return fmt.Errorf("Parse conf error: proxy [%s] bind_port not found", name)
|
||||
}
|
||||
} else {
|
||||
if err = cfg.LocalSvrConf.UnmarshalFromIni(prefix, name, section); err != nil {
|
||||
return
|
||||
}
|
||||
if err = cfg.LocalSvrConf.UnmarshalFromIni(prefix, name, section); err != nil {
|
||||
return
|
||||
}
|
||||
return
|
||||
}
|
||||
@@ -666,19 +770,12 @@ func (cfg *StcpProxyConf) MarshalToMsg(pMsg *msg.NewProxy) {
|
||||
}
|
||||
|
||||
func (cfg *StcpProxyConf) CheckForCli() (err error) {
|
||||
if cfg.Role != "server" && cfg.Role != "visitor" {
|
||||
err = fmt.Errorf("role should be 'server' or 'visitor'")
|
||||
if err = cfg.BaseProxyConf.checkForCli(); err != nil {
|
||||
return
|
||||
}
|
||||
if cfg.Role == "visitor" {
|
||||
if cfg.BindAddr == "" {
|
||||
err = fmt.Errorf("bind_addr shouldn't be empty")
|
||||
return
|
||||
}
|
||||
if cfg.BindPort == 0 {
|
||||
err = fmt.Errorf("bind_port should be set")
|
||||
return
|
||||
}
|
||||
if cfg.Role != "server" {
|
||||
err = fmt.Errorf("role should be 'server'")
|
||||
return
|
||||
}
|
||||
return
|
||||
}
|
||||
@@ -693,14 +790,6 @@ type XtcpProxyConf struct {
|
||||
|
||||
Role string `json:"role"`
|
||||
Sk string `json:"sk"`
|
||||
|
||||
// used in role server
|
||||
LocalSvrConf
|
||||
|
||||
// used in role visitor
|
||||
ServerName string `json:"server_name"`
|
||||
BindAddr string `json:"bind_addr"`
|
||||
BindPort int `json:"bind_port"`
|
||||
}
|
||||
|
||||
func (cfg *XtcpProxyConf) Compare(cmp ProxyConf) bool {
|
||||
@@ -712,10 +801,7 @@ func (cfg *XtcpProxyConf) Compare(cmp ProxyConf) bool {
|
||||
if !cfg.BaseProxyConf.compare(&cmpConf.BaseProxyConf) ||
|
||||
!cfg.LocalSvrConf.compare(&cmpConf.LocalSvrConf) ||
|
||||
cfg.Role != cmpConf.Role ||
|
||||
cfg.Sk != cmpConf.Sk ||
|
||||
cfg.ServerName != cmpConf.ServerName ||
|
||||
cfg.BindAddr != cmpConf.BindAddr ||
|
||||
cfg.BindPort != cmpConf.BindPort {
|
||||
cfg.Sk != cmpConf.Sk {
|
||||
return false
|
||||
}
|
||||
return true
|
||||
@@ -732,36 +818,15 @@ func (cfg *XtcpProxyConf) UnmarshalFromIni(prefix string, name string, section i
|
||||
return
|
||||
}
|
||||
|
||||
tmpStr := section["role"]
|
||||
if tmpStr == "" {
|
||||
tmpStr = "server"
|
||||
}
|
||||
if tmpStr == "server" || tmpStr == "visitor" {
|
||||
cfg.Role = tmpStr
|
||||
} else {
|
||||
return fmt.Errorf("Parse conf error: proxy [%s] incorrect role [%s]", name, tmpStr)
|
||||
cfg.Role = section["role"]
|
||||
if cfg.Role != "server" {
|
||||
return fmt.Errorf("Parse conf error: proxy [%s] incorrect role [%s]", name, cfg.Role)
|
||||
}
|
||||
|
||||
cfg.Sk = section["sk"]
|
||||
|
||||
if tmpStr == "visitor" {
|
||||
prefix := section["prefix"]
|
||||
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 error", name)
|
||||
}
|
||||
} else {
|
||||
return fmt.Errorf("Parse conf error: proxy [%s] bind_port not found", name)
|
||||
}
|
||||
} else {
|
||||
if err = cfg.LocalSvrConf.UnmarshalFromIni(prefix, name, section); err != nil {
|
||||
return
|
||||
}
|
||||
if err = cfg.LocalSvrConf.UnmarshalFromIni(prefix, name, section); err != nil {
|
||||
return
|
||||
}
|
||||
return
|
||||
}
|
||||
@@ -772,19 +837,12 @@ func (cfg *XtcpProxyConf) MarshalToMsg(pMsg *msg.NewProxy) {
|
||||
}
|
||||
|
||||
func (cfg *XtcpProxyConf) CheckForCli() (err error) {
|
||||
if cfg.Role != "server" && cfg.Role != "visitor" {
|
||||
err = fmt.Errorf("role should be 'server' or 'visitor'")
|
||||
if err = cfg.BaseProxyConf.checkForCli(); err != nil {
|
||||
return
|
||||
}
|
||||
if cfg.Role == "visitor" {
|
||||
if cfg.BindAddr == "" {
|
||||
err = fmt.Errorf("bind_addr shouldn't be empty")
|
||||
return
|
||||
}
|
||||
if cfg.BindPort == 0 {
|
||||
err = fmt.Errorf("bind_port should be set")
|
||||
return
|
||||
}
|
||||
if cfg.Role != "server" {
|
||||
err = fmt.Errorf("role should be 'server'")
|
||||
return
|
||||
}
|
||||
return
|
||||
}
|
||||
@@ -827,8 +885,14 @@ func ParseRangeSection(name string, section ini.Section) (sections map[string]in
|
||||
|
||||
// if len(startProxy) is 0, start all
|
||||
// otherwise just start proxies in startProxy map
|
||||
func LoadProxyConfFromIni(prefix string, conf ini.File, startProxy map[string]struct{}) (
|
||||
proxyConfs map[string]ProxyConf, visitorConfs map[string]ProxyConf, err error) {
|
||||
func LoadAllConfFromIni(prefix string, content string, startProxy map[string]struct{}) (
|
||||
proxyConfs map[string]ProxyConf, visitorConfs map[string]VisitorConf, err error) {
|
||||
|
||||
conf, errRet := ini.Load(strings.NewReader(content))
|
||||
if errRet != nil {
|
||||
err = errRet
|
||||
return
|
||||
}
|
||||
|
||||
if prefix != "" {
|
||||
prefix += "."
|
||||
@@ -839,7 +903,7 @@ func LoadProxyConfFromIni(prefix string, conf ini.File, startProxy map[string]st
|
||||
startAll = false
|
||||
}
|
||||
proxyConfs = make(map[string]ProxyConf)
|
||||
visitorConfs = make(map[string]ProxyConf)
|
||||
visitorConfs = make(map[string]VisitorConf)
|
||||
for name, section := range conf {
|
||||
if name == "common" {
|
||||
continue
|
||||
@@ -864,16 +928,27 @@ func LoadProxyConfFromIni(prefix string, conf ini.File, startProxy map[string]st
|
||||
}
|
||||
|
||||
for subName, subSection := range subSections {
|
||||
cfg, err := NewProxyConfFromIni(prefix, subName, subSection)
|
||||
if err != nil {
|
||||
return proxyConfs, visitorConfs, err
|
||||
if subSection["role"] == "" {
|
||||
subSection["role"] = "server"
|
||||
}
|
||||
|
||||
role := subSection["role"]
|
||||
if role == "visitor" {
|
||||
if role == "server" {
|
||||
cfg, errRet := NewProxyConfFromIni(prefix, subName, subSection)
|
||||
if errRet != nil {
|
||||
err = errRet
|
||||
return
|
||||
}
|
||||
proxyConfs[prefix+subName] = cfg
|
||||
} else if role == "visitor" {
|
||||
cfg, errRet := NewVisitorConfFromIni(prefix, subName, subSection)
|
||||
if errRet != nil {
|
||||
err = errRet
|
||||
return
|
||||
}
|
||||
visitorConfs[prefix+subName] = cfg
|
||||
} else {
|
||||
proxyConfs[prefix+subName] = cfg
|
||||
err = fmt.Errorf("role should be 'server' or 'visitor'")
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@@ -51,8 +51,11 @@ type ServerCommonConf struct {
|
||||
VhostHttpPort int `json:"vhost_http_port"`
|
||||
|
||||
// if VhostHttpsPort equals 0, don't listen a public port for https protocol
|
||||
VhostHttpsPort int `json:"vhost_http_port"`
|
||||
DashboardAddr string `json:"dashboard_addr"`
|
||||
VhostHttpsPort int `json:"vhost_http_port"`
|
||||
|
||||
VhostHttpTimeout int64 `json:"vhost_http_timeout"`
|
||||
|
||||
DashboardAddr string `json:"dashboard_addr"`
|
||||
|
||||
// if DashboardPort equals 0, dashboard is not available
|
||||
DashboardPort int `json:"dashboard_port"`
|
||||
@@ -64,7 +67,6 @@ type ServerCommonConf struct {
|
||||
LogLevel string `json:"log_level"`
|
||||
LogMaxDays int64 `json:"log_max_days"`
|
||||
Token string `json:"token"`
|
||||
AuthTimeout int64 `json:"auth_timeout"`
|
||||
SubDomainHost string `json:"subdomain_host"`
|
||||
TcpMux bool `json:"tcp_mux"`
|
||||
|
||||
@@ -84,6 +86,7 @@ func GetDefaultServerConf() *ServerCommonConf {
|
||||
ProxyBindAddr: "0.0.0.0",
|
||||
VhostHttpPort: 0,
|
||||
VhostHttpsPort: 0,
|
||||
VhostHttpTimeout: 60,
|
||||
DashboardAddr: "0.0.0.0",
|
||||
DashboardPort: 0,
|
||||
DashboardUser: "admin",
|
||||
@@ -94,7 +97,6 @@ func GetDefaultServerConf() *ServerCommonConf {
|
||||
LogLevel: "info",
|
||||
LogMaxDays: 3,
|
||||
Token: "",
|
||||
AuthTimeout: 900,
|
||||
SubDomainHost: "",
|
||||
TcpMux: true,
|
||||
AllowPorts: make(map[int]struct{}),
|
||||
@@ -181,6 +183,16 @@ func UnmarshalServerConfFromIni(defaultCfg *ServerCommonConf, content string) (c
|
||||
cfg.VhostHttpsPort = 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 {
|
||||
@@ -271,16 +283,6 @@ func UnmarshalServerConfFromIni(defaultCfg *ServerCommonConf, content string) (c
|
||||
}
|
||||
}
|
||||
|
||||
if tmpStr, ok = conf.Get("common", "authentication_timeout"); ok {
|
||||
v, errRet := strconv.ParseInt(tmpStr, 10, 64)
|
||||
if errRet != nil {
|
||||
err = fmt.Errorf("Parse conf error: authentication_timeout is incorrect")
|
||||
return
|
||||
} else {
|
||||
cfg.AuthTimeout = v
|
||||
}
|
||||
}
|
||||
|
||||
if tmpStr, ok = conf.Get("common", "subdomain_host"); ok {
|
||||
cfg.SubDomainHost = strings.ToLower(strings.TrimSpace(tmpStr))
|
||||
}
|
||||
|
64
models/config/value.go
Normal file
64
models/config/value.go
Normal file
@@ -0,0 +1,64 @@
|
||||
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
|
||||
}
|
213
models/config/visitor.go
Normal file
213
models/config/visitor.go
Normal file
@@ -0,0 +1,213 @@
|
||||
// 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
|
||||
}
|
@@ -86,17 +86,20 @@ type NewProxy struct {
|
||||
ProxyType string `json:"proxy_type"`
|
||||
UseEncryption bool `json:"use_encryption"`
|
||||
UseCompression bool `json:"use_compression"`
|
||||
Group string `json:"group"`
|
||||
GroupKey string `json:"group_key"`
|
||||
|
||||
// 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"`
|
||||
HostHeaderRewrite string `json:"host_header_rewrite"`
|
||||
HttpUser string `json:"http_user"`
|
||||
HttpPwd string `json:"http_pwd"`
|
||||
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"`
|
||||
|
@@ -1,4 +1,4 @@
|
||||
package server
|
||||
package nathole
|
||||
|
||||
import (
|
||||
"bytes"
|
@@ -18,9 +18,9 @@ import (
|
||||
"io"
|
||||
"net/http"
|
||||
|
||||
"github.com/julienschmidt/httprouter"
|
||||
|
||||
frpNet "github.com/fatedier/frp/utils/net"
|
||||
|
||||
"github.com/gorilla/mux"
|
||||
)
|
||||
|
||||
const PluginStaticFile = "static_file"
|
||||
@@ -61,9 +61,10 @@ func NewStaticFilePlugin(params map[string]string) (Plugin, error) {
|
||||
} else {
|
||||
prefix = "/"
|
||||
}
|
||||
router := httprouter.New()
|
||||
router.Handler("GET", prefix+"*filepath", frpNet.MakeHttpGzipHandler(
|
||||
frpNet.NewHttpBasicAuthWraper(http.StripPrefix(prefix, http.FileServer(http.Dir(localPath))), httpUser, httpPasswd)))
|
||||
|
||||
router := mux.NewRouter()
|
||||
router.Use(frpNet.NewHttpAuthMiddleware(httpUser, httpPasswd).Middleware)
|
||||
router.PathPrefix(prefix).Handler(frpNet.MakeHttpGzipHandler(http.StripPrefix(prefix, http.FileServer(http.Dir(localPath))))).Methods("GET")
|
||||
sp.s = &http.Server{
|
||||
Handler: router,
|
||||
}
|
||||
|
@@ -15,7 +15,7 @@ rm -rf ./packages
|
||||
mkdir ./packages
|
||||
|
||||
os_all='linux windows darwin freebsd'
|
||||
arch_all='386 amd64 arm mips64 mips64le mips mipsle'
|
||||
arch_all='386 amd64 arm arm64 mips64 mips64le mips mipsle'
|
||||
|
||||
for os in $os_all; do
|
||||
for arch in $arch_all; do
|
||||
|
@@ -26,6 +26,9 @@ import (
|
||||
"github.com/fatedier/frp/models/consts"
|
||||
frpErr "github.com/fatedier/frp/models/errors"
|
||||
"github.com/fatedier/frp/models/msg"
|
||||
"github.com/fatedier/frp/server/controller"
|
||||
"github.com/fatedier/frp/server/proxy"
|
||||
"github.com/fatedier/frp/server/stats"
|
||||
"github.com/fatedier/frp/utils/net"
|
||||
"github.com/fatedier/frp/utils/version"
|
||||
|
||||
@@ -34,9 +37,53 @@ import (
|
||||
"github.com/fatedier/golib/errors"
|
||||
)
|
||||
|
||||
type ControlManager struct {
|
||||
// controls indexed by run id
|
||||
ctlsByRunId map[string]*Control
|
||||
|
||||
mu sync.RWMutex
|
||||
}
|
||||
|
||||
func NewControlManager() *ControlManager {
|
||||
return &ControlManager{
|
||||
ctlsByRunId: make(map[string]*Control),
|
||||
}
|
||||
}
|
||||
|
||||
func (cm *ControlManager) Add(runId string, ctl *Control) (oldCtl *Control) {
|
||||
cm.mu.Lock()
|
||||
defer cm.mu.Unlock()
|
||||
|
||||
oldCtl, ok := cm.ctlsByRunId[runId]
|
||||
if ok {
|
||||
oldCtl.Replaced(ctl)
|
||||
}
|
||||
cm.ctlsByRunId[runId] = ctl
|
||||
return
|
||||
}
|
||||
|
||||
func (cm *ControlManager) Del(runId string) {
|
||||
cm.mu.Lock()
|
||||
defer cm.mu.Unlock()
|
||||
delete(cm.ctlsByRunId, runId)
|
||||
}
|
||||
|
||||
func (cm *ControlManager) GetById(runId string) (ctl *Control, ok bool) {
|
||||
cm.mu.RLock()
|
||||
defer cm.mu.RUnlock()
|
||||
ctl, ok = cm.ctlsByRunId[runId]
|
||||
return
|
||||
}
|
||||
|
||||
type Control struct {
|
||||
// frps service
|
||||
svr *Service
|
||||
// all resource managers and controllers
|
||||
rc *controller.ResourceController
|
||||
|
||||
// proxy manager
|
||||
pxyManager *proxy.ProxyManager
|
||||
|
||||
// stats collector to store stats info of clients and proxies
|
||||
statsCollector stats.Collector
|
||||
|
||||
// login message
|
||||
loginMsg *msg.Login
|
||||
@@ -54,7 +101,7 @@ type Control struct {
|
||||
workConnCh chan net.Conn
|
||||
|
||||
// proxies in one client
|
||||
proxies map[string]Proxy
|
||||
proxies map[string]proxy.Proxy
|
||||
|
||||
// pool count
|
||||
poolCount int
|
||||
@@ -81,15 +128,19 @@ type Control struct {
|
||||
mu sync.RWMutex
|
||||
}
|
||||
|
||||
func NewControl(svr *Service, ctlConn net.Conn, loginMsg *msg.Login) *Control {
|
||||
func NewControl(rc *controller.ResourceController, pxyManager *proxy.ProxyManager,
|
||||
statsCollector stats.Collector, ctlConn net.Conn, loginMsg *msg.Login) *Control {
|
||||
|
||||
return &Control{
|
||||
svr: svr,
|
||||
rc: rc,
|
||||
pxyManager: pxyManager,
|
||||
statsCollector: statsCollector,
|
||||
conn: ctlConn,
|
||||
loginMsg: loginMsg,
|
||||
sendCh: make(chan msg.Message, 10),
|
||||
readCh: make(chan msg.Message, 10),
|
||||
workConnCh: make(chan net.Conn, loginMsg.PoolCount+10),
|
||||
proxies: make(map[string]Proxy),
|
||||
proxies: make(map[string]proxy.Proxy),
|
||||
poolCount: loginMsg.PoolCount,
|
||||
portsUsedNum: 0,
|
||||
lastPing: time.Now(),
|
||||
@@ -284,14 +335,22 @@ func (ctl *Control) stoper() {
|
||||
|
||||
for _, pxy := range ctl.proxies {
|
||||
pxy.Close()
|
||||
ctl.svr.DelProxy(pxy.GetName())
|
||||
StatsCloseProxy(pxy.GetName(), pxy.GetConf().GetBaseInfo().ProxyType)
|
||||
ctl.pxyManager.Del(pxy.GetName())
|
||||
ctl.statsCollector.Mark(stats.TypeCloseProxy, &stats.CloseProxyPayload{
|
||||
Name: pxy.GetName(),
|
||||
ProxyType: pxy.GetConf().GetBaseInfo().ProxyType,
|
||||
})
|
||||
}
|
||||
|
||||
ctl.allShutdown.Done()
|
||||
ctl.conn.Info("client exit success")
|
||||
|
||||
StatsCloseClient()
|
||||
ctl.statsCollector.Mark(stats.TypeCloseClient, &stats.CloseClientPayload{})
|
||||
}
|
||||
|
||||
// block until Control closed
|
||||
func (ctl *Control) WaitClosed() {
|
||||
ctl.allShutdown.WaitDone()
|
||||
}
|
||||
|
||||
func (ctl *Control) manager() {
|
||||
@@ -333,7 +392,10 @@ func (ctl *Control) manager() {
|
||||
} else {
|
||||
resp.RemoteAddr = remoteAddr
|
||||
ctl.conn.Info("new proxy [%s] success", m.ProxyName)
|
||||
StatsNewProxy(m.ProxyName, m.ProxyType)
|
||||
ctl.statsCollector.Mark(stats.TypeNewProxy, &stats.NewProxyPayload{
|
||||
Name: m.ProxyName,
|
||||
ProxyType: m.ProxyType,
|
||||
})
|
||||
}
|
||||
ctl.sendCh <- resp
|
||||
case *msg.CloseProxy:
|
||||
@@ -358,7 +420,7 @@ func (ctl *Control) RegisterProxy(pxyMsg *msg.NewProxy) (remoteAddr string, err
|
||||
|
||||
// NewProxy will return a interface Proxy.
|
||||
// In fact it create different proxies by different proxy type, we just call run() here.
|
||||
pxy, err := NewProxy(ctl, pxyConf)
|
||||
pxy, err := proxy.NewProxy(ctl.runId, ctl.rc, ctl.statsCollector, ctl.poolCount, ctl.GetWorkConn, pxyConf)
|
||||
if err != nil {
|
||||
return remoteAddr, err
|
||||
}
|
||||
@@ -393,7 +455,7 @@ func (ctl *Control) RegisterProxy(pxyMsg *msg.NewProxy) (remoteAddr string, err
|
||||
}
|
||||
}()
|
||||
|
||||
err = ctl.svr.RegisterProxy(pxyMsg.ProxyName, pxy)
|
||||
err = ctl.pxyManager.Add(pxyMsg.ProxyName, pxy)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
@@ -406,7 +468,6 @@ func (ctl *Control) RegisterProxy(pxyMsg *msg.NewProxy) (remoteAddr string, err
|
||||
|
||||
func (ctl *Control) CloseProxy(closeMsg *msg.CloseProxy) (err error) {
|
||||
ctl.mu.Lock()
|
||||
|
||||
pxy, ok := ctl.proxies[closeMsg.ProxyName]
|
||||
if !ok {
|
||||
ctl.mu.Unlock()
|
||||
@@ -417,10 +478,13 @@ func (ctl *Control) CloseProxy(closeMsg *msg.CloseProxy) (err error) {
|
||||
ctl.portsUsedNum = ctl.portsUsedNum - pxy.GetUsedPortsNum()
|
||||
}
|
||||
pxy.Close()
|
||||
ctl.svr.DelProxy(pxy.GetName())
|
||||
ctl.pxyManager.Del(pxy.GetName())
|
||||
delete(ctl.proxies, closeMsg.ProxyName)
|
||||
ctl.mu.Unlock()
|
||||
|
||||
StatsCloseProxy(pxy.GetName(), pxy.GetConf().GetBaseInfo().ProxyType)
|
||||
ctl.statsCollector.Mark(stats.TypeCloseProxy, &stats.CloseProxyPayload{
|
||||
Name: pxy.GetName(),
|
||||
ProxyType: pxy.GetConf().GetBaseInfo().ProxyType,
|
||||
})
|
||||
return
|
||||
}
|
||||
|
46
server/controller/resource.go
Normal file
46
server/controller/resource.go
Normal file
@@ -0,0 +1,46 @@
|
||||
// Copyright 2019 fatedier, fatedier@gmail.com
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
package controller
|
||||
|
||||
import (
|
||||
"github.com/fatedier/frp/models/nathole"
|
||||
"github.com/fatedier/frp/server/group"
|
||||
"github.com/fatedier/frp/server/ports"
|
||||
"github.com/fatedier/frp/utils/vhost"
|
||||
)
|
||||
|
||||
// All resource managers and controllers
|
||||
type ResourceController struct {
|
||||
// Manage all visitor listeners
|
||||
VisitorManager *VisitorManager
|
||||
|
||||
// Tcp Group Controller
|
||||
TcpGroupCtl *group.TcpGroupCtl
|
||||
|
||||
// Manage all tcp ports
|
||||
TcpPortManager *ports.PortManager
|
||||
|
||||
// Manage all udp ports
|
||||
UdpPortManager *ports.PortManager
|
||||
|
||||
// For http proxies, forwarding http requests
|
||||
HttpReverseProxy *vhost.HttpReverseProxy
|
||||
|
||||
// For https proxies, route requests to different clients by hostname and other infomation
|
||||
VhostHttpsMuxer *vhost.HttpsMuxer
|
||||
|
||||
// Controller for nat hole connections
|
||||
NatHoleController *nathole.NatHoleController
|
||||
}
|
@@ -1,4 +1,4 @@
|
||||
// Copyright 2017 fatedier, fatedier@gmail.com
|
||||
// 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.
|
||||
@@ -12,7 +12,7 @@
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
package server
|
||||
package controller
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
@@ -25,75 +25,6 @@ import (
|
||||
frpIo "github.com/fatedier/golib/io"
|
||||
)
|
||||
|
||||
type ControlManager struct {
|
||||
// controls indexed by run id
|
||||
ctlsByRunId map[string]*Control
|
||||
|
||||
mu sync.RWMutex
|
||||
}
|
||||
|
||||
func NewControlManager() *ControlManager {
|
||||
return &ControlManager{
|
||||
ctlsByRunId: make(map[string]*Control),
|
||||
}
|
||||
}
|
||||
|
||||
func (cm *ControlManager) Add(runId string, ctl *Control) (oldCtl *Control) {
|
||||
cm.mu.Lock()
|
||||
defer cm.mu.Unlock()
|
||||
|
||||
oldCtl, ok := cm.ctlsByRunId[runId]
|
||||
if ok {
|
||||
oldCtl.Replaced(ctl)
|
||||
}
|
||||
cm.ctlsByRunId[runId] = ctl
|
||||
return
|
||||
}
|
||||
|
||||
func (cm *ControlManager) GetById(runId string) (ctl *Control, ok bool) {
|
||||
cm.mu.RLock()
|
||||
defer cm.mu.RUnlock()
|
||||
ctl, ok = cm.ctlsByRunId[runId]
|
||||
return
|
||||
}
|
||||
|
||||
type ProxyManager struct {
|
||||
// proxies indexed by proxy name
|
||||
pxys map[string]Proxy
|
||||
|
||||
mu sync.RWMutex
|
||||
}
|
||||
|
||||
func NewProxyManager() *ProxyManager {
|
||||
return &ProxyManager{
|
||||
pxys: make(map[string]Proxy),
|
||||
}
|
||||
}
|
||||
|
||||
func (pm *ProxyManager) Add(name string, pxy Proxy) error {
|
||||
pm.mu.Lock()
|
||||
defer pm.mu.Unlock()
|
||||
if _, ok := pm.pxys[name]; ok {
|
||||
return fmt.Errorf("proxy name [%s] is already in use", name)
|
||||
}
|
||||
|
||||
pm.pxys[name] = pxy
|
||||
return nil
|
||||
}
|
||||
|
||||
func (pm *ProxyManager) Del(name string) {
|
||||
pm.mu.Lock()
|
||||
defer pm.mu.Unlock()
|
||||
delete(pm.pxys, name)
|
||||
}
|
||||
|
||||
func (pm *ProxyManager) GetByName(name string) (pxy Proxy, ok bool) {
|
||||
pm.mu.RLock()
|
||||
defer pm.mu.RUnlock()
|
||||
pxy, ok = pm.pxys[name]
|
||||
return
|
||||
}
|
||||
|
||||
// Manager for visitor listeners.
|
||||
type VisitorManager struct {
|
||||
visitorListeners map[string]*frpNet.CustomListener
|
@@ -24,7 +24,7 @@ import (
|
||||
"github.com/fatedier/frp/g"
|
||||
frpNet "github.com/fatedier/frp/utils/net"
|
||||
|
||||
"github.com/julienschmidt/httprouter"
|
||||
"github.com/gorilla/mux"
|
||||
)
|
||||
|
||||
var (
|
||||
@@ -32,32 +32,26 @@ var (
|
||||
httpServerWriteTimeout = 10 * time.Second
|
||||
)
|
||||
|
||||
func RunDashboardServer(addr string, port int) (err error) {
|
||||
func (svr *Service) RunDashboardServer(addr string, port int) (err error) {
|
||||
// url router
|
||||
router := httprouter.New()
|
||||
router := mux.NewRouter()
|
||||
|
||||
user, passwd := g.GlbServerCfg.DashboardUser, g.GlbServerCfg.DashboardPwd
|
||||
router.Use(frpNet.NewHttpAuthMiddleware(user, passwd).Middleware)
|
||||
|
||||
// api, see dashboard_api.go
|
||||
router.GET("/api/serverinfo", frpNet.HttprouterBasicAuth(apiServerInfo, user, passwd))
|
||||
router.GET("/api/proxy/tcp/:name", frpNet.HttprouterBasicAuth(apiProxyTcpByName, user, passwd))
|
||||
router.GET("/api/proxy/udp/:name", frpNet.HttprouterBasicAuth(apiProxyUdpByName, user, passwd))
|
||||
router.GET("/api/proxy/http/:name", frpNet.HttprouterBasicAuth(apiProxyHttpByName, user, passwd))
|
||||
router.GET("/api/proxy/https/:name", frpNet.HttprouterBasicAuth(apiProxyHttpsByName, user, passwd))
|
||||
router.GET("/api/proxy/tcp", frpNet.HttprouterBasicAuth(apiProxyTcp, user, passwd))
|
||||
router.GET("/api/proxy/udp", frpNet.HttprouterBasicAuth(apiProxyUdp, user, passwd))
|
||||
router.GET("/api/proxy/http", frpNet.HttprouterBasicAuth(apiProxyHttp, user, passwd))
|
||||
router.GET("/api/proxy/https", frpNet.HttprouterBasicAuth(apiProxyHttps, user, passwd))
|
||||
router.GET("/api/proxy/traffic/:name", frpNet.HttprouterBasicAuth(apiProxyTraffic, user, passwd))
|
||||
router.HandleFunc("/api/serverinfo", svr.ApiServerInfo).Methods("GET")
|
||||
router.HandleFunc("/api/proxy/{type}", svr.ApiProxyByType).Methods("GET")
|
||||
router.HandleFunc("/api/proxy/{type}/{name}", svr.ApiProxyByTypeAndName).Methods("GET")
|
||||
router.HandleFunc("/api/traffic/{name}", svr.ApiProxyTraffic).Methods("GET")
|
||||
|
||||
// view
|
||||
router.Handler("GET", "/favicon.ico", http.FileServer(assets.FileSystem))
|
||||
router.Handler("GET", "/static/*filepath", frpNet.MakeHttpGzipHandler(
|
||||
frpNet.NewHttpBasicAuthWraper(http.StripPrefix("/static/", http.FileServer(assets.FileSystem)), user, passwd)))
|
||||
router.Handle("/favicon.ico", http.FileServer(assets.FileSystem)).Methods("GET")
|
||||
router.PathPrefix("/static/").Handler(frpNet.MakeHttpGzipHandler(http.StripPrefix("/static/", http.FileServer(assets.FileSystem)))).Methods("GET")
|
||||
|
||||
router.HandlerFunc("GET", "/", frpNet.HttpBasicAuth(func(w http.ResponseWriter, r *http.Request) {
|
||||
router.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
|
||||
http.Redirect(w, r, "/static/", http.StatusMovedPermanently)
|
||||
}, user, passwd))
|
||||
})
|
||||
|
||||
address := fmt.Sprintf("%s:%d", addr, port)
|
||||
server := &http.Server{
|
||||
|
@@ -24,7 +24,7 @@ import (
|
||||
"github.com/fatedier/frp/utils/log"
|
||||
"github.com/fatedier/frp/utils/version"
|
||||
|
||||
"github.com/julienschmidt/httprouter"
|
||||
"github.com/gorilla/mux"
|
||||
)
|
||||
|
||||
type GeneralResponse struct {
|
||||
@@ -32,7 +32,6 @@ type GeneralResponse struct {
|
||||
Msg string `json:"msg"`
|
||||
}
|
||||
|
||||
// api/serverinfo
|
||||
type ServerInfoResp struct {
|
||||
GeneralResponse
|
||||
|
||||
@@ -42,7 +41,6 @@ type ServerInfoResp struct {
|
||||
VhostHttpPort int `json:"vhost_http_port"`
|
||||
VhostHttpsPort int `json:"vhost_https_port"`
|
||||
KcpBindPort int `json:"kcp_bind_port"`
|
||||
AuthTimeout int64 `json:"auth_timeout"`
|
||||
SubdomainHost string `json:"subdomain_host"`
|
||||
MaxPoolCount int64 `json:"max_pool_count"`
|
||||
MaxPortsPerClient int64 `json:"max_ports_per_client"`
|
||||
@@ -55,18 +53,19 @@ type ServerInfoResp struct {
|
||||
ProxyTypeCounts map[string]int64 `json:"proxy_type_count"`
|
||||
}
|
||||
|
||||
func apiServerInfo(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {
|
||||
// api/serverinfo
|
||||
func (svr *Service) ApiServerInfo(w http.ResponseWriter, r *http.Request) {
|
||||
var (
|
||||
buf []byte
|
||||
res ServerInfoResp
|
||||
)
|
||||
defer func() {
|
||||
log.Info("Http response [/api/serverinfo]: code [%d]", res.Code)
|
||||
log.Info("Http response [%s]: code [%d]", r.URL.Path, res.Code)
|
||||
}()
|
||||
|
||||
log.Info("Http request: [/api/serverinfo]")
|
||||
log.Info("Http request: [%s]", r.URL.Path)
|
||||
cfg := &g.GlbServerCfg.ServerCommonConf
|
||||
serverStats := StatsGetServer()
|
||||
serverStats := svr.statsCollector.GetServer()
|
||||
res = ServerInfoResp{
|
||||
Version: version.Full(),
|
||||
BindPort: cfg.BindPort,
|
||||
@@ -74,7 +73,6 @@ func apiServerInfo(w http.ResponseWriter, r *http.Request, _ httprouter.Params)
|
||||
VhostHttpPort: cfg.VhostHttpPort,
|
||||
VhostHttpsPort: cfg.VhostHttpsPort,
|
||||
KcpBindPort: cfg.KcpBindPort,
|
||||
AuthTimeout: cfg.AuthTimeout,
|
||||
SubdomainHost: cfg.SubDomainHost,
|
||||
MaxPoolCount: cfg.MaxPoolCount,
|
||||
MaxPortsPerClient: cfg.MaxPortsPerClient,
|
||||
@@ -91,16 +89,69 @@ func apiServerInfo(w http.ResponseWriter, r *http.Request, _ httprouter.Params)
|
||||
w.Write(buf)
|
||||
}
|
||||
|
||||
type BaseOutConf struct {
|
||||
config.BaseProxyConf
|
||||
}
|
||||
|
||||
type TcpOutConf struct {
|
||||
BaseOutConf
|
||||
RemotePort int `json:"remote_port"`
|
||||
}
|
||||
|
||||
type UdpOutConf struct {
|
||||
BaseOutConf
|
||||
RemotePort int `json:"remote_port"`
|
||||
}
|
||||
|
||||
type HttpOutConf struct {
|
||||
BaseOutConf
|
||||
config.DomainConf
|
||||
Locations []string `json:"locations"`
|
||||
HostHeaderRewrite string `json:"host_header_rewrite"`
|
||||
}
|
||||
|
||||
type HttpsOutConf struct {
|
||||
BaseOutConf
|
||||
config.DomainConf
|
||||
}
|
||||
|
||||
type StcpOutConf struct {
|
||||
BaseOutConf
|
||||
}
|
||||
|
||||
type XtcpOutConf struct {
|
||||
BaseOutConf
|
||||
}
|
||||
|
||||
func getConfByType(proxyType string) interface{} {
|
||||
switch proxyType {
|
||||
case consts.TcpProxy:
|
||||
return &TcpOutConf{}
|
||||
case consts.UdpProxy:
|
||||
return &UdpOutConf{}
|
||||
case consts.HttpProxy:
|
||||
return &HttpOutConf{}
|
||||
case consts.HttpsProxy:
|
||||
return &HttpsOutConf{}
|
||||
case consts.StcpProxy:
|
||||
return &StcpOutConf{}
|
||||
case consts.XtcpProxy:
|
||||
return &XtcpOutConf{}
|
||||
default:
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
// Get proxy info.
|
||||
type ProxyStatsInfo struct {
|
||||
Name string `json:"name"`
|
||||
Conf config.ProxyConf `json:"conf"`
|
||||
TodayTrafficIn int64 `json:"today_traffic_in"`
|
||||
TodayTrafficOut int64 `json:"today_traffic_out"`
|
||||
CurConns int64 `json:"cur_conns"`
|
||||
LastStartTime string `json:"last_start_time"`
|
||||
LastCloseTime string `json:"last_close_time"`
|
||||
Status string `json:"status"`
|
||||
Name string `json:"name"`
|
||||
Conf interface{} `json:"conf"`
|
||||
TodayTrafficIn int64 `json:"today_traffic_in"`
|
||||
TodayTrafficOut int64 `json:"today_traffic_out"`
|
||||
CurConns int64 `json:"cur_conns"`
|
||||
LastStartTime string `json:"last_start_time"`
|
||||
LastCloseTime string `json:"last_close_time"`
|
||||
Status string `json:"status"`
|
||||
}
|
||||
|
||||
type GetProxyInfoResp struct {
|
||||
@@ -108,81 +159,45 @@ type GetProxyInfoResp struct {
|
||||
Proxies []*ProxyStatsInfo `json:"proxies"`
|
||||
}
|
||||
|
||||
// api/proxy/tcp
|
||||
func apiProxyTcp(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {
|
||||
// api/proxy/:type
|
||||
func (svr *Service) ApiProxyByType(w http.ResponseWriter, r *http.Request) {
|
||||
var (
|
||||
buf []byte
|
||||
res GetProxyInfoResp
|
||||
)
|
||||
defer func() {
|
||||
log.Info("Http response [/api/proxy/tcp]: code [%d]", res.Code)
|
||||
}()
|
||||
log.Info("Http request: [/api/proxy/tcp]")
|
||||
params := mux.Vars(r)
|
||||
proxyType := params["type"]
|
||||
|
||||
res.Proxies = getProxyStatsByType(consts.TcpProxy)
|
||||
defer func() {
|
||||
log.Info("Http response [%s]: code [%d]", r.URL.Path, res.Code)
|
||||
log.Info(r.URL.Path)
|
||||
log.Info(r.URL.RawPath)
|
||||
}()
|
||||
log.Info("Http request: [%s]", r.URL.Path)
|
||||
|
||||
res.Proxies = svr.getProxyStatsByType(proxyType)
|
||||
|
||||
buf, _ = json.Marshal(&res)
|
||||
w.Write(buf)
|
||||
|
||||
}
|
||||
|
||||
// api/proxy/udp
|
||||
func apiProxyUdp(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {
|
||||
var (
|
||||
buf []byte
|
||||
res GetProxyInfoResp
|
||||
)
|
||||
defer func() {
|
||||
log.Info("Http response [/api/proxy/udp]: code [%d]", res.Code)
|
||||
}()
|
||||
log.Info("Http request: [/api/proxy/udp]")
|
||||
|
||||
res.Proxies = getProxyStatsByType(consts.UdpProxy)
|
||||
|
||||
buf, _ = json.Marshal(&res)
|
||||
w.Write(buf)
|
||||
}
|
||||
|
||||
// api/proxy/http
|
||||
func apiProxyHttp(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {
|
||||
var (
|
||||
buf []byte
|
||||
res GetProxyInfoResp
|
||||
)
|
||||
defer func() {
|
||||
log.Info("Http response [/api/proxy/http]: code [%d]", res.Code)
|
||||
}()
|
||||
log.Info("Http request: [/api/proxy/http]")
|
||||
|
||||
res.Proxies = getProxyStatsByType(consts.HttpProxy)
|
||||
|
||||
buf, _ = json.Marshal(&res)
|
||||
w.Write(buf)
|
||||
}
|
||||
|
||||
// api/proxy/https
|
||||
func apiProxyHttps(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {
|
||||
var (
|
||||
buf []byte
|
||||
res GetProxyInfoResp
|
||||
)
|
||||
defer func() {
|
||||
log.Info("Http response [/api/proxy/https]: code [%d]", res.Code)
|
||||
}()
|
||||
log.Info("Http request: [/api/proxy/https]")
|
||||
|
||||
res.Proxies = getProxyStatsByType(consts.HttpsProxy)
|
||||
|
||||
buf, _ = json.Marshal(&res)
|
||||
w.Write(buf)
|
||||
}
|
||||
|
||||
func getProxyStatsByType(proxyType string) (proxyInfos []*ProxyStatsInfo) {
|
||||
proxyStats := StatsGetProxiesByType(proxyType)
|
||||
func (svr *Service) getProxyStatsByType(proxyType string) (proxyInfos []*ProxyStatsInfo) {
|
||||
proxyStats := svr.statsCollector.GetProxiesByType(proxyType)
|
||||
proxyInfos = make([]*ProxyStatsInfo, 0, len(proxyStats))
|
||||
for _, ps := range proxyStats {
|
||||
proxyInfo := &ProxyStatsInfo{}
|
||||
if pxy, ok := ServerService.pxyManager.GetByName(ps.Name); ok {
|
||||
proxyInfo.Conf = pxy.GetConf()
|
||||
if pxy, ok := svr.pxyManager.GetByName(ps.Name); ok {
|
||||
content, err := json.Marshal(pxy.GetConf())
|
||||
if err != nil {
|
||||
log.Warn("marshal proxy [%s] conf info error: %v", ps.Name, err)
|
||||
continue
|
||||
}
|
||||
proxyInfo.Conf = getConfByType(ps.Type)
|
||||
if err = json.Unmarshal(content, &proxyInfo.Conf); err != nil {
|
||||
log.Warn("unmarshal proxy [%s] conf info error: %v", ps.Name, err)
|
||||
continue
|
||||
}
|
||||
proxyInfo.Status = consts.Online
|
||||
} else {
|
||||
proxyInfo.Status = consts.Offline
|
||||
@@ -202,101 +217,59 @@ func getProxyStatsByType(proxyType string) (proxyInfos []*ProxyStatsInfo) {
|
||||
type GetProxyStatsResp struct {
|
||||
GeneralResponse
|
||||
|
||||
Name string `json:"name"`
|
||||
Conf config.ProxyConf `json:"conf"`
|
||||
TodayTrafficIn int64 `json:"today_traffic_in"`
|
||||
TodayTrafficOut int64 `json:"today_traffic_out"`
|
||||
CurConns int64 `json:"cur_conns"`
|
||||
LastStartTime string `json:"last_start_time"`
|
||||
LastCloseTime string `json:"last_close_time"`
|
||||
Status string `json:"status"`
|
||||
Name string `json:"name"`
|
||||
Conf interface{} `json:"conf"`
|
||||
TodayTrafficIn int64 `json:"today_traffic_in"`
|
||||
TodayTrafficOut int64 `json:"today_traffic_out"`
|
||||
CurConns int64 `json:"cur_conns"`
|
||||
LastStartTime string `json:"last_start_time"`
|
||||
LastCloseTime string `json:"last_close_time"`
|
||||
Status string `json:"status"`
|
||||
}
|
||||
|
||||
// api/proxy/tcp/:name
|
||||
func apiProxyTcpByName(w http.ResponseWriter, r *http.Request, params httprouter.Params) {
|
||||
// api/proxy/:type/:name
|
||||
func (svr *Service) ApiProxyByTypeAndName(w http.ResponseWriter, r *http.Request) {
|
||||
var (
|
||||
buf []byte
|
||||
res GetProxyStatsResp
|
||||
)
|
||||
name := params.ByName("name")
|
||||
params := mux.Vars(r)
|
||||
proxyType := params["type"]
|
||||
name := params["name"]
|
||||
|
||||
defer func() {
|
||||
log.Info("Http response [/api/proxy/tcp/:name]: code [%d]", res.Code)
|
||||
log.Info("Http response [%s]: code [%d]", r.URL.Path, res.Code)
|
||||
}()
|
||||
log.Info("Http request: [/api/proxy/tcp/:name]")
|
||||
log.Info("Http request: [%s]", r.URL.Path)
|
||||
|
||||
res = getProxyStatsByTypeAndName(consts.TcpProxy, name)
|
||||
res = svr.getProxyStatsByTypeAndName(proxyType, name)
|
||||
|
||||
buf, _ = json.Marshal(&res)
|
||||
w.Write(buf)
|
||||
}
|
||||
|
||||
// api/proxy/udp/:name
|
||||
func apiProxyUdpByName(w http.ResponseWriter, r *http.Request, params httprouter.Params) {
|
||||
var (
|
||||
buf []byte
|
||||
res GetProxyStatsResp
|
||||
)
|
||||
name := params.ByName("name")
|
||||
|
||||
defer func() {
|
||||
log.Info("Http response [/api/proxy/udp/:name]: code [%d]", res.Code)
|
||||
}()
|
||||
log.Info("Http request: [/api/proxy/udp/:name]")
|
||||
|
||||
res = getProxyStatsByTypeAndName(consts.UdpProxy, name)
|
||||
|
||||
buf, _ = json.Marshal(&res)
|
||||
w.Write(buf)
|
||||
}
|
||||
|
||||
// api/proxy/http/:name
|
||||
func apiProxyHttpByName(w http.ResponseWriter, r *http.Request, params httprouter.Params) {
|
||||
var (
|
||||
buf []byte
|
||||
res GetProxyStatsResp
|
||||
)
|
||||
name := params.ByName("name")
|
||||
|
||||
defer func() {
|
||||
log.Info("Http response [/api/proxy/http/:name]: code [%d]", res.Code)
|
||||
}()
|
||||
log.Info("Http request: [/api/proxy/http/:name]")
|
||||
|
||||
res = getProxyStatsByTypeAndName(consts.HttpProxy, name)
|
||||
|
||||
buf, _ = json.Marshal(&res)
|
||||
w.Write(buf)
|
||||
}
|
||||
|
||||
// api/proxy/https/:name
|
||||
func apiProxyHttpsByName(w http.ResponseWriter, r *http.Request, params httprouter.Params) {
|
||||
var (
|
||||
buf []byte
|
||||
res GetProxyStatsResp
|
||||
)
|
||||
name := params.ByName("name")
|
||||
|
||||
defer func() {
|
||||
log.Info("Http response [/api/proxy/https/:name]: code [%d]", res.Code)
|
||||
}()
|
||||
log.Info("Http request: [/api/proxy/https/:name]")
|
||||
|
||||
res = getProxyStatsByTypeAndName(consts.HttpsProxy, name)
|
||||
|
||||
buf, _ = json.Marshal(&res)
|
||||
w.Write(buf)
|
||||
}
|
||||
|
||||
func getProxyStatsByTypeAndName(proxyType string, proxyName string) (proxyInfo GetProxyStatsResp) {
|
||||
func (svr *Service) getProxyStatsByTypeAndName(proxyType string, proxyName string) (proxyInfo GetProxyStatsResp) {
|
||||
proxyInfo.Name = proxyName
|
||||
ps := StatsGetProxiesByTypeAndName(proxyType, proxyName)
|
||||
ps := svr.statsCollector.GetProxiesByTypeAndName(proxyType, proxyName)
|
||||
if ps == nil {
|
||||
proxyInfo.Code = 1
|
||||
proxyInfo.Msg = "no proxy info found"
|
||||
} else {
|
||||
if pxy, ok := ServerService.pxyManager.GetByName(proxyName); ok {
|
||||
proxyInfo.Conf = pxy.GetConf()
|
||||
if pxy, ok := svr.pxyManager.GetByName(proxyName); ok {
|
||||
content, err := json.Marshal(pxy.GetConf())
|
||||
if err != nil {
|
||||
log.Warn("marshal proxy [%s] conf info error: %v", ps.Name, err)
|
||||
proxyInfo.Code = 2
|
||||
proxyInfo.Msg = "parse conf error"
|
||||
return
|
||||
}
|
||||
proxyInfo.Conf = getConfByType(ps.Type)
|
||||
if err = json.Unmarshal(content, &proxyInfo.Conf); err != nil {
|
||||
log.Warn("unmarshal proxy [%s] conf info error: %v", ps.Name, err)
|
||||
proxyInfo.Code = 2
|
||||
proxyInfo.Msg = "parse conf error"
|
||||
return
|
||||
}
|
||||
proxyInfo.Status = consts.Online
|
||||
} else {
|
||||
proxyInfo.Status = consts.Offline
|
||||
@@ -311,7 +284,7 @@ func getProxyStatsByTypeAndName(proxyType string, proxyName string) (proxyInfo G
|
||||
return
|
||||
}
|
||||
|
||||
// api/proxy/traffic/:name
|
||||
// api/traffic/:name
|
||||
type GetProxyTrafficResp struct {
|
||||
GeneralResponse
|
||||
|
||||
@@ -320,20 +293,21 @@ type GetProxyTrafficResp struct {
|
||||
TrafficOut []int64 `json:"traffic_out"`
|
||||
}
|
||||
|
||||
func apiProxyTraffic(w http.ResponseWriter, r *http.Request, params httprouter.Params) {
|
||||
func (svr *Service) ApiProxyTraffic(w http.ResponseWriter, r *http.Request) {
|
||||
var (
|
||||
buf []byte
|
||||
res GetProxyTrafficResp
|
||||
)
|
||||
name := params.ByName("name")
|
||||
params := mux.Vars(r)
|
||||
name := params["name"]
|
||||
|
||||
defer func() {
|
||||
log.Info("Http response [/api/proxy/traffic/:name]: code [%d]", res.Code)
|
||||
log.Info("Http response [%s]: code [%d]", r.URL.Path, res.Code)
|
||||
}()
|
||||
log.Info("Http request: [/api/proxy/traffic/:name]")
|
||||
log.Info("Http request: [%s]", r.URL.Path)
|
||||
|
||||
res.Name = name
|
||||
proxyTrafficInfo := StatsGetProxyTraffic(name)
|
||||
proxyTrafficInfo := svr.statsCollector.GetProxyTraffic(name)
|
||||
if proxyTrafficInfo == nil {
|
||||
res.Code = 1
|
||||
res.Msg = "no proxy info found"
|
||||
|
26
server/group/group.go
Normal file
26
server/group/group.go
Normal file
@@ -0,0 +1,26 @@
|
||||
// Copyright 2018 fatedier, fatedier@gmail.com
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
package group
|
||||
|
||||
import (
|
||||
"errors"
|
||||
)
|
||||
|
||||
var (
|
||||
ErrGroupAuthFailed = errors.New("group auth failed")
|
||||
ErrGroupParamsInvalid = errors.New("group params invalid")
|
||||
ErrListenerClosed = errors.New("group listener closed")
|
||||
ErrGroupDifferentPort = errors.New("group should have same remote port")
|
||||
)
|
204
server/group/tcp.go
Normal file
204
server/group/tcp.go
Normal file
@@ -0,0 +1,204 @@
|
||||
// Copyright 2018 fatedier, fatedier@gmail.com
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
package group
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"net"
|
||||
"sync"
|
||||
|
||||
"github.com/fatedier/frp/server/ports"
|
||||
|
||||
gerr "github.com/fatedier/golib/errors"
|
||||
)
|
||||
|
||||
type TcpGroupListener struct {
|
||||
groupName string
|
||||
group *TcpGroup
|
||||
|
||||
addr net.Addr
|
||||
closeCh chan struct{}
|
||||
}
|
||||
|
||||
func newTcpGroupListener(name string, group *TcpGroup, addr net.Addr) *TcpGroupListener {
|
||||
return &TcpGroupListener{
|
||||
groupName: name,
|
||||
group: group,
|
||||
addr: addr,
|
||||
closeCh: make(chan struct{}),
|
||||
}
|
||||
}
|
||||
|
||||
func (ln *TcpGroupListener) Accept() (c net.Conn, err error) {
|
||||
var ok bool
|
||||
select {
|
||||
case <-ln.closeCh:
|
||||
return nil, ErrListenerClosed
|
||||
case c, ok = <-ln.group.Accept():
|
||||
if !ok {
|
||||
return nil, ErrListenerClosed
|
||||
}
|
||||
return c, nil
|
||||
}
|
||||
}
|
||||
|
||||
func (ln *TcpGroupListener) Addr() net.Addr {
|
||||
return ln.addr
|
||||
}
|
||||
|
||||
func (ln *TcpGroupListener) Close() (err error) {
|
||||
close(ln.closeCh)
|
||||
ln.group.CloseListener(ln)
|
||||
return
|
||||
}
|
||||
|
||||
type TcpGroup struct {
|
||||
group string
|
||||
groupKey string
|
||||
addr string
|
||||
port int
|
||||
realPort int
|
||||
|
||||
acceptCh chan net.Conn
|
||||
index uint64
|
||||
tcpLn net.Listener
|
||||
lns []*TcpGroupListener
|
||||
ctl *TcpGroupCtl
|
||||
mu sync.Mutex
|
||||
}
|
||||
|
||||
func NewTcpGroup(ctl *TcpGroupCtl) *TcpGroup {
|
||||
return &TcpGroup{
|
||||
lns: make([]*TcpGroupListener, 0),
|
||||
ctl: ctl,
|
||||
acceptCh: make(chan net.Conn),
|
||||
}
|
||||
}
|
||||
|
||||
func (tg *TcpGroup) Listen(proxyName string, group string, groupKey string, addr string, port int) (ln *TcpGroupListener, realPort int, err error) {
|
||||
tg.mu.Lock()
|
||||
defer tg.mu.Unlock()
|
||||
if len(tg.lns) == 0 {
|
||||
realPort, err = tg.ctl.portManager.Acquire(proxyName, port)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
tcpLn, errRet := net.Listen("tcp", fmt.Sprintf("%s:%d", addr, port))
|
||||
if errRet != nil {
|
||||
err = errRet
|
||||
return
|
||||
}
|
||||
ln = newTcpGroupListener(group, tg, tcpLn.Addr())
|
||||
|
||||
tg.group = group
|
||||
tg.groupKey = groupKey
|
||||
tg.addr = addr
|
||||
tg.port = port
|
||||
tg.realPort = realPort
|
||||
tg.tcpLn = tcpLn
|
||||
tg.lns = append(tg.lns, ln)
|
||||
if tg.acceptCh == nil {
|
||||
tg.acceptCh = make(chan net.Conn)
|
||||
}
|
||||
go tg.worker()
|
||||
} else {
|
||||
if tg.group != group || tg.addr != addr {
|
||||
err = ErrGroupParamsInvalid
|
||||
return
|
||||
}
|
||||
if tg.port != port {
|
||||
err = ErrGroupDifferentPort
|
||||
return
|
||||
}
|
||||
if tg.groupKey != groupKey {
|
||||
err = ErrGroupAuthFailed
|
||||
return
|
||||
}
|
||||
ln = newTcpGroupListener(group, tg, tg.lns[0].Addr())
|
||||
realPort = tg.realPort
|
||||
tg.lns = append(tg.lns, ln)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
func (tg *TcpGroup) worker() {
|
||||
for {
|
||||
c, err := tg.tcpLn.Accept()
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
err = gerr.PanicToError(func() {
|
||||
tg.acceptCh <- c
|
||||
})
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (tg *TcpGroup) Accept() <-chan net.Conn {
|
||||
return tg.acceptCh
|
||||
}
|
||||
|
||||
func (tg *TcpGroup) CloseListener(ln *TcpGroupListener) {
|
||||
tg.mu.Lock()
|
||||
defer tg.mu.Unlock()
|
||||
for i, tmpLn := range tg.lns {
|
||||
if tmpLn == ln {
|
||||
tg.lns = append(tg.lns[:i], tg.lns[i+1:]...)
|
||||
break
|
||||
}
|
||||
}
|
||||
if len(tg.lns) == 0 {
|
||||
close(tg.acceptCh)
|
||||
tg.tcpLn.Close()
|
||||
tg.ctl.portManager.Release(tg.realPort)
|
||||
tg.ctl.RemoveGroup(tg.group)
|
||||
}
|
||||
}
|
||||
|
||||
type TcpGroupCtl struct {
|
||||
groups map[string]*TcpGroup
|
||||
|
||||
portManager *ports.PortManager
|
||||
mu sync.Mutex
|
||||
}
|
||||
|
||||
func NewTcpGroupCtl(portManager *ports.PortManager) *TcpGroupCtl {
|
||||
return &TcpGroupCtl{
|
||||
groups: make(map[string]*TcpGroup),
|
||||
portManager: portManager,
|
||||
}
|
||||
}
|
||||
|
||||
func (tgc *TcpGroupCtl) Listen(proxyNanme string, group string, groupKey string,
|
||||
addr string, port int) (l net.Listener, realPort int, err error) {
|
||||
|
||||
tgc.mu.Lock()
|
||||
defer tgc.mu.Unlock()
|
||||
if tcpGroup, ok := tgc.groups[group]; ok {
|
||||
return tcpGroup.Listen(proxyNanme, group, groupKey, addr, port)
|
||||
} else {
|
||||
tcpGroup = NewTcpGroup(tgc)
|
||||
tgc.groups[group] = tcpGroup
|
||||
return tcpGroup.Listen(proxyNanme, group, groupKey, addr, port)
|
||||
}
|
||||
}
|
||||
|
||||
func (tgc *TcpGroupCtl) RemoveGroup(group string) {
|
||||
tgc.mu.Lock()
|
||||
defer tgc.mu.Unlock()
|
||||
delete(tgc.groups, group)
|
||||
}
|
316
server/metric.go
316
server/metric.go
@@ -1,316 +0,0 @@
|
||||
// Copyright 2017 fatedier, fatedier@gmail.com
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
package server
|
||||
|
||||
import (
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/fatedier/frp/g"
|
||||
"github.com/fatedier/frp/utils/log"
|
||||
"github.com/fatedier/frp/utils/metric"
|
||||
)
|
||||
|
||||
const (
|
||||
ReserveDays = 7
|
||||
)
|
||||
|
||||
var globalStats *ServerStatistics
|
||||
|
||||
type ServerStatistics struct {
|
||||
TotalTrafficIn metric.DateCounter
|
||||
TotalTrafficOut metric.DateCounter
|
||||
CurConns metric.Counter
|
||||
|
||||
// counter for clients
|
||||
ClientCounts metric.Counter
|
||||
|
||||
// counter for proxy types
|
||||
ProxyTypeCounts map[string]metric.Counter
|
||||
|
||||
// statistics for different proxies
|
||||
// key is proxy name
|
||||
ProxyStatistics map[string]*ProxyStatistics
|
||||
|
||||
mu sync.Mutex
|
||||
}
|
||||
|
||||
type ProxyStatistics struct {
|
||||
Name string
|
||||
ProxyType string
|
||||
TrafficIn metric.DateCounter
|
||||
TrafficOut metric.DateCounter
|
||||
CurConns metric.Counter
|
||||
LastStartTime time.Time
|
||||
LastCloseTime time.Time
|
||||
}
|
||||
|
||||
func init() {
|
||||
globalStats = &ServerStatistics{
|
||||
TotalTrafficIn: metric.NewDateCounter(ReserveDays),
|
||||
TotalTrafficOut: metric.NewDateCounter(ReserveDays),
|
||||
CurConns: metric.NewCounter(),
|
||||
|
||||
ClientCounts: metric.NewCounter(),
|
||||
ProxyTypeCounts: make(map[string]metric.Counter),
|
||||
|
||||
ProxyStatistics: make(map[string]*ProxyStatistics),
|
||||
}
|
||||
|
||||
go func() {
|
||||
for {
|
||||
time.Sleep(12 * time.Hour)
|
||||
log.Debug("start to clear useless proxy statistics data...")
|
||||
StatsClearUselessInfo()
|
||||
log.Debug("finish to clear useless proxy statistics data")
|
||||
}
|
||||
}()
|
||||
}
|
||||
|
||||
func StatsClearUselessInfo() {
|
||||
// To check if there are proxies that closed than 7 days and drop them.
|
||||
globalStats.mu.Lock()
|
||||
defer globalStats.mu.Unlock()
|
||||
for name, data := range globalStats.ProxyStatistics {
|
||||
if !data.LastCloseTime.IsZero() && time.Since(data.LastCloseTime) > time.Duration(7*24)*time.Hour {
|
||||
delete(globalStats.ProxyStatistics, name)
|
||||
log.Trace("clear proxy [%s]'s statistics data, lastCloseTime: [%s]", name, data.LastCloseTime.String())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func StatsNewClient() {
|
||||
if g.GlbServerCfg.DashboardPort != 0 {
|
||||
globalStats.ClientCounts.Inc(1)
|
||||
}
|
||||
}
|
||||
|
||||
func StatsCloseClient() {
|
||||
if g.GlbServerCfg.DashboardPort != 0 {
|
||||
globalStats.ClientCounts.Dec(1)
|
||||
}
|
||||
}
|
||||
|
||||
func StatsNewProxy(name string, proxyType string) {
|
||||
if g.GlbServerCfg.DashboardPort != 0 {
|
||||
globalStats.mu.Lock()
|
||||
defer globalStats.mu.Unlock()
|
||||
counter, ok := globalStats.ProxyTypeCounts[proxyType]
|
||||
if !ok {
|
||||
counter = metric.NewCounter()
|
||||
}
|
||||
counter.Inc(1)
|
||||
globalStats.ProxyTypeCounts[proxyType] = counter
|
||||
|
||||
proxyStats, ok := globalStats.ProxyStatistics[name]
|
||||
if !(ok && proxyStats.ProxyType == proxyType) {
|
||||
proxyStats = &ProxyStatistics{
|
||||
Name: name,
|
||||
ProxyType: proxyType,
|
||||
CurConns: metric.NewCounter(),
|
||||
TrafficIn: metric.NewDateCounter(ReserveDays),
|
||||
TrafficOut: metric.NewDateCounter(ReserveDays),
|
||||
}
|
||||
globalStats.ProxyStatistics[name] = proxyStats
|
||||
}
|
||||
proxyStats.LastStartTime = time.Now()
|
||||
}
|
||||
}
|
||||
|
||||
func StatsCloseProxy(proxyName string, proxyType string) {
|
||||
if g.GlbServerCfg.DashboardPort != 0 {
|
||||
globalStats.mu.Lock()
|
||||
defer globalStats.mu.Unlock()
|
||||
if counter, ok := globalStats.ProxyTypeCounts[proxyType]; ok {
|
||||
counter.Dec(1)
|
||||
}
|
||||
if proxyStats, ok := globalStats.ProxyStatistics[proxyName]; ok {
|
||||
proxyStats.LastCloseTime = time.Now()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func StatsOpenConnection(name string) {
|
||||
if g.GlbServerCfg.DashboardPort != 0 {
|
||||
globalStats.CurConns.Inc(1)
|
||||
|
||||
globalStats.mu.Lock()
|
||||
defer globalStats.mu.Unlock()
|
||||
proxyStats, ok := globalStats.ProxyStatistics[name]
|
||||
if ok {
|
||||
proxyStats.CurConns.Inc(1)
|
||||
globalStats.ProxyStatistics[name] = proxyStats
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func StatsCloseConnection(name string) {
|
||||
if g.GlbServerCfg.DashboardPort != 0 {
|
||||
globalStats.CurConns.Dec(1)
|
||||
|
||||
globalStats.mu.Lock()
|
||||
defer globalStats.mu.Unlock()
|
||||
proxyStats, ok := globalStats.ProxyStatistics[name]
|
||||
if ok {
|
||||
proxyStats.CurConns.Dec(1)
|
||||
globalStats.ProxyStatistics[name] = proxyStats
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func StatsAddTrafficIn(name string, trafficIn int64) {
|
||||
if g.GlbServerCfg.DashboardPort != 0 {
|
||||
globalStats.TotalTrafficIn.Inc(trafficIn)
|
||||
|
||||
globalStats.mu.Lock()
|
||||
defer globalStats.mu.Unlock()
|
||||
|
||||
proxyStats, ok := globalStats.ProxyStatistics[name]
|
||||
if ok {
|
||||
proxyStats.TrafficIn.Inc(trafficIn)
|
||||
globalStats.ProxyStatistics[name] = proxyStats
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func StatsAddTrafficOut(name string, trafficOut int64) {
|
||||
if g.GlbServerCfg.DashboardPort != 0 {
|
||||
globalStats.TotalTrafficOut.Inc(trafficOut)
|
||||
|
||||
globalStats.mu.Lock()
|
||||
defer globalStats.mu.Unlock()
|
||||
|
||||
proxyStats, ok := globalStats.ProxyStatistics[name]
|
||||
if ok {
|
||||
proxyStats.TrafficOut.Inc(trafficOut)
|
||||
globalStats.ProxyStatistics[name] = proxyStats
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Functions for getting server stats.
|
||||
type ServerStats struct {
|
||||
TotalTrafficIn int64
|
||||
TotalTrafficOut int64
|
||||
CurConns int64
|
||||
ClientCounts int64
|
||||
ProxyTypeCounts map[string]int64
|
||||
}
|
||||
|
||||
func StatsGetServer() *ServerStats {
|
||||
globalStats.mu.Lock()
|
||||
defer globalStats.mu.Unlock()
|
||||
s := &ServerStats{
|
||||
TotalTrafficIn: globalStats.TotalTrafficIn.TodayCount(),
|
||||
TotalTrafficOut: globalStats.TotalTrafficOut.TodayCount(),
|
||||
CurConns: globalStats.CurConns.Count(),
|
||||
ClientCounts: globalStats.ClientCounts.Count(),
|
||||
ProxyTypeCounts: make(map[string]int64),
|
||||
}
|
||||
for k, v := range globalStats.ProxyTypeCounts {
|
||||
s.ProxyTypeCounts[k] = v.Count()
|
||||
}
|
||||
return s
|
||||
}
|
||||
|
||||
type ProxyStats struct {
|
||||
Name string
|
||||
Type string
|
||||
TodayTrafficIn int64
|
||||
TodayTrafficOut int64
|
||||
LastStartTime string
|
||||
LastCloseTime string
|
||||
CurConns int64
|
||||
}
|
||||
|
||||
func StatsGetProxiesByType(proxyType string) []*ProxyStats {
|
||||
res := make([]*ProxyStats, 0)
|
||||
globalStats.mu.Lock()
|
||||
defer globalStats.mu.Unlock()
|
||||
|
||||
for name, proxyStats := range globalStats.ProxyStatistics {
|
||||
if proxyStats.ProxyType != proxyType {
|
||||
continue
|
||||
}
|
||||
|
||||
ps := &ProxyStats{
|
||||
Name: name,
|
||||
Type: proxyStats.ProxyType,
|
||||
TodayTrafficIn: proxyStats.TrafficIn.TodayCount(),
|
||||
TodayTrafficOut: proxyStats.TrafficOut.TodayCount(),
|
||||
CurConns: proxyStats.CurConns.Count(),
|
||||
}
|
||||
if !proxyStats.LastStartTime.IsZero() {
|
||||
ps.LastStartTime = proxyStats.LastStartTime.Format("01-02 15:04:05")
|
||||
}
|
||||
if !proxyStats.LastCloseTime.IsZero() {
|
||||
ps.LastCloseTime = proxyStats.LastCloseTime.Format("01-02 15:04:05")
|
||||
}
|
||||
res = append(res, ps)
|
||||
}
|
||||
return res
|
||||
}
|
||||
|
||||
func StatsGetProxiesByTypeAndName(proxyType string, proxyName string) (res *ProxyStats) {
|
||||
globalStats.mu.Lock()
|
||||
defer globalStats.mu.Unlock()
|
||||
|
||||
for name, proxyStats := range globalStats.ProxyStatistics {
|
||||
if proxyStats.ProxyType != proxyType {
|
||||
continue
|
||||
}
|
||||
|
||||
if name != proxyName {
|
||||
continue
|
||||
}
|
||||
|
||||
res = &ProxyStats{
|
||||
Name: name,
|
||||
Type: proxyStats.ProxyType,
|
||||
TodayTrafficIn: proxyStats.TrafficIn.TodayCount(),
|
||||
TodayTrafficOut: proxyStats.TrafficOut.TodayCount(),
|
||||
CurConns: proxyStats.CurConns.Count(),
|
||||
}
|
||||
if !proxyStats.LastStartTime.IsZero() {
|
||||
res.LastStartTime = proxyStats.LastStartTime.Format("01-02 15:04:05")
|
||||
}
|
||||
if !proxyStats.LastCloseTime.IsZero() {
|
||||
res.LastCloseTime = proxyStats.LastCloseTime.Format("01-02 15:04:05")
|
||||
}
|
||||
break
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
type ProxyTrafficInfo struct {
|
||||
Name string
|
||||
TrafficIn []int64
|
||||
TrafficOut []int64
|
||||
}
|
||||
|
||||
func StatsGetProxyTraffic(name string) (res *ProxyTrafficInfo) {
|
||||
globalStats.mu.Lock()
|
||||
defer globalStats.mu.Unlock()
|
||||
|
||||
proxyStats, ok := globalStats.ProxyStatistics[name]
|
||||
if ok {
|
||||
res = &ProxyTrafficInfo{
|
||||
Name: name,
|
||||
}
|
||||
res.TrafficIn = proxyStats.TrafficIn.GetLastDaysCount(ReserveDays)
|
||||
res.TrafficOut = proxyStats.TrafficOut.GetLastDaysCount(ReserveDays)
|
||||
}
|
||||
return
|
||||
}
|
@@ -1,4 +1,4 @@
|
||||
package server
|
||||
package ports
|
||||
|
||||
import (
|
||||
"errors"
|
667
server/proxy.go
667
server/proxy.go
@@ -1,667 +0,0 @@
|
||||
// Copyright 2017 fatedier, fatedier@gmail.com
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
package server
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"io"
|
||||
"net"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/fatedier/frp/g"
|
||||
"github.com/fatedier/frp/models/config"
|
||||
"github.com/fatedier/frp/models/msg"
|
||||
"github.com/fatedier/frp/models/proto/udp"
|
||||
"github.com/fatedier/frp/utils/log"
|
||||
frpNet "github.com/fatedier/frp/utils/net"
|
||||
"github.com/fatedier/frp/utils/util"
|
||||
"github.com/fatedier/frp/utils/vhost"
|
||||
|
||||
"github.com/fatedier/golib/errors"
|
||||
frpIo "github.com/fatedier/golib/io"
|
||||
)
|
||||
|
||||
type Proxy interface {
|
||||
Run() (remoteAddr string, err error)
|
||||
GetControl() *Control
|
||||
GetName() string
|
||||
GetConf() config.ProxyConf
|
||||
GetWorkConnFromPool() (workConn frpNet.Conn, err error)
|
||||
GetUsedPortsNum() int
|
||||
Close()
|
||||
log.Logger
|
||||
}
|
||||
|
||||
type BaseProxy struct {
|
||||
name string
|
||||
ctl *Control
|
||||
listeners []frpNet.Listener
|
||||
usedPortsNum int
|
||||
|
||||
mu sync.RWMutex
|
||||
log.Logger
|
||||
}
|
||||
|
||||
func (pxy *BaseProxy) GetName() string {
|
||||
return pxy.name
|
||||
}
|
||||
|
||||
func (pxy *BaseProxy) GetControl() *Control {
|
||||
return pxy.ctl
|
||||
}
|
||||
|
||||
func (pxy *BaseProxy) GetUsedPortsNum() int {
|
||||
return pxy.usedPortsNum
|
||||
}
|
||||
|
||||
func (pxy *BaseProxy) Close() {
|
||||
pxy.Info("proxy closing")
|
||||
for _, l := range pxy.listeners {
|
||||
l.Close()
|
||||
}
|
||||
}
|
||||
|
||||
func (pxy *BaseProxy) GetWorkConnFromPool() (workConn frpNet.Conn, err error) {
|
||||
ctl := pxy.GetControl()
|
||||
// try all connections from the pool
|
||||
for i := 0; i < ctl.poolCount+1; i++ {
|
||||
if workConn, err = ctl.GetWorkConn(); err != nil {
|
||||
pxy.Warn("failed to get work connection: %v", err)
|
||||
return
|
||||
}
|
||||
pxy.Info("get a new work connection: [%s]", workConn.RemoteAddr().String())
|
||||
workConn.AddLogPrefix(pxy.GetName())
|
||||
|
||||
err := msg.WriteMsg(workConn, &msg.StartWorkConn{
|
||||
ProxyName: pxy.GetName(),
|
||||
})
|
||||
if err != nil {
|
||||
workConn.Warn("failed to send message to work connection from pool: %v, times: %d", err, i)
|
||||
workConn.Close()
|
||||
} else {
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
if err != nil {
|
||||
pxy.Error("try to get work connection failed in the end")
|
||||
return
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
// startListenHandler start a goroutine handler for each listener.
|
||||
// p: p will just be passed to handler(Proxy, frpNet.Conn).
|
||||
// handler: each proxy type can set different handler function to deal with connections accepted from listeners.
|
||||
func (pxy *BaseProxy) startListenHandler(p Proxy, handler func(Proxy, frpNet.Conn)) {
|
||||
for _, listener := range pxy.listeners {
|
||||
go func(l frpNet.Listener) {
|
||||
for {
|
||||
// block
|
||||
// if listener is closed, err returned
|
||||
c, err := l.Accept()
|
||||
if err != nil {
|
||||
pxy.Info("listener is closed")
|
||||
return
|
||||
}
|
||||
pxy.Debug("get a user connection [%s]", c.RemoteAddr().String())
|
||||
go handler(p, c)
|
||||
}
|
||||
}(listener)
|
||||
}
|
||||
}
|
||||
|
||||
func NewProxy(ctl *Control, pxyConf config.ProxyConf) (pxy Proxy, err error) {
|
||||
basePxy := BaseProxy{
|
||||
name: pxyConf.GetBaseInfo().ProxyName,
|
||||
ctl: ctl,
|
||||
listeners: make([]frpNet.Listener, 0),
|
||||
Logger: log.NewPrefixLogger(ctl.runId),
|
||||
}
|
||||
switch cfg := pxyConf.(type) {
|
||||
case *config.TcpProxyConf:
|
||||
basePxy.usedPortsNum = 1
|
||||
pxy = &TcpProxy{
|
||||
BaseProxy: basePxy,
|
||||
cfg: cfg,
|
||||
}
|
||||
case *config.HttpProxyConf:
|
||||
pxy = &HttpProxy{
|
||||
BaseProxy: basePxy,
|
||||
cfg: cfg,
|
||||
}
|
||||
case *config.HttpsProxyConf:
|
||||
pxy = &HttpsProxy{
|
||||
BaseProxy: basePxy,
|
||||
cfg: cfg,
|
||||
}
|
||||
case *config.UdpProxyConf:
|
||||
basePxy.usedPortsNum = 1
|
||||
pxy = &UdpProxy{
|
||||
BaseProxy: basePxy,
|
||||
cfg: cfg,
|
||||
}
|
||||
case *config.StcpProxyConf:
|
||||
pxy = &StcpProxy{
|
||||
BaseProxy: basePxy,
|
||||
cfg: cfg,
|
||||
}
|
||||
case *config.XtcpProxyConf:
|
||||
pxy = &XtcpProxy{
|
||||
BaseProxy: basePxy,
|
||||
cfg: cfg,
|
||||
}
|
||||
default:
|
||||
return pxy, fmt.Errorf("proxy type not support")
|
||||
}
|
||||
pxy.AddLogPrefix(pxy.GetName())
|
||||
return
|
||||
}
|
||||
|
||||
type TcpProxy struct {
|
||||
BaseProxy
|
||||
cfg *config.TcpProxyConf
|
||||
|
||||
realPort int
|
||||
}
|
||||
|
||||
func (pxy *TcpProxy) Run() (remoteAddr string, err error) {
|
||||
pxy.realPort, err = pxy.ctl.svr.tcpPortManager.Acquire(pxy.name, pxy.cfg.RemotePort)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
defer func() {
|
||||
if err != nil {
|
||||
pxy.ctl.svr.tcpPortManager.Release(pxy.realPort)
|
||||
}
|
||||
}()
|
||||
|
||||
remoteAddr = fmt.Sprintf(":%d", pxy.realPort)
|
||||
pxy.cfg.RemotePort = pxy.realPort
|
||||
listener, errRet := frpNet.ListenTcp(g.GlbServerCfg.ProxyBindAddr, pxy.realPort)
|
||||
if errRet != nil {
|
||||
err = errRet
|
||||
return
|
||||
}
|
||||
listener.AddLogPrefix(pxy.name)
|
||||
pxy.listeners = append(pxy.listeners, listener)
|
||||
pxy.Info("tcp proxy listen port [%d]", pxy.cfg.RemotePort)
|
||||
|
||||
pxy.startListenHandler(pxy, HandleUserTcpConnection)
|
||||
return
|
||||
}
|
||||
|
||||
func (pxy *TcpProxy) GetConf() config.ProxyConf {
|
||||
return pxy.cfg
|
||||
}
|
||||
|
||||
func (pxy *TcpProxy) Close() {
|
||||
pxy.BaseProxy.Close()
|
||||
pxy.ctl.svr.tcpPortManager.Release(pxy.realPort)
|
||||
}
|
||||
|
||||
type HttpProxy struct {
|
||||
BaseProxy
|
||||
cfg *config.HttpProxyConf
|
||||
|
||||
closeFuncs []func()
|
||||
}
|
||||
|
||||
func (pxy *HttpProxy) Run() (remoteAddr string, err error) {
|
||||
routeConfig := vhost.VhostRouteConfig{
|
||||
RewriteHost: pxy.cfg.HostHeaderRewrite,
|
||||
Username: pxy.cfg.HttpUser,
|
||||
Password: pxy.cfg.HttpPwd,
|
||||
CreateConnFn: pxy.GetRealConn,
|
||||
}
|
||||
|
||||
locations := pxy.cfg.Locations
|
||||
if len(locations) == 0 {
|
||||
locations = []string{""}
|
||||
}
|
||||
|
||||
addrs := make([]string, 0)
|
||||
for _, domain := range pxy.cfg.CustomDomains {
|
||||
routeConfig.Domain = domain
|
||||
for _, location := range locations {
|
||||
routeConfig.Location = location
|
||||
err = pxy.ctl.svr.httpReverseProxy.Register(routeConfig)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
tmpDomain := routeConfig.Domain
|
||||
tmpLocation := routeConfig.Location
|
||||
addrs = append(addrs, util.CanonicalAddr(tmpDomain, int(g.GlbServerCfg.VhostHttpPort)))
|
||||
pxy.closeFuncs = append(pxy.closeFuncs, func() {
|
||||
pxy.ctl.svr.httpReverseProxy.UnRegister(tmpDomain, tmpLocation)
|
||||
})
|
||||
pxy.Info("http proxy listen for host [%s] location [%s]", routeConfig.Domain, routeConfig.Location)
|
||||
}
|
||||
}
|
||||
|
||||
if pxy.cfg.SubDomain != "" {
|
||||
routeConfig.Domain = pxy.cfg.SubDomain + "." + g.GlbServerCfg.SubDomainHost
|
||||
for _, location := range locations {
|
||||
routeConfig.Location = location
|
||||
err = pxy.ctl.svr.httpReverseProxy.Register(routeConfig)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
tmpDomain := routeConfig.Domain
|
||||
tmpLocation := routeConfig.Location
|
||||
addrs = append(addrs, util.CanonicalAddr(tmpDomain, g.GlbServerCfg.VhostHttpPort))
|
||||
pxy.closeFuncs = append(pxy.closeFuncs, func() {
|
||||
pxy.ctl.svr.httpReverseProxy.UnRegister(tmpDomain, tmpLocation)
|
||||
})
|
||||
pxy.Info("http proxy listen for host [%s] location [%s]", routeConfig.Domain, routeConfig.Location)
|
||||
}
|
||||
}
|
||||
remoteAddr = strings.Join(addrs, ",")
|
||||
return
|
||||
}
|
||||
|
||||
func (pxy *HttpProxy) GetConf() config.ProxyConf {
|
||||
return pxy.cfg
|
||||
}
|
||||
|
||||
func (pxy *HttpProxy) GetRealConn() (workConn frpNet.Conn, err error) {
|
||||
tmpConn, errRet := pxy.GetWorkConnFromPool()
|
||||
if errRet != nil {
|
||||
err = errRet
|
||||
return
|
||||
}
|
||||
|
||||
var rwc io.ReadWriteCloser = tmpConn
|
||||
if pxy.cfg.UseEncryption {
|
||||
rwc, err = frpIo.WithEncryption(rwc, []byte(g.GlbServerCfg.Token))
|
||||
if err != nil {
|
||||
pxy.Error("create encryption stream error: %v", err)
|
||||
return
|
||||
}
|
||||
}
|
||||
if pxy.cfg.UseCompression {
|
||||
rwc = frpIo.WithCompression(rwc)
|
||||
}
|
||||
workConn = frpNet.WrapReadWriteCloserToConn(rwc, tmpConn)
|
||||
workConn = frpNet.WrapStatsConn(workConn, pxy.updateStatsAfterClosedConn)
|
||||
StatsOpenConnection(pxy.GetName())
|
||||
return
|
||||
}
|
||||
|
||||
func (pxy *HttpProxy) updateStatsAfterClosedConn(totalRead, totalWrite int64) {
|
||||
name := pxy.GetName()
|
||||
StatsCloseConnection(name)
|
||||
StatsAddTrafficIn(name, totalWrite)
|
||||
StatsAddTrafficOut(name, totalRead)
|
||||
}
|
||||
|
||||
func (pxy *HttpProxy) Close() {
|
||||
pxy.BaseProxy.Close()
|
||||
for _, closeFn := range pxy.closeFuncs {
|
||||
closeFn()
|
||||
}
|
||||
}
|
||||
|
||||
type HttpsProxy struct {
|
||||
BaseProxy
|
||||
cfg *config.HttpsProxyConf
|
||||
}
|
||||
|
||||
func (pxy *HttpsProxy) Run() (remoteAddr string, err error) {
|
||||
routeConfig := &vhost.VhostRouteConfig{}
|
||||
|
||||
addrs := make([]string, 0)
|
||||
for _, domain := range pxy.cfg.CustomDomains {
|
||||
routeConfig.Domain = domain
|
||||
l, errRet := pxy.ctl.svr.VhostHttpsMuxer.Listen(routeConfig)
|
||||
if errRet != nil {
|
||||
err = errRet
|
||||
return
|
||||
}
|
||||
l.AddLogPrefix(pxy.name)
|
||||
pxy.Info("https proxy listen for host [%s]", routeConfig.Domain)
|
||||
pxy.listeners = append(pxy.listeners, l)
|
||||
addrs = append(addrs, util.CanonicalAddr(routeConfig.Domain, g.GlbServerCfg.VhostHttpsPort))
|
||||
}
|
||||
|
||||
if pxy.cfg.SubDomain != "" {
|
||||
routeConfig.Domain = pxy.cfg.SubDomain + "." + g.GlbServerCfg.SubDomainHost
|
||||
l, errRet := pxy.ctl.svr.VhostHttpsMuxer.Listen(routeConfig)
|
||||
if errRet != nil {
|
||||
err = errRet
|
||||
return
|
||||
}
|
||||
l.AddLogPrefix(pxy.name)
|
||||
pxy.Info("https proxy listen for host [%s]", routeConfig.Domain)
|
||||
pxy.listeners = append(pxy.listeners, l)
|
||||
addrs = append(addrs, util.CanonicalAddr(routeConfig.Domain, int(g.GlbServerCfg.VhostHttpsPort)))
|
||||
}
|
||||
|
||||
pxy.startListenHandler(pxy, HandleUserTcpConnection)
|
||||
remoteAddr = strings.Join(addrs, ",")
|
||||
return
|
||||
}
|
||||
|
||||
func (pxy *HttpsProxy) GetConf() config.ProxyConf {
|
||||
return pxy.cfg
|
||||
}
|
||||
|
||||
func (pxy *HttpsProxy) Close() {
|
||||
pxy.BaseProxy.Close()
|
||||
}
|
||||
|
||||
type StcpProxy struct {
|
||||
BaseProxy
|
||||
cfg *config.StcpProxyConf
|
||||
}
|
||||
|
||||
func (pxy *StcpProxy) Run() (remoteAddr string, err error) {
|
||||
listener, errRet := pxy.ctl.svr.visitorManager.Listen(pxy.GetName(), pxy.cfg.Sk)
|
||||
if errRet != nil {
|
||||
err = errRet
|
||||
return
|
||||
}
|
||||
listener.AddLogPrefix(pxy.name)
|
||||
pxy.listeners = append(pxy.listeners, listener)
|
||||
pxy.Info("stcp proxy custom listen success")
|
||||
|
||||
pxy.startListenHandler(pxy, HandleUserTcpConnection)
|
||||
return
|
||||
}
|
||||
|
||||
func (pxy *StcpProxy) GetConf() config.ProxyConf {
|
||||
return pxy.cfg
|
||||
}
|
||||
|
||||
func (pxy *StcpProxy) Close() {
|
||||
pxy.BaseProxy.Close()
|
||||
pxy.ctl.svr.visitorManager.CloseListener(pxy.GetName())
|
||||
}
|
||||
|
||||
type XtcpProxy struct {
|
||||
BaseProxy
|
||||
cfg *config.XtcpProxyConf
|
||||
|
||||
closeCh chan struct{}
|
||||
}
|
||||
|
||||
func (pxy *XtcpProxy) Run() (remoteAddr string, err error) {
|
||||
if pxy.ctl.svr.natHoleController == nil {
|
||||
pxy.Error("udp port for xtcp is not specified.")
|
||||
err = fmt.Errorf("xtcp is not supported in frps")
|
||||
return
|
||||
}
|
||||
sidCh := pxy.ctl.svr.natHoleController.ListenClient(pxy.GetName(), pxy.cfg.Sk)
|
||||
go func() {
|
||||
for {
|
||||
select {
|
||||
case <-pxy.closeCh:
|
||||
break
|
||||
case sid := <-sidCh:
|
||||
workConn, errRet := pxy.GetWorkConnFromPool()
|
||||
if errRet != nil {
|
||||
continue
|
||||
}
|
||||
m := &msg.NatHoleSid{
|
||||
Sid: sid,
|
||||
}
|
||||
errRet = msg.WriteMsg(workConn, m)
|
||||
if errRet != nil {
|
||||
pxy.Warn("write nat hole sid package error, %v", errRet)
|
||||
}
|
||||
}
|
||||
}
|
||||
}()
|
||||
return
|
||||
}
|
||||
|
||||
func (pxy *XtcpProxy) GetConf() config.ProxyConf {
|
||||
return pxy.cfg
|
||||
}
|
||||
|
||||
func (pxy *XtcpProxy) Close() {
|
||||
pxy.BaseProxy.Close()
|
||||
pxy.ctl.svr.natHoleController.CloseClient(pxy.GetName())
|
||||
errors.PanicToError(func() {
|
||||
close(pxy.closeCh)
|
||||
})
|
||||
}
|
||||
|
||||
type UdpProxy struct {
|
||||
BaseProxy
|
||||
cfg *config.UdpProxyConf
|
||||
|
||||
realPort int
|
||||
|
||||
// udpConn is the listener of udp packages
|
||||
udpConn *net.UDPConn
|
||||
|
||||
// there are always only one workConn at the same time
|
||||
// get another one if it closed
|
||||
workConn net.Conn
|
||||
|
||||
// sendCh is used for sending packages to workConn
|
||||
sendCh chan *msg.UdpPacket
|
||||
|
||||
// readCh is used for reading packages from workConn
|
||||
readCh chan *msg.UdpPacket
|
||||
|
||||
// checkCloseCh is used for watching if workConn is closed
|
||||
checkCloseCh chan int
|
||||
|
||||
isClosed bool
|
||||
}
|
||||
|
||||
func (pxy *UdpProxy) Run() (remoteAddr string, err error) {
|
||||
pxy.realPort, err = pxy.ctl.svr.udpPortManager.Acquire(pxy.name, pxy.cfg.RemotePort)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
defer func() {
|
||||
if err != nil {
|
||||
pxy.ctl.svr.udpPortManager.Release(pxy.realPort)
|
||||
}
|
||||
}()
|
||||
|
||||
remoteAddr = fmt.Sprintf(":%d", pxy.realPort)
|
||||
pxy.cfg.RemotePort = pxy.realPort
|
||||
addr, errRet := net.ResolveUDPAddr("udp", fmt.Sprintf("%s:%d", g.GlbServerCfg.ProxyBindAddr, pxy.realPort))
|
||||
if errRet != nil {
|
||||
err = errRet
|
||||
return
|
||||
}
|
||||
udpConn, errRet := net.ListenUDP("udp", addr)
|
||||
if errRet != nil {
|
||||
err = errRet
|
||||
pxy.Warn("listen udp port error: %v", err)
|
||||
return
|
||||
}
|
||||
pxy.Info("udp proxy listen port [%d]", pxy.cfg.RemotePort)
|
||||
|
||||
pxy.udpConn = udpConn
|
||||
pxy.sendCh = make(chan *msg.UdpPacket, 1024)
|
||||
pxy.readCh = make(chan *msg.UdpPacket, 1024)
|
||||
pxy.checkCloseCh = make(chan int)
|
||||
|
||||
// read message from workConn, if it returns any error, notify proxy to start a new workConn
|
||||
workConnReaderFn := func(conn net.Conn) {
|
||||
for {
|
||||
var (
|
||||
rawMsg msg.Message
|
||||
errRet error
|
||||
)
|
||||
pxy.Trace("loop waiting message from udp workConn")
|
||||
// client will send heartbeat in workConn for keeping alive
|
||||
conn.SetReadDeadline(time.Now().Add(time.Duration(60) * time.Second))
|
||||
if rawMsg, errRet = msg.ReadMsg(conn); errRet != nil {
|
||||
pxy.Warn("read from workConn for udp error: %v", errRet)
|
||||
conn.Close()
|
||||
// notify proxy to start a new work connection
|
||||
// ignore error here, it means the proxy is closed
|
||||
errors.PanicToError(func() {
|
||||
pxy.checkCloseCh <- 1
|
||||
})
|
||||
return
|
||||
}
|
||||
conn.SetReadDeadline(time.Time{})
|
||||
switch m := rawMsg.(type) {
|
||||
case *msg.Ping:
|
||||
pxy.Trace("udp work conn get ping message")
|
||||
continue
|
||||
case *msg.UdpPacket:
|
||||
if errRet := errors.PanicToError(func() {
|
||||
pxy.Trace("get udp message from workConn: %s", m.Content)
|
||||
pxy.readCh <- m
|
||||
StatsAddTrafficOut(pxy.GetName(), int64(len(m.Content)))
|
||||
}); errRet != nil {
|
||||
conn.Close()
|
||||
pxy.Info("reader goroutine for udp work connection closed")
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// send message to workConn
|
||||
workConnSenderFn := func(conn net.Conn, ctx context.Context) {
|
||||
var errRet error
|
||||
for {
|
||||
select {
|
||||
case udpMsg, ok := <-pxy.sendCh:
|
||||
if !ok {
|
||||
pxy.Info("sender goroutine for udp work connection closed")
|
||||
return
|
||||
}
|
||||
if errRet = msg.WriteMsg(conn, udpMsg); errRet != nil {
|
||||
pxy.Info("sender goroutine for udp work connection closed: %v", errRet)
|
||||
conn.Close()
|
||||
return
|
||||
} else {
|
||||
pxy.Trace("send message to udp workConn: %s", udpMsg.Content)
|
||||
StatsAddTrafficIn(pxy.GetName(), int64(len(udpMsg.Content)))
|
||||
continue
|
||||
}
|
||||
case <-ctx.Done():
|
||||
pxy.Info("sender goroutine for udp work connection closed")
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
go func() {
|
||||
// Sleep a while for waiting control send the NewProxyResp to client.
|
||||
time.Sleep(500 * time.Millisecond)
|
||||
for {
|
||||
workConn, err := pxy.GetWorkConnFromPool()
|
||||
if err != nil {
|
||||
time.Sleep(1 * time.Second)
|
||||
// check if proxy is closed
|
||||
select {
|
||||
case _, ok := <-pxy.checkCloseCh:
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
default:
|
||||
}
|
||||
continue
|
||||
}
|
||||
// close the old workConn and replac it with a new one
|
||||
if pxy.workConn != nil {
|
||||
pxy.workConn.Close()
|
||||
}
|
||||
pxy.workConn = workConn
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
go workConnReaderFn(workConn)
|
||||
go workConnSenderFn(workConn, ctx)
|
||||
_, ok := <-pxy.checkCloseCh
|
||||
cancel()
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
}
|
||||
}()
|
||||
|
||||
// Read from user connections and send wrapped udp message to sendCh (forwarded by workConn).
|
||||
// Client will transfor udp message to local udp service and waiting for response for a while.
|
||||
// Response will be wrapped to be forwarded by work connection to server.
|
||||
// Close readCh and sendCh at the end.
|
||||
go func() {
|
||||
udp.ForwardUserConn(udpConn, pxy.readCh, pxy.sendCh)
|
||||
pxy.Close()
|
||||
}()
|
||||
return remoteAddr, nil
|
||||
}
|
||||
|
||||
func (pxy *UdpProxy) GetConf() config.ProxyConf {
|
||||
return pxy.cfg
|
||||
}
|
||||
|
||||
func (pxy *UdpProxy) Close() {
|
||||
pxy.mu.Lock()
|
||||
defer pxy.mu.Unlock()
|
||||
if !pxy.isClosed {
|
||||
pxy.isClosed = true
|
||||
|
||||
pxy.BaseProxy.Close()
|
||||
if pxy.workConn != nil {
|
||||
pxy.workConn.Close()
|
||||
}
|
||||
pxy.udpConn.Close()
|
||||
|
||||
// all channels only closed here
|
||||
close(pxy.checkCloseCh)
|
||||
close(pxy.readCh)
|
||||
close(pxy.sendCh)
|
||||
}
|
||||
pxy.ctl.svr.udpPortManager.Release(pxy.realPort)
|
||||
}
|
||||
|
||||
// HandleUserTcpConnection is used for incoming tcp user connections.
|
||||
// It can be used for tcp, http, https type.
|
||||
func HandleUserTcpConnection(pxy Proxy, userConn frpNet.Conn) {
|
||||
defer userConn.Close()
|
||||
|
||||
// try all connections from the pool
|
||||
workConn, err := pxy.GetWorkConnFromPool()
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
defer workConn.Close()
|
||||
|
||||
var local io.ReadWriteCloser = workConn
|
||||
cfg := pxy.GetConf().GetBaseInfo()
|
||||
if cfg.UseEncryption {
|
||||
local, err = frpIo.WithEncryption(local, []byte(g.GlbServerCfg.Token))
|
||||
if err != nil {
|
||||
pxy.Error("create encryption stream error: %v", err)
|
||||
return
|
||||
}
|
||||
}
|
||||
if cfg.UseCompression {
|
||||
local = frpIo.WithCompression(local)
|
||||
}
|
||||
pxy.Debug("join connections, workConn(l[%s] r[%s]) userConn(l[%s] r[%s])", workConn.LocalAddr().String(),
|
||||
workConn.RemoteAddr().String(), userConn.LocalAddr().String(), userConn.RemoteAddr().String())
|
||||
|
||||
StatsOpenConnection(pxy.GetName())
|
||||
inCount, outCount := frpIo.Join(local, userConn)
|
||||
StatsCloseConnection(pxy.GetName())
|
||||
StatsAddTrafficIn(pxy.GetName(), inCount)
|
||||
StatsAddTrafficOut(pxy.GetName(), outCount)
|
||||
pxy.Debug("join connections closed")
|
||||
}
|
138
server/proxy/http.go
Normal file
138
server/proxy/http.go
Normal file
@@ -0,0 +1,138 @@
|
||||
// Copyright 2019 fatedier, fatedier@gmail.com
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
package proxy
|
||||
|
||||
import (
|
||||
"io"
|
||||
"strings"
|
||||
|
||||
"github.com/fatedier/frp/g"
|
||||
"github.com/fatedier/frp/models/config"
|
||||
"github.com/fatedier/frp/server/stats"
|
||||
frpNet "github.com/fatedier/frp/utils/net"
|
||||
"github.com/fatedier/frp/utils/util"
|
||||
"github.com/fatedier/frp/utils/vhost"
|
||||
|
||||
frpIo "github.com/fatedier/golib/io"
|
||||
)
|
||||
|
||||
type HttpProxy struct {
|
||||
BaseProxy
|
||||
cfg *config.HttpProxyConf
|
||||
|
||||
closeFuncs []func()
|
||||
}
|
||||
|
||||
func (pxy *HttpProxy) Run() (remoteAddr string, err error) {
|
||||
routeConfig := vhost.VhostRouteConfig{
|
||||
RewriteHost: pxy.cfg.HostHeaderRewrite,
|
||||
Headers: pxy.cfg.Headers,
|
||||
Username: pxy.cfg.HttpUser,
|
||||
Password: pxy.cfg.HttpPwd,
|
||||
CreateConnFn: pxy.GetRealConn,
|
||||
}
|
||||
|
||||
locations := pxy.cfg.Locations
|
||||
if len(locations) == 0 {
|
||||
locations = []string{""}
|
||||
}
|
||||
|
||||
addrs := make([]string, 0)
|
||||
for _, domain := range pxy.cfg.CustomDomains {
|
||||
routeConfig.Domain = domain
|
||||
for _, location := range locations {
|
||||
routeConfig.Location = location
|
||||
err = pxy.rc.HttpReverseProxy.Register(routeConfig)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
tmpDomain := routeConfig.Domain
|
||||
tmpLocation := routeConfig.Location
|
||||
addrs = append(addrs, util.CanonicalAddr(tmpDomain, int(g.GlbServerCfg.VhostHttpPort)))
|
||||
pxy.closeFuncs = append(pxy.closeFuncs, func() {
|
||||
pxy.rc.HttpReverseProxy.UnRegister(tmpDomain, tmpLocation)
|
||||
})
|
||||
pxy.Info("http proxy listen for host [%s] location [%s]", routeConfig.Domain, routeConfig.Location)
|
||||
}
|
||||
}
|
||||
|
||||
if pxy.cfg.SubDomain != "" {
|
||||
routeConfig.Domain = pxy.cfg.SubDomain + "." + g.GlbServerCfg.SubDomainHost
|
||||
for _, location := range locations {
|
||||
routeConfig.Location = location
|
||||
err = pxy.rc.HttpReverseProxy.Register(routeConfig)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
tmpDomain := routeConfig.Domain
|
||||
tmpLocation := routeConfig.Location
|
||||
addrs = append(addrs, util.CanonicalAddr(tmpDomain, g.GlbServerCfg.VhostHttpPort))
|
||||
pxy.closeFuncs = append(pxy.closeFuncs, func() {
|
||||
pxy.rc.HttpReverseProxy.UnRegister(tmpDomain, tmpLocation)
|
||||
})
|
||||
pxy.Info("http proxy listen for host [%s] location [%s]", routeConfig.Domain, routeConfig.Location)
|
||||
}
|
||||
}
|
||||
remoteAddr = strings.Join(addrs, ",")
|
||||
return
|
||||
}
|
||||
|
||||
func (pxy *HttpProxy) GetConf() config.ProxyConf {
|
||||
return pxy.cfg
|
||||
}
|
||||
|
||||
func (pxy *HttpProxy) GetRealConn() (workConn frpNet.Conn, err error) {
|
||||
tmpConn, errRet := pxy.GetWorkConnFromPool()
|
||||
if errRet != nil {
|
||||
err = errRet
|
||||
return
|
||||
}
|
||||
|
||||
var rwc io.ReadWriteCloser = tmpConn
|
||||
if pxy.cfg.UseEncryption {
|
||||
rwc, err = frpIo.WithEncryption(rwc, []byte(g.GlbServerCfg.Token))
|
||||
if err != nil {
|
||||
pxy.Error("create encryption stream error: %v", err)
|
||||
return
|
||||
}
|
||||
}
|
||||
if pxy.cfg.UseCompression {
|
||||
rwc = frpIo.WithCompression(rwc)
|
||||
}
|
||||
workConn = frpNet.WrapReadWriteCloserToConn(rwc, tmpConn)
|
||||
workConn = frpNet.WrapStatsConn(workConn, pxy.updateStatsAfterClosedConn)
|
||||
pxy.statsCollector.Mark(stats.TypeOpenConnection, &stats.OpenConnectionPayload{ProxyName: pxy.GetName()})
|
||||
return
|
||||
}
|
||||
|
||||
func (pxy *HttpProxy) updateStatsAfterClosedConn(totalRead, totalWrite int64) {
|
||||
name := pxy.GetName()
|
||||
pxy.statsCollector.Mark(stats.TypeCloseProxy, &stats.CloseConnectionPayload{ProxyName: name})
|
||||
pxy.statsCollector.Mark(stats.TypeAddTrafficIn, &stats.AddTrafficInPayload{
|
||||
ProxyName: name,
|
||||
TrafficBytes: totalWrite,
|
||||
})
|
||||
pxy.statsCollector.Mark(stats.TypeAddTrafficOut, &stats.AddTrafficOutPayload{
|
||||
ProxyName: name,
|
||||
TrafficBytes: totalRead,
|
||||
})
|
||||
}
|
||||
|
||||
func (pxy *HttpProxy) Close() {
|
||||
pxy.BaseProxy.Close()
|
||||
for _, closeFn := range pxy.closeFuncs {
|
||||
closeFn()
|
||||
}
|
||||
}
|
72
server/proxy/https.go
Normal file
72
server/proxy/https.go
Normal file
@@ -0,0 +1,72 @@
|
||||
// Copyright 2019 fatedier, fatedier@gmail.com
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
package proxy
|
||||
|
||||
import (
|
||||
"strings"
|
||||
|
||||
"github.com/fatedier/frp/g"
|
||||
"github.com/fatedier/frp/models/config"
|
||||
"github.com/fatedier/frp/utils/util"
|
||||
"github.com/fatedier/frp/utils/vhost"
|
||||
)
|
||||
|
||||
type HttpsProxy struct {
|
||||
BaseProxy
|
||||
cfg *config.HttpsProxyConf
|
||||
}
|
||||
|
||||
func (pxy *HttpsProxy) Run() (remoteAddr string, err error) {
|
||||
routeConfig := &vhost.VhostRouteConfig{}
|
||||
|
||||
addrs := make([]string, 0)
|
||||
for _, domain := range pxy.cfg.CustomDomains {
|
||||
routeConfig.Domain = domain
|
||||
l, errRet := pxy.rc.VhostHttpsMuxer.Listen(routeConfig)
|
||||
if errRet != nil {
|
||||
err = errRet
|
||||
return
|
||||
}
|
||||
l.AddLogPrefix(pxy.name)
|
||||
pxy.Info("https proxy listen for host [%s]", routeConfig.Domain)
|
||||
pxy.listeners = append(pxy.listeners, l)
|
||||
addrs = append(addrs, util.CanonicalAddr(routeConfig.Domain, g.GlbServerCfg.VhostHttpsPort))
|
||||
}
|
||||
|
||||
if pxy.cfg.SubDomain != "" {
|
||||
routeConfig.Domain = pxy.cfg.SubDomain + "." + g.GlbServerCfg.SubDomainHost
|
||||
l, errRet := pxy.rc.VhostHttpsMuxer.Listen(routeConfig)
|
||||
if errRet != nil {
|
||||
err = errRet
|
||||
return
|
||||
}
|
||||
l.AddLogPrefix(pxy.name)
|
||||
pxy.Info("https proxy listen for host [%s]", routeConfig.Domain)
|
||||
pxy.listeners = append(pxy.listeners, l)
|
||||
addrs = append(addrs, util.CanonicalAddr(routeConfig.Domain, int(g.GlbServerCfg.VhostHttpsPort)))
|
||||
}
|
||||
|
||||
pxy.startListenHandler(pxy, HandleUserTcpConnection)
|
||||
remoteAddr = strings.Join(addrs, ",")
|
||||
return
|
||||
}
|
||||
|
||||
func (pxy *HttpsProxy) GetConf() config.ProxyConf {
|
||||
return pxy.cfg
|
||||
}
|
||||
|
||||
func (pxy *HttpsProxy) Close() {
|
||||
pxy.BaseProxy.Close()
|
||||
}
|
250
server/proxy/proxy.go
Normal file
250
server/proxy/proxy.go
Normal file
@@ -0,0 +1,250 @@
|
||||
// Copyright 2017 fatedier, fatedier@gmail.com
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
package proxy
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"io"
|
||||
"sync"
|
||||
|
||||
"github.com/fatedier/frp/g"
|
||||
"github.com/fatedier/frp/models/config"
|
||||
"github.com/fatedier/frp/models/msg"
|
||||
"github.com/fatedier/frp/server/controller"
|
||||
"github.com/fatedier/frp/server/stats"
|
||||
"github.com/fatedier/frp/utils/log"
|
||||
frpNet "github.com/fatedier/frp/utils/net"
|
||||
|
||||
frpIo "github.com/fatedier/golib/io"
|
||||
)
|
||||
|
||||
type GetWorkConnFn func() (frpNet.Conn, error)
|
||||
|
||||
type Proxy interface {
|
||||
Run() (remoteAddr string, err error)
|
||||
GetName() string
|
||||
GetConf() config.ProxyConf
|
||||
GetWorkConnFromPool() (workConn frpNet.Conn, err error)
|
||||
GetUsedPortsNum() int
|
||||
Close()
|
||||
log.Logger
|
||||
}
|
||||
|
||||
type BaseProxy struct {
|
||||
name string
|
||||
rc *controller.ResourceController
|
||||
statsCollector stats.Collector
|
||||
listeners []frpNet.Listener
|
||||
usedPortsNum int
|
||||
poolCount int
|
||||
getWorkConnFn GetWorkConnFn
|
||||
|
||||
mu sync.RWMutex
|
||||
log.Logger
|
||||
}
|
||||
|
||||
func (pxy *BaseProxy) GetName() string {
|
||||
return pxy.name
|
||||
}
|
||||
|
||||
func (pxy *BaseProxy) GetUsedPortsNum() int {
|
||||
return pxy.usedPortsNum
|
||||
}
|
||||
|
||||
func (pxy *BaseProxy) Close() {
|
||||
pxy.Info("proxy closing")
|
||||
for _, l := range pxy.listeners {
|
||||
l.Close()
|
||||
}
|
||||
}
|
||||
|
||||
func (pxy *BaseProxy) GetWorkConnFromPool() (workConn frpNet.Conn, err error) {
|
||||
// try all connections from the pool
|
||||
for i := 0; i < pxy.poolCount+1; i++ {
|
||||
if workConn, err = pxy.getWorkConnFn(); err != nil {
|
||||
pxy.Warn("failed to get work connection: %v", err)
|
||||
return
|
||||
}
|
||||
pxy.Info("get a new work connection: [%s]", workConn.RemoteAddr().String())
|
||||
workConn.AddLogPrefix(pxy.GetName())
|
||||
|
||||
err := msg.WriteMsg(workConn, &msg.StartWorkConn{
|
||||
ProxyName: pxy.GetName(),
|
||||
})
|
||||
if err != nil {
|
||||
workConn.Warn("failed to send message to work connection from pool: %v, times: %d", err, i)
|
||||
workConn.Close()
|
||||
} else {
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
if err != nil {
|
||||
pxy.Error("try to get work connection failed in the end")
|
||||
return
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
// startListenHandler start a goroutine handler for each listener.
|
||||
// p: p will just be passed to handler(Proxy, frpNet.Conn).
|
||||
// handler: each proxy type can set different handler function to deal with connections accepted from listeners.
|
||||
func (pxy *BaseProxy) startListenHandler(p Proxy, handler func(Proxy, frpNet.Conn, stats.Collector)) {
|
||||
for _, listener := range pxy.listeners {
|
||||
go func(l frpNet.Listener) {
|
||||
for {
|
||||
// block
|
||||
// if listener is closed, err returned
|
||||
c, err := l.Accept()
|
||||
if err != nil {
|
||||
pxy.Info("listener is closed")
|
||||
return
|
||||
}
|
||||
pxy.Debug("get a user connection [%s]", c.RemoteAddr().String())
|
||||
go handler(p, c, pxy.statsCollector)
|
||||
}
|
||||
}(listener)
|
||||
}
|
||||
}
|
||||
|
||||
func NewProxy(runId string, rc *controller.ResourceController, statsCollector stats.Collector, poolCount int,
|
||||
getWorkConnFn GetWorkConnFn, pxyConf config.ProxyConf) (pxy Proxy, err error) {
|
||||
|
||||
basePxy := BaseProxy{
|
||||
name: pxyConf.GetBaseInfo().ProxyName,
|
||||
rc: rc,
|
||||
statsCollector: statsCollector,
|
||||
listeners: make([]frpNet.Listener, 0),
|
||||
poolCount: poolCount,
|
||||
getWorkConnFn: getWorkConnFn,
|
||||
Logger: log.NewPrefixLogger(runId),
|
||||
}
|
||||
switch cfg := pxyConf.(type) {
|
||||
case *config.TcpProxyConf:
|
||||
basePxy.usedPortsNum = 1
|
||||
pxy = &TcpProxy{
|
||||
BaseProxy: basePxy,
|
||||
cfg: cfg,
|
||||
}
|
||||
case *config.HttpProxyConf:
|
||||
pxy = &HttpProxy{
|
||||
BaseProxy: basePxy,
|
||||
cfg: cfg,
|
||||
}
|
||||
case *config.HttpsProxyConf:
|
||||
pxy = &HttpsProxy{
|
||||
BaseProxy: basePxy,
|
||||
cfg: cfg,
|
||||
}
|
||||
case *config.UdpProxyConf:
|
||||
basePxy.usedPortsNum = 1
|
||||
pxy = &UdpProxy{
|
||||
BaseProxy: basePxy,
|
||||
cfg: cfg,
|
||||
}
|
||||
case *config.StcpProxyConf:
|
||||
pxy = &StcpProxy{
|
||||
BaseProxy: basePxy,
|
||||
cfg: cfg,
|
||||
}
|
||||
case *config.XtcpProxyConf:
|
||||
pxy = &XtcpProxy{
|
||||
BaseProxy: basePxy,
|
||||
cfg: cfg,
|
||||
}
|
||||
default:
|
||||
return pxy, fmt.Errorf("proxy type not support")
|
||||
}
|
||||
pxy.AddLogPrefix(pxy.GetName())
|
||||
return
|
||||
}
|
||||
|
||||
// HandleUserTcpConnection is used for incoming tcp user connections.
|
||||
// It can be used for tcp, http, https type.
|
||||
func HandleUserTcpConnection(pxy Proxy, userConn frpNet.Conn, statsCollector stats.Collector) {
|
||||
defer userConn.Close()
|
||||
|
||||
// try all connections from the pool
|
||||
workConn, err := pxy.GetWorkConnFromPool()
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
defer workConn.Close()
|
||||
|
||||
var local io.ReadWriteCloser = workConn
|
||||
cfg := pxy.GetConf().GetBaseInfo()
|
||||
if cfg.UseEncryption {
|
||||
local, err = frpIo.WithEncryption(local, []byte(g.GlbServerCfg.Token))
|
||||
if err != nil {
|
||||
pxy.Error("create encryption stream error: %v", err)
|
||||
return
|
||||
}
|
||||
}
|
||||
if cfg.UseCompression {
|
||||
local = frpIo.WithCompression(local)
|
||||
}
|
||||
pxy.Debug("join connections, workConn(l[%s] r[%s]) userConn(l[%s] r[%s])", workConn.LocalAddr().String(),
|
||||
workConn.RemoteAddr().String(), userConn.LocalAddr().String(), userConn.RemoteAddr().String())
|
||||
|
||||
statsCollector.Mark(stats.TypeOpenConnection, &stats.OpenConnectionPayload{ProxyName: pxy.GetName()})
|
||||
inCount, outCount := frpIo.Join(local, userConn)
|
||||
statsCollector.Mark(stats.TypeCloseConnection, &stats.CloseConnectionPayload{ProxyName: pxy.GetName()})
|
||||
statsCollector.Mark(stats.TypeAddTrafficIn, &stats.AddTrafficInPayload{
|
||||
ProxyName: pxy.GetName(),
|
||||
TrafficBytes: inCount,
|
||||
})
|
||||
statsCollector.Mark(stats.TypeAddTrafficOut, &stats.AddTrafficOutPayload{
|
||||
ProxyName: pxy.GetName(),
|
||||
TrafficBytes: outCount,
|
||||
})
|
||||
pxy.Debug("join connections closed")
|
||||
}
|
||||
|
||||
type ProxyManager struct {
|
||||
// proxies indexed by proxy name
|
||||
pxys map[string]Proxy
|
||||
|
||||
mu sync.RWMutex
|
||||
}
|
||||
|
||||
func NewProxyManager() *ProxyManager {
|
||||
return &ProxyManager{
|
||||
pxys: make(map[string]Proxy),
|
||||
}
|
||||
}
|
||||
|
||||
func (pm *ProxyManager) Add(name string, pxy Proxy) error {
|
||||
pm.mu.Lock()
|
||||
defer pm.mu.Unlock()
|
||||
if _, ok := pm.pxys[name]; ok {
|
||||
return fmt.Errorf("proxy name [%s] is already in use", name)
|
||||
}
|
||||
|
||||
pm.pxys[name] = pxy
|
||||
return nil
|
||||
}
|
||||
|
||||
func (pm *ProxyManager) Del(name string) {
|
||||
pm.mu.Lock()
|
||||
defer pm.mu.Unlock()
|
||||
delete(pm.pxys, name)
|
||||
}
|
||||
|
||||
func (pm *ProxyManager) GetByName(name string) (pxy Proxy, ok bool) {
|
||||
pm.mu.RLock()
|
||||
defer pm.mu.RUnlock()
|
||||
pxy, ok = pm.pxys[name]
|
||||
return
|
||||
}
|
47
server/proxy/stcp.go
Normal file
47
server/proxy/stcp.go
Normal file
@@ -0,0 +1,47 @@
|
||||
// Copyright 2019 fatedier, fatedier@gmail.com
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
package proxy
|
||||
|
||||
import (
|
||||
"github.com/fatedier/frp/models/config"
|
||||
)
|
||||
|
||||
type StcpProxy struct {
|
||||
BaseProxy
|
||||
cfg *config.StcpProxyConf
|
||||
}
|
||||
|
||||
func (pxy *StcpProxy) Run() (remoteAddr string, err error) {
|
||||
listener, errRet := pxy.rc.VisitorManager.Listen(pxy.GetName(), pxy.cfg.Sk)
|
||||
if errRet != nil {
|
||||
err = errRet
|
||||
return
|
||||
}
|
||||
listener.AddLogPrefix(pxy.name)
|
||||
pxy.listeners = append(pxy.listeners, listener)
|
||||
pxy.Info("stcp proxy custom listen success")
|
||||
|
||||
pxy.startListenHandler(pxy, HandleUserTcpConnection)
|
||||
return
|
||||
}
|
||||
|
||||
func (pxy *StcpProxy) GetConf() config.ProxyConf {
|
||||
return pxy.cfg
|
||||
}
|
||||
|
||||
func (pxy *StcpProxy) Close() {
|
||||
pxy.BaseProxy.Close()
|
||||
pxy.rc.VisitorManager.CloseListener(pxy.GetName())
|
||||
}
|
84
server/proxy/tcp.go
Normal file
84
server/proxy/tcp.go
Normal file
@@ -0,0 +1,84 @@
|
||||
// Copyright 2019 fatedier, fatedier@gmail.com
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
package proxy
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
|
||||
"github.com/fatedier/frp/g"
|
||||
"github.com/fatedier/frp/models/config"
|
||||
frpNet "github.com/fatedier/frp/utils/net"
|
||||
)
|
||||
|
||||
type TcpProxy struct {
|
||||
BaseProxy
|
||||
cfg *config.TcpProxyConf
|
||||
|
||||
realPort int
|
||||
}
|
||||
|
||||
func (pxy *TcpProxy) Run() (remoteAddr string, err error) {
|
||||
if pxy.cfg.Group != "" {
|
||||
l, realPort, errRet := pxy.rc.TcpGroupCtl.Listen(pxy.name, pxy.cfg.Group, pxy.cfg.GroupKey, g.GlbServerCfg.ProxyBindAddr, pxy.cfg.RemotePort)
|
||||
if errRet != nil {
|
||||
err = errRet
|
||||
return
|
||||
}
|
||||
defer func() {
|
||||
if err != nil {
|
||||
l.Close()
|
||||
}
|
||||
}()
|
||||
pxy.realPort = realPort
|
||||
listener := frpNet.WrapLogListener(l)
|
||||
listener.AddLogPrefix(pxy.name)
|
||||
pxy.listeners = append(pxy.listeners, listener)
|
||||
pxy.Info("tcp proxy listen port [%d] in group [%s]", pxy.cfg.RemotePort, pxy.cfg.Group)
|
||||
} else {
|
||||
pxy.realPort, err = pxy.rc.TcpPortManager.Acquire(pxy.name, pxy.cfg.RemotePort)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
defer func() {
|
||||
if err != nil {
|
||||
pxy.rc.TcpPortManager.Release(pxy.realPort)
|
||||
}
|
||||
}()
|
||||
listener, errRet := frpNet.ListenTcp(g.GlbServerCfg.ProxyBindAddr, pxy.realPort)
|
||||
if errRet != nil {
|
||||
err = errRet
|
||||
return
|
||||
}
|
||||
listener.AddLogPrefix(pxy.name)
|
||||
pxy.listeners = append(pxy.listeners, listener)
|
||||
pxy.Info("tcp proxy listen port [%d]", pxy.cfg.RemotePort)
|
||||
}
|
||||
|
||||
pxy.cfg.RemotePort = pxy.realPort
|
||||
remoteAddr = fmt.Sprintf(":%d", pxy.realPort)
|
||||
pxy.startListenHandler(pxy, HandleUserTcpConnection)
|
||||
return
|
||||
}
|
||||
|
||||
func (pxy *TcpProxy) GetConf() config.ProxyConf {
|
||||
return pxy.cfg
|
||||
}
|
||||
|
||||
func (pxy *TcpProxy) Close() {
|
||||
pxy.BaseProxy.Close()
|
||||
if pxy.cfg.Group == "" {
|
||||
pxy.rc.TcpPortManager.Release(pxy.realPort)
|
||||
}
|
||||
}
|
225
server/proxy/udp.go
Normal file
225
server/proxy/udp.go
Normal file
@@ -0,0 +1,225 @@
|
||||
// Copyright 2019 fatedier, fatedier@gmail.com
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
package proxy
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"net"
|
||||
"time"
|
||||
|
||||
"github.com/fatedier/frp/g"
|
||||
"github.com/fatedier/frp/models/config"
|
||||
"github.com/fatedier/frp/models/msg"
|
||||
"github.com/fatedier/frp/models/proto/udp"
|
||||
"github.com/fatedier/frp/server/stats"
|
||||
|
||||
"github.com/fatedier/golib/errors"
|
||||
)
|
||||
|
||||
type UdpProxy struct {
|
||||
BaseProxy
|
||||
cfg *config.UdpProxyConf
|
||||
|
||||
realPort int
|
||||
|
||||
// udpConn is the listener of udp packages
|
||||
udpConn *net.UDPConn
|
||||
|
||||
// there are always only one workConn at the same time
|
||||
// get another one if it closed
|
||||
workConn net.Conn
|
||||
|
||||
// sendCh is used for sending packages to workConn
|
||||
sendCh chan *msg.UdpPacket
|
||||
|
||||
// readCh is used for reading packages from workConn
|
||||
readCh chan *msg.UdpPacket
|
||||
|
||||
// checkCloseCh is used for watching if workConn is closed
|
||||
checkCloseCh chan int
|
||||
|
||||
isClosed bool
|
||||
}
|
||||
|
||||
func (pxy *UdpProxy) Run() (remoteAddr string, err error) {
|
||||
pxy.realPort, err = pxy.rc.UdpPortManager.Acquire(pxy.name, pxy.cfg.RemotePort)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
defer func() {
|
||||
if err != nil {
|
||||
pxy.rc.UdpPortManager.Release(pxy.realPort)
|
||||
}
|
||||
}()
|
||||
|
||||
remoteAddr = fmt.Sprintf(":%d", pxy.realPort)
|
||||
pxy.cfg.RemotePort = pxy.realPort
|
||||
addr, errRet := net.ResolveUDPAddr("udp", fmt.Sprintf("%s:%d", g.GlbServerCfg.ProxyBindAddr, pxy.realPort))
|
||||
if errRet != nil {
|
||||
err = errRet
|
||||
return
|
||||
}
|
||||
udpConn, errRet := net.ListenUDP("udp", addr)
|
||||
if errRet != nil {
|
||||
err = errRet
|
||||
pxy.Warn("listen udp port error: %v", err)
|
||||
return
|
||||
}
|
||||
pxy.Info("udp proxy listen port [%d]", pxy.cfg.RemotePort)
|
||||
|
||||
pxy.udpConn = udpConn
|
||||
pxy.sendCh = make(chan *msg.UdpPacket, 1024)
|
||||
pxy.readCh = make(chan *msg.UdpPacket, 1024)
|
||||
pxy.checkCloseCh = make(chan int)
|
||||
|
||||
// read message from workConn, if it returns any error, notify proxy to start a new workConn
|
||||
workConnReaderFn := func(conn net.Conn) {
|
||||
for {
|
||||
var (
|
||||
rawMsg msg.Message
|
||||
errRet error
|
||||
)
|
||||
pxy.Trace("loop waiting message from udp workConn")
|
||||
// client will send heartbeat in workConn for keeping alive
|
||||
conn.SetReadDeadline(time.Now().Add(time.Duration(60) * time.Second))
|
||||
if rawMsg, errRet = msg.ReadMsg(conn); errRet != nil {
|
||||
pxy.Warn("read from workConn for udp error: %v", errRet)
|
||||
conn.Close()
|
||||
// notify proxy to start a new work connection
|
||||
// ignore error here, it means the proxy is closed
|
||||
errors.PanicToError(func() {
|
||||
pxy.checkCloseCh <- 1
|
||||
})
|
||||
return
|
||||
}
|
||||
conn.SetReadDeadline(time.Time{})
|
||||
switch m := rawMsg.(type) {
|
||||
case *msg.Ping:
|
||||
pxy.Trace("udp work conn get ping message")
|
||||
continue
|
||||
case *msg.UdpPacket:
|
||||
if errRet := errors.PanicToError(func() {
|
||||
pxy.Trace("get udp message from workConn: %s", m.Content)
|
||||
pxy.readCh <- m
|
||||
pxy.statsCollector.Mark(stats.TypeAddTrafficOut, &stats.AddTrafficOutPayload{
|
||||
ProxyName: pxy.GetName(),
|
||||
TrafficBytes: int64(len(m.Content)),
|
||||
})
|
||||
}); errRet != nil {
|
||||
conn.Close()
|
||||
pxy.Info("reader goroutine for udp work connection closed")
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// send message to workConn
|
||||
workConnSenderFn := func(conn net.Conn, ctx context.Context) {
|
||||
var errRet error
|
||||
for {
|
||||
select {
|
||||
case udpMsg, ok := <-pxy.sendCh:
|
||||
if !ok {
|
||||
pxy.Info("sender goroutine for udp work connection closed")
|
||||
return
|
||||
}
|
||||
if errRet = msg.WriteMsg(conn, udpMsg); errRet != nil {
|
||||
pxy.Info("sender goroutine for udp work connection closed: %v", errRet)
|
||||
conn.Close()
|
||||
return
|
||||
} else {
|
||||
pxy.Trace("send message to udp workConn: %s", udpMsg.Content)
|
||||
pxy.statsCollector.Mark(stats.TypeAddTrafficIn, &stats.AddTrafficInPayload{
|
||||
ProxyName: pxy.GetName(),
|
||||
TrafficBytes: int64(len(udpMsg.Content)),
|
||||
})
|
||||
continue
|
||||
}
|
||||
case <-ctx.Done():
|
||||
pxy.Info("sender goroutine for udp work connection closed")
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
go func() {
|
||||
// Sleep a while for waiting control send the NewProxyResp to client.
|
||||
time.Sleep(500 * time.Millisecond)
|
||||
for {
|
||||
workConn, err := pxy.GetWorkConnFromPool()
|
||||
if err != nil {
|
||||
time.Sleep(1 * time.Second)
|
||||
// check if proxy is closed
|
||||
select {
|
||||
case _, ok := <-pxy.checkCloseCh:
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
default:
|
||||
}
|
||||
continue
|
||||
}
|
||||
// close the old workConn and replac it with a new one
|
||||
if pxy.workConn != nil {
|
||||
pxy.workConn.Close()
|
||||
}
|
||||
pxy.workConn = workConn
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
go workConnReaderFn(workConn)
|
||||
go workConnSenderFn(workConn, ctx)
|
||||
_, ok := <-pxy.checkCloseCh
|
||||
cancel()
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
}
|
||||
}()
|
||||
|
||||
// Read from user connections and send wrapped udp message to sendCh (forwarded by workConn).
|
||||
// Client will transfor udp message to local udp service and waiting for response for a while.
|
||||
// Response will be wrapped to be forwarded by work connection to server.
|
||||
// Close readCh and sendCh at the end.
|
||||
go func() {
|
||||
udp.ForwardUserConn(udpConn, pxy.readCh, pxy.sendCh)
|
||||
pxy.Close()
|
||||
}()
|
||||
return remoteAddr, nil
|
||||
}
|
||||
|
||||
func (pxy *UdpProxy) GetConf() config.ProxyConf {
|
||||
return pxy.cfg
|
||||
}
|
||||
|
||||
func (pxy *UdpProxy) Close() {
|
||||
pxy.mu.Lock()
|
||||
defer pxy.mu.Unlock()
|
||||
if !pxy.isClosed {
|
||||
pxy.isClosed = true
|
||||
|
||||
pxy.BaseProxy.Close()
|
||||
if pxy.workConn != nil {
|
||||
pxy.workConn.Close()
|
||||
}
|
||||
pxy.udpConn.Close()
|
||||
|
||||
// all channels only closed here
|
||||
close(pxy.checkCloseCh)
|
||||
close(pxy.readCh)
|
||||
close(pxy.sendCh)
|
||||
}
|
||||
pxy.rc.UdpPortManager.Release(pxy.realPort)
|
||||
}
|
73
server/proxy/xtcp.go
Normal file
73
server/proxy/xtcp.go
Normal file
@@ -0,0 +1,73 @@
|
||||
// Copyright 2019 fatedier, fatedier@gmail.com
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
package proxy
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
|
||||
"github.com/fatedier/frp/models/config"
|
||||
"github.com/fatedier/frp/models/msg"
|
||||
|
||||
"github.com/fatedier/golib/errors"
|
||||
)
|
||||
|
||||
type XtcpProxy struct {
|
||||
BaseProxy
|
||||
cfg *config.XtcpProxyConf
|
||||
|
||||
closeCh chan struct{}
|
||||
}
|
||||
|
||||
func (pxy *XtcpProxy) Run() (remoteAddr string, err error) {
|
||||
if pxy.rc.NatHoleController == nil {
|
||||
pxy.Error("udp port for xtcp is not specified.")
|
||||
err = fmt.Errorf("xtcp is not supported in frps")
|
||||
return
|
||||
}
|
||||
sidCh := pxy.rc.NatHoleController.ListenClient(pxy.GetName(), pxy.cfg.Sk)
|
||||
go func() {
|
||||
for {
|
||||
select {
|
||||
case <-pxy.closeCh:
|
||||
break
|
||||
case sid := <-sidCh:
|
||||
workConn, errRet := pxy.GetWorkConnFromPool()
|
||||
if errRet != nil {
|
||||
continue
|
||||
}
|
||||
m := &msg.NatHoleSid{
|
||||
Sid: sid,
|
||||
}
|
||||
errRet = msg.WriteMsg(workConn, m)
|
||||
if errRet != nil {
|
||||
pxy.Warn("write nat hole sid package error, %v", errRet)
|
||||
}
|
||||
}
|
||||
}
|
||||
}()
|
||||
return
|
||||
}
|
||||
|
||||
func (pxy *XtcpProxy) GetConf() config.ProxyConf {
|
||||
return pxy.cfg
|
||||
}
|
||||
|
||||
func (pxy *XtcpProxy) Close() {
|
||||
pxy.BaseProxy.Close()
|
||||
pxy.rc.NatHoleController.CloseClient(pxy.GetName())
|
||||
errors.PanicToError(func() {
|
||||
close(pxy.closeCh)
|
||||
})
|
||||
}
|
@@ -15,6 +15,7 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"fmt"
|
||||
"io/ioutil"
|
||||
"net"
|
||||
@@ -24,6 +25,12 @@ import (
|
||||
"github.com/fatedier/frp/assets"
|
||||
"github.com/fatedier/frp/g"
|
||||
"github.com/fatedier/frp/models/msg"
|
||||
"github.com/fatedier/frp/models/nathole"
|
||||
"github.com/fatedier/frp/server/controller"
|
||||
"github.com/fatedier/frp/server/group"
|
||||
"github.com/fatedier/frp/server/ports"
|
||||
"github.com/fatedier/frp/server/proxy"
|
||||
"github.com/fatedier/frp/server/stats"
|
||||
"github.com/fatedier/frp/utils/log"
|
||||
frpNet "github.com/fatedier/frp/utils/net"
|
||||
"github.com/fatedier/frp/utils/util"
|
||||
@@ -40,51 +47,48 @@ const (
|
||||
|
||||
var ServerService *Service
|
||||
|
||||
// Server service.
|
||||
// Server service
|
||||
type Service struct {
|
||||
// Dispatch connections to different handlers listen on same port.
|
||||
// Dispatch connections to different handlers listen on same port
|
||||
muxer *mux.Mux
|
||||
|
||||
// Accept connections from client.
|
||||
// Accept connections from client
|
||||
listener frpNet.Listener
|
||||
|
||||
// Accept connections using kcp.
|
||||
// Accept connections using kcp
|
||||
kcpListener frpNet.Listener
|
||||
|
||||
// For https proxies, route requests to different clients by hostname and other infomation.
|
||||
VhostHttpsMuxer *vhost.HttpsMuxer
|
||||
// Accept connections using websocket
|
||||
websocketListener frpNet.Listener
|
||||
|
||||
httpReverseProxy *vhost.HttpReverseProxy
|
||||
|
||||
// Manage all controllers.
|
||||
// Manage all controllers
|
||||
ctlManager *ControlManager
|
||||
|
||||
// Manage all proxies.
|
||||
pxyManager *ProxyManager
|
||||
// Manage all proxies
|
||||
pxyManager *proxy.ProxyManager
|
||||
|
||||
// Manage all visitor listeners.
|
||||
visitorManager *VisitorManager
|
||||
// All resource managers and controllers
|
||||
rc *controller.ResourceController
|
||||
|
||||
// Manage all tcp ports.
|
||||
tcpPortManager *PortManager
|
||||
|
||||
// Manage all udp ports.
|
||||
udpPortManager *PortManager
|
||||
|
||||
// Controller for nat hole connections.
|
||||
natHoleController *NatHoleController
|
||||
// stats collector to store server and proxies stats info
|
||||
statsCollector stats.Collector
|
||||
}
|
||||
|
||||
func NewService() (svr *Service, err error) {
|
||||
cfg := &g.GlbServerCfg.ServerCommonConf
|
||||
svr = &Service{
|
||||
ctlManager: NewControlManager(),
|
||||
pxyManager: NewProxyManager(),
|
||||
visitorManager: NewVisitorManager(),
|
||||
tcpPortManager: NewPortManager("tcp", cfg.ProxyBindAddr, cfg.AllowPorts),
|
||||
udpPortManager: NewPortManager("udp", cfg.ProxyBindAddr, cfg.AllowPorts),
|
||||
ctlManager: NewControlManager(),
|
||||
pxyManager: proxy.NewProxyManager(),
|
||||
rc: &controller.ResourceController{
|
||||
VisitorManager: controller.NewVisitorManager(),
|
||||
TcpPortManager: ports.NewPortManager("tcp", cfg.ProxyBindAddr, cfg.AllowPorts),
|
||||
UdpPortManager: ports.NewPortManager("udp", cfg.ProxyBindAddr, cfg.AllowPorts),
|
||||
},
|
||||
}
|
||||
|
||||
// Init group controller
|
||||
svr.rc.TcpGroupCtl = group.NewTcpGroupCtl(svr.rc.TcpPortManager)
|
||||
|
||||
// Init assets.
|
||||
err = assets.Load(cfg.AssetsDir)
|
||||
if err != nil {
|
||||
@@ -103,9 +107,6 @@ func NewService() (svr *Service, err error) {
|
||||
if cfg.BindPort == cfg.VhostHttpsPort {
|
||||
httpsMuxOn = true
|
||||
}
|
||||
if httpMuxOn || httpsMuxOn {
|
||||
svr.muxer = mux.NewMux()
|
||||
}
|
||||
}
|
||||
|
||||
// Listen for accepting connections from client.
|
||||
@@ -114,10 +115,11 @@ func NewService() (svr *Service, err error) {
|
||||
err = fmt.Errorf("Create server listener error, %v", err)
|
||||
return
|
||||
}
|
||||
if svr.muxer != nil {
|
||||
go svr.muxer.Serve(ln)
|
||||
ln = svr.muxer.DefaultListener()
|
||||
}
|
||||
|
||||
svr.muxer = mux.NewMux(ln)
|
||||
go svr.muxer.Serve()
|
||||
ln = svr.muxer.DefaultListener()
|
||||
|
||||
svr.listener = frpNet.WrapLogListener(ln)
|
||||
log.Info("frps tcp listen on %s:%d", cfg.BindAddr, cfg.BindPort)
|
||||
|
||||
@@ -131,10 +133,19 @@ func NewService() (svr *Service, err error) {
|
||||
log.Info("frps kcp listen on udp %s:%d", cfg.BindAddr, cfg.KcpBindPort)
|
||||
}
|
||||
|
||||
// Listen for accepting connections from client using websocket protocol.
|
||||
websocketPrefix := []byte("GET " + frpNet.FrpWebsocketPath)
|
||||
websocketLn := svr.muxer.Listen(0, uint32(len(websocketPrefix)), func(data []byte) bool {
|
||||
return bytes.Equal(data, websocketPrefix)
|
||||
})
|
||||
svr.websocketListener = frpNet.NewWebsocketListener(websocketLn)
|
||||
|
||||
// Create http vhost muxer.
|
||||
if cfg.VhostHttpPort > 0 {
|
||||
rp := vhost.NewHttpReverseProxy()
|
||||
svr.httpReverseProxy = rp
|
||||
rp := vhost.NewHttpReverseProxy(vhost.HttpReverseProxyOptions{
|
||||
ResponseHeaderTimeoutS: cfg.VhostHttpTimeout,
|
||||
})
|
||||
svr.rc.HttpReverseProxy = rp
|
||||
|
||||
address := fmt.Sprintf("%s:%d", cfg.ProxyBindAddr, cfg.VhostHttpPort)
|
||||
server := &http.Server{
|
||||
@@ -143,7 +154,7 @@ func NewService() (svr *Service, err error) {
|
||||
}
|
||||
var l net.Listener
|
||||
if httpMuxOn {
|
||||
l = svr.muxer.ListenHttp(0)
|
||||
l = svr.muxer.ListenHttp(1)
|
||||
} else {
|
||||
l, err = net.Listen("tcp", address)
|
||||
if err != nil {
|
||||
@@ -159,7 +170,7 @@ func NewService() (svr *Service, err error) {
|
||||
if cfg.VhostHttpsPort > 0 {
|
||||
var l net.Listener
|
||||
if httpsMuxOn {
|
||||
l = svr.muxer.ListenHttps(0)
|
||||
l = svr.muxer.ListenHttps(1)
|
||||
} else {
|
||||
l, err = net.Listen("tcp", fmt.Sprintf("%s:%d", cfg.ProxyBindAddr, cfg.VhostHttpsPort))
|
||||
if err != nil {
|
||||
@@ -168,7 +179,7 @@ func NewService() (svr *Service, err error) {
|
||||
}
|
||||
}
|
||||
|
||||
svr.VhostHttpsMuxer, err = vhost.NewHttpsMuxer(frpNet.WrapLogListener(l), 30*time.Second)
|
||||
svr.rc.VhostHttpsMuxer, err = vhost.NewHttpsMuxer(frpNet.WrapLogListener(l), 30*time.Second)
|
||||
if err != nil {
|
||||
err = fmt.Errorf("Create vhost httpsMuxer error, %v", err)
|
||||
return
|
||||
@@ -178,38 +189,44 @@ func NewService() (svr *Service, err error) {
|
||||
|
||||
// Create nat hole controller.
|
||||
if cfg.BindUdpPort > 0 {
|
||||
var nc *NatHoleController
|
||||
var nc *nathole.NatHoleController
|
||||
addr := fmt.Sprintf("%s:%d", cfg.BindAddr, cfg.BindUdpPort)
|
||||
nc, err = NewNatHoleController(addr)
|
||||
nc, err = nathole.NewNatHoleController(addr)
|
||||
if err != nil {
|
||||
err = fmt.Errorf("Create nat hole controller error, %v", err)
|
||||
return
|
||||
}
|
||||
svr.natHoleController = nc
|
||||
svr.rc.NatHoleController = nc
|
||||
log.Info("nat hole udp service listen on %s:%d", cfg.BindAddr, cfg.BindUdpPort)
|
||||
}
|
||||
|
||||
var statsEnable bool
|
||||
// Create dashboard web server.
|
||||
if cfg.DashboardPort > 0 {
|
||||
err = RunDashboardServer(cfg.DashboardAddr, cfg.DashboardPort)
|
||||
err = svr.RunDashboardServer(cfg.DashboardAddr, cfg.DashboardPort)
|
||||
if err != nil {
|
||||
err = fmt.Errorf("Create dashboard web server error, %v", err)
|
||||
return
|
||||
}
|
||||
log.Info("Dashboard listen on %s:%d", cfg.DashboardAddr, cfg.DashboardPort)
|
||||
statsEnable = true
|
||||
}
|
||||
|
||||
svr.statsCollector = stats.NewInternalCollector(statsEnable)
|
||||
return
|
||||
}
|
||||
|
||||
func (svr *Service) Run() {
|
||||
if svr.natHoleController != nil {
|
||||
go svr.natHoleController.Run()
|
||||
if svr.rc.NatHoleController != nil {
|
||||
go svr.rc.NatHoleController.Run()
|
||||
}
|
||||
if g.GlbServerCfg.KcpBindPort > 0 {
|
||||
go svr.HandleListener(svr.kcpListener)
|
||||
}
|
||||
svr.HandleListener(svr.listener)
|
||||
|
||||
go svr.HandleListener(svr.websocketListener)
|
||||
|
||||
svr.HandleListener(svr.listener)
|
||||
}
|
||||
|
||||
func (svr *Service) HandleListener(l frpNet.Listener) {
|
||||
@@ -270,6 +287,7 @@ func (svr *Service) HandleListener(l frpNet.Listener) {
|
||||
|
||||
if g.GlbServerCfg.TcpMux {
|
||||
fmuxCfg := fmux.DefaultConfig()
|
||||
fmuxCfg.KeepAliveInterval = 20 * time.Second
|
||||
fmuxCfg.LogOutput = ioutil.Discard
|
||||
session, err := fmux.Server(frpConn, fmuxCfg)
|
||||
if err != nil {
|
||||
@@ -306,11 +324,6 @@ func (svr *Service) RegisterControl(ctlConn frpNet.Conn, loginMsg *msg.Login) (e
|
||||
}
|
||||
|
||||
// Check auth.
|
||||
nowTime := time.Now().Unix()
|
||||
if g.GlbServerCfg.AuthTimeout != 0 && nowTime-loginMsg.Timestamp > g.GlbServerCfg.AuthTimeout {
|
||||
err = fmt.Errorf("authorization timeout")
|
||||
return
|
||||
}
|
||||
if util.GetAuthKey(g.GlbServerCfg.Token, loginMsg.Timestamp) != loginMsg.PrivilegeKey {
|
||||
err = fmt.Errorf("authorization failed")
|
||||
return
|
||||
@@ -325,7 +338,7 @@ func (svr *Service) RegisterControl(ctlConn frpNet.Conn, loginMsg *msg.Login) (e
|
||||
}
|
||||
}
|
||||
|
||||
ctl := NewControl(svr, ctlConn, loginMsg)
|
||||
ctl := NewControl(svr.rc, svr.pxyManager, svr.statsCollector, ctlConn, loginMsg)
|
||||
|
||||
if oldCtl := svr.ctlManager.Add(loginMsg.RunId, ctl); oldCtl != nil {
|
||||
oldCtl.allShutdown.WaitDone()
|
||||
@@ -335,7 +348,13 @@ func (svr *Service) RegisterControl(ctlConn frpNet.Conn, loginMsg *msg.Login) (e
|
||||
ctl.Start()
|
||||
|
||||
// for statistics
|
||||
StatsNewClient()
|
||||
svr.statsCollector.Mark(stats.TypeNewClient, &stats.NewClientPayload{})
|
||||
|
||||
go func() {
|
||||
// block until control closed
|
||||
ctl.WaitClosed()
|
||||
svr.ctlManager.Del(loginMsg.RunId)
|
||||
}()
|
||||
return
|
||||
}
|
||||
|
||||
@@ -351,14 +370,6 @@ func (svr *Service) RegisterWorkConn(workConn frpNet.Conn, newMsg *msg.NewWorkCo
|
||||
}
|
||||
|
||||
func (svr *Service) RegisterVisitorConn(visitorConn frpNet.Conn, newMsg *msg.NewVisitorConn) error {
|
||||
return svr.visitorManager.NewConn(newMsg.ProxyName, visitorConn, newMsg.Timestamp, newMsg.SignKey,
|
||||
return svr.rc.VisitorManager.NewConn(newMsg.ProxyName, visitorConn, newMsg.Timestamp, newMsg.SignKey,
|
||||
newMsg.UseEncryption, newMsg.UseCompression)
|
||||
}
|
||||
|
||||
func (svr *Service) RegisterProxy(name string, pxy Proxy) error {
|
||||
return svr.pxyManager.Add(name, pxy)
|
||||
}
|
||||
|
||||
func (svr *Service) DelProxy(name string) {
|
||||
svr.pxyManager.Del(name)
|
||||
}
|
||||
|
273
server/stats/internal.go
Normal file
273
server/stats/internal.go
Normal file
@@ -0,0 +1,273 @@
|
||||
// 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 stats
|
||||
|
||||
import (
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/fatedier/frp/utils/log"
|
||||
"github.com/fatedier/frp/utils/metric"
|
||||
)
|
||||
|
||||
type internalCollector struct {
|
||||
enable bool
|
||||
info *ServerStatistics
|
||||
mu sync.Mutex
|
||||
}
|
||||
|
||||
func NewInternalCollector(enable bool) Collector {
|
||||
return &internalCollector{
|
||||
enable: enable,
|
||||
info: &ServerStatistics{
|
||||
TotalTrafficIn: metric.NewDateCounter(ReserveDays),
|
||||
TotalTrafficOut: metric.NewDateCounter(ReserveDays),
|
||||
CurConns: metric.NewCounter(),
|
||||
|
||||
ClientCounts: metric.NewCounter(),
|
||||
ProxyTypeCounts: make(map[string]metric.Counter),
|
||||
|
||||
ProxyStatistics: make(map[string]*ProxyStatistics),
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
func (collector *internalCollector) Run() error {
|
||||
go func() {
|
||||
for {
|
||||
time.Sleep(12 * time.Hour)
|
||||
log.Debug("start to clear useless proxy statistics data...")
|
||||
collector.ClearUselessInfo()
|
||||
log.Debug("finish to clear useless proxy statistics data")
|
||||
}
|
||||
}()
|
||||
return nil
|
||||
}
|
||||
|
||||
func (collector *internalCollector) ClearUselessInfo() {
|
||||
// To check if there are proxies that closed than 7 days and drop them.
|
||||
collector.mu.Lock()
|
||||
defer collector.mu.Unlock()
|
||||
for name, data := range collector.info.ProxyStatistics {
|
||||
if !data.LastCloseTime.IsZero() && time.Since(data.LastCloseTime) > time.Duration(7*24)*time.Hour {
|
||||
delete(collector.info.ProxyStatistics, name)
|
||||
log.Trace("clear proxy [%s]'s statistics data, lastCloseTime: [%s]", name, data.LastCloseTime.String())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (collector *internalCollector) Mark(statsType StatsType, payload interface{}) {
|
||||
if !collector.enable {
|
||||
return
|
||||
}
|
||||
|
||||
switch v := payload.(type) {
|
||||
case *NewClientPayload:
|
||||
collector.newClient(v)
|
||||
case *CloseClientPayload:
|
||||
collector.closeClient(v)
|
||||
case *OpenConnectionPayload:
|
||||
collector.openConnection(v)
|
||||
case *CloseConnectionPayload:
|
||||
collector.closeConnection(v)
|
||||
case *AddTrafficInPayload:
|
||||
collector.addTrafficIn(v)
|
||||
case *AddTrafficOutPayload:
|
||||
collector.addTrafficOut(v)
|
||||
}
|
||||
}
|
||||
|
||||
func (collector *internalCollector) newClient(payload *NewClientPayload) {
|
||||
collector.info.ClientCounts.Inc(1)
|
||||
}
|
||||
|
||||
func (collector *internalCollector) closeClient(payload *CloseClientPayload) {
|
||||
collector.info.ClientCounts.Dec(1)
|
||||
}
|
||||
|
||||
func (collector *internalCollector) newProxy(payload *NewProxyPayload) {
|
||||
collector.mu.Lock()
|
||||
defer collector.mu.Unlock()
|
||||
counter, ok := collector.info.ProxyTypeCounts[payload.ProxyType]
|
||||
if !ok {
|
||||
counter = metric.NewCounter()
|
||||
}
|
||||
counter.Inc(1)
|
||||
collector.info.ProxyTypeCounts[payload.ProxyType] = counter
|
||||
|
||||
proxyStats, ok := collector.info.ProxyStatistics[payload.Name]
|
||||
if !(ok && proxyStats.ProxyType == payload.ProxyType) {
|
||||
proxyStats = &ProxyStatistics{
|
||||
Name: payload.Name,
|
||||
ProxyType: payload.ProxyType,
|
||||
CurConns: metric.NewCounter(),
|
||||
TrafficIn: metric.NewDateCounter(ReserveDays),
|
||||
TrafficOut: metric.NewDateCounter(ReserveDays),
|
||||
}
|
||||
collector.info.ProxyStatistics[payload.Name] = proxyStats
|
||||
}
|
||||
proxyStats.LastStartTime = time.Now()
|
||||
}
|
||||
|
||||
func (collector *internalCollector) closeProxy(payload *CloseProxyPayload) {
|
||||
collector.mu.Lock()
|
||||
defer collector.mu.Unlock()
|
||||
if counter, ok := collector.info.ProxyTypeCounts[payload.ProxyType]; ok {
|
||||
counter.Dec(1)
|
||||
}
|
||||
if proxyStats, ok := collector.info.ProxyStatistics[payload.Name]; ok {
|
||||
proxyStats.LastCloseTime = time.Now()
|
||||
}
|
||||
}
|
||||
|
||||
func (collector *internalCollector) openConnection(payload *OpenConnectionPayload) {
|
||||
collector.info.CurConns.Inc(1)
|
||||
|
||||
collector.mu.Lock()
|
||||
defer collector.mu.Unlock()
|
||||
proxyStats, ok := collector.info.ProxyStatistics[payload.ProxyName]
|
||||
if ok {
|
||||
proxyStats.CurConns.Inc(1)
|
||||
collector.info.ProxyStatistics[payload.ProxyName] = proxyStats
|
||||
}
|
||||
}
|
||||
|
||||
func (collector *internalCollector) closeConnection(payload *CloseConnectionPayload) {
|
||||
collector.info.CurConns.Dec(1)
|
||||
|
||||
collector.mu.Lock()
|
||||
defer collector.mu.Unlock()
|
||||
proxyStats, ok := collector.info.ProxyStatistics[payload.ProxyName]
|
||||
if ok {
|
||||
proxyStats.CurConns.Dec(1)
|
||||
collector.info.ProxyStatistics[payload.ProxyName] = proxyStats
|
||||
}
|
||||
}
|
||||
|
||||
func (collector *internalCollector) addTrafficIn(payload *AddTrafficInPayload) {
|
||||
collector.info.TotalTrafficIn.Inc(payload.TrafficBytes)
|
||||
|
||||
collector.mu.Lock()
|
||||
defer collector.mu.Unlock()
|
||||
|
||||
proxyStats, ok := collector.info.ProxyStatistics[payload.ProxyName]
|
||||
if ok {
|
||||
proxyStats.TrafficIn.Inc(payload.TrafficBytes)
|
||||
collector.info.ProxyStatistics[payload.ProxyName] = proxyStats
|
||||
}
|
||||
}
|
||||
|
||||
func (collector *internalCollector) addTrafficOut(payload *AddTrafficOutPayload) {
|
||||
collector.info.TotalTrafficOut.Inc(payload.TrafficBytes)
|
||||
|
||||
collector.mu.Lock()
|
||||
defer collector.mu.Unlock()
|
||||
|
||||
proxyStats, ok := collector.info.ProxyStatistics[payload.ProxyName]
|
||||
if ok {
|
||||
proxyStats.TrafficOut.Inc(payload.TrafficBytes)
|
||||
collector.info.ProxyStatistics[payload.ProxyName] = proxyStats
|
||||
}
|
||||
}
|
||||
|
||||
func (collector *internalCollector) GetServer() *ServerStats {
|
||||
collector.mu.Lock()
|
||||
defer collector.mu.Unlock()
|
||||
s := &ServerStats{
|
||||
TotalTrafficIn: collector.info.TotalTrafficIn.TodayCount(),
|
||||
TotalTrafficOut: collector.info.TotalTrafficOut.TodayCount(),
|
||||
CurConns: collector.info.CurConns.Count(),
|
||||
ClientCounts: collector.info.ClientCounts.Count(),
|
||||
ProxyTypeCounts: make(map[string]int64),
|
||||
}
|
||||
for k, v := range collector.info.ProxyTypeCounts {
|
||||
s.ProxyTypeCounts[k] = v.Count()
|
||||
}
|
||||
return s
|
||||
}
|
||||
|
||||
func (collector *internalCollector) GetProxiesByType(proxyType string) []*ProxyStats {
|
||||
res := make([]*ProxyStats, 0)
|
||||
collector.mu.Lock()
|
||||
defer collector.mu.Unlock()
|
||||
|
||||
for name, proxyStats := range collector.info.ProxyStatistics {
|
||||
if proxyStats.ProxyType != proxyType {
|
||||
continue
|
||||
}
|
||||
|
||||
ps := &ProxyStats{
|
||||
Name: name,
|
||||
Type: proxyStats.ProxyType,
|
||||
TodayTrafficIn: proxyStats.TrafficIn.TodayCount(),
|
||||
TodayTrafficOut: proxyStats.TrafficOut.TodayCount(),
|
||||
CurConns: proxyStats.CurConns.Count(),
|
||||
}
|
||||
if !proxyStats.LastStartTime.IsZero() {
|
||||
ps.LastStartTime = proxyStats.LastStartTime.Format("01-02 15:04:05")
|
||||
}
|
||||
if !proxyStats.LastCloseTime.IsZero() {
|
||||
ps.LastCloseTime = proxyStats.LastCloseTime.Format("01-02 15:04:05")
|
||||
}
|
||||
res = append(res, ps)
|
||||
}
|
||||
return res
|
||||
}
|
||||
|
||||
func (collector *internalCollector) GetProxiesByTypeAndName(proxyType string, proxyName string) (res *ProxyStats) {
|
||||
collector.mu.Lock()
|
||||
defer collector.mu.Unlock()
|
||||
|
||||
for name, proxyStats := range collector.info.ProxyStatistics {
|
||||
if proxyStats.ProxyType != proxyType {
|
||||
continue
|
||||
}
|
||||
|
||||
if name != proxyName {
|
||||
continue
|
||||
}
|
||||
|
||||
res = &ProxyStats{
|
||||
Name: name,
|
||||
Type: proxyStats.ProxyType,
|
||||
TodayTrafficIn: proxyStats.TrafficIn.TodayCount(),
|
||||
TodayTrafficOut: proxyStats.TrafficOut.TodayCount(),
|
||||
CurConns: proxyStats.CurConns.Count(),
|
||||
}
|
||||
if !proxyStats.LastStartTime.IsZero() {
|
||||
res.LastStartTime = proxyStats.LastStartTime.Format("01-02 15:04:05")
|
||||
}
|
||||
if !proxyStats.LastCloseTime.IsZero() {
|
||||
res.LastCloseTime = proxyStats.LastCloseTime.Format("01-02 15:04:05")
|
||||
}
|
||||
break
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
func (collector *internalCollector) GetProxyTraffic(name string) (res *ProxyTrafficInfo) {
|
||||
collector.mu.Lock()
|
||||
defer collector.mu.Unlock()
|
||||
|
||||
proxyStats, ok := collector.info.ProxyStatistics[name]
|
||||
if ok {
|
||||
res = &ProxyTrafficInfo{
|
||||
Name: name,
|
||||
}
|
||||
res.TrafficIn = proxyStats.TrafficIn.GetLastDaysCount(ReserveDays)
|
||||
res.TrafficOut = proxyStats.TrafficOut.GetLastDaysCount(ReserveDays)
|
||||
}
|
||||
return
|
||||
}
|
129
server/stats/stats.go
Normal file
129
server/stats/stats.go
Normal file
@@ -0,0 +1,129 @@
|
||||
// Copyright 2017 fatedier, fatedier@gmail.com
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
package stats
|
||||
|
||||
import (
|
||||
"time"
|
||||
|
||||
"github.com/fatedier/frp/utils/metric"
|
||||
)
|
||||
|
||||
const (
|
||||
ReserveDays = 7
|
||||
)
|
||||
|
||||
type StatsType int
|
||||
|
||||
const (
|
||||
TypeNewClient StatsType = iota
|
||||
TypeCloseClient
|
||||
TypeNewProxy
|
||||
TypeCloseProxy
|
||||
TypeOpenConnection
|
||||
TypeCloseConnection
|
||||
TypeAddTrafficIn
|
||||
TypeAddTrafficOut
|
||||
)
|
||||
|
||||
type ServerStats struct {
|
||||
TotalTrafficIn int64
|
||||
TotalTrafficOut int64
|
||||
CurConns int64
|
||||
ClientCounts int64
|
||||
ProxyTypeCounts map[string]int64
|
||||
}
|
||||
|
||||
type ProxyStats struct {
|
||||
Name string
|
||||
Type string
|
||||
TodayTrafficIn int64
|
||||
TodayTrafficOut int64
|
||||
LastStartTime string
|
||||
LastCloseTime string
|
||||
CurConns int64
|
||||
}
|
||||
|
||||
type ProxyTrafficInfo struct {
|
||||
Name string
|
||||
TrafficIn []int64
|
||||
TrafficOut []int64
|
||||
}
|
||||
|
||||
type ProxyStatistics struct {
|
||||
Name string
|
||||
ProxyType string
|
||||
TrafficIn metric.DateCounter
|
||||
TrafficOut metric.DateCounter
|
||||
CurConns metric.Counter
|
||||
LastStartTime time.Time
|
||||
LastCloseTime time.Time
|
||||
}
|
||||
|
||||
type ServerStatistics struct {
|
||||
TotalTrafficIn metric.DateCounter
|
||||
TotalTrafficOut metric.DateCounter
|
||||
CurConns metric.Counter
|
||||
|
||||
// counter for clients
|
||||
ClientCounts metric.Counter
|
||||
|
||||
// counter for proxy types
|
||||
ProxyTypeCounts map[string]metric.Counter
|
||||
|
||||
// statistics for different proxies
|
||||
// key is proxy name
|
||||
ProxyStatistics map[string]*ProxyStatistics
|
||||
}
|
||||
|
||||
type Collector interface {
|
||||
Mark(statsType StatsType, payload interface{})
|
||||
Run() error
|
||||
GetServer() *ServerStats
|
||||
GetProxiesByType(proxyType string) []*ProxyStats
|
||||
GetProxiesByTypeAndName(proxyType string, proxyName string) *ProxyStats
|
||||
GetProxyTraffic(name string) *ProxyTrafficInfo
|
||||
}
|
||||
|
||||
type NewClientPayload struct{}
|
||||
|
||||
type CloseClientPayload struct{}
|
||||
|
||||
type NewProxyPayload struct {
|
||||
Name string
|
||||
ProxyType string
|
||||
}
|
||||
|
||||
type CloseProxyPayload struct {
|
||||
Name string
|
||||
ProxyType string
|
||||
}
|
||||
|
||||
type OpenConnectionPayload struct {
|
||||
ProxyName string
|
||||
}
|
||||
|
||||
type CloseConnectionPayload struct {
|
||||
ProxyName string
|
||||
}
|
||||
|
||||
type AddTrafficInPayload struct {
|
||||
ProxyName string
|
||||
TrafficBytes int64
|
||||
}
|
||||
|
||||
type AddTrafficOutPayload struct {
|
||||
ProxyName string
|
||||
TrafficBytes int64
|
||||
}
|
@@ -1,7 +1,7 @@
|
||||
[common]
|
||||
server_addr = 127.0.0.1
|
||||
server_port = 10700
|
||||
log_file = ./frpc.log
|
||||
log_file = console
|
||||
# debug, info, warn, error
|
||||
log_level = debug
|
||||
token = 123456
|
||||
@@ -23,6 +23,22 @@ remote_port = 10901
|
||||
use_encryption = true
|
||||
use_compression = true
|
||||
|
||||
[tcp_group1]
|
||||
type = tcp
|
||||
local_ip = 127.0.0.1
|
||||
local_port = 10701
|
||||
remote_port = 10802
|
||||
group = test1
|
||||
group_key = 123
|
||||
|
||||
[tcp_group2]
|
||||
type = tcp
|
||||
local_ip = 127.0.0.1
|
||||
local_port = 10702
|
||||
remote_port = 10802
|
||||
group = test1
|
||||
group_key = 123
|
||||
|
||||
[udp_normal]
|
||||
type = udp
|
||||
local_ip = 127.0.0.1
|
||||
@@ -103,6 +119,14 @@ use_compression = true
|
||||
http_user = test
|
||||
http_user = test
|
||||
|
||||
[web06]
|
||||
type = http
|
||||
local_ip = 127.0.0.1
|
||||
local_port = 10704
|
||||
custom_domains = test6.frp.com
|
||||
host_header_rewrite = test6.frp.com
|
||||
header_X-From-Where = frp
|
||||
|
||||
[subhost01]
|
||||
type = http
|
||||
local_ip = 127.0.0.1
|
@@ -1,7 +1,7 @@
|
||||
[common]
|
||||
server_addr = 0.0.0.0
|
||||
server_port = 10700
|
||||
log_file = ./frpc_visitor.log
|
||||
log_file = console
|
||||
# debug, info, warn, error
|
||||
log_level = debug
|
||||
token = 123456
|
@@ -2,7 +2,7 @@
|
||||
bind_addr = 0.0.0.0
|
||||
bind_port = 10700
|
||||
vhost_http_port = 10804
|
||||
log_file = ./frps.log
|
||||
log_file = console
|
||||
log_level = debug
|
||||
token = 123456
|
||||
allow_ports = 10000-20000,20002,30000-50000
|
85
tests/ci/cmd_test.go
Normal file
85
tests/ci/cmd_test.go
Normal file
@@ -0,0 +1,85 @@
|
||||
package ci
|
||||
|
||||
import (
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/fatedier/frp/tests/consts"
|
||||
"github.com/fatedier/frp/tests/util"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
)
|
||||
|
||||
func TestCmdTcp(t *testing.T) {
|
||||
assert := assert.New(t)
|
||||
|
||||
var err error
|
||||
s := util.NewProcess(consts.FRPS_BIN_PATH, []string{"-t", "123", "-p", "20000"})
|
||||
err = s.Start()
|
||||
if assert.NoError(err) {
|
||||
defer s.Stop()
|
||||
}
|
||||
time.Sleep(100 * time.Millisecond)
|
||||
|
||||
c := util.NewProcess(consts.FRPC_BIN_PATH, []string{"tcp", "-s", "127.0.0.1:20000", "-t", "123", "-u", "test",
|
||||
"-l", "10701", "-r", "20801", "-n", "tcp_test"})
|
||||
err = c.Start()
|
||||
if assert.NoError(err) {
|
||||
defer c.Stop()
|
||||
}
|
||||
time.Sleep(250 * time.Millisecond)
|
||||
|
||||
res, err := util.SendTcpMsg("127.0.0.1:20801", consts.TEST_TCP_ECHO_STR)
|
||||
assert.NoError(err)
|
||||
assert.Equal(consts.TEST_TCP_ECHO_STR, res)
|
||||
}
|
||||
|
||||
func TestCmdUdp(t *testing.T) {
|
||||
assert := assert.New(t)
|
||||
|
||||
var err error
|
||||
s := util.NewProcess(consts.FRPS_BIN_PATH, []string{"-t", "123", "-p", "20000"})
|
||||
err = s.Start()
|
||||
if assert.NoError(err) {
|
||||
defer s.Stop()
|
||||
}
|
||||
time.Sleep(100 * time.Millisecond)
|
||||
|
||||
c := util.NewProcess(consts.FRPC_BIN_PATH, []string{"udp", "-s", "127.0.0.1:20000", "-t", "123", "-u", "test",
|
||||
"-l", "10702", "-r", "20802", "-n", "udp_test"})
|
||||
err = c.Start()
|
||||
if assert.NoError(err) {
|
||||
defer c.Stop()
|
||||
}
|
||||
time.Sleep(250 * time.Millisecond)
|
||||
|
||||
res, err := util.SendUdpMsg("127.0.0.1:20802", consts.TEST_UDP_ECHO_STR)
|
||||
assert.NoError(err)
|
||||
assert.Equal(consts.TEST_UDP_ECHO_STR, res)
|
||||
}
|
||||
|
||||
func TestCmdHttp(t *testing.T) {
|
||||
assert := assert.New(t)
|
||||
|
||||
var err error
|
||||
s := util.NewProcess(consts.FRPS_BIN_PATH, []string{"-t", "123", "-p", "20000", "--vhost_http_port", "20001"})
|
||||
err = s.Start()
|
||||
if assert.NoError(err) {
|
||||
defer s.Stop()
|
||||
}
|
||||
time.Sleep(100 * time.Millisecond)
|
||||
|
||||
c := util.NewProcess(consts.FRPC_BIN_PATH, []string{"http", "-s", "127.0.0.1:20000", "-t", "123", "-u", "test",
|
||||
"-n", "udp_test", "-l", "10704", "--custom_domain", "127.0.0.1"})
|
||||
err = c.Start()
|
||||
if assert.NoError(err) {
|
||||
defer c.Stop()
|
||||
}
|
||||
time.Sleep(250 * time.Millisecond)
|
||||
|
||||
code, body, _, err := util.SendHttpMsg("GET", "http://127.0.0.1:20001", "", nil, "")
|
||||
if assert.NoError(err) {
|
||||
assert.Equal(200, code)
|
||||
assert.Equal(consts.TEST_HTTP_NORMAL_STR, body)
|
||||
}
|
||||
}
|
247
tests/ci/health/health_test.go
Normal file
247
tests/ci/health/health_test.go
Normal file
@@ -0,0 +1,247 @@
|
||||
package health
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"os"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/fatedier/frp/tests/config"
|
||||
"github.com/fatedier/frp/tests/consts"
|
||||
"github.com/fatedier/frp/tests/mock"
|
||||
"github.com/fatedier/frp/tests/util"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
)
|
||||
|
||||
const FRPS_CONF = `
|
||||
[common]
|
||||
bind_addr = 0.0.0.0
|
||||
bind_port = 14000
|
||||
vhost_http_port = 14000
|
||||
log_file = console
|
||||
log_level = debug
|
||||
token = 123456
|
||||
`
|
||||
|
||||
const FRPC_CONF = `
|
||||
[common]
|
||||
server_addr = 127.0.0.1
|
||||
server_port = 14000
|
||||
log_file = console
|
||||
log_level = debug
|
||||
token = 123456
|
||||
|
||||
[tcp1]
|
||||
type = tcp
|
||||
local_port = 15001
|
||||
remote_port = 15000
|
||||
group = test
|
||||
group_key = 123
|
||||
health_check_type = tcp
|
||||
health_check_interval_s = 1
|
||||
|
||||
[tcp2]
|
||||
type = tcp
|
||||
local_port = 15002
|
||||
remote_port = 15000
|
||||
group = test
|
||||
group_key = 123
|
||||
health_check_type = tcp
|
||||
health_check_interval_s = 1
|
||||
|
||||
[http1]
|
||||
type = http
|
||||
local_port = 15003
|
||||
custom_domains = test1.com
|
||||
health_check_type = http
|
||||
health_check_interval_s = 1
|
||||
health_check_url = /health
|
||||
|
||||
[http2]
|
||||
type = http
|
||||
local_port = 15004
|
||||
custom_domains = test2.com
|
||||
health_check_type = http
|
||||
health_check_interval_s = 1
|
||||
health_check_url = /health
|
||||
`
|
||||
|
||||
func TestHealthCheck(t *testing.T) {
|
||||
assert := assert.New(t)
|
||||
|
||||
// ****** start backgroud services ******
|
||||
echoSvc1 := mock.NewEchoServer(15001, 1, "echo1")
|
||||
err := echoSvc1.Start()
|
||||
if assert.NoError(err) {
|
||||
defer echoSvc1.Stop()
|
||||
}
|
||||
|
||||
echoSvc2 := mock.NewEchoServer(15002, 1, "echo2")
|
||||
err = echoSvc2.Start()
|
||||
if assert.NoError(err) {
|
||||
defer echoSvc2.Stop()
|
||||
}
|
||||
|
||||
var healthMu sync.RWMutex
|
||||
svc1Health := true
|
||||
svc2Health := true
|
||||
httpSvc1 := mock.NewHttpServer(15003, func(w http.ResponseWriter, r *http.Request) {
|
||||
if strings.Contains(r.URL.Path, "health") {
|
||||
healthMu.RLock()
|
||||
defer healthMu.RUnlock()
|
||||
if svc1Health {
|
||||
w.WriteHeader(200)
|
||||
} else {
|
||||
w.WriteHeader(500)
|
||||
}
|
||||
} else {
|
||||
w.Write([]byte("http1"))
|
||||
}
|
||||
})
|
||||
err = httpSvc1.Start()
|
||||
if assert.NoError(err) {
|
||||
defer httpSvc1.Stop()
|
||||
}
|
||||
|
||||
httpSvc2 := mock.NewHttpServer(15004, func(w http.ResponseWriter, r *http.Request) {
|
||||
if strings.Contains(r.URL.Path, "health") {
|
||||
healthMu.RLock()
|
||||
defer healthMu.RUnlock()
|
||||
if svc2Health {
|
||||
w.WriteHeader(200)
|
||||
} else {
|
||||
w.WriteHeader(500)
|
||||
}
|
||||
} else {
|
||||
w.Write([]byte("http2"))
|
||||
}
|
||||
})
|
||||
err = httpSvc2.Start()
|
||||
if assert.NoError(err) {
|
||||
defer httpSvc2.Stop()
|
||||
}
|
||||
|
||||
time.Sleep(200 * time.Millisecond)
|
||||
|
||||
// ****** start frps and frpc ******
|
||||
frpsCfgPath, err := config.GenerateConfigFile(consts.FRPS_NORMAL_CONFIG, FRPS_CONF)
|
||||
if assert.NoError(err) {
|
||||
defer os.Remove(frpsCfgPath)
|
||||
}
|
||||
|
||||
frpcCfgPath, err := config.GenerateConfigFile(consts.FRPC_NORMAL_CONFIG, FRPC_CONF)
|
||||
if assert.NoError(err) {
|
||||
defer os.Remove(frpcCfgPath)
|
||||
}
|
||||
|
||||
frpsProcess := util.NewProcess(consts.FRPS_SUB_BIN_PATH, []string{"-c", frpsCfgPath})
|
||||
err = frpsProcess.Start()
|
||||
if assert.NoError(err) {
|
||||
defer frpsProcess.Stop()
|
||||
}
|
||||
|
||||
time.Sleep(100 * time.Millisecond)
|
||||
|
||||
frpcProcess := util.NewProcess(consts.FRPC_SUB_BIN_PATH, []string{"-c", frpcCfgPath})
|
||||
err = frpcProcess.Start()
|
||||
if assert.NoError(err) {
|
||||
defer frpcProcess.Stop()
|
||||
}
|
||||
time.Sleep(1000 * time.Millisecond)
|
||||
|
||||
// ****** healcheck type tcp ******
|
||||
// echo1 and echo2 is ok
|
||||
result := make([]string, 0)
|
||||
res, err := util.SendTcpMsg("127.0.0.1:15000", "echo")
|
||||
assert.NoError(err)
|
||||
result = append(result, res)
|
||||
|
||||
res, err = util.SendTcpMsg("127.0.0.1:15000", "echo")
|
||||
assert.NoError(err)
|
||||
result = append(result, res)
|
||||
|
||||
assert.Contains(result, "echo1")
|
||||
assert.Contains(result, "echo2")
|
||||
|
||||
// close echo2 server, echo1 is work
|
||||
echoSvc2.Stop()
|
||||
time.Sleep(1200 * time.Millisecond)
|
||||
|
||||
result = make([]string, 0)
|
||||
res, err = util.SendTcpMsg("127.0.0.1:15000", "echo")
|
||||
assert.NoError(err)
|
||||
result = append(result, res)
|
||||
|
||||
res, err = util.SendTcpMsg("127.0.0.1:15000", "echo")
|
||||
assert.NoError(err)
|
||||
result = append(result, res)
|
||||
|
||||
assert.NotContains(result, "echo2")
|
||||
|
||||
// resume echo2 server, all services are ok
|
||||
echoSvc2 = mock.NewEchoServer(15002, 1, "echo2")
|
||||
err = echoSvc2.Start()
|
||||
if assert.NoError(err) {
|
||||
defer echoSvc2.Stop()
|
||||
}
|
||||
|
||||
time.Sleep(1200 * time.Millisecond)
|
||||
|
||||
result = make([]string, 0)
|
||||
res, err = util.SendTcpMsg("127.0.0.1:15000", "echo")
|
||||
assert.NoError(err)
|
||||
result = append(result, res)
|
||||
|
||||
res, err = util.SendTcpMsg("127.0.0.1:15000", "echo")
|
||||
assert.NoError(err)
|
||||
result = append(result, res)
|
||||
|
||||
assert.Contains(result, "echo1")
|
||||
assert.Contains(result, "echo2")
|
||||
|
||||
// ****** healcheck type http ******
|
||||
// http1 and http2 is ok
|
||||
code, body, _, err := util.SendHttpMsg("GET", "http://127.0.0.1:14000/xxx", "test1.com", nil, "")
|
||||
assert.NoError(err)
|
||||
assert.Equal(200, code)
|
||||
assert.Equal("http1", body)
|
||||
|
||||
code, body, _, err = util.SendHttpMsg("GET", "http://127.0.0.1:14000/xxx", "test2.com", nil, "")
|
||||
assert.NoError(err)
|
||||
assert.Equal(200, code)
|
||||
assert.Equal("http2", body)
|
||||
|
||||
// http2 health check error
|
||||
healthMu.Lock()
|
||||
svc2Health = false
|
||||
healthMu.Unlock()
|
||||
time.Sleep(1200 * time.Millisecond)
|
||||
|
||||
code, body, _, err = util.SendHttpMsg("GET", "http://127.0.0.1:14000/xxx", "test1.com", nil, "")
|
||||
assert.NoError(err)
|
||||
assert.Equal(200, code)
|
||||
assert.Equal("http1", body)
|
||||
|
||||
code, _, _, err = util.SendHttpMsg("GET", "http://127.0.0.1:14000/xxx", "test2.com", nil, "")
|
||||
assert.NoError(err)
|
||||
assert.Equal(404, code)
|
||||
|
||||
// resume http2 service, http1 and http2 are ok
|
||||
healthMu.Lock()
|
||||
svc2Health = true
|
||||
healthMu.Unlock()
|
||||
time.Sleep(1200 * time.Millisecond)
|
||||
|
||||
code, body, _, err = util.SendHttpMsg("GET", "http://127.0.0.1:14000/xxx", "test1.com", nil, "")
|
||||
assert.NoError(err)
|
||||
assert.Equal(200, code)
|
||||
assert.Equal("http1", body)
|
||||
|
||||
code, body, _, err = util.SendHttpMsg("GET", "http://127.0.0.1:14000/xxx", "test2.com", nil, "")
|
||||
assert.NoError(err)
|
||||
assert.Equal(200, code)
|
||||
assert.Equal("http2", body)
|
||||
}
|
327
tests/ci/normal_test.go
Normal file
327
tests/ci/normal_test.go
Normal file
@@ -0,0 +1,327 @@
|
||||
package ci
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"os"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/gorilla/websocket"
|
||||
"github.com/stretchr/testify/assert"
|
||||
|
||||
"github.com/fatedier/frp/client/proxy"
|
||||
"github.com/fatedier/frp/server/ports"
|
||||
"github.com/fatedier/frp/tests/consts"
|
||||
"github.com/fatedier/frp/tests/mock"
|
||||
"github.com/fatedier/frp/tests/util"
|
||||
|
||||
gnet "github.com/fatedier/golib/net"
|
||||
)
|
||||
|
||||
func TestMain(m *testing.M) {
|
||||
var err error
|
||||
tcpEcho1 := mock.NewEchoServer(consts.TEST_TCP_PORT, 1, "")
|
||||
tcpEcho2 := mock.NewEchoServer(consts.TEST_TCP2_PORT, 2, "")
|
||||
|
||||
if err = tcpEcho1.Start(); err != nil {
|
||||
panic(err)
|
||||
}
|
||||
if err = tcpEcho2.Start(); err != nil {
|
||||
panic(err)
|
||||
}
|
||||
|
||||
go mock.StartUdpEchoServer(consts.TEST_UDP_PORT)
|
||||
go mock.StartUnixDomainServer(consts.TEST_UNIX_DOMAIN_ADDR)
|
||||
go mock.StartHttpServer(consts.TEST_HTTP_PORT)
|
||||
|
||||
p1 := util.NewProcess(consts.FRPS_BIN_PATH, []string{"-c", "./auto_test_frps.ini"})
|
||||
if err = p1.Start(); err != nil {
|
||||
panic(err)
|
||||
}
|
||||
|
||||
time.Sleep(200 * time.Millisecond)
|
||||
p2 := util.NewProcess(consts.FRPC_BIN_PATH, []string{"-c", "./auto_test_frpc.ini"})
|
||||
if err = p2.Start(); err != nil {
|
||||
panic(err)
|
||||
}
|
||||
|
||||
p3 := util.NewProcess(consts.FRPC_BIN_PATH, []string{"-c", "./auto_test_frpc_visitor.ini"})
|
||||
if err = p3.Start(); err != nil {
|
||||
panic(err)
|
||||
}
|
||||
time.Sleep(500 * time.Millisecond)
|
||||
|
||||
exitCode := m.Run()
|
||||
p1.Stop()
|
||||
p2.Stop()
|
||||
p3.Stop()
|
||||
os.Exit(exitCode)
|
||||
}
|
||||
|
||||
func TestTcp(t *testing.T) {
|
||||
assert := assert.New(t)
|
||||
// Normal
|
||||
addr := fmt.Sprintf("127.0.0.1:%d", consts.TEST_TCP_FRP_PORT)
|
||||
res, err := util.SendTcpMsg(addr, consts.TEST_TCP_ECHO_STR)
|
||||
assert.NoError(err)
|
||||
assert.Equal(consts.TEST_TCP_ECHO_STR, res)
|
||||
|
||||
// Encrytion and compression
|
||||
addr = fmt.Sprintf("127.0.0.1:%d", consts.TEST_TCP_EC_FRP_PORT)
|
||||
res, err = util.SendTcpMsg(addr, consts.TEST_TCP_ECHO_STR)
|
||||
assert.NoError(err)
|
||||
assert.Equal(consts.TEST_TCP_ECHO_STR, res)
|
||||
}
|
||||
|
||||
func TestUdp(t *testing.T) {
|
||||
assert := assert.New(t)
|
||||
// Normal
|
||||
addr := fmt.Sprintf("127.0.0.1:%d", consts.TEST_UDP_FRP_PORT)
|
||||
res, err := util.SendUdpMsg(addr, consts.TEST_UDP_ECHO_STR)
|
||||
assert.NoError(err)
|
||||
assert.Equal(consts.TEST_UDP_ECHO_STR, res)
|
||||
|
||||
// Encrytion and compression
|
||||
addr = fmt.Sprintf("127.0.0.1:%d", consts.TEST_UDP_EC_FRP_PORT)
|
||||
res, err = util.SendUdpMsg(addr, consts.TEST_UDP_ECHO_STR)
|
||||
assert.NoError(err)
|
||||
assert.Equal(consts.TEST_UDP_ECHO_STR, res)
|
||||
}
|
||||
|
||||
func TestUnixDomain(t *testing.T) {
|
||||
assert := assert.New(t)
|
||||
// Normal
|
||||
addr := fmt.Sprintf("127.0.0.1:%d", consts.TEST_UNIX_DOMAIN_FRP_PORT)
|
||||
res, err := util.SendTcpMsg(addr, consts.TEST_UNIX_DOMAIN_STR)
|
||||
if assert.NoError(err) {
|
||||
assert.Equal(consts.TEST_UNIX_DOMAIN_STR, res)
|
||||
}
|
||||
}
|
||||
|
||||
func TestStcp(t *testing.T) {
|
||||
assert := assert.New(t)
|
||||
// Normal
|
||||
addr := fmt.Sprintf("127.0.0.1:%d", consts.TEST_STCP_FRP_PORT)
|
||||
res, err := util.SendTcpMsg(addr, consts.TEST_STCP_ECHO_STR)
|
||||
if assert.NoError(err) {
|
||||
assert.Equal(consts.TEST_STCP_ECHO_STR, res)
|
||||
}
|
||||
|
||||
// Encrytion and compression
|
||||
addr = fmt.Sprintf("127.0.0.1:%d", consts.TEST_STCP_EC_FRP_PORT)
|
||||
res, err = util.SendTcpMsg(addr, consts.TEST_STCP_ECHO_STR)
|
||||
if assert.NoError(err) {
|
||||
assert.Equal(consts.TEST_STCP_ECHO_STR, res)
|
||||
}
|
||||
}
|
||||
|
||||
func TestHttp(t *testing.T) {
|
||||
assert := assert.New(t)
|
||||
// web01
|
||||
code, body, _, err := util.SendHttpMsg("GET", fmt.Sprintf("http://127.0.0.1:%d", consts.TEST_HTTP_FRP_PORT), "", nil, "")
|
||||
if assert.NoError(err) {
|
||||
assert.Equal(200, code)
|
||||
assert.Equal(consts.TEST_HTTP_NORMAL_STR, body)
|
||||
}
|
||||
|
||||
// web02
|
||||
code, body, _, err = util.SendHttpMsg("GET", fmt.Sprintf("http://127.0.0.1:%d", consts.TEST_HTTP_FRP_PORT), "test2.frp.com", nil, "")
|
||||
if assert.NoError(err) {
|
||||
assert.Equal(200, code)
|
||||
assert.Equal(consts.TEST_HTTP_NORMAL_STR, body)
|
||||
}
|
||||
|
||||
// error host header
|
||||
code, body, _, err = util.SendHttpMsg("GET", fmt.Sprintf("http://127.0.0.1:%d", consts.TEST_HTTP_FRP_PORT), "errorhost.frp.com", nil, "")
|
||||
if assert.NoError(err) {
|
||||
assert.Equal(404, code)
|
||||
}
|
||||
|
||||
// web03
|
||||
code, body, _, err = util.SendHttpMsg("GET", fmt.Sprintf("http://127.0.0.1:%d", consts.TEST_HTTP_FRP_PORT), "test3.frp.com", nil, "")
|
||||
if assert.NoError(err) {
|
||||
assert.Equal(200, code)
|
||||
assert.Equal(consts.TEST_HTTP_NORMAL_STR, body)
|
||||
}
|
||||
|
||||
code, body, _, err = util.SendHttpMsg("GET", fmt.Sprintf("http://127.0.0.1:%d/foo", consts.TEST_HTTP_FRP_PORT), "test3.frp.com", nil, "")
|
||||
if assert.NoError(err) {
|
||||
assert.Equal(200, code)
|
||||
assert.Equal(consts.TEST_HTTP_FOO_STR, body)
|
||||
}
|
||||
|
||||
// web04
|
||||
code, body, _, err = util.SendHttpMsg("GET", fmt.Sprintf("http://127.0.0.1:%d/bar", consts.TEST_HTTP_FRP_PORT), "test3.frp.com", nil, "")
|
||||
if assert.NoError(err) {
|
||||
assert.Equal(200, code)
|
||||
assert.Equal(consts.TEST_HTTP_BAR_STR, body)
|
||||
}
|
||||
|
||||
// web05
|
||||
code, body, _, err = util.SendHttpMsg("GET", fmt.Sprintf("http://127.0.0.1:%d", consts.TEST_HTTP_FRP_PORT), "test5.frp.com", nil, "")
|
||||
if assert.NoError(err) {
|
||||
assert.Equal(401, code)
|
||||
}
|
||||
|
||||
headers := make(map[string]string)
|
||||
headers["Authorization"] = util.BasicAuth("test", "test")
|
||||
code, body, _, err = util.SendHttpMsg("GET", fmt.Sprintf("http://127.0.0.1:%d", consts.TEST_HTTP_FRP_PORT), "test5.frp.com", headers, "")
|
||||
if assert.NoError(err) {
|
||||
assert.Equal(401, code)
|
||||
}
|
||||
|
||||
// web06
|
||||
var header http.Header
|
||||
code, body, header, err = util.SendHttpMsg("GET", fmt.Sprintf("http://127.0.0.1:%d", consts.TEST_HTTP_FRP_PORT), "test6.frp.com", nil, "")
|
||||
if assert.NoError(err) {
|
||||
assert.Equal(200, code)
|
||||
assert.Equal(consts.TEST_HTTP_NORMAL_STR, body)
|
||||
assert.Equal("true", header.Get("X-Header-Set"))
|
||||
}
|
||||
|
||||
// subhost01
|
||||
code, body, _, err = util.SendHttpMsg("GET", fmt.Sprintf("http://127.0.0.1:%d", consts.TEST_HTTP_FRP_PORT), "test01.sub.com", nil, "")
|
||||
if assert.NoError(err) {
|
||||
assert.Equal(200, code)
|
||||
assert.Equal("test01.sub.com", body)
|
||||
}
|
||||
|
||||
// subhost02
|
||||
code, body, _, err = util.SendHttpMsg("GET", fmt.Sprintf("http://127.0.0.1:%d", consts.TEST_HTTP_FRP_PORT), "test02.sub.com", nil, "")
|
||||
if assert.NoError(err) {
|
||||
assert.Equal(200, code)
|
||||
assert.Equal("test02.sub.com", body)
|
||||
}
|
||||
}
|
||||
|
||||
func TestWebSocket(t *testing.T) {
|
||||
assert := assert.New(t)
|
||||
|
||||
u := url.URL{Scheme: "ws", Host: fmt.Sprintf("%s:%d", "127.0.0.1", consts.TEST_HTTP_FRP_PORT), Path: "/ws"}
|
||||
c, _, err := websocket.DefaultDialer.Dial(u.String(), nil)
|
||||
assert.NoError(err)
|
||||
defer c.Close()
|
||||
|
||||
err = c.WriteMessage(websocket.TextMessage, []byte(consts.TEST_HTTP_NORMAL_STR))
|
||||
assert.NoError(err)
|
||||
|
||||
_, msg, err := c.ReadMessage()
|
||||
assert.NoError(err)
|
||||
assert.Equal(consts.TEST_HTTP_NORMAL_STR, string(msg))
|
||||
}
|
||||
|
||||
func TestAllowPorts(t *testing.T) {
|
||||
assert := assert.New(t)
|
||||
// Port not allowed
|
||||
status, err := util.GetProxyStatus(consts.ADMIN_ADDR, consts.ADMIN_USER, consts.ADMIN_PWD, consts.ProxyTcpPortNotAllowed)
|
||||
if assert.NoError(err) {
|
||||
assert.Equal(proxy.ProxyStatusStartErr, status.Status)
|
||||
assert.True(strings.Contains(status.Err, ports.ErrPortNotAllowed.Error()))
|
||||
}
|
||||
|
||||
status, err = util.GetProxyStatus(consts.ADMIN_ADDR, consts.ADMIN_USER, consts.ADMIN_PWD, consts.ProxyUdpPortNotAllowed)
|
||||
if assert.NoError(err) {
|
||||
assert.Equal(proxy.ProxyStatusStartErr, status.Status)
|
||||
assert.True(strings.Contains(status.Err, ports.ErrPortNotAllowed.Error()))
|
||||
}
|
||||
|
||||
status, err = util.GetProxyStatus(consts.ADMIN_ADDR, consts.ADMIN_USER, consts.ADMIN_PWD, consts.ProxyTcpPortUnavailable)
|
||||
if assert.NoError(err) {
|
||||
assert.Equal(proxy.ProxyStatusStartErr, status.Status)
|
||||
assert.True(strings.Contains(status.Err, ports.ErrPortUnAvailable.Error()))
|
||||
}
|
||||
|
||||
// Port normal
|
||||
status, err = util.GetProxyStatus(consts.ADMIN_ADDR, consts.ADMIN_USER, consts.ADMIN_PWD, consts.ProxyTcpPortNormal)
|
||||
if assert.NoError(err) {
|
||||
assert.Equal(proxy.ProxyStatusRunning, status.Status)
|
||||
}
|
||||
|
||||
status, err = util.GetProxyStatus(consts.ADMIN_ADDR, consts.ADMIN_USER, consts.ADMIN_PWD, consts.ProxyUdpPortNormal)
|
||||
if assert.NoError(err) {
|
||||
assert.Equal(proxy.ProxyStatusRunning, status.Status)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRandomPort(t *testing.T) {
|
||||
assert := assert.New(t)
|
||||
// tcp
|
||||
status, err := util.GetProxyStatus(consts.ADMIN_ADDR, consts.ADMIN_USER, consts.ADMIN_PWD, consts.ProxyTcpRandomPort)
|
||||
if assert.NoError(err) {
|
||||
addr := status.RemoteAddr
|
||||
res, err := util.SendTcpMsg(addr, consts.TEST_TCP_ECHO_STR)
|
||||
assert.NoError(err)
|
||||
assert.Equal(consts.TEST_TCP_ECHO_STR, res)
|
||||
}
|
||||
|
||||
// udp
|
||||
status, err = util.GetProxyStatus(consts.ADMIN_ADDR, consts.ADMIN_USER, consts.ADMIN_PWD, consts.ProxyUdpRandomPort)
|
||||
if assert.NoError(err) {
|
||||
addr := status.RemoteAddr
|
||||
res, err := util.SendUdpMsg(addr, consts.TEST_UDP_ECHO_STR)
|
||||
assert.NoError(err)
|
||||
assert.Equal(consts.TEST_UDP_ECHO_STR, res)
|
||||
}
|
||||
}
|
||||
|
||||
func TestPluginHttpProxy(t *testing.T) {
|
||||
assert := assert.New(t)
|
||||
status, err := util.GetProxyStatus(consts.ADMIN_ADDR, consts.ADMIN_USER, consts.ADMIN_PWD, consts.ProxyHttpProxy)
|
||||
if assert.NoError(err) {
|
||||
assert.Equal(proxy.ProxyStatusRunning, status.Status)
|
||||
|
||||
// http proxy
|
||||
addr := status.RemoteAddr
|
||||
code, body, _, err := util.SendHttpMsg("GET", fmt.Sprintf("http://127.0.0.1:%d", consts.TEST_HTTP_FRP_PORT),
|
||||
"", nil, "http://"+addr)
|
||||
if assert.NoError(err) {
|
||||
assert.Equal(200, code)
|
||||
assert.Equal(consts.TEST_HTTP_NORMAL_STR, body)
|
||||
}
|
||||
|
||||
// connect method
|
||||
conn, err := gnet.DialTcpByProxy("http://"+addr, fmt.Sprintf("127.0.0.1:%d", consts.TEST_TCP_FRP_PORT))
|
||||
if assert.NoError(err) {
|
||||
res, err := util.SendTcpMsgByConn(conn, consts.TEST_TCP_ECHO_STR)
|
||||
assert.NoError(err)
|
||||
assert.Equal(consts.TEST_TCP_ECHO_STR, res)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestRangePortsMapping(t *testing.T) {
|
||||
assert := assert.New(t)
|
||||
|
||||
for i := 0; i < 3; i++ {
|
||||
name := fmt.Sprintf("%s_%d", consts.ProxyRangeTcpPrefix, i)
|
||||
status, err := util.GetProxyStatus(consts.ADMIN_ADDR, consts.ADMIN_USER, consts.ADMIN_PWD, name)
|
||||
if assert.NoError(err) {
|
||||
assert.Equal(proxy.ProxyStatusRunning, status.Status)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestGroup(t *testing.T) {
|
||||
assert := assert.New(t)
|
||||
|
||||
var (
|
||||
p1 int
|
||||
p2 int
|
||||
)
|
||||
addr := fmt.Sprintf("127.0.0.1:%d", consts.TEST_TCP2_FRP_PORT)
|
||||
|
||||
for i := 0; i < 6; i++ {
|
||||
res, err := util.SendTcpMsg(addr, consts.TEST_TCP_ECHO_STR)
|
||||
assert.NoError(err)
|
||||
switch res {
|
||||
case consts.TEST_TCP_ECHO_STR:
|
||||
p1++
|
||||
case consts.TEST_TCP_ECHO_STR + consts.TEST_TCP_ECHO_STR:
|
||||
p2++
|
||||
}
|
||||
}
|
||||
assert.True(p1 > 0 && p2 > 0, "group proxies load balancing")
|
||||
}
|
115
tests/ci/reconnect_test.go
Normal file
115
tests/ci/reconnect_test.go
Normal file
@@ -0,0 +1,115 @@
|
||||
package ci
|
||||
|
||||
import (
|
||||
"os"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/fatedier/frp/tests/config"
|
||||
"github.com/fatedier/frp/tests/consts"
|
||||
"github.com/fatedier/frp/tests/util"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
)
|
||||
|
||||
const FRPS_RECONNECT_CONF = `
|
||||
[common]
|
||||
bind_addr = 0.0.0.0
|
||||
bind_port = 20000
|
||||
log_file = console
|
||||
log_level = debug
|
||||
token = 123456
|
||||
`
|
||||
|
||||
const FRPC_RECONNECT_CONF = `
|
||||
[common]
|
||||
server_addr = 127.0.0.1
|
||||
server_port = 20000
|
||||
log_file = console
|
||||
log_level = debug
|
||||
token = 123456
|
||||
admin_port = 21000
|
||||
admin_user = abc
|
||||
admin_pwd = abc
|
||||
|
||||
[tcp]
|
||||
type = tcp
|
||||
local_port = 10701
|
||||
remote_port = 20801
|
||||
`
|
||||
|
||||
func TestReconnect(t *testing.T) {
|
||||
assert := assert.New(t)
|
||||
frpsCfgPath, err := config.GenerateConfigFile(consts.FRPS_NORMAL_CONFIG, FRPS_RECONNECT_CONF)
|
||||
if assert.NoError(err) {
|
||||
defer os.Remove(frpsCfgPath)
|
||||
}
|
||||
|
||||
frpcCfgPath, err := config.GenerateConfigFile(consts.FRPC_NORMAL_CONFIG, FRPC_RECONNECT_CONF)
|
||||
if assert.NoError(err) {
|
||||
defer os.Remove(frpcCfgPath)
|
||||
}
|
||||
|
||||
frpsProcess := util.NewProcess(consts.FRPS_BIN_PATH, []string{"-c", frpsCfgPath})
|
||||
err = frpsProcess.Start()
|
||||
if assert.NoError(err) {
|
||||
defer frpsProcess.Stop()
|
||||
}
|
||||
|
||||
time.Sleep(100 * time.Millisecond)
|
||||
|
||||
frpcProcess := util.NewProcess(consts.FRPC_BIN_PATH, []string{"-c", frpcCfgPath})
|
||||
err = frpcProcess.Start()
|
||||
if assert.NoError(err) {
|
||||
defer frpcProcess.Stop()
|
||||
}
|
||||
time.Sleep(250 * time.Millisecond)
|
||||
|
||||
// test tcp
|
||||
res, err := util.SendTcpMsg("127.0.0.1:20801", consts.TEST_TCP_ECHO_STR)
|
||||
assert.NoError(err)
|
||||
assert.Equal(consts.TEST_TCP_ECHO_STR, res)
|
||||
|
||||
// stop frpc
|
||||
frpcProcess.Stop()
|
||||
time.Sleep(100 * time.Millisecond)
|
||||
|
||||
// test tcp, expect failed
|
||||
_, err = util.SendTcpMsg("127.0.0.1:20801", consts.TEST_TCP_ECHO_STR)
|
||||
assert.Error(err)
|
||||
|
||||
// restart frpc
|
||||
newFrpcProcess := util.NewProcess(consts.FRPC_BIN_PATH, []string{"-c", frpcCfgPath})
|
||||
err = newFrpcProcess.Start()
|
||||
if assert.NoError(err) {
|
||||
defer newFrpcProcess.Stop()
|
||||
}
|
||||
time.Sleep(250 * time.Millisecond)
|
||||
|
||||
// test tcp
|
||||
res, err = util.SendTcpMsg("127.0.0.1:20801", consts.TEST_TCP_ECHO_STR)
|
||||
assert.NoError(err)
|
||||
assert.Equal(consts.TEST_TCP_ECHO_STR, res)
|
||||
|
||||
// stop frps
|
||||
frpsProcess.Stop()
|
||||
time.Sleep(100 * time.Millisecond)
|
||||
|
||||
// test tcp, expect failed
|
||||
_, err = util.SendTcpMsg("127.0.0.1:20801", consts.TEST_TCP_ECHO_STR)
|
||||
assert.Error(err)
|
||||
|
||||
// restart frps
|
||||
newFrpsProcess := util.NewProcess(consts.FRPS_BIN_PATH, []string{"-c", frpsCfgPath})
|
||||
err = newFrpsProcess.Start()
|
||||
if assert.NoError(err) {
|
||||
defer newFrpsProcess.Stop()
|
||||
}
|
||||
|
||||
time.Sleep(2 * time.Second)
|
||||
|
||||
// test tcp
|
||||
res, err = util.SendTcpMsg("127.0.0.1:20801", consts.TEST_TCP_ECHO_STR)
|
||||
assert.NoError(err)
|
||||
assert.Equal(consts.TEST_TCP_ECHO_STR, res)
|
||||
}
|
150
tests/ci/reload_test.go
Normal file
150
tests/ci/reload_test.go
Normal file
@@ -0,0 +1,150 @@
|
||||
package ci
|
||||
|
||||
import (
|
||||
"os"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
|
||||
"github.com/fatedier/frp/tests/config"
|
||||
"github.com/fatedier/frp/tests/consts"
|
||||
"github.com/fatedier/frp/tests/util"
|
||||
)
|
||||
|
||||
const FRPS_RELOAD_CONF = `
|
||||
[common]
|
||||
bind_addr = 0.0.0.0
|
||||
bind_port = 20000
|
||||
log_file = console
|
||||
# debug, info, warn, error
|
||||
log_level = debug
|
||||
token = 123456
|
||||
`
|
||||
|
||||
const FRPC_RELOAD_CONF_1 = `
|
||||
[common]
|
||||
server_addr = 127.0.0.1
|
||||
server_port = 20000
|
||||
log_file = console
|
||||
# debug, info, warn, error
|
||||
log_level = debug
|
||||
token = 123456
|
||||
admin_port = 21000
|
||||
admin_user = abc
|
||||
admin_pwd = abc
|
||||
|
||||
[tcp]
|
||||
type = tcp
|
||||
local_port = 10701
|
||||
remote_port = 20801
|
||||
|
||||
# change remote port
|
||||
[tcp2]
|
||||
type = tcp
|
||||
local_port = 10701
|
||||
remote_port = 20802
|
||||
|
||||
# delete
|
||||
[tcp3]
|
||||
type = tcp
|
||||
local_port = 10701
|
||||
remote_port = 20803
|
||||
`
|
||||
|
||||
const FRPC_RELOAD_CONF_2 = `
|
||||
[common]
|
||||
server_addr = 127.0.0.1
|
||||
server_port = 20000
|
||||
log_file = console
|
||||
# debug, info, warn, error
|
||||
log_level = debug
|
||||
token = 123456
|
||||
admin_port = 21000
|
||||
admin_user = abc
|
||||
admin_pwd = abc
|
||||
|
||||
[tcp]
|
||||
type = tcp
|
||||
local_port = 10701
|
||||
remote_port = 20801
|
||||
|
||||
[tcp2]
|
||||
type = tcp
|
||||
local_port = 10701
|
||||
remote_port = 20902
|
||||
`
|
||||
|
||||
func TestReload(t *testing.T) {
|
||||
assert := assert.New(t)
|
||||
frpsCfgPath, err := config.GenerateConfigFile(consts.FRPS_NORMAL_CONFIG, FRPS_RELOAD_CONF)
|
||||
if assert.NoError(err) {
|
||||
defer os.Remove(frpsCfgPath)
|
||||
}
|
||||
|
||||
frpcCfgPath, err := config.GenerateConfigFile(consts.FRPC_NORMAL_CONFIG, FRPC_RELOAD_CONF_1)
|
||||
if assert.NoError(err) {
|
||||
rmFile1 := frpcCfgPath
|
||||
defer os.Remove(rmFile1)
|
||||
}
|
||||
|
||||
frpsProcess := util.NewProcess(consts.FRPS_BIN_PATH, []string{"-c", frpsCfgPath})
|
||||
err = frpsProcess.Start()
|
||||
if assert.NoError(err) {
|
||||
defer frpsProcess.Stop()
|
||||
}
|
||||
|
||||
time.Sleep(100 * time.Millisecond)
|
||||
|
||||
frpcProcess := util.NewProcess(consts.FRPC_BIN_PATH, []string{"-c", frpcCfgPath})
|
||||
err = frpcProcess.Start()
|
||||
if assert.NoError(err) {
|
||||
defer frpcProcess.Stop()
|
||||
}
|
||||
|
||||
time.Sleep(250 * time.Millisecond)
|
||||
|
||||
// test tcp1
|
||||
res, err := util.SendTcpMsg("127.0.0.1:20801", consts.TEST_TCP_ECHO_STR)
|
||||
assert.NoError(err)
|
||||
assert.Equal(consts.TEST_TCP_ECHO_STR, res)
|
||||
|
||||
// test tcp2
|
||||
res, err = util.SendTcpMsg("127.0.0.1:20802", consts.TEST_TCP_ECHO_STR)
|
||||
assert.NoError(err)
|
||||
assert.Equal(consts.TEST_TCP_ECHO_STR, res)
|
||||
|
||||
// test tcp3
|
||||
res, err = util.SendTcpMsg("127.0.0.1:20803", consts.TEST_TCP_ECHO_STR)
|
||||
assert.NoError(err)
|
||||
assert.Equal(consts.TEST_TCP_ECHO_STR, res)
|
||||
|
||||
// reload frpc config
|
||||
frpcCfgPath, err = config.GenerateConfigFile(consts.FRPC_NORMAL_CONFIG, FRPC_RELOAD_CONF_2)
|
||||
if assert.NoError(err) {
|
||||
rmFile2 := frpcCfgPath
|
||||
defer os.Remove(rmFile2)
|
||||
}
|
||||
err = util.ReloadConf("127.0.0.1:21000", "abc", "abc")
|
||||
assert.NoError(err)
|
||||
|
||||
time.Sleep(time.Second)
|
||||
|
||||
// test tcp1
|
||||
res, err = util.SendTcpMsg("127.0.0.1:20801", consts.TEST_TCP_ECHO_STR)
|
||||
assert.NoError(err)
|
||||
assert.Equal(consts.TEST_TCP_ECHO_STR, res)
|
||||
|
||||
// test origin tcp2, expect failed
|
||||
res, err = util.SendTcpMsg("127.0.0.1:20802", consts.TEST_TCP_ECHO_STR)
|
||||
assert.Error(err)
|
||||
|
||||
// test new origin tcp2 with different port
|
||||
res, err = util.SendTcpMsg("127.0.0.1:20902", consts.TEST_TCP_ECHO_STR)
|
||||
assert.NoError(err)
|
||||
assert.Equal(consts.TEST_TCP_ECHO_STR, res)
|
||||
|
||||
// test tcp3, expect failed
|
||||
res, err = util.SendTcpMsg("127.0.0.1:20803", consts.TEST_TCP_ECHO_STR)
|
||||
assert.Error(err)
|
||||
}
|
72
tests/ci/template_test.go
Normal file
72
tests/ci/template_test.go
Normal file
@@ -0,0 +1,72 @@
|
||||
package ci
|
||||
|
||||
import (
|
||||
"os"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/fatedier/frp/tests/config"
|
||||
"github.com/fatedier/frp/tests/consts"
|
||||
"github.com/fatedier/frp/tests/util"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
)
|
||||
|
||||
const FRPS_TEMPLATE_CONF = `
|
||||
[common]
|
||||
bind_addr = 0.0.0.0
|
||||
bind_port = {{ .Envs.SERVER_PORT }}
|
||||
log_file = console
|
||||
# debug, info, warn, error
|
||||
log_level = debug
|
||||
token = 123456
|
||||
`
|
||||
|
||||
const FRPC_TEMPLATE_CONF = `
|
||||
[common]
|
||||
server_addr = 127.0.0.1
|
||||
server_port = 20000
|
||||
log_file = console
|
||||
# debug, info, warn, error
|
||||
log_level = debug
|
||||
token = {{ .Envs.FRP_TOKEN }}
|
||||
|
||||
[tcp]
|
||||
type = tcp
|
||||
local_port = 10701
|
||||
remote_port = {{ .Envs.TCP_REMOTE_PORT }}
|
||||
`
|
||||
|
||||
func TestConfTemplate(t *testing.T) {
|
||||
assert := assert.New(t)
|
||||
frpsCfgPath, err := config.GenerateConfigFile(consts.FRPS_NORMAL_CONFIG, FRPS_TEMPLATE_CONF)
|
||||
if assert.NoError(err) {
|
||||
defer os.Remove(frpsCfgPath)
|
||||
}
|
||||
|
||||
frpcCfgPath, err := config.GenerateConfigFile(consts.FRPC_NORMAL_CONFIG, FRPC_TEMPLATE_CONF)
|
||||
if assert.NoError(err) {
|
||||
defer os.Remove(frpcCfgPath)
|
||||
}
|
||||
|
||||
frpsProcess := util.NewProcess("env", []string{"SERVER_PORT=20000", consts.FRPS_BIN_PATH, "-c", frpsCfgPath})
|
||||
err = frpsProcess.Start()
|
||||
if assert.NoError(err) {
|
||||
defer frpsProcess.Stop()
|
||||
}
|
||||
|
||||
time.Sleep(100 * time.Millisecond)
|
||||
|
||||
frpcProcess := util.NewProcess("env", []string{"FRP_TOKEN=123456", "TCP_REMOTE_PORT=20801", consts.FRPC_BIN_PATH, "-c", frpcCfgPath})
|
||||
err = frpcProcess.Start()
|
||||
if assert.NoError(err) {
|
||||
defer frpcProcess.Stop()
|
||||
}
|
||||
|
||||
time.Sleep(250 * time.Millisecond)
|
||||
|
||||
// test tcp1
|
||||
res, err := util.SendTcpMsg("127.0.0.1:20801", consts.TEST_TCP_ECHO_STR)
|
||||
assert.NoError(err)
|
||||
assert.Equal(consts.TEST_TCP_ECHO_STR, res)
|
||||
}
|
@@ -1,20 +0,0 @@
|
||||
#!/bin/bash
|
||||
|
||||
pid=`ps aux|grep './../bin/frps -c ./conf/auto_test_frps.ini'|grep -v grep|awk {'print $2'}`
|
||||
if [ -n "${pid}" ]; then
|
||||
kill ${pid}
|
||||
fi
|
||||
|
||||
pid=`ps aux|grep './../bin/frpc -c ./conf/auto_test_frpc.ini'|grep -v grep|awk {'print $2'}`
|
||||
if [ -n "${pid}" ]; then
|
||||
kill ${pid}
|
||||
fi
|
||||
|
||||
pid=`ps aux|grep './../bin/frpc -c ./conf/auto_test_frpc_visitor.ini'|grep -v grep|awk {'print $2'}`
|
||||
if [ -n "${pid}" ]; then
|
||||
kill ${pid}
|
||||
fi
|
||||
|
||||
rm -f ./frps.log
|
||||
rm -f ./frpc.log
|
||||
rm -f ./frpc_visitor.log
|
13
tests/config/config.go
Normal file
13
tests/config/config.go
Normal file
@@ -0,0 +1,13 @@
|
||||
package config
|
||||
|
||||
import (
|
||||
"io/ioutil"
|
||||
"os"
|
||||
"path/filepath"
|
||||
)
|
||||
|
||||
func GenerateConfigFile(path string, content string) (realPath string, err error) {
|
||||
realPath = filepath.Join(os.TempDir(), path)
|
||||
err = ioutil.WriteFile(realPath, []byte(content), 0666)
|
||||
return realPath, err
|
||||
}
|
71
tests/consts/consts.go
Normal file
71
tests/consts/consts.go
Normal file
@@ -0,0 +1,71 @@
|
||||
package consts
|
||||
|
||||
import "path/filepath"
|
||||
|
||||
var (
|
||||
FRPS_BIN_PATH = "../../bin/frps"
|
||||
FRPC_BIN_PATH = "../../bin/frpc"
|
||||
|
||||
FRPS_SUB_BIN_PATH = "../../../bin/frps"
|
||||
FRPC_SUB_BIN_PATH = "../../../bin/frpc"
|
||||
|
||||
FRPS_NORMAL_CONFIG = "./auto_test_frps.ini"
|
||||
FRPC_NORMAL_CONFIG = "./auto_test_frpc.ini"
|
||||
|
||||
SERVER_ADDR = "127.0.0.1"
|
||||
ADMIN_ADDR = "127.0.0.1:10600"
|
||||
ADMIN_USER = "abc"
|
||||
ADMIN_PWD = "abc"
|
||||
|
||||
TEST_STR = "frp is a fast reverse proxy to help you expose a local server behind a NAT or firewall to the internet."
|
||||
TEST_TCP_PORT int = 10701
|
||||
TEST_TCP2_PORT int = 10702
|
||||
TEST_TCP_FRP_PORT int = 10801
|
||||
TEST_TCP2_FRP_PORT int = 10802
|
||||
TEST_TCP_EC_FRP_PORT int = 10901
|
||||
TEST_TCP_ECHO_STR string = "tcp type:" + TEST_STR
|
||||
|
||||
TEST_UDP_PORT int = 10702
|
||||
TEST_UDP_FRP_PORT int = 10802
|
||||
TEST_UDP_EC_FRP_PORT int = 10902
|
||||
TEST_UDP_ECHO_STR string = "udp type:" + TEST_STR
|
||||
|
||||
TEST_UNIX_DOMAIN_ADDR string = "/tmp/frp_echo_server.sock"
|
||||
TEST_UNIX_DOMAIN_FRP_PORT int = 10803
|
||||
TEST_UNIX_DOMAIN_STR string = "unix domain type:" + TEST_STR
|
||||
|
||||
TEST_HTTP_PORT int = 10704
|
||||
TEST_HTTP_FRP_PORT int = 10804
|
||||
TEST_HTTP_NORMAL_STR string = "http normal string: " + TEST_STR
|
||||
TEST_HTTP_FOO_STR string = "http foo string: " + TEST_STR
|
||||
TEST_HTTP_BAR_STR string = "http bar string: " + TEST_STR
|
||||
|
||||
TEST_STCP_FRP_PORT int = 10805
|
||||
TEST_STCP_EC_FRP_PORT int = 10905
|
||||
TEST_STCP_ECHO_STR string = "stcp type:" + TEST_STR
|
||||
|
||||
ProxyTcpPortNotAllowed string = "tcp_port_not_allowed"
|
||||
ProxyTcpPortUnavailable string = "tcp_port_unavailable"
|
||||
ProxyTcpPortNormal string = "tcp_port_normal"
|
||||
ProxyTcpRandomPort string = "tcp_random_port"
|
||||
ProxyUdpPortNotAllowed string = "udp_port_not_allowed"
|
||||
ProxyUdpPortNormal string = "udp_port_normal"
|
||||
ProxyUdpRandomPort string = "udp_random_port"
|
||||
ProxyHttpProxy string = "http_proxy"
|
||||
|
||||
ProxyRangeTcpPrefix string = "range_tcp"
|
||||
)
|
||||
|
||||
func init() {
|
||||
if path, err := filepath.Abs(FRPS_BIN_PATH); err != nil {
|
||||
panic(err)
|
||||
} else {
|
||||
FRPS_BIN_PATH = path
|
||||
}
|
||||
|
||||
if path, err := filepath.Abs(FRPC_BIN_PATH); err != nil {
|
||||
panic(err)
|
||||
} else {
|
||||
FRPC_BIN_PATH = path
|
||||
}
|
||||
}
|
@@ -1,87 +0,0 @@
|
||||
package tests
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"io"
|
||||
"net"
|
||||
"os"
|
||||
"syscall"
|
||||
|
||||
frpNet "github.com/fatedier/frp/utils/net"
|
||||
)
|
||||
|
||||
func StartTcpEchoServer() {
|
||||
l, err := frpNet.ListenTcp("127.0.0.1", TEST_TCP_PORT)
|
||||
if err != nil {
|
||||
fmt.Printf("echo server listen error: %v\n", err)
|
||||
return
|
||||
}
|
||||
|
||||
for {
|
||||
c, err := l.Accept()
|
||||
if err != nil {
|
||||
fmt.Printf("echo server accept error: %v\n", err)
|
||||
return
|
||||
}
|
||||
|
||||
go echoWorker(c)
|
||||
}
|
||||
}
|
||||
|
||||
func StartUdpEchoServer() {
|
||||
l, err := frpNet.ListenUDP("127.0.0.1", TEST_UDP_PORT)
|
||||
if err != nil {
|
||||
fmt.Printf("udp echo server listen error: %v\n", err)
|
||||
return
|
||||
}
|
||||
|
||||
for {
|
||||
c, err := l.Accept()
|
||||
if err != nil {
|
||||
fmt.Printf("udp echo server accept error: %v\n", err)
|
||||
return
|
||||
}
|
||||
|
||||
go echoWorker(c)
|
||||
}
|
||||
}
|
||||
|
||||
func StartUnixDomainServer() {
|
||||
unixPath := TEST_UNIX_DOMAIN_ADDR
|
||||
os.Remove(unixPath)
|
||||
syscall.Umask(0)
|
||||
l, err := net.Listen("unix", unixPath)
|
||||
if err != nil {
|
||||
fmt.Printf("unix domain server listen error: %v\n", err)
|
||||
return
|
||||
}
|
||||
|
||||
for {
|
||||
c, err := l.Accept()
|
||||
if err != nil {
|
||||
fmt.Printf("unix domain server accept error: %v\n", err)
|
||||
return
|
||||
}
|
||||
|
||||
go echoWorker(c)
|
||||
}
|
||||
}
|
||||
|
||||
func echoWorker(c net.Conn) {
|
||||
buf := make([]byte, 2048)
|
||||
|
||||
for {
|
||||
n, err := c.Read(buf)
|
||||
if err != nil {
|
||||
if err == io.EOF {
|
||||
c.Close()
|
||||
break
|
||||
} else {
|
||||
fmt.Printf("echo server read error: %v\n", err)
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
c.Write(buf[:n])
|
||||
}
|
||||
}
|
@@ -1,302 +0,0 @@
|
||||
package tests
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"net/url"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/gorilla/websocket"
|
||||
"github.com/stretchr/testify/assert"
|
||||
|
||||
"github.com/fatedier/frp/client"
|
||||
"github.com/fatedier/frp/server"
|
||||
|
||||
gnet "github.com/fatedier/golib/net"
|
||||
)
|
||||
|
||||
var (
|
||||
SERVER_ADDR = "127.0.0.1"
|
||||
ADMIN_ADDR = "127.0.0.1:10600"
|
||||
ADMIN_USER = "abc"
|
||||
ADMIN_PWD = "abc"
|
||||
|
||||
TEST_STR = "frp is a fast reverse proxy to help you expose a local server behind a NAT or firewall to the internet."
|
||||
TEST_TCP_PORT int = 10701
|
||||
TEST_TCP_FRP_PORT int = 10801
|
||||
TEST_TCP_EC_FRP_PORT int = 10901
|
||||
TEST_TCP_ECHO_STR string = "tcp type:" + TEST_STR
|
||||
|
||||
TEST_UDP_PORT int = 10702
|
||||
TEST_UDP_FRP_PORT int = 10802
|
||||
TEST_UDP_EC_FRP_PORT int = 10902
|
||||
TEST_UDP_ECHO_STR string = "udp type:" + TEST_STR
|
||||
|
||||
TEST_UNIX_DOMAIN_ADDR string = "/tmp/frp_echo_server.sock"
|
||||
TEST_UNIX_DOMAIN_FRP_PORT int = 10803
|
||||
TEST_UNIX_DOMAIN_STR string = "unix domain type:" + TEST_STR
|
||||
|
||||
TEST_HTTP_PORT int = 10704
|
||||
TEST_HTTP_FRP_PORT int = 10804
|
||||
TEST_HTTP_NORMAL_STR string = "http normal string: " + TEST_STR
|
||||
TEST_HTTP_FOO_STR string = "http foo string: " + TEST_STR
|
||||
TEST_HTTP_BAR_STR string = "http bar string: " + TEST_STR
|
||||
|
||||
TEST_STCP_FRP_PORT int = 10805
|
||||
TEST_STCP_EC_FRP_PORT int = 10905
|
||||
TEST_STCP_ECHO_STR string = "stcp type:" + TEST_STR
|
||||
|
||||
ProxyTcpPortNotAllowed string = "tcp_port_not_allowed"
|
||||
ProxyTcpPortUnavailable string = "tcp_port_unavailable"
|
||||
ProxyTcpPortNormal string = "tcp_port_normal"
|
||||
ProxyTcpRandomPort string = "tcp_random_port"
|
||||
ProxyUdpPortNotAllowed string = "udp_port_not_allowed"
|
||||
ProxyUdpPortNormal string = "udp_port_normal"
|
||||
ProxyUdpRandomPort string = "udp_random_port"
|
||||
ProxyHttpProxy string = "http_proxy"
|
||||
|
||||
ProxyRangeTcpPrefix string = "range_tcp"
|
||||
)
|
||||
|
||||
func init() {
|
||||
go StartTcpEchoServer()
|
||||
go StartUdpEchoServer()
|
||||
go StartUnixDomainServer()
|
||||
go StartHttpServer()
|
||||
time.Sleep(500 * time.Millisecond)
|
||||
}
|
||||
|
||||
func TestTcp(t *testing.T) {
|
||||
assert := assert.New(t)
|
||||
// Normal
|
||||
addr := fmt.Sprintf("127.0.0.1:%d", TEST_TCP_FRP_PORT)
|
||||
res, err := sendTcpMsg(addr, TEST_TCP_ECHO_STR)
|
||||
assert.NoError(err)
|
||||
assert.Equal(TEST_TCP_ECHO_STR, res)
|
||||
|
||||
// Encrytion and compression
|
||||
addr = fmt.Sprintf("127.0.0.1:%d", TEST_TCP_EC_FRP_PORT)
|
||||
res, err = sendTcpMsg(addr, TEST_TCP_ECHO_STR)
|
||||
assert.NoError(err)
|
||||
assert.Equal(TEST_TCP_ECHO_STR, res)
|
||||
}
|
||||
|
||||
func TestUdp(t *testing.T) {
|
||||
assert := assert.New(t)
|
||||
// Normal
|
||||
addr := fmt.Sprintf("127.0.0.1:%d", TEST_UDP_FRP_PORT)
|
||||
res, err := sendUdpMsg(addr, TEST_UDP_ECHO_STR)
|
||||
assert.NoError(err)
|
||||
assert.Equal(TEST_UDP_ECHO_STR, res)
|
||||
|
||||
// Encrytion and compression
|
||||
addr = fmt.Sprintf("127.0.0.1:%d", TEST_UDP_EC_FRP_PORT)
|
||||
res, err = sendUdpMsg(addr, TEST_UDP_ECHO_STR)
|
||||
assert.NoError(err)
|
||||
assert.Equal(TEST_UDP_ECHO_STR, res)
|
||||
}
|
||||
|
||||
func TestUnixDomain(t *testing.T) {
|
||||
assert := assert.New(t)
|
||||
// Normal
|
||||
addr := fmt.Sprintf("127.0.0.1:%d", TEST_UNIX_DOMAIN_FRP_PORT)
|
||||
res, err := sendTcpMsg(addr, TEST_UNIX_DOMAIN_STR)
|
||||
if assert.NoError(err) {
|
||||
assert.Equal(TEST_UNIX_DOMAIN_STR, res)
|
||||
}
|
||||
}
|
||||
|
||||
func TestStcp(t *testing.T) {
|
||||
assert := assert.New(t)
|
||||
// Normal
|
||||
addr := fmt.Sprintf("127.0.0.1:%d", TEST_STCP_FRP_PORT)
|
||||
res, err := sendTcpMsg(addr, TEST_STCP_ECHO_STR)
|
||||
if assert.NoError(err) {
|
||||
assert.Equal(TEST_STCP_ECHO_STR, res)
|
||||
}
|
||||
|
||||
// Encrytion and compression
|
||||
addr = fmt.Sprintf("127.0.0.1:%d", TEST_STCP_EC_FRP_PORT)
|
||||
res, err = sendTcpMsg(addr, TEST_STCP_ECHO_STR)
|
||||
if assert.NoError(err) {
|
||||
assert.Equal(TEST_STCP_ECHO_STR, res)
|
||||
}
|
||||
}
|
||||
|
||||
func TestHttp(t *testing.T) {
|
||||
assert := assert.New(t)
|
||||
// web01
|
||||
code, body, err := sendHttpMsg("GET", fmt.Sprintf("http://127.0.0.1:%d", TEST_HTTP_FRP_PORT), "", nil, "")
|
||||
if assert.NoError(err) {
|
||||
assert.Equal(200, code)
|
||||
assert.Equal(TEST_HTTP_NORMAL_STR, body)
|
||||
}
|
||||
|
||||
// web02
|
||||
code, body, err = sendHttpMsg("GET", fmt.Sprintf("http://127.0.0.1:%d", TEST_HTTP_FRP_PORT), "test2.frp.com", nil, "")
|
||||
if assert.NoError(err) {
|
||||
assert.Equal(200, code)
|
||||
assert.Equal(TEST_HTTP_NORMAL_STR, body)
|
||||
}
|
||||
|
||||
// error host header
|
||||
code, body, err = sendHttpMsg("GET", fmt.Sprintf("http://127.0.0.1:%d", TEST_HTTP_FRP_PORT), "errorhost.frp.com", nil, "")
|
||||
if assert.NoError(err) {
|
||||
assert.Equal(404, code)
|
||||
}
|
||||
|
||||
// web03
|
||||
code, body, err = sendHttpMsg("GET", fmt.Sprintf("http://127.0.0.1:%d", TEST_HTTP_FRP_PORT), "test3.frp.com", nil, "")
|
||||
if assert.NoError(err) {
|
||||
assert.Equal(200, code)
|
||||
assert.Equal(TEST_HTTP_NORMAL_STR, body)
|
||||
}
|
||||
|
||||
code, body, err = sendHttpMsg("GET", fmt.Sprintf("http://127.0.0.1:%d/foo", TEST_HTTP_FRP_PORT), "test3.frp.com", nil, "")
|
||||
if assert.NoError(err) {
|
||||
assert.Equal(200, code)
|
||||
assert.Equal(TEST_HTTP_FOO_STR, body)
|
||||
}
|
||||
|
||||
// web04
|
||||
code, body, err = sendHttpMsg("GET", fmt.Sprintf("http://127.0.0.1:%d/bar", TEST_HTTP_FRP_PORT), "test3.frp.com", nil, "")
|
||||
if assert.NoError(err) {
|
||||
assert.Equal(200, code)
|
||||
assert.Equal(TEST_HTTP_BAR_STR, body)
|
||||
}
|
||||
|
||||
// web05
|
||||
code, body, err = sendHttpMsg("GET", fmt.Sprintf("http://127.0.0.1:%d", TEST_HTTP_FRP_PORT), "test5.frp.com", nil, "")
|
||||
if assert.NoError(err) {
|
||||
assert.Equal(401, code)
|
||||
}
|
||||
|
||||
header := make(map[string]string)
|
||||
header["Authorization"] = basicAuth("test", "test")
|
||||
code, body, err = sendHttpMsg("GET", fmt.Sprintf("http://127.0.0.1:%d", TEST_HTTP_FRP_PORT), "test5.frp.com", header, "")
|
||||
if assert.NoError(err) {
|
||||
assert.Equal(401, code)
|
||||
}
|
||||
|
||||
// subhost01
|
||||
code, body, err = sendHttpMsg("GET", fmt.Sprintf("http://127.0.0.1:%d", TEST_HTTP_FRP_PORT), "test01.sub.com", nil, "")
|
||||
if assert.NoError(err) {
|
||||
assert.Equal(200, code)
|
||||
assert.Equal("test01.sub.com", body)
|
||||
}
|
||||
|
||||
// subhost02
|
||||
code, body, err = sendHttpMsg("GET", fmt.Sprintf("http://127.0.0.1:%d", TEST_HTTP_FRP_PORT), "test02.sub.com", nil, "")
|
||||
if assert.NoError(err) {
|
||||
assert.Equal(200, code)
|
||||
assert.Equal("test02.sub.com", body)
|
||||
}
|
||||
}
|
||||
|
||||
func TestWebSocket(t *testing.T) {
|
||||
assert := assert.New(t)
|
||||
|
||||
u := url.URL{Scheme: "ws", Host: fmt.Sprintf("%s:%d", "127.0.0.1", TEST_HTTP_FRP_PORT), Path: "/ws"}
|
||||
c, _, err := websocket.DefaultDialer.Dial(u.String(), nil)
|
||||
assert.NoError(err)
|
||||
defer c.Close()
|
||||
|
||||
err = c.WriteMessage(websocket.TextMessage, []byte(TEST_HTTP_NORMAL_STR))
|
||||
assert.NoError(err)
|
||||
|
||||
_, msg, err := c.ReadMessage()
|
||||
assert.NoError(err)
|
||||
assert.Equal(TEST_HTTP_NORMAL_STR, string(msg))
|
||||
}
|
||||
|
||||
func TestAllowPorts(t *testing.T) {
|
||||
assert := assert.New(t)
|
||||
// Port not allowed
|
||||
status, err := getProxyStatus(ProxyTcpPortNotAllowed)
|
||||
if assert.NoError(err) {
|
||||
assert.Equal(client.ProxyStatusStartErr, status.Status)
|
||||
assert.True(strings.Contains(status.Err, server.ErrPortNotAllowed.Error()))
|
||||
}
|
||||
|
||||
status, err = getProxyStatus(ProxyUdpPortNotAllowed)
|
||||
if assert.NoError(err) {
|
||||
assert.Equal(client.ProxyStatusStartErr, status.Status)
|
||||
assert.True(strings.Contains(status.Err, server.ErrPortNotAllowed.Error()))
|
||||
}
|
||||
|
||||
status, err = getProxyStatus(ProxyTcpPortUnavailable)
|
||||
if assert.NoError(err) {
|
||||
assert.Equal(client.ProxyStatusStartErr, status.Status)
|
||||
assert.True(strings.Contains(status.Err, server.ErrPortUnAvailable.Error()))
|
||||
}
|
||||
|
||||
// Port normal
|
||||
status, err = getProxyStatus(ProxyTcpPortNormal)
|
||||
if assert.NoError(err) {
|
||||
assert.Equal(client.ProxyStatusRunning, status.Status)
|
||||
}
|
||||
|
||||
status, err = getProxyStatus(ProxyUdpPortNormal)
|
||||
if assert.NoError(err) {
|
||||
assert.Equal(client.ProxyStatusRunning, status.Status)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRandomPort(t *testing.T) {
|
||||
assert := assert.New(t)
|
||||
// tcp
|
||||
status, err := getProxyStatus(ProxyTcpRandomPort)
|
||||
if assert.NoError(err) {
|
||||
addr := status.RemoteAddr
|
||||
res, err := sendTcpMsg(addr, TEST_TCP_ECHO_STR)
|
||||
assert.NoError(err)
|
||||
assert.Equal(TEST_TCP_ECHO_STR, res)
|
||||
}
|
||||
|
||||
// udp
|
||||
status, err = getProxyStatus(ProxyUdpRandomPort)
|
||||
if assert.NoError(err) {
|
||||
addr := status.RemoteAddr
|
||||
res, err := sendUdpMsg(addr, TEST_UDP_ECHO_STR)
|
||||
assert.NoError(err)
|
||||
assert.Equal(TEST_UDP_ECHO_STR, res)
|
||||
}
|
||||
}
|
||||
|
||||
func TestPluginHttpProxy(t *testing.T) {
|
||||
assert := assert.New(t)
|
||||
status, err := getProxyStatus(ProxyHttpProxy)
|
||||
if assert.NoError(err) {
|
||||
assert.Equal(client.ProxyStatusRunning, status.Status)
|
||||
|
||||
// http proxy
|
||||
addr := status.RemoteAddr
|
||||
code, body, err := sendHttpMsg("GET", fmt.Sprintf("http://127.0.0.1:%d", TEST_HTTP_FRP_PORT),
|
||||
"", nil, "http://"+addr)
|
||||
if assert.NoError(err) {
|
||||
assert.Equal(200, code)
|
||||
assert.Equal(TEST_HTTP_NORMAL_STR, body)
|
||||
}
|
||||
|
||||
// connect method
|
||||
conn, err := gnet.DialTcpByProxy("http://"+addr, fmt.Sprintf("127.0.0.1:%d", TEST_TCP_FRP_PORT))
|
||||
if assert.NoError(err) {
|
||||
res, err := sendTcpMsgByConn(conn, TEST_TCP_ECHO_STR)
|
||||
assert.NoError(err)
|
||||
assert.Equal(TEST_TCP_ECHO_STR, res)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestRangePortsMapping(t *testing.T) {
|
||||
assert := assert.New(t)
|
||||
|
||||
for i := 0; i < 3; i++ {
|
||||
name := fmt.Sprintf("%s_%d", ProxyRangeTcpPrefix, i)
|
||||
status, err := getProxyStatus(name)
|
||||
if assert.NoError(err) {
|
||||
assert.Equal(client.ProxyStatusRunning, status.Status)
|
||||
}
|
||||
}
|
||||
}
|
120
tests/mock/echo_server.go
Normal file
120
tests/mock/echo_server.go
Normal file
@@ -0,0 +1,120 @@
|
||||
package mock
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"io"
|
||||
"net"
|
||||
"os"
|
||||
"syscall"
|
||||
|
||||
frpNet "github.com/fatedier/frp/utils/net"
|
||||
)
|
||||
|
||||
type EchoServer struct {
|
||||
l frpNet.Listener
|
||||
|
||||
port int
|
||||
repeatedNum int
|
||||
specifyStr string
|
||||
}
|
||||
|
||||
func NewEchoServer(port int, repeatedNum int, specifyStr string) *EchoServer {
|
||||
if repeatedNum <= 0 {
|
||||
repeatedNum = 1
|
||||
}
|
||||
return &EchoServer{
|
||||
port: port,
|
||||
repeatedNum: repeatedNum,
|
||||
specifyStr: specifyStr,
|
||||
}
|
||||
}
|
||||
|
||||
func (es *EchoServer) Start() error {
|
||||
l, err := frpNet.ListenTcp("127.0.0.1", es.port)
|
||||
if err != nil {
|
||||
fmt.Printf("echo server listen error: %v\n", err)
|
||||
return err
|
||||
}
|
||||
es.l = l
|
||||
|
||||
go func() {
|
||||
for {
|
||||
c, err := l.Accept()
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
go echoWorker(c, es.repeatedNum, es.specifyStr)
|
||||
}
|
||||
}()
|
||||
return nil
|
||||
}
|
||||
|
||||
func (es *EchoServer) Stop() {
|
||||
es.l.Close()
|
||||
}
|
||||
|
||||
func StartUdpEchoServer(port int) {
|
||||
l, err := frpNet.ListenUDP("127.0.0.1", port)
|
||||
if err != nil {
|
||||
fmt.Printf("udp echo server listen error: %v\n", err)
|
||||
return
|
||||
}
|
||||
|
||||
for {
|
||||
c, err := l.Accept()
|
||||
if err != nil {
|
||||
fmt.Printf("udp echo server accept error: %v\n", err)
|
||||
return
|
||||
}
|
||||
|
||||
go echoWorker(c, 1, "")
|
||||
}
|
||||
}
|
||||
|
||||
func StartUnixDomainServer(unixPath string) {
|
||||
os.Remove(unixPath)
|
||||
syscall.Umask(0)
|
||||
l, err := net.Listen("unix", unixPath)
|
||||
if err != nil {
|
||||
fmt.Printf("unix domain server listen error: %v\n", err)
|
||||
return
|
||||
}
|
||||
|
||||
for {
|
||||
c, err := l.Accept()
|
||||
if err != nil {
|
||||
fmt.Printf("unix domain server accept error: %v\n", err)
|
||||
return
|
||||
}
|
||||
|
||||
go echoWorker(c, 1, "")
|
||||
}
|
||||
}
|
||||
|
||||
func echoWorker(c net.Conn, repeatedNum int, specifyStr string) {
|
||||
buf := make([]byte, 2048)
|
||||
|
||||
for {
|
||||
n, err := c.Read(buf)
|
||||
if err != nil {
|
||||
if err == io.EOF {
|
||||
c.Close()
|
||||
break
|
||||
} else {
|
||||
fmt.Printf("echo server read error: %v\n", err)
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
if specifyStr != "" {
|
||||
c.Write([]byte(specifyStr))
|
||||
} else {
|
||||
var w []byte
|
||||
for i := 0; i < repeatedNum; i++ {
|
||||
w = append(w, buf[:n]...)
|
||||
}
|
||||
c.Write(w)
|
||||
}
|
||||
}
|
||||
}
|
@@ -1,21 +1,54 @@
|
||||
package tests
|
||||
package mock
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"log"
|
||||
"net"
|
||||
"net/http"
|
||||
"regexp"
|
||||
"strings"
|
||||
|
||||
"github.com/fatedier/frp/tests/consts"
|
||||
|
||||
"github.com/gorilla/websocket"
|
||||
)
|
||||
|
||||
type HttpServer struct {
|
||||
l net.Listener
|
||||
|
||||
port int
|
||||
handler http.HandlerFunc
|
||||
}
|
||||
|
||||
func NewHttpServer(port int, handler http.HandlerFunc) *HttpServer {
|
||||
return &HttpServer{
|
||||
port: port,
|
||||
handler: handler,
|
||||
}
|
||||
}
|
||||
|
||||
func (hs *HttpServer) Start() error {
|
||||
l, err := net.Listen("tcp", fmt.Sprintf("127.0.0.1:%d", hs.port))
|
||||
if err != nil {
|
||||
fmt.Printf("http server listen error: %v\n", err)
|
||||
return err
|
||||
}
|
||||
hs.l = l
|
||||
|
||||
go http.Serve(l, http.HandlerFunc(hs.handler))
|
||||
return nil
|
||||
}
|
||||
|
||||
func (hs *HttpServer) Stop() {
|
||||
hs.l.Close()
|
||||
}
|
||||
|
||||
var upgrader = websocket.Upgrader{}
|
||||
|
||||
func StartHttpServer() {
|
||||
func StartHttpServer(port int) {
|
||||
http.HandleFunc("/", handleHttp)
|
||||
http.HandleFunc("/ws", handleWebSocket)
|
||||
http.ListenAndServe(fmt.Sprintf("0.0.0.0:%d", TEST_HTTP_PORT), nil)
|
||||
http.ListenAndServe(fmt.Sprintf("0.0.0.0:%d", port), nil)
|
||||
}
|
||||
|
||||
func handleWebSocket(w http.ResponseWriter, r *http.Request) {
|
||||
@@ -39,6 +72,10 @@ func handleWebSocket(w http.ResponseWriter, r *http.Request) {
|
||||
}
|
||||
|
||||
func handleHttp(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Header.Get("X-From-Where") == "frp" {
|
||||
w.Header().Set("X-Header-Set", "true")
|
||||
}
|
||||
|
||||
match, err := regexp.Match(`.*\.sub\.com`, []byte(r.Host))
|
||||
if err != nil {
|
||||
w.WriteHeader(500)
|
||||
@@ -52,17 +89,17 @@ func handleHttp(w http.ResponseWriter, r *http.Request) {
|
||||
}
|
||||
|
||||
if strings.Contains(r.Host, "127.0.0.1") || strings.Contains(r.Host, "test2.frp.com") ||
|
||||
strings.Contains(r.Host, "test5.frp.com") {
|
||||
strings.Contains(r.Host, "test5.frp.com") || strings.Contains(r.Host, "test6.frp.com") {
|
||||
w.WriteHeader(200)
|
||||
w.Write([]byte(TEST_HTTP_NORMAL_STR))
|
||||
w.Write([]byte(consts.TEST_HTTP_NORMAL_STR))
|
||||
} else if strings.Contains(r.Host, "test3.frp.com") {
|
||||
w.WriteHeader(200)
|
||||
if strings.Contains(r.URL.Path, "foo") {
|
||||
w.Write([]byte(TEST_HTTP_FOO_STR))
|
||||
w.Write([]byte(consts.TEST_HTTP_FOO_STR))
|
||||
} else if strings.Contains(r.URL.Path, "bar") {
|
||||
w.Write([]byte(TEST_HTTP_BAR_STR))
|
||||
w.Write([]byte(consts.TEST_HTTP_BAR_STR))
|
||||
} else {
|
||||
w.Write([]byte(TEST_HTTP_NORMAL_STR))
|
||||
w.Write([]byte(consts.TEST_HTTP_NORMAL_STR))
|
||||
}
|
||||
} else {
|
||||
w.WriteHeader(404)
|
@@ -1,9 +0,0 @@
|
||||
#!/bin/bash
|
||||
|
||||
./../bin/frps -c ./conf/auto_test_frps.ini &
|
||||
sleep 1
|
||||
./../bin/frpc -c ./conf/auto_test_frpc.ini &
|
||||
./../bin/frpc -c ./conf/auto_test_frpc_visitor.ini &
|
||||
|
||||
# wait until proxies are connected
|
||||
sleep 2
|
47
tests/util/process.go
Normal file
47
tests/util/process.go
Normal file
@@ -0,0 +1,47 @@
|
||||
package util
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"os/exec"
|
||||
)
|
||||
|
||||
type Process struct {
|
||||
cmd *exec.Cmd
|
||||
cancel context.CancelFunc
|
||||
errorOutput *bytes.Buffer
|
||||
|
||||
beforeStopHandler func()
|
||||
}
|
||||
|
||||
func NewProcess(path string, params []string) *Process {
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
cmd := exec.CommandContext(ctx, path, params...)
|
||||
p := &Process{
|
||||
cmd: cmd,
|
||||
cancel: cancel,
|
||||
}
|
||||
p.errorOutput = bytes.NewBufferString("")
|
||||
cmd.Stderr = p.errorOutput
|
||||
return p
|
||||
}
|
||||
|
||||
func (p *Process) Start() error {
|
||||
return p.cmd.Start()
|
||||
}
|
||||
|
||||
func (p *Process) Stop() error {
|
||||
if p.beforeStopHandler != nil {
|
||||
p.beforeStopHandler()
|
||||
}
|
||||
p.cancel()
|
||||
return p.cmd.Wait()
|
||||
}
|
||||
|
||||
func (p *Process) ErrorOutput() string {
|
||||
return p.errorOutput.String()
|
||||
}
|
||||
|
||||
func (p *Process) SetBeforeStopHandler(fn func()) {
|
||||
p.beforeStopHandler = fn
|
||||
}
|
@@ -1,10 +1,11 @@
|
||||
package tests
|
||||
package util
|
||||
|
||||
import (
|
||||
"encoding/base64"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"io/ioutil"
|
||||
"net"
|
||||
"net/http"
|
||||
@@ -16,13 +17,13 @@ import (
|
||||
frpNet "github.com/fatedier/frp/utils/net"
|
||||
)
|
||||
|
||||
func getProxyStatus(name string) (status *client.ProxyStatusResp, err error) {
|
||||
req, err := http.NewRequest("GET", "http://"+ADMIN_ADDR+"/api/status", nil)
|
||||
func GetProxyStatus(statusAddr string, user string, passwd string, name string) (status *client.ProxyStatusResp, err error) {
|
||||
req, err := http.NewRequest("GET", "http://"+statusAddr+"/api/status", nil)
|
||||
if err != nil {
|
||||
return status, err
|
||||
}
|
||||
|
||||
authStr := "Basic " + base64.StdEncoding.EncodeToString([]byte(ADMIN_USER+":"+ADMIN_PWD))
|
||||
authStr := "Basic " + base64.StdEncoding.EncodeToString([]byte(user+":"+passwd))
|
||||
req.Header.Add("Authorization", authStr)
|
||||
resp, err := http.DefaultClient.Do(req)
|
||||
if err != nil {
|
||||
@@ -75,17 +76,38 @@ func getProxyStatus(name string) (status *client.ProxyStatusResp, err error) {
|
||||
return status, errors.New("no proxy status found")
|
||||
}
|
||||
|
||||
func sendTcpMsg(addr string, msg string) (res string, err error) {
|
||||
func ReloadConf(reloadAddr string, user string, passwd string) error {
|
||||
req, err := http.NewRequest("GET", "http://"+reloadAddr+"/api/reload", nil)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
authStr := "Basic " + base64.StdEncoding.EncodeToString([]byte(user+":"+passwd))
|
||||
req.Header.Add("Authorization", authStr)
|
||||
resp, err := http.DefaultClient.Do(req)
|
||||
if err != nil {
|
||||
return err
|
||||
} else {
|
||||
if resp.StatusCode != 200 {
|
||||
return fmt.Errorf("admin api status code [%d]", resp.StatusCode)
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
io.Copy(ioutil.Discard, resp.Body)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func SendTcpMsg(addr string, msg string) (res string, err error) {
|
||||
c, err := frpNet.ConnectTcpServer(addr)
|
||||
if err != nil {
|
||||
err = fmt.Errorf("connect to tcp server error: %v", err)
|
||||
return
|
||||
}
|
||||
defer c.Close()
|
||||
return sendTcpMsgByConn(c, msg)
|
||||
return SendTcpMsgByConn(c, msg)
|
||||
}
|
||||
|
||||
func sendTcpMsgByConn(c net.Conn, msg string) (res string, err error) {
|
||||
func SendTcpMsgByConn(c net.Conn, msg string) (res string, err error) {
|
||||
timer := time.Now().Add(5 * time.Second)
|
||||
c.SetDeadline(timer)
|
||||
c.Write([]byte(msg))
|
||||
@@ -99,7 +121,7 @@ func sendTcpMsgByConn(c net.Conn, msg string) (res string, err error) {
|
||||
return string(buf[:n]), nil
|
||||
}
|
||||
|
||||
func sendUdpMsg(addr string, msg string) (res string, err error) {
|
||||
func SendUdpMsg(addr string, msg string) (res string, err error) {
|
||||
udpAddr, errRet := net.ResolveUDPAddr("udp", addr)
|
||||
if errRet != nil {
|
||||
err = fmt.Errorf("resolve udp addr error: %v", err)
|
||||
@@ -126,7 +148,7 @@ func sendUdpMsg(addr string, msg string) (res string, err error) {
|
||||
return string(buf[:n]), nil
|
||||
}
|
||||
|
||||
func sendHttpMsg(method, urlStr string, host string, header map[string]string, proxy string) (code int, body string, err error) {
|
||||
func SendHttpMsg(method, urlStr string, host string, headers map[string]string, proxy string) (code int, body string, header http.Header, err error) {
|
||||
req, errRet := http.NewRequest(method, urlStr, nil)
|
||||
if errRet != nil {
|
||||
err = errRet
|
||||
@@ -136,7 +158,7 @@ func sendHttpMsg(method, urlStr string, host string, header map[string]string, p
|
||||
if host != "" {
|
||||
req.Host = host
|
||||
}
|
||||
for k, v := range header {
|
||||
for k, v := range headers {
|
||||
req.Header.Set(k, v)
|
||||
}
|
||||
|
||||
@@ -167,6 +189,7 @@ func sendHttpMsg(method, urlStr string, host string, header map[string]string, p
|
||||
return
|
||||
}
|
||||
code = resp.StatusCode
|
||||
header = resp.Header
|
||||
buf, errRet := ioutil.ReadAll(resp.Body)
|
||||
if errRet != nil {
|
||||
err = errRet
|
||||
@@ -176,7 +199,7 @@ func sendHttpMsg(method, urlStr string, host string, header map[string]string, p
|
||||
return
|
||||
}
|
||||
|
||||
func basicAuth(username, passwd string) string {
|
||||
func BasicAuth(username, passwd string) string {
|
||||
auth := username + ":" + passwd
|
||||
return "Basic " + base64.StdEncoding.EncodeToString([]byte(auth))
|
||||
}
|
@@ -96,45 +96,34 @@ func (conn *WrapReadWriteCloserConn) SetWriteDeadline(t time.Time) error {
|
||||
return &net.OpError{Op: "set", Net: "wrap", Source: nil, Addr: nil, Err: errors.New("deadline not supported")}
|
||||
}
|
||||
|
||||
func ConnectServer(protocol string, addr string) (c Conn, err error) {
|
||||
switch protocol {
|
||||
case "tcp":
|
||||
return ConnectTcpServer(addr)
|
||||
case "kcp":
|
||||
kcpConn, errRet := kcp.DialWithOptions(addr, nil, 10, 3)
|
||||
if errRet != nil {
|
||||
err = errRet
|
||||
return
|
||||
}
|
||||
kcpConn.SetStreamMode(true)
|
||||
kcpConn.SetWriteDelay(true)
|
||||
kcpConn.SetNoDelay(1, 20, 2, 1)
|
||||
kcpConn.SetWindowSize(128, 512)
|
||||
kcpConn.SetMtu(1350)
|
||||
kcpConn.SetACKNoDelay(false)
|
||||
kcpConn.SetReadBuffer(4194304)
|
||||
kcpConn.SetWriteBuffer(4194304)
|
||||
c = WrapConn(kcpConn)
|
||||
return
|
||||
default:
|
||||
return nil, fmt.Errorf("unsupport protocol: %s", protocol)
|
||||
type CloseNotifyConn struct {
|
||||
net.Conn
|
||||
log.Logger
|
||||
|
||||
// 1 means closed
|
||||
closeFlag int32
|
||||
|
||||
closeFn func()
|
||||
}
|
||||
|
||||
// closeFn will be only called once
|
||||
func WrapCloseNotifyConn(c net.Conn, closeFn func()) Conn {
|
||||
return &CloseNotifyConn{
|
||||
Conn: c,
|
||||
Logger: log.NewPrefixLogger(""),
|
||||
closeFn: closeFn,
|
||||
}
|
||||
}
|
||||
|
||||
func ConnectServerByProxy(proxyUrl string, protocol string, addr string) (c Conn, err error) {
|
||||
switch protocol {
|
||||
case "tcp":
|
||||
var conn net.Conn
|
||||
if conn, err = gnet.DialTcpByProxy(proxyUrl, addr); err != nil {
|
||||
return
|
||||
func (cc *CloseNotifyConn) Close() (err error) {
|
||||
pflag := atomic.SwapInt32(&cc.closeFlag, 1)
|
||||
if pflag == 0 {
|
||||
err = cc.Close()
|
||||
if cc.closeFn != nil {
|
||||
cc.closeFn()
|
||||
}
|
||||
return WrapConn(conn), nil
|
||||
case "kcp":
|
||||
// http proxy is not supported for kcp
|
||||
return ConnectServer(protocol, addr)
|
||||
default:
|
||||
return nil, fmt.Errorf("unsupport protocol: %s", protocol)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
type StatsConn struct {
|
||||
@@ -175,3 +164,46 @@ func (statsConn *StatsConn) Close() (err error) {
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
func ConnectServer(protocol string, addr string) (c Conn, err error) {
|
||||
switch protocol {
|
||||
case "tcp":
|
||||
return ConnectTcpServer(addr)
|
||||
case "kcp":
|
||||
kcpConn, errRet := kcp.DialWithOptions(addr, nil, 10, 3)
|
||||
if errRet != nil {
|
||||
err = errRet
|
||||
return
|
||||
}
|
||||
kcpConn.SetStreamMode(true)
|
||||
kcpConn.SetWriteDelay(true)
|
||||
kcpConn.SetNoDelay(1, 20, 2, 1)
|
||||
kcpConn.SetWindowSize(128, 512)
|
||||
kcpConn.SetMtu(1350)
|
||||
kcpConn.SetACKNoDelay(false)
|
||||
kcpConn.SetReadBuffer(4194304)
|
||||
kcpConn.SetWriteBuffer(4194304)
|
||||
c = WrapConn(kcpConn)
|
||||
return
|
||||
default:
|
||||
return nil, fmt.Errorf("unsupport protocol: %s", protocol)
|
||||
}
|
||||
}
|
||||
|
||||
func ConnectServerByProxy(proxyUrl string, protocol string, addr string) (c Conn, err error) {
|
||||
switch protocol {
|
||||
case "tcp":
|
||||
var conn net.Conn
|
||||
if conn, err = gnet.DialTcpByProxy(proxyUrl, addr); err != nil {
|
||||
return
|
||||
}
|
||||
return WrapConn(conn), nil
|
||||
case "kcp":
|
||||
// http proxy is not supported for kcp
|
||||
return ConnectServer(protocol, addr)
|
||||
case "websocket":
|
||||
return ConnectWebsocketServer(addr)
|
||||
default:
|
||||
return nil, fmt.Errorf("unsupport protocol: %s", protocol)
|
||||
}
|
||||
}
|
||||
|
@@ -19,8 +19,6 @@ import (
|
||||
"io"
|
||||
"net/http"
|
||||
"strings"
|
||||
|
||||
"github.com/julienschmidt/httprouter"
|
||||
)
|
||||
|
||||
type HttpAuthWraper struct {
|
||||
@@ -47,6 +45,31 @@ func (aw *HttpAuthWraper) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||
}
|
||||
}
|
||||
|
||||
type HttpAuthMiddleware struct {
|
||||
user string
|
||||
passwd string
|
||||
}
|
||||
|
||||
func NewHttpAuthMiddleware(user, passwd string) *HttpAuthMiddleware {
|
||||
return &HttpAuthMiddleware{
|
||||
user: user,
|
||||
passwd: passwd,
|
||||
}
|
||||
}
|
||||
|
||||
func (authMid *HttpAuthMiddleware) Middleware(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
reqUser, reqPasswd, hasAuth := r.BasicAuth()
|
||||
if (authMid.user == "" && authMid.passwd == "") ||
|
||||
(hasAuth && reqUser == authMid.user && reqPasswd == authMid.passwd) {
|
||||
next.ServeHTTP(w, r)
|
||||
} else {
|
||||
w.Header().Set("WWW-Authenticate", `Basic realm="Restricted"`)
|
||||
http.Error(w, http.StatusText(http.StatusUnauthorized), http.StatusUnauthorized)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func HttpBasicAuth(h http.HandlerFunc, user, passwd string) http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
reqUser, reqPasswd, hasAuth := r.BasicAuth()
|
||||
@@ -60,19 +83,6 @@ func HttpBasicAuth(h http.HandlerFunc, user, passwd string) http.HandlerFunc {
|
||||
}
|
||||
}
|
||||
|
||||
func HttprouterBasicAuth(h httprouter.Handle, user, passwd string) httprouter.Handle {
|
||||
return func(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
|
||||
reqUser, reqPasswd, hasAuth := r.BasicAuth()
|
||||
if (user == "" && passwd == "") ||
|
||||
(hasAuth && reqUser == user && reqPasswd == passwd) {
|
||||
h(w, r, ps)
|
||||
} else {
|
||||
w.Header().Set("WWW-Authenticate", `Basic realm="Restricted"`)
|
||||
http.Error(w, http.StatusText(http.StatusUnauthorized), http.StatusUnauthorized)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
type HttpGzipWraper struct {
|
||||
h http.Handler
|
||||
}
|
||||
|
105
utils/net/websocket.go
Normal file
105
utils/net/websocket.go
Normal file
@@ -0,0 +1,105 @@
|
||||
package net
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"net"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"time"
|
||||
|
||||
"github.com/fatedier/frp/utils/log"
|
||||
|
||||
"golang.org/x/net/websocket"
|
||||
)
|
||||
|
||||
var (
|
||||
ErrWebsocketListenerClosed = errors.New("websocket listener closed")
|
||||
)
|
||||
|
||||
const (
|
||||
FrpWebsocketPath = "/~!frp"
|
||||
)
|
||||
|
||||
type WebsocketListener struct {
|
||||
net.Addr
|
||||
ln net.Listener
|
||||
accept chan Conn
|
||||
log.Logger
|
||||
|
||||
server *http.Server
|
||||
httpMutex *http.ServeMux
|
||||
}
|
||||
|
||||
// ln: tcp listener for websocket connections
|
||||
func NewWebsocketListener(ln net.Listener) (wl *WebsocketListener) {
|
||||
wl = &WebsocketListener{
|
||||
Addr: ln.Addr(),
|
||||
accept: make(chan Conn),
|
||||
Logger: log.NewPrefixLogger(""),
|
||||
}
|
||||
|
||||
muxer := http.NewServeMux()
|
||||
muxer.Handle(FrpWebsocketPath, websocket.Handler(func(c *websocket.Conn) {
|
||||
notifyCh := make(chan struct{})
|
||||
conn := WrapCloseNotifyConn(c, func() {
|
||||
close(notifyCh)
|
||||
})
|
||||
wl.accept <- conn
|
||||
<-notifyCh
|
||||
}))
|
||||
|
||||
wl.server = &http.Server{
|
||||
Addr: ln.Addr().String(),
|
||||
Handler: muxer,
|
||||
}
|
||||
|
||||
go wl.server.Serve(ln)
|
||||
return
|
||||
}
|
||||
|
||||
func ListenWebsocket(bindAddr string, bindPort int) (*WebsocketListener, error) {
|
||||
tcpLn, err := net.Listen("tcp", fmt.Sprintf("%s:%d", bindAddr, bindPort))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
l := NewWebsocketListener(tcpLn)
|
||||
return l, nil
|
||||
}
|
||||
|
||||
func (p *WebsocketListener) Accept() (Conn, error) {
|
||||
c, ok := <-p.accept
|
||||
if !ok {
|
||||
return nil, ErrWebsocketListenerClosed
|
||||
}
|
||||
return c, nil
|
||||
}
|
||||
|
||||
func (p *WebsocketListener) Close() error {
|
||||
return p.server.Close()
|
||||
}
|
||||
|
||||
// addr: domain:port
|
||||
func ConnectWebsocketServer(addr string) (Conn, error) {
|
||||
addr = "ws://" + addr + FrpWebsocketPath
|
||||
uri, err := url.Parse(addr)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
origin := "http://" + uri.Host
|
||||
cfg, err := websocket.NewConfig(addr, origin)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
cfg.Dialer = &net.Dialer{
|
||||
Timeout: 10 * time.Second,
|
||||
}
|
||||
|
||||
conn, err := websocket.DialConfig(cfg)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
c := WrapConn(conn)
|
||||
return c, nil
|
||||
}
|
@@ -19,7 +19,7 @@ import (
|
||||
"strings"
|
||||
)
|
||||
|
||||
var version string = "0.19.1"
|
||||
var version string = "0.23.0"
|
||||
|
||||
func Full() string {
|
||||
return version
|
||||
|
@@ -31,8 +31,6 @@ import (
|
||||
)
|
||||
|
||||
var (
|
||||
responseHeaderTimeout = time.Duration(30) * time.Second
|
||||
|
||||
ErrRouterConfigConflict = errors.New("router config conflict")
|
||||
ErrNoDomain = errors.New("no such domain")
|
||||
)
|
||||
@@ -47,31 +45,45 @@ func getHostFromAddr(addr string) (host string) {
|
||||
return
|
||||
}
|
||||
|
||||
type HttpReverseProxyOptions struct {
|
||||
ResponseHeaderTimeoutS int64
|
||||
}
|
||||
|
||||
type HttpReverseProxy struct {
|
||||
proxy *ReverseProxy
|
||||
|
||||
vhostRouter *VhostRouters
|
||||
|
||||
cfgMu sync.RWMutex
|
||||
responseHeaderTimeout time.Duration
|
||||
cfgMu sync.RWMutex
|
||||
}
|
||||
|
||||
func NewHttpReverseProxy() *HttpReverseProxy {
|
||||
func NewHttpReverseProxy(option HttpReverseProxyOptions) *HttpReverseProxy {
|
||||
if option.ResponseHeaderTimeoutS <= 0 {
|
||||
option.ResponseHeaderTimeoutS = 60
|
||||
}
|
||||
rp := &HttpReverseProxy{
|
||||
vhostRouter: NewVhostRouters(),
|
||||
responseHeaderTimeout: time.Duration(option.ResponseHeaderTimeoutS) * time.Second,
|
||||
vhostRouter: NewVhostRouters(),
|
||||
}
|
||||
proxy := &ReverseProxy{
|
||||
Director: func(req *http.Request) {
|
||||
req.URL.Scheme = "http"
|
||||
url := req.Context().Value("url").(string)
|
||||
host := getHostFromAddr(req.Context().Value("host").(string))
|
||||
host = rp.GetRealHost(host, url)
|
||||
oldHost := getHostFromAddr(req.Context().Value("host").(string))
|
||||
host := rp.GetRealHost(oldHost, url)
|
||||
if host != "" {
|
||||
req.Host = host
|
||||
}
|
||||
req.URL.Host = req.Host
|
||||
|
||||
headers := rp.GetHeaders(oldHost, url)
|
||||
for k, v := range headers {
|
||||
req.Header.Set(k, v)
|
||||
}
|
||||
},
|
||||
Transport: &http.Transport{
|
||||
ResponseHeaderTimeout: responseHeaderTimeout,
|
||||
ResponseHeaderTimeout: rp.responseHeaderTimeout,
|
||||
DisableKeepAlives: true,
|
||||
DialContext: func(ctx context.Context, network, addr string) (net.Conn, error) {
|
||||
url := ctx.Value("url").(string)
|
||||
@@ -117,6 +129,14 @@ func (rp *HttpReverseProxy) GetRealHost(domain string, location string) (host st
|
||||
return
|
||||
}
|
||||
|
||||
func (rp *HttpReverseProxy) GetHeaders(domain string, location string) (headers map[string]string) {
|
||||
vr, ok := rp.getVhost(domain, location)
|
||||
if ok {
|
||||
headers = vr.payload.(*VhostRouteConfig).Headers
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
func (rp *HttpReverseProxy) CreateConnection(domain string, location string) (net.Conn, error) {
|
||||
vr, ok := rp.getVhost(domain, location)
|
||||
if ok {
|
||||
|
@@ -52,16 +52,13 @@ func (r *VhostRouters) Del(domain, location string) {
|
||||
if !found {
|
||||
return
|
||||
}
|
||||
|
||||
for i, vr := range vrs {
|
||||
if vr.location == location {
|
||||
if len(vrs) > i+1 {
|
||||
r.RouterByDomain[domain] = append(vrs[:i], vrs[i+1:]...)
|
||||
} else {
|
||||
r.RouterByDomain[domain] = vrs[:i]
|
||||
}
|
||||
newVrs := make([]*VhostRouter, 0)
|
||||
for _, vr := range vrs {
|
||||
if vr.location != location {
|
||||
newVrs = append(newVrs, vr)
|
||||
}
|
||||
}
|
||||
r.RouterByDomain[domain] = newVrs
|
||||
}
|
||||
|
||||
func (r *VhostRouters) Get(host, path string) (vr *VhostRouter, exist bool) {
|
||||
|
@@ -59,6 +59,7 @@ type VhostRouteConfig struct {
|
||||
RewriteHost string
|
||||
Username string
|
||||
Password string
|
||||
Headers map[string]string
|
||||
|
||||
CreateConnFn CreateConnFunc
|
||||
}
|
||||
|
4
vendor/github.com/fatedier/golib/msg/json/process.go
generated
vendored
4
vendor/github.com/fatedier/golib/msg/json/process.go
generated
vendored
@@ -23,6 +23,7 @@ import (
|
||||
var (
|
||||
ErrMsgType = errors.New("message type error")
|
||||
ErrMaxMsgLength = errors.New("message length exceed the limit")
|
||||
ErrMsgLength = errors.New("message length error")
|
||||
ErrMsgFormat = errors.New("message format error")
|
||||
)
|
||||
|
||||
@@ -46,6 +47,9 @@ func (msgCtl *MsgCtl) readMsg(c io.Reader) (typeByte byte, buffer []byte, err er
|
||||
if length > msgCtl.maxMsgLength {
|
||||
err = ErrMaxMsgLength
|
||||
return
|
||||
} else if length < 0 {
|
||||
err = ErrMsgLength
|
||||
return
|
||||
}
|
||||
|
||||
buffer = make([]byte, length)
|
||||
|
26
vendor/github.com/fatedier/golib/net/mux/mux.go
generated
vendored
26
vendor/github.com/fatedier/golib/net/mux/mux.go
generated
vendored
@@ -34,23 +34,29 @@ const (
|
||||
type Mux struct {
|
||||
ln net.Listener
|
||||
|
||||
defaultLn *listener
|
||||
defaultLn *listener
|
||||
|
||||
// sorted by priority
|
||||
lns []*listener
|
||||
maxNeedBytesNum uint32
|
||||
mu sync.RWMutex
|
||||
|
||||
mu sync.RWMutex
|
||||
}
|
||||
|
||||
func NewMux() (mux *Mux) {
|
||||
func NewMux(ln net.Listener) (mux *Mux) {
|
||||
mux = &Mux{
|
||||
ln: ln,
|
||||
lns: make([]*listener, 0),
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
// priority
|
||||
func (mux *Mux) Listen(priority int, needBytesNum uint32, fn MatchFunc) net.Listener {
|
||||
ln := &listener{
|
||||
c: make(chan net.Conn),
|
||||
mux: mux,
|
||||
priority: priority,
|
||||
needBytesNum: needBytesNum,
|
||||
matchFn: fn,
|
||||
}
|
||||
@@ -63,7 +69,10 @@ func (mux *Mux) Listen(priority int, needBytesNum uint32, fn MatchFunc) net.List
|
||||
|
||||
newlns := append(mux.copyLns(), ln)
|
||||
sort.Slice(newlns, func(i, j int) bool {
|
||||
return newlns[i].needBytesNum < newlns[j].needBytesNum
|
||||
if newlns[i].priority == newlns[j].priority {
|
||||
return newlns[i].needBytesNum < newlns[j].needBytesNum
|
||||
}
|
||||
return newlns[i].priority < newlns[j].priority
|
||||
})
|
||||
mux.lns = newlns
|
||||
return ln
|
||||
@@ -99,6 +108,7 @@ func (mux *Mux) release(ln *listener) bool {
|
||||
if l == ln {
|
||||
lns = append(lns[:i], lns[i+1:]...)
|
||||
result = true
|
||||
break
|
||||
}
|
||||
}
|
||||
mux.lns = lns
|
||||
@@ -114,15 +124,12 @@ func (mux *Mux) copyLns() []*listener {
|
||||
}
|
||||
|
||||
// Serve handles connections from ln and multiplexes then across registered listeners.
|
||||
func (mux *Mux) Serve(ln net.Listener) error {
|
||||
mux.mu.Lock()
|
||||
mux.ln = ln
|
||||
mux.mu.Unlock()
|
||||
func (mux *Mux) Serve() error {
|
||||
for {
|
||||
// Wait for the next connection.
|
||||
// If it returns a temporary error then simply retry.
|
||||
// If it returns any other error then exit immediately.
|
||||
conn, err := ln.Accept()
|
||||
conn, err := mux.ln.Accept()
|
||||
if err, ok := err.(interface {
|
||||
Temporary() bool
|
||||
}); ok && err.Temporary() {
|
||||
@@ -186,6 +193,7 @@ func (mux *Mux) handleConn(conn net.Conn) {
|
||||
type listener struct {
|
||||
mux *Mux
|
||||
|
||||
priority int
|
||||
needBytesNum uint32
|
||||
matchFn MatchFunc
|
||||
|
||||
|
1
vendor/github.com/fatedier/golib/net/proxy.go
generated
vendored
1
vendor/github.com/fatedier/golib/net/proxy.go
generated
vendored
@@ -43,6 +43,7 @@ func DialTcpByProxy(proxyStr string, addr string) (c net.Conn, err error) {
|
||||
|
||||
auth := &ProxyAuth{}
|
||||
if proxyUrl.User != nil {
|
||||
auth.Enable = true
|
||||
auth.Username = proxyUrl.User.Username()
|
||||
auth.Passwd, _ = proxyUrl.User.Password()
|
||||
}
|
||||
|
19
vendor/github.com/gorilla/context/.travis.yml
generated
vendored
Normal file
19
vendor/github.com/gorilla/context/.travis.yml
generated
vendored
Normal file
@@ -0,0 +1,19 @@
|
||||
language: go
|
||||
sudo: false
|
||||
|
||||
matrix:
|
||||
include:
|
||||
- go: 1.3
|
||||
- go: 1.4
|
||||
- go: 1.5
|
||||
- go: 1.6
|
||||
- go: 1.7
|
||||
- go: tip
|
||||
allow_failures:
|
||||
- go: tip
|
||||
|
||||
script:
|
||||
- go get -t -v ./...
|
||||
- diff -u <(echo -n) <(gofmt -d .)
|
||||
- go vet $(go list ./... | grep -v /vendor/)
|
||||
- go test -v -race ./...
|
27
vendor/github.com/gorilla/context/LICENSE
generated
vendored
Normal file
27
vendor/github.com/gorilla/context/LICENSE
generated
vendored
Normal file
@@ -0,0 +1,27 @@
|
||||
Copyright (c) 2012 Rodrigo Moraes. All rights reserved.
|
||||
|
||||
Redistribution and use in source and binary forms, with or without
|
||||
modification, are permitted provided that the following conditions are
|
||||
met:
|
||||
|
||||
* Redistributions of source code must retain the above copyright
|
||||
notice, this list of conditions and the following disclaimer.
|
||||
* Redistributions in binary form must reproduce the above
|
||||
copyright notice, this list of conditions and the following disclaimer
|
||||
in the documentation and/or other materials provided with the
|
||||
distribution.
|
||||
* Neither the name of Google Inc. nor the names of its
|
||||
contributors may be used to endorse or promote products derived from
|
||||
this software without specific prior written permission.
|
||||
|
||||
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
|
||||
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
|
||||
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
|
||||
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
|
||||
OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
|
||||
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
|
||||
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
|
||||
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
|
||||
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
||||
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
||||
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
10
vendor/github.com/gorilla/context/README.md
generated
vendored
Normal file
10
vendor/github.com/gorilla/context/README.md
generated
vendored
Normal file
@@ -0,0 +1,10 @@
|
||||
context
|
||||
=======
|
||||
[](https://travis-ci.org/gorilla/context)
|
||||
|
||||
gorilla/context is a general purpose registry for global request variables.
|
||||
|
||||
> Note: gorilla/context, having been born well before `context.Context` existed, does not play well
|
||||
> with the shallow copying of the request that [`http.Request.WithContext`](https://golang.org/pkg/net/http/#Request.WithContext) (added to net/http Go 1.7 onwards) performs. You should either use *just* gorilla/context, or moving forward, the new `http.Request.Context()`.
|
||||
|
||||
Read the full documentation here: http://www.gorillatoolkit.org/pkg/context
|
143
vendor/github.com/gorilla/context/context.go
generated
vendored
Normal file
143
vendor/github.com/gorilla/context/context.go
generated
vendored
Normal file
@@ -0,0 +1,143 @@
|
||||
// Copyright 2012 The Gorilla Authors. All rights reserved.
|
||||
// Use of this source code is governed by a BSD-style
|
||||
// license that can be found in the LICENSE file.
|
||||
|
||||
package context
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"sync"
|
||||
"time"
|
||||
)
|
||||
|
||||
var (
|
||||
mutex sync.RWMutex
|
||||
data = make(map[*http.Request]map[interface{}]interface{})
|
||||
datat = make(map[*http.Request]int64)
|
||||
)
|
||||
|
||||
// Set stores a value for a given key in a given request.
|
||||
func Set(r *http.Request, key, val interface{}) {
|
||||
mutex.Lock()
|
||||
if data[r] == nil {
|
||||
data[r] = make(map[interface{}]interface{})
|
||||
datat[r] = time.Now().Unix()
|
||||
}
|
||||
data[r][key] = val
|
||||
mutex.Unlock()
|
||||
}
|
||||
|
||||
// Get returns a value stored for a given key in a given request.
|
||||
func Get(r *http.Request, key interface{}) interface{} {
|
||||
mutex.RLock()
|
||||
if ctx := data[r]; ctx != nil {
|
||||
value := ctx[key]
|
||||
mutex.RUnlock()
|
||||
return value
|
||||
}
|
||||
mutex.RUnlock()
|
||||
return nil
|
||||
}
|
||||
|
||||
// GetOk returns stored value and presence state like multi-value return of map access.
|
||||
func GetOk(r *http.Request, key interface{}) (interface{}, bool) {
|
||||
mutex.RLock()
|
||||
if _, ok := data[r]; ok {
|
||||
value, ok := data[r][key]
|
||||
mutex.RUnlock()
|
||||
return value, ok
|
||||
}
|
||||
mutex.RUnlock()
|
||||
return nil, false
|
||||
}
|
||||
|
||||
// GetAll returns all stored values for the request as a map. Nil is returned for invalid requests.
|
||||
func GetAll(r *http.Request) map[interface{}]interface{} {
|
||||
mutex.RLock()
|
||||
if context, ok := data[r]; ok {
|
||||
result := make(map[interface{}]interface{}, len(context))
|
||||
for k, v := range context {
|
||||
result[k] = v
|
||||
}
|
||||
mutex.RUnlock()
|
||||
return result
|
||||
}
|
||||
mutex.RUnlock()
|
||||
return nil
|
||||
}
|
||||
|
||||
// GetAllOk returns all stored values for the request as a map and a boolean value that indicates if
|
||||
// the request was registered.
|
||||
func GetAllOk(r *http.Request) (map[interface{}]interface{}, bool) {
|
||||
mutex.RLock()
|
||||
context, ok := data[r]
|
||||
result := make(map[interface{}]interface{}, len(context))
|
||||
for k, v := range context {
|
||||
result[k] = v
|
||||
}
|
||||
mutex.RUnlock()
|
||||
return result, ok
|
||||
}
|
||||
|
||||
// Delete removes a value stored for a given key in a given request.
|
||||
func Delete(r *http.Request, key interface{}) {
|
||||
mutex.Lock()
|
||||
if data[r] != nil {
|
||||
delete(data[r], key)
|
||||
}
|
||||
mutex.Unlock()
|
||||
}
|
||||
|
||||
// Clear removes all values stored for a given request.
|
||||
//
|
||||
// This is usually called by a handler wrapper to clean up request
|
||||
// variables at the end of a request lifetime. See ClearHandler().
|
||||
func Clear(r *http.Request) {
|
||||
mutex.Lock()
|
||||
clear(r)
|
||||
mutex.Unlock()
|
||||
}
|
||||
|
||||
// clear is Clear without the lock.
|
||||
func clear(r *http.Request) {
|
||||
delete(data, r)
|
||||
delete(datat, r)
|
||||
}
|
||||
|
||||
// Purge removes request data stored for longer than maxAge, in seconds.
|
||||
// It returns the amount of requests removed.
|
||||
//
|
||||
// If maxAge <= 0, all request data is removed.
|
||||
//
|
||||
// This is only used for sanity check: in case context cleaning was not
|
||||
// properly set some request data can be kept forever, consuming an increasing
|
||||
// amount of memory. In case this is detected, Purge() must be called
|
||||
// periodically until the problem is fixed.
|
||||
func Purge(maxAge int) int {
|
||||
mutex.Lock()
|
||||
count := 0
|
||||
if maxAge <= 0 {
|
||||
count = len(data)
|
||||
data = make(map[*http.Request]map[interface{}]interface{})
|
||||
datat = make(map[*http.Request]int64)
|
||||
} else {
|
||||
min := time.Now().Unix() - int64(maxAge)
|
||||
for r := range data {
|
||||
if datat[r] < min {
|
||||
clear(r)
|
||||
count++
|
||||
}
|
||||
}
|
||||
}
|
||||
mutex.Unlock()
|
||||
return count
|
||||
}
|
||||
|
||||
// ClearHandler wraps an http.Handler and clears request values at the end
|
||||
// of a request lifetime.
|
||||
func ClearHandler(h http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
defer Clear(r)
|
||||
h.ServeHTTP(w, r)
|
||||
})
|
||||
}
|
88
vendor/github.com/gorilla/context/doc.go
generated
vendored
Normal file
88
vendor/github.com/gorilla/context/doc.go
generated
vendored
Normal file
@@ -0,0 +1,88 @@
|
||||
// Copyright 2012 The Gorilla Authors. All rights reserved.
|
||||
// Use of this source code is governed by a BSD-style
|
||||
// license that can be found in the LICENSE file.
|
||||
|
||||
/*
|
||||
Package context stores values shared during a request lifetime.
|
||||
|
||||
Note: gorilla/context, having been born well before `context.Context` existed,
|
||||
does not play well > with the shallow copying of the request that
|
||||
[`http.Request.WithContext`](https://golang.org/pkg/net/http/#Request.WithContext)
|
||||
(added to net/http Go 1.7 onwards) performs. You should either use *just*
|
||||
gorilla/context, or moving forward, the new `http.Request.Context()`.
|
||||
|
||||
For example, a router can set variables extracted from the URL and later
|
||||
application handlers can access those values, or it can be used to store
|
||||
sessions values to be saved at the end of a request. There are several
|
||||
others common uses.
|
||||
|
||||
The idea was posted by Brad Fitzpatrick to the go-nuts mailing list:
|
||||
|
||||
http://groups.google.com/group/golang-nuts/msg/e2d679d303aa5d53
|
||||
|
||||
Here's the basic usage: first define the keys that you will need. The key
|
||||
type is interface{} so a key can be of any type that supports equality.
|
||||
Here we define a key using a custom int type to avoid name collisions:
|
||||
|
||||
package foo
|
||||
|
||||
import (
|
||||
"github.com/gorilla/context"
|
||||
)
|
||||
|
||||
type key int
|
||||
|
||||
const MyKey key = 0
|
||||
|
||||
Then set a variable. Variables are bound to an http.Request object, so you
|
||||
need a request instance to set a value:
|
||||
|
||||
context.Set(r, MyKey, "bar")
|
||||
|
||||
The application can later access the variable using the same key you provided:
|
||||
|
||||
func MyHandler(w http.ResponseWriter, r *http.Request) {
|
||||
// val is "bar".
|
||||
val := context.Get(r, foo.MyKey)
|
||||
|
||||
// returns ("bar", true)
|
||||
val, ok := context.GetOk(r, foo.MyKey)
|
||||
// ...
|
||||
}
|
||||
|
||||
And that's all about the basic usage. We discuss some other ideas below.
|
||||
|
||||
Any type can be stored in the context. To enforce a given type, make the key
|
||||
private and wrap Get() and Set() to accept and return values of a specific
|
||||
type:
|
||||
|
||||
type key int
|
||||
|
||||
const mykey key = 0
|
||||
|
||||
// GetMyKey returns a value for this package from the request values.
|
||||
func GetMyKey(r *http.Request) SomeType {
|
||||
if rv := context.Get(r, mykey); rv != nil {
|
||||
return rv.(SomeType)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// SetMyKey sets a value for this package in the request values.
|
||||
func SetMyKey(r *http.Request, val SomeType) {
|
||||
context.Set(r, mykey, val)
|
||||
}
|
||||
|
||||
Variables must be cleared at the end of a request, to remove all values
|
||||
that were stored. This can be done in an http.Handler, after a request was
|
||||
served. Just call Clear() passing the request:
|
||||
|
||||
context.Clear(r)
|
||||
|
||||
...or use ClearHandler(), which conveniently wraps an http.Handler to clear
|
||||
variables at the end of a request lifetime.
|
||||
|
||||
The Routers from the packages gorilla/mux and gorilla/pat call Clear()
|
||||
so if you are using either of them you don't need to clear the context manually.
|
||||
*/
|
||||
package context
|
23
vendor/github.com/gorilla/mux/.travis.yml
generated
vendored
Normal file
23
vendor/github.com/gorilla/mux/.travis.yml
generated
vendored
Normal file
@@ -0,0 +1,23 @@
|
||||
language: go
|
||||
sudo: false
|
||||
|
||||
matrix:
|
||||
include:
|
||||
- go: 1.5.x
|
||||
- go: 1.6.x
|
||||
- go: 1.7.x
|
||||
- go: 1.8.x
|
||||
- go: 1.9.x
|
||||
- go: 1.10.x
|
||||
- go: tip
|
||||
allow_failures:
|
||||
- go: tip
|
||||
|
||||
install:
|
||||
- # Skip
|
||||
|
||||
script:
|
||||
- go get -t -v ./...
|
||||
- diff -u <(echo -n) <(gofmt -d .)
|
||||
- go tool vet .
|
||||
- go test -v -race ./...
|
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user