新增代理服务与边缘节点注册功能

This commit is contained in:
2025-05-13 18:48:17 +08:00
parent 536f36ae02
commit d69a77df38
17 changed files with 573 additions and 203 deletions

View File

@@ -2,99 +2,112 @@ package client
import (
"bufio"
"flag"
"fmt"
"io"
"log/slog"
"net"
"net/http"
"os"
"proxy-server/client/core"
"proxy-server/client/geo"
"proxy-server/client/report"
"proxy-server/pkg/utils"
"runtime"
"strconv"
"time"
"errors"
"github.com/joho/godotenv"
"github.com/pkg/errors"
_ "net/http/pprof"
)
const Version byte = 1
var Geo geo.Func = geo.Ipapi
type Config struct {
Name string
FwdHost string
FwdCtrlPort uint
FwdDataPort uint
RetryInterval uint
}
func Start() error {
var cfg Config
// 初始化环境变量
slog.SetLogLoggerLevel(slog.LevelDebug)
var frpCtrlAddr string
var frpDataAddr string
func Start() {
initLog()
initCmd()
initDevEnv()
frpCtrlAddr = net.JoinHostPort(cfg.FwdHost, strconv.Itoa(int(cfg.FwdCtrlPort)))
frpDataAddr = net.JoinHostPort(cfg.FwdHost, strconv.Itoa(int(cfg.FwdDataPort)))
err := godotenv.Load()
if err != nil {
slog.Debug("没有本地环境变量文件")
} else {
online := os.Getenv("ENDPOINT_ONLINE")
if online != "" {
core.EndpointOnline = online
}
offline := os.Getenv("ENDPOINT_OFFLINE")
if offline != "" {
core.EndpointOffline = offline
}
}
// 性能监控
go func() {
runtime.SetBlockProfileRate(1)
err := http.ListenAndServe(":7070", nil)
if err != nil {
slog.Error("性能监控服务启动失败", "err", err)
}
}()
// go func() {
// runtime.SetBlockProfileRate(1)
// err := http.ListenAndServe(":7070", nil)
// if err != nil {
// slog.Error("性能监控服务启动失败", "err", err)
// }
// }()
// 获取归属地
slog.Debug("获取节点归属地...")
prov, city, isp, err := Geo()
if err != nil {
slog.Error("获取归属地失败", "err", err)
}
// 注册节点
slog.Debug("注册节点...")
host, err := report.Online(prov, city, isp)
if err != nil {
slog.Error("节点注册失败", "err", err)
return err
}
// 建立控制通道
for {
err := ctrl()
err := ctrl(host)
if err != nil {
slog.Error("建立控制通道失败", err)
slog.Info(fmt.Sprintf("%d 秒后重试", cfg.RetryInterval))
time.Sleep(time.Duration(cfg.RetryInterval) * time.Second)
slog.Error("建立控制通道失败", "err", err)
slog.Info(fmt.Sprintf("%d 秒后重试", core.RetryInterval))
time.Sleep(time.Duration(core.RetryInterval) * time.Second)
}
}
}
func ctrl() error {
slog.Info("建立控制通道", "addr", frpCtrlAddr)
func ctrl(host string) error {
ctrlAddr := net.JoinHostPort(host, fmt.Sprintf("%d", core.FwdCtrlPort))
dataAddr := net.JoinHostPort(host, fmt.Sprintf("%d", core.FwdDataPort))
conn, err := net.Dial("tcp", frpCtrlAddr)
slog.Info("建立控制通道", "addr", ctrlAddr)
conn, err := net.Dial("tcp", ctrlAddr)
if err != nil {
return errors.Wrap(err, "连接失败")
return errors.New("连接失败")
}
defer utils.Close(conn)
reader := bufio.NewReader(conn)
// 请求转发端口
_, err = conn.Write([]byte{Version})
_, err = conn.Write([]byte{core.Version})
if err != nil {
return errors.Wrap(err, "发送版本号失败")
return errors.New("发送版本号失败")
}
// 发送客户端名称
nameLen := byte(len(cfg.Name))
nameLen := byte(len(core.Name))
nameBuf := make([]byte, 1+nameLen)
nameBuf[0] = nameLen
copy(nameBuf[1:], cfg.Name)
copy(nameBuf[1:], core.Name)
_, err = conn.Write(nameBuf)
if err != nil {
return errors.Wrap(err, "发送 name 失败")
return errors.New("发送 name 失败")
}
// 等待服务端响应
respBuf, err := reader.ReadByte()
if err != nil {
return errors.Wrap(err, "接收响应失败")
return errors.New("接收响应失败")
}
if respBuf != 1 {
return errors.New("服务端响应失败")
@@ -110,40 +123,40 @@ func ctrl() error {
// 接收 dst
dstLen, err := reader.ReadByte()
if err != nil {
return errors.Wrap(err, "接收 dstLen 失败")
return errors.New("接收 dstLen 失败")
}
dstBuf, err := utils.ReadBuffer(reader, int(dstLen))
if err != nil {
return errors.Wrap(err, "接收 dstBuf 失败")
return errors.New("接收 dstBuf 失败")
}
addr := string(dstBuf)
// 接收 tag
tagLen, err := reader.ReadByte()
if err != nil {
return errors.Wrap(err, "接收 tagLen 失败")
return errors.New("接收 tagLen 失败")
}
tagBuf, err := utils.ReadBuffer(reader, int(tagLen))
if err != nil {
return errors.Wrap(err, "接收 tagBuf 失败")
return errors.New("接收 tagBuf 失败")
}
// 建立数据通道
go func() {
err := data(addr, tagBuf)
err := data(dataAddr, addr, tagBuf)
if err != nil {
slog.Error("建立数据通道失败", err)
slog.Error("建立数据通道失败", "err", err)
}
}()
}
}
func data(addr string, tag []byte) error {
func data(dataAddr string, dest string, tag []byte) error {
// 向服务端建立连接
src, err := net.Dial("tcp", frpDataAddr)
src, err := net.Dial("tcp", dataAddr)
if err != nil {
return errors.Wrap(err, "连接服务端失败")
return errors.New("连接服务端失败")
}
tagLen := byte(len(tag))
@@ -152,7 +165,7 @@ func data(addr string, tag []byte) error {
copy(tagBuf[2:], tag)
// 向目标地址建立连接
dst, dstErr := net.Dial("tcp", addr)
dst, dstErr := net.Dial("tcp", dest)
if dstErr != nil {
tagBuf[0] = 0
} else {
@@ -166,7 +179,7 @@ func data(addr string, tag []byte) error {
if dst != nil {
utils.Close(dst)
}
return errors.Wrap(err, "发送连接状态失败")
return errors.New("发送连接状态失败")
}
if tagBuf[0] == 0 {
@@ -174,7 +187,7 @@ func data(addr string, tag []byte) error {
if dst != nil {
utils.Close(dst)
}
return errors.Wrap(dstErr, "连接目标地址失败")
return errors.New("连接目标地址失败")
}
go func() {
@@ -193,31 +206,3 @@ func data(addr string, tag []byte) error {
}()
return nil
}
func initLog() {
slog.SetLogLoggerLevel(slog.LevelDebug)
}
func initCmd() {
flag.StringVar(&cfg.Name, "n", "", "客户端名称")
flag.StringVar(&cfg.FwdHost, "h", "", "转发服务器地址")
flag.UintVar(&cfg.FwdCtrlPort, "c", 18080, "转发服务器控制通道端口")
flag.UintVar(&cfg.FwdDataPort, "d", 18081, "转发服务器数据通道端口")
flag.UintVar(&cfg.RetryInterval, "r", 5, "重试间隔时间")
flag.Parse()
if cfg.Name == "" {
slog.Error("客户端名称不能为空")
flag.Usage()
os.Exit(1)
}
}
func initDevEnv() {
err := godotenv.Load()
if err != nil {
slog.Debug("没有本地环境变量文件")
}
cfg.FwdHost = os.Getenv("FWD_HOST")
}

12
client/core/env.go Normal file
View File

@@ -0,0 +1,12 @@
package core
const Version byte = 1
const Name = "test-edge"
var FwdCtrlPort uint = 18080
var FwdDataPort uint = 18081
var RetryInterval uint = 5
var EndpointOnline = "https://api.lanhuip.com/api/edge/online"
var EndpointOffline = "https://api.lanhuip.com/api/edge/offline"
var EndpointGeo = "http://cip.cc"

57
client/geo/cip.go Normal file
View File

@@ -0,0 +1,57 @@
package geo
import (
"bufio"
"github.com/pkg/errors"
"log/slog"
"net/http"
"net/textproto"
"strings"
)
func Cip() (prov, city, isp string, err error) {
const endpoint = "http://cip.cc"
req, err := http.NewRequest("GET", endpoint, nil)
if err != nil {
return "", "", "", errors.Wrap(err, "创建请求失败")
}
req.Header.Set("User-Agent", "curl/8.9.1")
req.Header.Set("Accept", "*/*")
resp, err := http.DefaultClient.Do(req)
if err != nil {
return "", "", "", errors.Wrap(err, "请求失败")
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return "", "", "", errors.New("请求失败,状态码: " + resp.Status)
}
reader := textproto.NewReader(bufio.NewReader(resp.Body))
_, err = reader.ReadLine()
if err != nil {
return "", "", "", errors.Wrap(err, "读取响应失败")
}
addrLine, err := reader.ReadLine()
if err != nil {
return "", "", "", errors.Wrap(err, "读取响应失败")
}
addr := strings.Split(strings.Split(addrLine, ":")[1], " ")
prov = strings.TrimSpace(addr[1])
city = strings.TrimSpace(addr[2])
ispLine, err := reader.ReadLine()
if err != nil {
return "", "", "", errors.Wrap(err, "读取响应失败")
}
isp = strings.TrimSpace(strings.Split(ispLine, ":")[1])
if prov == "" || city == "" || isp == "" {
return "", "", "", errors.New("解析数据为空")
}
slog.Debug("获取归属地", "prov", prov, "city", city, "isp", isp)
return prov, city, isp, nil
}

3
client/geo/geo.go Normal file
View File

@@ -0,0 +1,3 @@
package geo
type Func func() (prov, city, isp string, err error)

40
client/geo/ipapi.go Normal file
View File

@@ -0,0 +1,40 @@
package geo
import (
"encoding/json"
"github.com/pkg/errors"
"net/http"
)
func Ipapi() (prov, city, isp string, err error) {
const endpoint = "http://ip-api.com/json/?fields=regionName,city,as&lang=zh-CN"
resp, err := http.Get(endpoint)
if err != nil {
return "", "", "", err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return "", "", "", err
}
var data struct {
RegionName string `json:"regionName"`
City string `json:"city"`
As string `json:"as"`
}
err = json.NewDecoder(resp.Body).Decode(&data)
if err != nil {
return "", "", "", err
}
prov = data.RegionName
city = data.City
isp = data.As
if prov == "" || city == "" || isp == "" {
return "", "", "", errors.New("解析数据为空")
}
return prov, city, isp, nil
}

66
client/report/online.go Normal file
View File

@@ -0,0 +1,66 @@
package report
import (
"encoding/json"
"errors"
"io"
"net/http"
"proxy-server/client/core"
"strings"
)
func Online(prov, city, isp string) (host string, err error) {
var ispInt = 0
switch isp {
case "电信":
ispInt = 1
case "联通":
ispInt = 2
case "移动":
ispInt = 3
}
body, err := json.Marshal(map[string]any{
"prov": prov,
"city": city,
"isp": ispInt,
"name": core.Name,
"version": core.Version,
})
if err != nil {
return "", err
}
req, err := http.NewRequest("POST", core.EndpointOnline, strings.NewReader(string(body)))
if err != nil {
return "", errors.New("创建节点注册请求失败")
}
req.Header.Set("Content-Type", "application/json")
resp, err := http.DefaultClient.Do(req)
if err != nil {
return "", errors.New("节点注册失败")
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return "", errors.New("节点注册失败,状态码: " + resp.Status)
}
bytes, err := io.ReadAll(resp.Body)
if err != nil {
return "", errors.New("读取节点注册响应失败")
}
var respBody struct {
Host string `json:"host"`
}
err = json.Unmarshal(bytes, &respBody)
if err != nil {
return "", errors.New("解析节点注册响应失败")
}
if respBody.Host == "" {
return "", errors.New("节点注册失败,响应体为空")
}
return respBody.Host, nil
}