Compare commits
116 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 69f62188cf | |||
| f786d60219 | |||
| bdc3513a68 | |||
| acb20a13b7 | |||
| c890ec783d | |||
| 8ccc5e054a | |||
| aef329149d | |||
| 8473b9040f | |||
| 89ab12dcdf | |||
| 919339cdb1 | |||
| 6a8996b17a | |||
| 7557e02e54 | |||
| 90debf144b | |||
| cec5fe9adb | |||
| 6790336885 | |||
| 5aea281e16 | |||
| 3b697f4d13 | |||
| b4a8b582fa | |||
| 34becb6604 | |||
| a6e8722e27 | |||
| 83256a5e26 | |||
| 27e7e065ef | |||
| fdfb6512bb | |||
| cb76b2161e | |||
| 9b19e45711 | |||
| 0cf81a783c | |||
| f0893afe42 | |||
| ae2da67efd | |||
| 63e9d80023 | |||
| b205b47414 | |||
| d517695544 | |||
| 29e58ec66a | |||
| de9146334e | |||
| 00079ac7af | |||
| 2affb31b3e | |||
| 49884d54ac | |||
| dae6286e58 | |||
| da52b66cd2 | |||
| a8da752f5c | |||
| 32763358ea | |||
| 3d9432e3bc | |||
| d515d610b9 | |||
| 08f5b3aa33 | |||
| 67f935c46f | |||
| 79f8aab600 | |||
| 5f42c50689 | |||
| 2b2f914bec | |||
| c18703eba2 | |||
| 3f2150828d | |||
| c76bb77b93 | |||
| 01d5c25df1 | |||
| a19e8d2bcb | |||
| 76f443f900 | |||
| 47b1663938 | |||
| 406f5bb380 | |||
| 85ea6c17a4 | |||
| 3420dc5460 | |||
| 3d7a0b697d | |||
| 065b23d9c3 | |||
| 7919dfde59 | |||
| 565d732967 | |||
| bf88b0dd7e | |||
| 20dc151aec | |||
| 630ed969d3 | |||
| e94aa01213 | |||
| 67d8f7a381 | |||
| 0c7b7deaf5 | |||
| a4def9c5f3 | |||
| 6582348da2 | |||
| 3a14b22ebc | |||
| d7b44916bf | |||
| f8a0bda3fd | |||
| 634562e56d | |||
| d06e02998b | |||
| 169df953d8 | |||
| 7bc33f63ba | |||
| 5925a84a6d | |||
| bbffe5872c | |||
| 98db0e6a5e | |||
| 30591a008a | |||
| 52885d1821 | |||
| 124cf1ced2 | |||
| 36ba2f95ef | |||
| 858f9ef1d5 | |||
| 218084b542 | |||
| a9c304546e | |||
| 85250aa2d3 | |||
| aeeb57b89d | |||
| 4e163163cb | |||
| eb5464511a | |||
| efa6c0e322 | |||
| fef4c28777 | |||
| 9ab5140258 | |||
| 11dc21e46f | |||
| 576654fc5a | |||
| a1454a3549 | |||
| 1c72fb233a | |||
| ac1c2fa6bf | |||
| 4af2186e35 | |||
| 9fe9798677 | |||
| cfee6092c7 | |||
| 7ab6545594 | |||
| 2e2c182a0d | |||
| 96eec61a92 | |||
| 6e4bde4053 | |||
| 33f347d1db | |||
| 17e5f4f95a | |||
| b0304876a8 | |||
| 2710cd1674 | |||
| a74eb9f431 | |||
| d5c0060cd9 | |||
| 7f9c05172b | |||
| d720b9e00c | |||
| 15cf25f74b | |||
| ae6c65e9a9 | |||
| 8a85ab2844 |
@@ -0,0 +1,43 @@
|
|||||||
|
name: Deploy Docs
|
||||||
|
on:
|
||||||
|
push:
|
||||||
|
branches:
|
||||||
|
- main
|
||||||
|
- master
|
||||||
|
- beta
|
||||||
|
paths:
|
||||||
|
- 'doc/**'
|
||||||
|
- 'mkdocs.yml'
|
||||||
|
|
||||||
|
permissions:
|
||||||
|
contents: write
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
deploy:
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
steps:
|
||||||
|
- uses: actions/checkout@v4
|
||||||
|
|
||||||
|
- name: Configure Git Credentials
|
||||||
|
run: |
|
||||||
|
git config user.name github-actions[bot]
|
||||||
|
git config user.email 41898282+github-actions[bot]@users.noreply.github.com
|
||||||
|
|
||||||
|
- uses: actions/setup-python@v5
|
||||||
|
with:
|
||||||
|
python-version: 3.x
|
||||||
|
|
||||||
|
- run: echo "cache_id=$(date --utc '+%V')" >> $GITHUB_ENV
|
||||||
|
|
||||||
|
- uses: actions/cache@v4
|
||||||
|
with:
|
||||||
|
key: mkdocs-material-${{ env.cache_id }}
|
||||||
|
path: .cache
|
||||||
|
restore-keys: |
|
||||||
|
mkdocs-material-
|
||||||
|
|
||||||
|
- name: Install MkDocs and Material Theme
|
||||||
|
run: pip install mkdocs-material
|
||||||
|
|
||||||
|
- name: Build and Deploy
|
||||||
|
run: mkdocs gh-deploy --force
|
||||||
@@ -212,8 +212,8 @@ jobs:
|
|||||||
docker buildx build \
|
docker buildx build \
|
||||||
--platform linux/amd64,linux/arm64 \
|
--platform linux/amd64,linux/arm64 \
|
||||||
--push \
|
--push \
|
||||||
-t ${{ env.REGISTRY }}/${OWNER}/go-backend:latest \
|
-t ${{ env.REGISTRY }}/${OWNER}/flux-panel-backend:latest \
|
||||||
-t ${{ env.REGISTRY }}/${OWNER}/go-backend:${VERSION} \
|
-t ${{ env.REGISTRY }}/${OWNER}/flux-panel-backend:${VERSION} \
|
||||||
./go-backend
|
./go-backend
|
||||||
|
|
||||||
create-release:
|
create-release:
|
||||||
@@ -253,9 +253,9 @@ jobs:
|
|||||||
cp docker-compose-v6.yml ./artifacts/docker-compose-v6.yml
|
cp docker-compose-v6.yml ./artifacts/docker-compose-v6.yml
|
||||||
|
|
||||||
# 替换镜像地址为 GHCR
|
# 替换镜像地址为 GHCR
|
||||||
sed -i "s|image: .*go-backend:[^[:space:]]*|image: ${{ env.REGISTRY }}/${OWNER}/go-backend:${VERSION}|g" ./artifacts/docker-compose-v4.yml
|
sed -i "s|image: .*flux-panel-backend:[^[:space:]]*|image: ${{ env.REGISTRY }}/${OWNER}/flux-panel-backend:${VERSION}|g" ./artifacts/docker-compose-v4.yml
|
||||||
sed -i "s|image: .*vite-frontend:[^[:space:]]*|image: ${{ env.REGISTRY }}/${OWNER}/vite-frontend:${VERSION}|g" ./artifacts/docker-compose-v4.yml
|
sed -i "s|image: .*vite-frontend:[^[:space:]]*|image: ${{ env.REGISTRY }}/${OWNER}/vite-frontend:${VERSION}|g" ./artifacts/docker-compose-v4.yml
|
||||||
sed -i "s|image: .*go-backend:[^[:space:]]*|image: ${{ env.REGISTRY }}/${OWNER}/go-backend:${VERSION}|g" ./artifacts/docker-compose-v6.yml
|
sed -i "s|image: .*flux-panel-backend:[^[:space:]]*|image: ${{ env.REGISTRY }}/${OWNER}/flux-panel-backend:${VERSION}|g" ./artifacts/docker-compose-v6.yml
|
||||||
sed -i "s|image: .*vite-frontend:[^[:space:]]*|image: ${{ env.REGISTRY }}/${OWNER}/vite-frontend:${VERSION}|g" ./artifacts/docker-compose-v6.yml
|
sed -i "s|image: .*vite-frontend:[^[:space:]]*|image: ${{ env.REGISTRY }}/${OWNER}/vite-frontend:${VERSION}|g" ./artifacts/docker-compose-v6.yml
|
||||||
|
|
||||||
# 复制并修改安装脚本
|
# 复制并修改安装脚本
|
||||||
@@ -268,6 +268,10 @@ jobs:
|
|||||||
sed -i "s|2.0.7-beta|${VERSION}|g" ./artifacts/install.sh
|
sed -i "s|2.0.7-beta|${VERSION}|g" ./artifacts/install.sh
|
||||||
sed -i "s|2.0.7-beta|${VERSION}|g" ./artifacts/panel_install.sh
|
sed -i "s|2.0.7-beta|${VERSION}|g" ./artifacts/panel_install.sh
|
||||||
|
|
||||||
|
# 注入固定版本号,使从 Release 页下载的脚本只安装该版本
|
||||||
|
sed -i "s|^PINNED_VERSION=\"\"|PINNED_VERSION=\"${VERSION}\"|" ./artifacts/install.sh
|
||||||
|
sed -i "s|^PINNED_VERSION=\"\"|PINNED_VERSION=\"${VERSION}\"|" ./artifacts/panel_install.sh
|
||||||
|
|
||||||
- name: Create Release
|
- name: Create Release
|
||||||
env:
|
env:
|
||||||
GH_TOKEN: ${{ github.token }}
|
GH_TOKEN: ${{ github.token }}
|
||||||
@@ -295,7 +299,7 @@ jobs:
|
|||||||
|
|
||||||
\`\`\`bash
|
\`\`\`bash
|
||||||
# Backend
|
# Backend
|
||||||
docker pull ${{ env.REGISTRY }}/${OWNER}/go-backend:${VERSION}
|
docker pull ${{ env.REGISTRY }}/${OWNER}/flux-panel-backend:${VERSION}
|
||||||
|
|
||||||
# Frontend
|
# Frontend
|
||||||
docker pull ${{ env.REGISTRY }}/${OWNER}/vite-frontend:${VERSION}
|
docker pull ${{ env.REGISTRY }}/${OWNER}/vite-frontend:${VERSION}
|
||||||
@@ -303,14 +307,22 @@ jobs:
|
|||||||
|
|
||||||
## 🚀 Quick Install
|
## 🚀 Quick Install
|
||||||
|
|
||||||
**Panel:**
|
**Panel (安装此版本 ${VERSION}):**
|
||||||
\`\`\`bash
|
\`\`\`bash
|
||||||
curl -L https://github.com/${{ github.repository }}/releases/download/${VERSION}/panel_install.sh -o panel_install.sh && chmod +x panel_install.sh && ./panel_install.sh
|
curl -L https://github.com/${{ github.repository }}/releases/download/${VERSION}/panel_install.sh -o panel_install.sh && chmod +x panel_install.sh && ./panel_install.sh
|
||||||
\`\`\`
|
\`\`\`
|
||||||
|
|
||||||
**Node:**
|
**Node (安装此版本 ${VERSION}):**
|
||||||
\`\`\`bash
|
\`\`\`bash
|
||||||
curl -L https://github.com/${{ github.repository }}/releases/download/${VERSION}/install.sh -o install.sh && chmod +x install.sh && ./install.sh
|
curl -L https://github.com/${{ github.repository }}/releases/download/${VERSION}/install.sh -o install.sh && chmod +x install.sh && ./install.sh
|
||||||
|
\`\`\`
|
||||||
|
|
||||||
|
**安装最新版:**
|
||||||
|
\`\`\`bash
|
||||||
|
# 面板端
|
||||||
|
curl -L https://raw.githubusercontent.com/${{ github.repository }}/main/panel_install.sh -o panel_install.sh && chmod +x panel_install.sh && ./panel_install.sh
|
||||||
|
# 节点端
|
||||||
|
curl -L https://raw.githubusercontent.com/${{ github.repository }}/main/install.sh -o install.sh && chmod +x install.sh && ./install.sh
|
||||||
\`\`\`" \
|
\`\`\`" \
|
||||||
--repo ${{ github.repository }}
|
--repo ${{ github.repository }}
|
||||||
|
|
||||||
|
|||||||
@@ -176,6 +176,7 @@ build/
|
|||||||
*.so
|
*.so
|
||||||
*.dylib
|
*.dylib
|
||||||
your_app.exe
|
your_app.exe
|
||||||
|
go-backend/paneld
|
||||||
|
|
||||||
# Go 测试二进制文件
|
# Go 测试二进制文件
|
||||||
*.test
|
*.test
|
||||||
|
|||||||
@@ -1,42 +0,0 @@
|
|||||||
// Package controller provides HTTP request handlers and controllers for the 3x-ui web management panel.
|
|
||||||
// It handles routing, authentication, and API endpoints for managing Xray inbounds, settings, and more.
|
|
||||||
package controller
|
|
||||||
|
|
||||||
import (
|
|
||||||
"net/http"
|
|
||||||
|
|
||||||
"github.com/mhsanaei/3x-ui/v2/logger"
|
|
||||||
"github.com/mhsanaei/3x-ui/v2/web/locale"
|
|
||||||
"github.com/mhsanaei/3x-ui/v2/web/session"
|
|
||||||
|
|
||||||
"github.com/gin-gonic/gin"
|
|
||||||
)
|
|
||||||
|
|
||||||
// BaseController provides common functionality for all controllers, including authentication checks.
|
|
||||||
type BaseController struct{}
|
|
||||||
|
|
||||||
// checkLogin is a middleware that verifies user authentication and handles unauthorized access.
|
|
||||||
func (a *BaseController) checkLogin(c *gin.Context) {
|
|
||||||
if !session.IsLogin(c) {
|
|
||||||
if isAjax(c) {
|
|
||||||
pureJsonMsg(c, http.StatusUnauthorized, false, I18nWeb(c, "pages.login.loginAgain"))
|
|
||||||
} else {
|
|
||||||
c.Redirect(http.StatusTemporaryRedirect, c.GetString("base_path"))
|
|
||||||
}
|
|
||||||
c.Abort()
|
|
||||||
} else {
|
|
||||||
c.Next()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// I18nWeb retrieves an internationalized message for the web interface based on the current locale.
|
|
||||||
func I18nWeb(c *gin.Context, name string, params ...string) string {
|
|
||||||
anyfunc, funcExists := c.Get("I18n")
|
|
||||||
if !funcExists {
|
|
||||||
logger.Warning("I18n function not exists in gin context!")
|
|
||||||
return ""
|
|
||||||
}
|
|
||||||
i18nFunc, _ := anyfunc.(func(i18nType locale.I18nType, key string, keyParams ...string) string)
|
|
||||||
msg := i18nFunc(locale.Web, name, params...)
|
|
||||||
return msg
|
|
||||||
}
|
|
||||||
@@ -1,424 +0,0 @@
|
|||||||
package controller
|
|
||||||
|
|
||||||
import (
|
|
||||||
"encoding/json"
|
|
||||||
"fmt"
|
|
||||||
"strconv"
|
|
||||||
|
|
||||||
"github.com/mhsanaei/3x-ui/v2/database/model"
|
|
||||||
"github.com/mhsanaei/3x-ui/v2/web/service"
|
|
||||||
"github.com/mhsanaei/3x-ui/v2/web/session"
|
|
||||||
"github.com/mhsanaei/3x-ui/v2/web/websocket"
|
|
||||||
|
|
||||||
"github.com/gin-gonic/gin"
|
|
||||||
)
|
|
||||||
|
|
||||||
// InboundController handles HTTP requests related to Xray inbounds management.
|
|
||||||
type InboundController struct {
|
|
||||||
inboundService service.InboundService
|
|
||||||
xrayService service.XrayService
|
|
||||||
}
|
|
||||||
|
|
||||||
// NewInboundController creates a new InboundController and sets up its routes.
|
|
||||||
func NewInboundController(g *gin.RouterGroup) *InboundController {
|
|
||||||
a := &InboundController{}
|
|
||||||
a.initRouter(g)
|
|
||||||
return a
|
|
||||||
}
|
|
||||||
|
|
||||||
// initRouter initializes the routes for inbound-related operations.
|
|
||||||
func (a *InboundController) initRouter(g *gin.RouterGroup) {
|
|
||||||
|
|
||||||
g.GET("/list", a.getInbounds)
|
|
||||||
g.GET("/get/:id", a.getInbound)
|
|
||||||
g.GET("/getClientTraffics/:email", a.getClientTraffics)
|
|
||||||
g.GET("/getClientTrafficsById/:id", a.getClientTrafficsById)
|
|
||||||
|
|
||||||
g.POST("/add", a.addInbound)
|
|
||||||
g.POST("/del/:id", a.delInbound)
|
|
||||||
g.POST("/update/:id", a.updateInbound)
|
|
||||||
g.POST("/clientIps/:email", a.getClientIps)
|
|
||||||
g.POST("/clearClientIps/:email", a.clearClientIps)
|
|
||||||
g.POST("/addClient", a.addInboundClient)
|
|
||||||
g.POST("/:id/delClient/:clientId", a.delInboundClient)
|
|
||||||
g.POST("/updateClient/:clientId", a.updateInboundClient)
|
|
||||||
g.POST("/:id/resetClientTraffic/:email", a.resetClientTraffic)
|
|
||||||
g.POST("/resetAllTraffics", a.resetAllTraffics)
|
|
||||||
g.POST("/resetAllClientTraffics/:id", a.resetAllClientTraffics)
|
|
||||||
g.POST("/delDepletedClients/:id", a.delDepletedClients)
|
|
||||||
g.POST("/import", a.importInbound)
|
|
||||||
g.POST("/onlines", a.onlines)
|
|
||||||
g.POST("/lastOnline", a.lastOnline)
|
|
||||||
g.POST("/updateClientTraffic/:email", a.updateClientTraffic)
|
|
||||||
g.POST("/:id/delClientByEmail/:email", a.delInboundClientByEmail)
|
|
||||||
}
|
|
||||||
|
|
||||||
// getInbounds retrieves the list of inbounds for the logged-in user.
|
|
||||||
func (a *InboundController) getInbounds(c *gin.Context) {
|
|
||||||
user := session.GetLoginUser(c)
|
|
||||||
inbounds, err := a.inboundService.GetInbounds(user.Id)
|
|
||||||
if err != nil {
|
|
||||||
jsonMsg(c, I18nWeb(c, "pages.inbounds.toasts.obtain"), err)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
jsonObj(c, inbounds, nil)
|
|
||||||
}
|
|
||||||
|
|
||||||
// getInbound retrieves a specific inbound by its ID.
|
|
||||||
func (a *InboundController) getInbound(c *gin.Context) {
|
|
||||||
id, err := strconv.Atoi(c.Param("id"))
|
|
||||||
if err != nil {
|
|
||||||
jsonMsg(c, I18nWeb(c, "get"), err)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
inbound, err := a.inboundService.GetInbound(id)
|
|
||||||
if err != nil {
|
|
||||||
jsonMsg(c, I18nWeb(c, "pages.inbounds.toasts.obtain"), err)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
jsonObj(c, inbound, nil)
|
|
||||||
}
|
|
||||||
|
|
||||||
// getClientTraffics retrieves client traffic information by email.
|
|
||||||
func (a *InboundController) getClientTraffics(c *gin.Context) {
|
|
||||||
email := c.Param("email")
|
|
||||||
clientTraffics, err := a.inboundService.GetClientTrafficByEmail(email)
|
|
||||||
if err != nil {
|
|
||||||
jsonMsg(c, I18nWeb(c, "pages.inbounds.toasts.trafficGetError"), err)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
jsonObj(c, clientTraffics, nil)
|
|
||||||
}
|
|
||||||
|
|
||||||
// getClientTrafficsById retrieves client traffic information by inbound ID.
|
|
||||||
func (a *InboundController) getClientTrafficsById(c *gin.Context) {
|
|
||||||
id := c.Param("id")
|
|
||||||
clientTraffics, err := a.inboundService.GetClientTrafficByID(id)
|
|
||||||
if err != nil {
|
|
||||||
jsonMsg(c, I18nWeb(c, "pages.inbounds.toasts.trafficGetError"), err)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
jsonObj(c, clientTraffics, nil)
|
|
||||||
}
|
|
||||||
|
|
||||||
// addInbound creates a new inbound configuration.
|
|
||||||
func (a *InboundController) addInbound(c *gin.Context) {
|
|
||||||
inbound := &model.Inbound{}
|
|
||||||
err := c.ShouldBind(inbound)
|
|
||||||
if err != nil {
|
|
||||||
jsonMsg(c, I18nWeb(c, "pages.inbounds.toasts.inboundCreateSuccess"), err)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
user := session.GetLoginUser(c)
|
|
||||||
inbound.UserId = user.Id
|
|
||||||
if inbound.Listen == "" || inbound.Listen == "0.0.0.0" || inbound.Listen == "::" || inbound.Listen == "::0" {
|
|
||||||
inbound.Tag = fmt.Sprintf("inbound-%v", inbound.Port)
|
|
||||||
} else {
|
|
||||||
inbound.Tag = fmt.Sprintf("inbound-%v:%v", inbound.Listen, inbound.Port)
|
|
||||||
}
|
|
||||||
|
|
||||||
inbound, needRestart, err := a.inboundService.AddInbound(inbound)
|
|
||||||
if err != nil {
|
|
||||||
jsonMsg(c, I18nWeb(c, "somethingWentWrong"), err)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
jsonMsgObj(c, I18nWeb(c, "pages.inbounds.toasts.inboundCreateSuccess"), inbound, nil)
|
|
||||||
if needRestart {
|
|
||||||
a.xrayService.SetToNeedRestart()
|
|
||||||
}
|
|
||||||
// Broadcast inbounds update via WebSocket
|
|
||||||
inbounds, _ := a.inboundService.GetInbounds(user.Id)
|
|
||||||
websocket.BroadcastInbounds(inbounds)
|
|
||||||
}
|
|
||||||
|
|
||||||
// delInbound deletes an inbound configuration by its ID.
|
|
||||||
func (a *InboundController) delInbound(c *gin.Context) {
|
|
||||||
id, err := strconv.Atoi(c.Param("id"))
|
|
||||||
if err != nil {
|
|
||||||
jsonMsg(c, I18nWeb(c, "pages.inbounds.toasts.inboundDeleteSuccess"), err)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
needRestart, err := a.inboundService.DelInbound(id)
|
|
||||||
if err != nil {
|
|
||||||
jsonMsg(c, I18nWeb(c, "somethingWentWrong"), err)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
jsonMsgObj(c, I18nWeb(c, "pages.inbounds.toasts.inboundDeleteSuccess"), id, nil)
|
|
||||||
if needRestart {
|
|
||||||
a.xrayService.SetToNeedRestart()
|
|
||||||
}
|
|
||||||
// Broadcast inbounds update via WebSocket
|
|
||||||
user := session.GetLoginUser(c)
|
|
||||||
inbounds, _ := a.inboundService.GetInbounds(user.Id)
|
|
||||||
websocket.BroadcastInbounds(inbounds)
|
|
||||||
}
|
|
||||||
|
|
||||||
// updateInbound updates an existing inbound configuration.
|
|
||||||
func (a *InboundController) updateInbound(c *gin.Context) {
|
|
||||||
id, err := strconv.Atoi(c.Param("id"))
|
|
||||||
if err != nil {
|
|
||||||
jsonMsg(c, I18nWeb(c, "pages.inbounds.toasts.inboundUpdateSuccess"), err)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
inbound := &model.Inbound{
|
|
||||||
Id: id,
|
|
||||||
}
|
|
||||||
err = c.ShouldBind(inbound)
|
|
||||||
if err != nil {
|
|
||||||
jsonMsg(c, I18nWeb(c, "pages.inbounds.toasts.inboundUpdateSuccess"), err)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
inbound, needRestart, err := a.inboundService.UpdateInbound(inbound)
|
|
||||||
if err != nil {
|
|
||||||
jsonMsg(c, I18nWeb(c, "somethingWentWrong"), err)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
jsonMsgObj(c, I18nWeb(c, "pages.inbounds.toasts.inboundUpdateSuccess"), inbound, nil)
|
|
||||||
if needRestart {
|
|
||||||
a.xrayService.SetToNeedRestart()
|
|
||||||
}
|
|
||||||
// Broadcast inbounds update via WebSocket
|
|
||||||
user := session.GetLoginUser(c)
|
|
||||||
inbounds, _ := a.inboundService.GetInbounds(user.Id)
|
|
||||||
websocket.BroadcastInbounds(inbounds)
|
|
||||||
}
|
|
||||||
|
|
||||||
// getClientIps retrieves the IP addresses associated with a client by email.
|
|
||||||
func (a *InboundController) getClientIps(c *gin.Context) {
|
|
||||||
email := c.Param("email")
|
|
||||||
|
|
||||||
ips, err := a.inboundService.GetInboundClientIps(email)
|
|
||||||
if err != nil || ips == "" {
|
|
||||||
jsonObj(c, "No IP Record", nil)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
jsonObj(c, ips, nil)
|
|
||||||
}
|
|
||||||
|
|
||||||
// clearClientIps clears the IP addresses for a client by email.
|
|
||||||
func (a *InboundController) clearClientIps(c *gin.Context) {
|
|
||||||
email := c.Param("email")
|
|
||||||
|
|
||||||
err := a.inboundService.ClearClientIps(email)
|
|
||||||
if err != nil {
|
|
||||||
jsonMsg(c, I18nWeb(c, "pages.inbounds.toasts.updateSuccess"), err)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
jsonMsg(c, I18nWeb(c, "pages.inbounds.toasts.logCleanSuccess"), nil)
|
|
||||||
}
|
|
||||||
|
|
||||||
// addInboundClient adds a new client to an existing inbound.
|
|
||||||
func (a *InboundController) addInboundClient(c *gin.Context) {
|
|
||||||
data := &model.Inbound{}
|
|
||||||
err := c.ShouldBind(data)
|
|
||||||
if err != nil {
|
|
||||||
jsonMsg(c, I18nWeb(c, "pages.inbounds.toasts.inboundUpdateSuccess"), err)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
needRestart, err := a.inboundService.AddInboundClient(data)
|
|
||||||
if err != nil {
|
|
||||||
jsonMsg(c, I18nWeb(c, "somethingWentWrong"), err)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
jsonMsg(c, I18nWeb(c, "pages.inbounds.toasts.inboundClientAddSuccess"), nil)
|
|
||||||
if needRestart {
|
|
||||||
a.xrayService.SetToNeedRestart()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// delInboundClient deletes a client from an inbound by inbound ID and client ID.
|
|
||||||
func (a *InboundController) delInboundClient(c *gin.Context) {
|
|
||||||
id, err := strconv.Atoi(c.Param("id"))
|
|
||||||
if err != nil {
|
|
||||||
jsonMsg(c, I18nWeb(c, "pages.inbounds.toasts.inboundUpdateSuccess"), err)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
clientId := c.Param("clientId")
|
|
||||||
|
|
||||||
needRestart, err := a.inboundService.DelInboundClient(id, clientId)
|
|
||||||
if err != nil {
|
|
||||||
jsonMsg(c, I18nWeb(c, "somethingWentWrong"), err)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
jsonMsg(c, I18nWeb(c, "pages.inbounds.toasts.inboundClientDeleteSuccess"), nil)
|
|
||||||
if needRestart {
|
|
||||||
a.xrayService.SetToNeedRestart()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// updateInboundClient updates a client's configuration in an inbound.
|
|
||||||
func (a *InboundController) updateInboundClient(c *gin.Context) {
|
|
||||||
clientId := c.Param("clientId")
|
|
||||||
|
|
||||||
inbound := &model.Inbound{}
|
|
||||||
err := c.ShouldBind(inbound)
|
|
||||||
if err != nil {
|
|
||||||
jsonMsg(c, I18nWeb(c, "pages.inbounds.toasts.inboundUpdateSuccess"), err)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
needRestart, err := a.inboundService.UpdateInboundClient(inbound, clientId)
|
|
||||||
if err != nil {
|
|
||||||
jsonMsg(c, I18nWeb(c, "somethingWentWrong"), err)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
jsonMsg(c, I18nWeb(c, "pages.inbounds.toasts.inboundClientUpdateSuccess"), nil)
|
|
||||||
if needRestart {
|
|
||||||
a.xrayService.SetToNeedRestart()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// resetClientTraffic resets the traffic counter for a specific client in an inbound.
|
|
||||||
func (a *InboundController) resetClientTraffic(c *gin.Context) {
|
|
||||||
id, err := strconv.Atoi(c.Param("id"))
|
|
||||||
if err != nil {
|
|
||||||
jsonMsg(c, I18nWeb(c, "pages.inbounds.toasts.inboundUpdateSuccess"), err)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
email := c.Param("email")
|
|
||||||
|
|
||||||
needRestart, err := a.inboundService.ResetClientTraffic(id, email)
|
|
||||||
if err != nil {
|
|
||||||
jsonMsg(c, I18nWeb(c, "somethingWentWrong"), err)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
jsonMsg(c, I18nWeb(c, "pages.inbounds.toasts.resetInboundClientTrafficSuccess"), nil)
|
|
||||||
if needRestart {
|
|
||||||
a.xrayService.SetToNeedRestart()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// resetAllTraffics resets all traffic counters across all inbounds.
|
|
||||||
func (a *InboundController) resetAllTraffics(c *gin.Context) {
|
|
||||||
err := a.inboundService.ResetAllTraffics()
|
|
||||||
if err != nil {
|
|
||||||
jsonMsg(c, I18nWeb(c, "somethingWentWrong"), err)
|
|
||||||
return
|
|
||||||
} else {
|
|
||||||
a.xrayService.SetToNeedRestart()
|
|
||||||
}
|
|
||||||
jsonMsg(c, I18nWeb(c, "pages.inbounds.toasts.resetAllTrafficSuccess"), nil)
|
|
||||||
}
|
|
||||||
|
|
||||||
// resetAllClientTraffics resets traffic counters for all clients in a specific inbound.
|
|
||||||
func (a *InboundController) resetAllClientTraffics(c *gin.Context) {
|
|
||||||
id, err := strconv.Atoi(c.Param("id"))
|
|
||||||
if err != nil {
|
|
||||||
jsonMsg(c, I18nWeb(c, "pages.inbounds.toasts.inboundUpdateSuccess"), err)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
err = a.inboundService.ResetAllClientTraffics(id)
|
|
||||||
if err != nil {
|
|
||||||
jsonMsg(c, I18nWeb(c, "somethingWentWrong"), err)
|
|
||||||
return
|
|
||||||
} else {
|
|
||||||
a.xrayService.SetToNeedRestart()
|
|
||||||
}
|
|
||||||
jsonMsg(c, I18nWeb(c, "pages.inbounds.toasts.resetAllClientTrafficSuccess"), nil)
|
|
||||||
}
|
|
||||||
|
|
||||||
// importInbound imports an inbound configuration from provided data.
|
|
||||||
func (a *InboundController) importInbound(c *gin.Context) {
|
|
||||||
inbound := &model.Inbound{}
|
|
||||||
err := json.Unmarshal([]byte(c.PostForm("data")), inbound)
|
|
||||||
if err != nil {
|
|
||||||
jsonMsg(c, I18nWeb(c, "somethingWentWrong"), err)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
user := session.GetLoginUser(c)
|
|
||||||
inbound.Id = 0
|
|
||||||
inbound.UserId = user.Id
|
|
||||||
if inbound.Listen == "" || inbound.Listen == "0.0.0.0" || inbound.Listen == "::" || inbound.Listen == "::0" {
|
|
||||||
inbound.Tag = fmt.Sprintf("inbound-%v", inbound.Port)
|
|
||||||
} else {
|
|
||||||
inbound.Tag = fmt.Sprintf("inbound-%v:%v", inbound.Listen, inbound.Port)
|
|
||||||
}
|
|
||||||
|
|
||||||
for index := range inbound.ClientStats {
|
|
||||||
inbound.ClientStats[index].Id = 0
|
|
||||||
inbound.ClientStats[index].Enable = true
|
|
||||||
}
|
|
||||||
|
|
||||||
needRestart := false
|
|
||||||
inbound, needRestart, err = a.inboundService.AddInbound(inbound)
|
|
||||||
jsonMsgObj(c, I18nWeb(c, "pages.inbounds.toasts.inboundCreateSuccess"), inbound, err)
|
|
||||||
if err == nil && needRestart {
|
|
||||||
a.xrayService.SetToNeedRestart()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// delDepletedClients deletes clients in an inbound who have exhausted their traffic limits.
|
|
||||||
func (a *InboundController) delDepletedClients(c *gin.Context) {
|
|
||||||
id, err := strconv.Atoi(c.Param("id"))
|
|
||||||
if err != nil {
|
|
||||||
jsonMsg(c, I18nWeb(c, "pages.inbounds.toasts.inboundUpdateSuccess"), err)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
err = a.inboundService.DelDepletedClients(id)
|
|
||||||
if err != nil {
|
|
||||||
jsonMsg(c, I18nWeb(c, "somethingWentWrong"), err)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
jsonMsg(c, I18nWeb(c, "pages.inbounds.toasts.delDepletedClientsSuccess"), nil)
|
|
||||||
}
|
|
||||||
|
|
||||||
// onlines retrieves the list of currently online clients.
|
|
||||||
func (a *InboundController) onlines(c *gin.Context) {
|
|
||||||
jsonObj(c, a.inboundService.GetOnlineClients(), nil)
|
|
||||||
}
|
|
||||||
|
|
||||||
// lastOnline retrieves the last online timestamps for clients.
|
|
||||||
func (a *InboundController) lastOnline(c *gin.Context) {
|
|
||||||
data, err := a.inboundService.GetClientsLastOnline()
|
|
||||||
jsonObj(c, data, err)
|
|
||||||
}
|
|
||||||
|
|
||||||
// updateClientTraffic updates the traffic statistics for a client by email.
|
|
||||||
func (a *InboundController) updateClientTraffic(c *gin.Context) {
|
|
||||||
email := c.Param("email")
|
|
||||||
|
|
||||||
// Define the request structure for traffic update
|
|
||||||
type TrafficUpdateRequest struct {
|
|
||||||
Upload int64 `json:"upload"`
|
|
||||||
Download int64 `json:"download"`
|
|
||||||
}
|
|
||||||
|
|
||||||
var request TrafficUpdateRequest
|
|
||||||
err := c.ShouldBindJSON(&request)
|
|
||||||
if err != nil {
|
|
||||||
jsonMsg(c, I18nWeb(c, "pages.inbounds.toasts.inboundUpdateSuccess"), err)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
err = a.inboundService.UpdateClientTrafficByEmail(email, request.Upload, request.Download)
|
|
||||||
if err != nil {
|
|
||||||
jsonMsg(c, I18nWeb(c, "somethingWentWrong"), err)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
jsonMsg(c, I18nWeb(c, "pages.inbounds.toasts.inboundClientUpdateSuccess"), nil)
|
|
||||||
}
|
|
||||||
|
|
||||||
// delInboundClientByEmail deletes a client from an inbound by email address.
|
|
||||||
func (a *InboundController) delInboundClientByEmail(c *gin.Context) {
|
|
||||||
inboundId, err := strconv.Atoi(c.Param("id"))
|
|
||||||
if err != nil {
|
|
||||||
jsonMsg(c, "Invalid inbound ID", err)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
email := c.Param("email")
|
|
||||||
needRestart, err := a.inboundService.DelInboundClientByEmail(inboundId, email)
|
|
||||||
if err != nil {
|
|
||||||
jsonMsg(c, "Failed to delete client by email", err)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
jsonMsg(c, "Client deleted successfully", nil)
|
|
||||||
if needRestart {
|
|
||||||
a.xrayService.SetToNeedRestart()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,54 +0,0 @@
|
|||||||
package controller
|
|
||||||
|
|
||||||
import (
|
|
||||||
"github.com/gin-gonic/gin"
|
|
||||||
)
|
|
||||||
|
|
||||||
// XUIController is the main controller for the X-UI panel, managing sub-controllers.
|
|
||||||
type XUIController struct {
|
|
||||||
BaseController
|
|
||||||
|
|
||||||
settingController *SettingController
|
|
||||||
xraySettingController *XraySettingController
|
|
||||||
}
|
|
||||||
|
|
||||||
// NewXUIController creates a new XUIController and initializes its routes.
|
|
||||||
func NewXUIController(g *gin.RouterGroup) *XUIController {
|
|
||||||
a := &XUIController{}
|
|
||||||
a.initRouter(g)
|
|
||||||
return a
|
|
||||||
}
|
|
||||||
|
|
||||||
// initRouter sets up the main panel routes and initializes sub-controllers.
|
|
||||||
func (a *XUIController) initRouter(g *gin.RouterGroup) {
|
|
||||||
g = g.Group("/panel")
|
|
||||||
g.Use(a.checkLogin)
|
|
||||||
|
|
||||||
g.GET("/", a.index)
|
|
||||||
g.GET("/inbounds", a.inbounds)
|
|
||||||
g.GET("/settings", a.settings)
|
|
||||||
g.GET("/xray", a.xraySettings)
|
|
||||||
|
|
||||||
a.settingController = NewSettingController(g)
|
|
||||||
a.xraySettingController = NewXraySettingController(g)
|
|
||||||
}
|
|
||||||
|
|
||||||
// index renders the main panel index page.
|
|
||||||
func (a *XUIController) index(c *gin.Context) {
|
|
||||||
html(c, "index.html", "pages.index.title", nil)
|
|
||||||
}
|
|
||||||
|
|
||||||
// inbounds renders the inbounds management page.
|
|
||||||
func (a *XUIController) inbounds(c *gin.Context) {
|
|
||||||
html(c, "inbounds.html", "pages.inbounds.title", nil)
|
|
||||||
}
|
|
||||||
|
|
||||||
// settings renders the settings management page.
|
|
||||||
func (a *XUIController) settings(c *gin.Context) {
|
|
||||||
html(c, "settings.html", "pages.settings.title", nil)
|
|
||||||
}
|
|
||||||
|
|
||||||
// xraySettings renders the Xray settings page.
|
|
||||||
func (a *XUIController) xraySettings(c *gin.Context) {
|
|
||||||
html(c, "xray.html", "pages.xray.title", nil)
|
|
||||||
}
|
|
||||||
@@ -5,17 +5,15 @@
|
|||||||
**Branch:** beta
|
**Branch:** beta
|
||||||
|
|
||||||
## OVERVIEW
|
## OVERVIEW
|
||||||
Flux Panel is a traffic forwarding management system built on a forked GOST v3 stack. It ships as Dockerized Spring Boot (admin API) + Vite/React UI + Go forwarding agent, with optional mobile WebView wrappers.
|
FLVX (formerly Flux Panel) is a traffic forwarding management system built on a forked GOST v3 stack. It ships as a Go-based admin API (SQLite) + Vite/React UI + Go forwarding agent, with optional mobile WebView wrappers.
|
||||||
|
|
||||||
## STRUCTURE
|
## STRUCTURE
|
||||||
```
|
```
|
||||||
./
|
./
|
||||||
├── go-gost/ # Go forwarding agent (forked gost + local x/)
|
├── go-gost/ # Go forwarding agent (forked gost + local x/)
|
||||||
│ └── x/ # Local fork of github.com/go-gost/x (replace => ./x)
|
│ └── x/ # Local fork of github.com/go-gost/x (replace => ./x)
|
||||||
├── springboot-backend/ # Java/Spring Boot admin API (SQLite/MyBatis)
|
├── go-backend/ # Go Admin API (SQLite, net/http)
|
||||||
├── vite-frontend/ # React/Vite dashboard (HeroUI + Tailwind)
|
├── vite-frontend/ # React/Vite dashboard (HeroUI + Tailwind)
|
||||||
├── android-app/ # Android WebView wrapper (optional)
|
|
||||||
├── ios-app/ # iOS WebView wrapper (optional)
|
|
||||||
├── docker-compose-v4.yml # Panel deploy (IPv4-only bridge)
|
├── docker-compose-v4.yml # Panel deploy (IPv4-only bridge)
|
||||||
├── docker-compose-v6.yml # Panel deploy (IPv6-enabled bridge)
|
├── docker-compose-v6.yml # Panel deploy (IPv6-enabled bridge)
|
||||||
├── panel_install.sh # Panel installer/upgrader (downloads compose)
|
├── panel_install.sh # Panel installer/upgrader (downloads compose)
|
||||||
@@ -30,16 +28,22 @@ Flux Panel is a traffic forwarding management system built on a forked GOST v3 s
|
|||||||
| **Deploy (IPv6)** | `docker-compose-v6.yml` | Same as v4 + IPv6-enabled bridge |
|
| **Deploy (IPv6)** | `docker-compose-v6.yml` | Same as v4 + IPv6-enabled bridge |
|
||||||
| **Panel install** | `panel_install.sh` | Picks v4/v6, generates `JWT_SECRET`, downloads compose |
|
| **Panel install** | `panel_install.sh` | Picks v4/v6, generates `JWT_SECRET`, downloads compose |
|
||||||
| **Node install** | `install.sh` | Installs `/etc/flux_agent/flux_agent` + writes `config.json`/`gost.json` + systemd `flux_agent.service` |
|
| **Node install** | `install.sh` | Installs `/etc/flux_agent/flux_agent` + writes `config.json`/`gost.json` + systemd `flux_agent.service` |
|
||||||
| **Admin API entry** | `springboot-backend/src/main/java/com/admin/AdminApplication.java` | Spring Boot app |
|
| **Admin API** | `go-backend/` | Go Admin API (SQLite) |
|
||||||
| **Admin API routes** | `springboot-backend/src/main/java/com/admin/controller/` | Mostly `/api/v1/*` controllers |
|
| **Web UI** | `vite-frontend/` | React/Vite dashboard (HeroUI + Tailwind) |
|
||||||
| **Admin auth** | `springboot-backend/src/main/java/com/admin/common/interceptor/JwtInterceptor.java` | Checks `Authorization` header |
|
| **Go Agent** | `go-gost/` | Forwarding agent (forked gost + local x/) |
|
||||||
| **Web UI routing** | `vite-frontend/src/App.tsx` | React Router v6 + ProtectedRoute/H5 layouts |
|
| **Go Core** | `go-gost/x/` | Handlers/listeners/dialers + management API |
|
||||||
| **Web UI API client** | `vite-frontend/src/api/network.ts` | Axios `baseURL` + `Authorization` header |
|
|
||||||
| **Go agent entry** | `go-gost/main.go` | Reads panel `config.json` + starts gost services |
|
## CODE MAP
|
||||||
| **Go x fork** | `go-gost/x/` | Handlers/listeners/dialers + management API |
|
| Symbol | Type | Location | Role |
|
||||||
|
|--------|------|----------|------|
|
||||||
|
| `flvx` | Project | `.` | Root directory |
|
||||||
|
| `main` | Func | `go-backend/cmd/paneld/main.go` | Backend Entry |
|
||||||
|
| `App` | Component | `vite-frontend/src/App.tsx` | Frontend Entry |
|
||||||
|
| `main` | Func | `go-gost/main.go` | Agent Entry |
|
||||||
|
|
||||||
|
|
||||||
## CONVENTIONS
|
## CONVENTIONS
|
||||||
- `Authorization` header carries the raw JWT token (no `Bearer` prefix) between `vite-frontend/` and `springboot-backend/`.
|
- `Authorization` header carries the raw JWT token (no `Bearer` prefix) between `vite-frontend/` and `go-backend/`.
|
||||||
- `go-gost/` uses `replace github.com/go-gost/x => ./x` and `go-gost/x/` is also its own Go module.
|
- `go-gost/` uses `replace github.com/go-gost/x => ./x` and `go-gost/x/` is also its own Go module.
|
||||||
|
|
||||||
## ANTI-PATTERNS (THIS PROJECT)
|
## ANTI-PATTERNS (THIS PROJECT)
|
||||||
@@ -56,7 +60,7 @@ docker compose -f docker-compose-v6.yml up -d
|
|||||||
./install.sh
|
./install.sh
|
||||||
|
|
||||||
# Local dev (per subproject)
|
# Local dev (per subproject)
|
||||||
(cd springboot-backend && mvn clean package)
|
(cd go-backend && make build)
|
||||||
(cd vite-frontend && npm run dev)
|
(cd vite-frontend && npm run dev)
|
||||||
(cd go-gost && go run .)
|
(cd go-gost && go run .)
|
||||||
```
|
```
|
||||||
|
|||||||
@@ -1,201 +1,674 @@
|
|||||||
Apache License
|
GNU GENERAL PUBLIC LICENSE
|
||||||
Version 2.0, January 2004
|
Version 3, 29 June 2007
|
||||||
http://www.apache.org/licenses/
|
|
||||||
|
|
||||||
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
|
||||||
|
Everyone is permitted to copy and distribute verbatim copies
|
||||||
|
of this license document, but changing it is not allowed.
|
||||||
|
|
||||||
1. Definitions.
|
Preamble
|
||||||
|
|
||||||
"License" shall mean the terms and conditions for use, reproduction,
|
The GNU General Public License is a free, copyleft license for
|
||||||
and distribution as defined by Sections 1 through 9 of this document.
|
software and other kinds of works.
|
||||||
|
|
||||||
"Licensor" shall mean the copyright owner or entity authorized by
|
The licenses for most software and other practical works are designed
|
||||||
the copyright owner that is granting the License.
|
to take away your freedom to share and change the works. By contrast,
|
||||||
|
the GNU General Public License is intended to guarantee your freedom to
|
||||||
|
share and change all versions of a program--to make sure it remains free
|
||||||
|
software for all its users. We, the Free Software Foundation, use the
|
||||||
|
GNU General Public License for most of our software; it applies also to
|
||||||
|
any other work released this way by its authors. You can apply it to
|
||||||
|
your programs, too.
|
||||||
|
|
||||||
"Legal Entity" shall mean the union of the acting entity and all
|
When we speak of free software, we are referring to freedom, not
|
||||||
other entities that control, are controlled by, or are under common
|
price. Our General Public Licenses are designed to make sure that you
|
||||||
control with that entity. For the purposes of this definition,
|
have the freedom to distribute copies of free software (and charge for
|
||||||
"control" means (i) the power, direct or indirect, to cause the
|
them if you wish), that you receive source code or can get it if you
|
||||||
direction or management of such entity, whether by contract or
|
want it, that you can change the software or use pieces of it in new
|
||||||
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
free programs, and that you know you can do these things.
|
||||||
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
||||||
|
|
||||||
"You" (or "Your") shall mean an individual or Legal Entity
|
To protect your rights, we need to prevent others from denying you
|
||||||
exercising permissions granted by this License.
|
these rights or asking you to surrender the rights. Therefore, you have
|
||||||
|
certain responsibilities if you distribute copies of the software, or if
|
||||||
|
you modify it: responsibilities to respect the freedom of others.
|
||||||
|
|
||||||
"Source" form shall mean the preferred form for making modifications,
|
For example, if you distribute copies of such a program, whether
|
||||||
including but not limited to software source code, documentation
|
gratis or for a fee, you must pass on to the recipients the same
|
||||||
source, and configuration files.
|
freedoms that you received. You must make sure that they, too, receive
|
||||||
|
or can get the source code. And you must show them these terms so they
|
||||||
|
know their rights.
|
||||||
|
|
||||||
"Object" form shall mean any form resulting from mechanical
|
Developers that use the GNU GPL protect your rights with two steps:
|
||||||
transformation or translation of a Source form, including but
|
(1) assert copyright on the software, and (2) offer you this License
|
||||||
not limited to compiled object code, generated documentation,
|
giving you legal permission to copy, distribute and/or modify it.
|
||||||
and conversions to other media types.
|
|
||||||
|
|
||||||
"Work" shall mean the work of authorship, whether in Source or
|
For the developers' and authors' protection, the GPL clearly explains
|
||||||
Object form, made available under the License, as indicated by a
|
that there is no warranty for this free software. For both users' and
|
||||||
copyright notice that is included in or attached to the work
|
authors' sake, the GPL requires that modified versions be marked as
|
||||||
(an example is provided in the Appendix below).
|
changed, so that their problems will not be attributed erroneously to
|
||||||
|
authors of previous versions.
|
||||||
|
|
||||||
"Derivative Works" shall mean any work, whether in Source or Object
|
Some devices are designed to deny users access to install or run
|
||||||
form, that is based on (or derived from) the Work and for which the
|
modified versions of the software inside them, although the manufacturer
|
||||||
editorial revisions, annotations, elaborations, or other modifications
|
can do so. This is fundamentally incompatible with the aim of
|
||||||
represent, as a whole, an original work of authorship. For the purposes
|
protecting users' freedom to change the software. The systematic
|
||||||
of this License, Derivative Works shall not include works that remain
|
pattern of such abuse occurs in the area of products for individuals to
|
||||||
separable from, or merely link (or bind by name) to the interfaces of,
|
use, which is precisely where it is most unacceptable. Therefore, we
|
||||||
the Work and Derivative Works thereof.
|
have designed this version of the GPL to prohibit the practice for those
|
||||||
|
products. If such problems arise substantially in other domains, we
|
||||||
|
stand ready to extend this provision to those domains in future versions
|
||||||
|
of the GPL, as needed to protect the freedom of users.
|
||||||
|
|
||||||
"Contribution" shall mean any work of authorship, including
|
Finally, every program is threatened constantly by software patents.
|
||||||
the original version of the Work and any modifications or additions
|
States should not allow patents to restrict development and use of
|
||||||
to that Work or Derivative Works thereof, that is intentionally
|
software on general-purpose computers, but in those that do, we wish to
|
||||||
submitted to Licensor for inclusion in the Work by the copyright owner
|
avoid the special danger that patents applied to a free program could
|
||||||
or by an individual or Legal Entity authorized to submit on behalf of
|
make it effectively proprietary. To prevent this, the GPL assures that
|
||||||
the copyright owner. For the purposes of this definition, "submitted"
|
patents cannot be used to render the program non-free.
|
||||||
means any form of electronic, verbal, or written communication sent
|
|
||||||
to the Licensor or its representatives, including but not limited to
|
|
||||||
communication on electronic mailing lists, source code control systems,
|
|
||||||
and issue tracking systems that are managed by, or on behalf of, the
|
|
||||||
Licensor for the purpose of discussing and improving the Work, but
|
|
||||||
excluding communication that is conspicuously marked or otherwise
|
|
||||||
designated in writing by the copyright owner as "Not a Contribution."
|
|
||||||
|
|
||||||
"Contributor" shall mean Licensor and any individual or Legal Entity
|
The precise terms and conditions for copying, distribution and
|
||||||
on behalf of whom a Contribution has been received by Licensor and
|
modification follow.
|
||||||
subsequently incorporated within the Work.
|
|
||||||
|
|
||||||
2. Grant of Copyright License. Subject to the terms and conditions of
|
TERMS AND CONDITIONS
|
||||||
this License, each Contributor hereby grants to You a perpetual,
|
|
||||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
||||||
copyright license to reproduce, prepare Derivative Works of,
|
|
||||||
publicly display, publicly perform, sublicense, and distribute the
|
|
||||||
Work and such Derivative Works in Source or Object form.
|
|
||||||
|
|
||||||
3. Grant of Patent License. Subject to the terms and conditions of
|
0. Definitions.
|
||||||
this License, each Contributor hereby grants to You a perpetual,
|
|
||||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
||||||
(except as stated in this section) patent license to make, have made,
|
|
||||||
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
||||||
where such license applies only to those patent claims licensable
|
|
||||||
by such Contributor that are necessarily infringed by their
|
|
||||||
Contribution(s) alone or by combination of their Contribution(s)
|
|
||||||
with the Work to which such Contribution(s) was submitted. If You
|
|
||||||
institute patent litigation against any entity (including a
|
|
||||||
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
||||||
or a Contribution incorporated within the Work constitutes direct
|
|
||||||
or contributory patent infringement, then any patent licenses
|
|
||||||
granted to You under this License for that Work shall terminate
|
|
||||||
as of the date such litigation is filed.
|
|
||||||
|
|
||||||
4. Redistribution. You may reproduce and distribute copies of the
|
"This License" refers to version 3 of the GNU General Public License.
|
||||||
Work or Derivative Works thereof in any medium, with or without
|
|
||||||
modifications, and in Source or Object form, provided that You
|
|
||||||
meet the following conditions:
|
|
||||||
|
|
||||||
(a) You must give any other recipients of the Work or
|
"Copyright" also means copyright-like laws that apply to other kinds of
|
||||||
Derivative Works a copy of this License; and
|
works, such as semiconductor masks.
|
||||||
|
|
||||||
(b) You must cause any modified files to carry prominent notices
|
"The Program" refers to any copyrightable work licensed under this
|
||||||
stating that You changed the files; and
|
License. Each licensee is addressed as "you". "Licensees" and
|
||||||
|
"recipients" may be individuals or organizations.
|
||||||
|
|
||||||
(c) You must retain, in the Source form of any Derivative Works
|
To "modify" a work means to copy from or adapt all or part of the work
|
||||||
that You distribute, all copyright, patent, trademark, and
|
in a fashion requiring copyright permission, other than the making of an
|
||||||
attribution notices from the Source form of the Work,
|
exact copy. The resulting work is called a "modified version" of the
|
||||||
excluding those notices that do not pertain to any part of
|
earlier work or a work "based on" the earlier work.
|
||||||
the Derivative Works; and
|
|
||||||
|
|
||||||
(d) If the Work includes a "NOTICE" text file as part of its
|
A "covered work" means either the unmodified Program or a work based
|
||||||
distribution, then any Derivative Works that You distribute must
|
on the Program.
|
||||||
include a readable copy of the attribution notices contained
|
|
||||||
within such NOTICE file, excluding those notices that do not
|
|
||||||
pertain to any part of the Derivative Works, in at least one
|
|
||||||
of the following places: within a NOTICE text file distributed
|
|
||||||
as part of the Derivative Works; within the Source form or
|
|
||||||
documentation, if provided along with the Derivative Works; or,
|
|
||||||
within a display generated by the Derivative Works, if and
|
|
||||||
wherever such third-party notices normally appear. The contents
|
|
||||||
of the NOTICE file are for informational purposes only and
|
|
||||||
do not modify the License. You may add Your own attribution
|
|
||||||
notices within Derivative Works that You distribute, alongside
|
|
||||||
or as an addendum to the NOTICE text from the Work, provided
|
|
||||||
that such additional attribution notices cannot be construed
|
|
||||||
as modifying the License.
|
|
||||||
|
|
||||||
You may add Your own copyright statement to Your modifications and
|
To "propagate" a work means to do anything with it that, without
|
||||||
may provide additional or different license terms and conditions
|
permission, would make you directly or secondarily liable for
|
||||||
for use, reproduction, or distribution of Your modifications, or
|
infringement under applicable copyright law, except executing it on a
|
||||||
for any such Derivative Works as a whole, provided Your use,
|
computer or modifying a private copy. Propagation includes copying,
|
||||||
reproduction, and distribution of the Work otherwise complies with
|
distribution (with or without modification), making available to the
|
||||||
the conditions stated in this License.
|
public, and in some countries other activities as well.
|
||||||
|
|
||||||
5. Submission of Contributions. Unless You explicitly state otherwise,
|
To "convey" a work means any kind of propagation that enables other
|
||||||
any Contribution intentionally submitted for inclusion in the Work
|
parties to make or receive copies. Mere interaction with a user through
|
||||||
by You to the Licensor shall be under the terms and conditions of
|
a computer network, with no transfer of a copy, is not conveying.
|
||||||
this License, without any additional terms or conditions.
|
|
||||||
Notwithstanding the above, nothing herein shall supersede or modify
|
|
||||||
the terms of any separate license agreement you may have executed
|
|
||||||
with Licensor regarding such Contributions.
|
|
||||||
|
|
||||||
6. Trademarks. This License does not grant permission to use the trade
|
An interactive user interface displays "Appropriate Legal Notices"
|
||||||
names, trademarks, service marks, or product names of the Licensor,
|
to the extent that it includes a convenient and prominently visible
|
||||||
except as required for reasonable and customary use in describing the
|
feature that (1) displays an appropriate copyright notice, and (2)
|
||||||
origin of the Work and reproducing the content of the NOTICE file.
|
tells the user that there is no warranty for the work (except to the
|
||||||
|
extent that warranties are provided), that licensees may convey the
|
||||||
|
work under this License, and how to view a copy of this License. If
|
||||||
|
the interface presents a list of user commands or options, such as a
|
||||||
|
menu, a prominent item in the list meets this criterion.
|
||||||
|
|
||||||
7. Disclaimer of Warranty. Unless required by applicable law or
|
1. Source Code.
|
||||||
agreed to in writing, Licensor provides the Work (and each
|
|
||||||
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
||||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
||||||
implied, including, without limitation, any warranties or conditions
|
|
||||||
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
||||||
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
||||||
appropriateness of using or redistributing the Work and assume any
|
|
||||||
risks associated with Your exercise of permissions under this License.
|
|
||||||
|
|
||||||
8. Limitation of Liability. In no event and under no legal theory,
|
The "source code" for a work means the preferred form of the work
|
||||||
whether in tort (including negligence), contract, or otherwise,
|
for making modifications to it. "Object code" means any non-source
|
||||||
unless required by applicable law (such as deliberate and grossly
|
form of a work.
|
||||||
negligent acts) or agreed to in writing, shall any Contributor be
|
|
||||||
liable to You for damages, including any direct, indirect, special,
|
|
||||||
incidental, or consequential damages of any character arising as a
|
|
||||||
result of this License or out of the use or inability to use the
|
|
||||||
Work (including but not limited to damages for loss of goodwill,
|
|
||||||
work stoppage, computer failure or malfunction, or any and all
|
|
||||||
other commercial damages or losses), even if such Contributor
|
|
||||||
has been advised of the possibility of such damages.
|
|
||||||
|
|
||||||
9. Accepting Warranty or Additional Liability. While redistributing
|
A "Standard Interface" means an interface that either is an official
|
||||||
the Work or Derivative Works thereof, You may choose to offer,
|
standard defined by a recognized standards body, or, in the case of
|
||||||
and charge a fee for, acceptance of support, warranty, indemnity,
|
interfaces specified for a particular programming language, one that
|
||||||
or other liability obligations and/or rights consistent with this
|
is widely used among developers working in that language.
|
||||||
License. However, in accepting such obligations, You may act only
|
|
||||||
on Your own behalf and on Your sole responsibility, not on behalf
|
|
||||||
of any other Contributor, and only if You agree to indemnify,
|
|
||||||
defend, and hold each Contributor harmless for any liability
|
|
||||||
incurred by, or claims asserted against, such Contributor by reason
|
|
||||||
of your accepting any such warranty or additional liability.
|
|
||||||
|
|
||||||
END OF TERMS AND CONDITIONS
|
The "System Libraries" of an executable work include anything, other
|
||||||
|
than the work as a whole, that (a) is included in the normal form of
|
||||||
|
packaging a Major Component, but which is not part of that Major
|
||||||
|
Component, and (b) serves only to enable use of the work with that
|
||||||
|
Major Component, or to implement a Standard Interface for which an
|
||||||
|
implementation is available to the public in source code form. A
|
||||||
|
"Major Component", in this context, means a major essential component
|
||||||
|
(kernel, window system, and so on) of the specific operating system
|
||||||
|
(if any) on which the executable work runs, or a compiler used to
|
||||||
|
produce the work, or an object code interpreter used to run it.
|
||||||
|
|
||||||
APPENDIX: How to apply the Apache License to your work.
|
The "Corresponding Source" for a work in object code form means all
|
||||||
|
the source code needed to generate, install, and (for an executable
|
||||||
|
work) run the object code and to modify the work, including scripts to
|
||||||
|
control those activities. However, it does not include the work's
|
||||||
|
System Libraries, or general-purpose tools or generally available free
|
||||||
|
programs which are used unmodified in performing those activities but
|
||||||
|
which are not part of the work. For example, Corresponding Source
|
||||||
|
includes interface definition files associated with source files for
|
||||||
|
the work, and the source code for shared libraries and dynamically
|
||||||
|
linked subprograms that the work is specifically designed to require,
|
||||||
|
such as by intimate data communication or control flow between those
|
||||||
|
subprograms and other parts of the work.
|
||||||
|
|
||||||
To apply the Apache License to your work, attach the following
|
The Corresponding Source need not include anything that users
|
||||||
boilerplate notice, with the fields enclosed by brackets "[]"
|
can regenerate automatically from other parts of the Corresponding
|
||||||
replaced with your own identifying information. (Don't include
|
Source.
|
||||||
the brackets!) The text should be enclosed in the appropriate
|
|
||||||
comment syntax for the file format. We also recommend that a
|
|
||||||
file or class name and description of purpose be included on the
|
|
||||||
same "printed page" as the copyright notice for easier
|
|
||||||
identification within third-party archives.
|
|
||||||
|
|
||||||
Copyright [yyyy] [name of copyright owner]
|
The Corresponding Source for a work in source code form is that
|
||||||
|
same work.
|
||||||
|
|
||||||
Licensed under the Apache License, Version 2.0 (the "License");
|
2. Basic Permissions.
|
||||||
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
|
All rights granted under this License are granted for the term of
|
||||||
|
copyright on the Program, and are irrevocable provided the stated
|
||||||
|
conditions are met. This License explicitly affirms your unlimited
|
||||||
|
permission to run the unmodified Program. The output from running a
|
||||||
|
covered work is covered by this License only if the output, given its
|
||||||
|
content, constitutes a covered work. This License acknowledges your
|
||||||
|
rights of fair use or other equivalent, as provided by copyright law.
|
||||||
|
|
||||||
Unless required by applicable law or agreed to in writing, software
|
You may make, run and propagate covered works that you do not
|
||||||
distributed under the License is distributed on an "AS IS" BASIS,
|
convey, without conditions so long as your license otherwise remains
|
||||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
in force. You may convey covered works to others for the sole purpose
|
||||||
See the License for the specific language governing permissions and
|
of having them make modifications exclusively for you, or provide you
|
||||||
limitations under the License.
|
with facilities for running those works, provided that you comply with
|
||||||
|
the terms of this License in conveying all material for which you do
|
||||||
|
not control copyright. Those thus making or running the covered works
|
||||||
|
for you must do so exclusively on your behalf, under your direction
|
||||||
|
and control, on terms that prohibit them from making any copies of
|
||||||
|
your copyrighted material outside their relationship with you.
|
||||||
|
|
||||||
|
Conveying under any other circumstances is permitted solely under
|
||||||
|
the conditions stated below. Sublicensing is not allowed; section 10
|
||||||
|
makes it unnecessary.
|
||||||
|
|
||||||
|
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
|
||||||
|
|
||||||
|
No covered work shall be deemed part of an effective technological
|
||||||
|
measure under any applicable law fulfilling obligations under article
|
||||||
|
11 of the WIPO copyright treaty adopted on 20 December 1996, or
|
||||||
|
similar laws prohibiting or restricting circumvention of such
|
||||||
|
measures.
|
||||||
|
|
||||||
|
When you convey a covered work, you waive any legal power to forbid
|
||||||
|
circumvention of technological measures to the extent such circumvention
|
||||||
|
is effected by exercising rights under this License with respect to
|
||||||
|
the covered work, and you disclaim any intention to limit operation or
|
||||||
|
modification of the work as a means of enforcing, against the work's
|
||||||
|
users, your or third parties' legal rights to forbid circumvention of
|
||||||
|
technological measures.
|
||||||
|
|
||||||
|
4. Conveying Verbatim Copies.
|
||||||
|
|
||||||
|
You may convey verbatim copies of the Program's source code as you
|
||||||
|
receive it, in any medium, provided that you conspicuously and
|
||||||
|
appropriately publish on each copy an appropriate copyright notice;
|
||||||
|
keep intact all notices stating that this License and any
|
||||||
|
non-permissive terms added in accord with section 7 apply to the code;
|
||||||
|
keep intact all notices of the absence of any warranty; and give all
|
||||||
|
recipients a copy of this License along with the Program.
|
||||||
|
|
||||||
|
You may charge any price or no price for each copy that you convey,
|
||||||
|
and you may offer support or warranty protection for a fee.
|
||||||
|
|
||||||
|
5. Conveying Modified Source Versions.
|
||||||
|
|
||||||
|
You may convey a work based on the Program, or the modifications to
|
||||||
|
produce it from the Program, in the form of source code under the
|
||||||
|
terms of section 4, provided that you also meet all of these conditions:
|
||||||
|
|
||||||
|
a) The work must carry prominent notices stating that you modified
|
||||||
|
it, and giving a relevant date.
|
||||||
|
|
||||||
|
b) The work must carry prominent notices stating that it is
|
||||||
|
released under this License and any conditions added under section
|
||||||
|
7. This requirement modifies the requirement in section 4 to
|
||||||
|
"keep intact all notices".
|
||||||
|
|
||||||
|
c) You must license the entire work, as a whole, under this
|
||||||
|
License to anyone who comes into possession of a copy. This
|
||||||
|
License will therefore apply, along with any applicable section 7
|
||||||
|
additional terms, to the whole of the work, and all its parts,
|
||||||
|
regardless of how they are packaged. This License gives no
|
||||||
|
permission to license the work in any other way, but it does not
|
||||||
|
invalidate such permission if you have separately received it.
|
||||||
|
|
||||||
|
d) If the work has interactive user interfaces, each must display
|
||||||
|
Appropriate Legal Notices; however, if the Program has interactive
|
||||||
|
interfaces that do not display Appropriate Legal Notices, your
|
||||||
|
work need not make them do so.
|
||||||
|
|
||||||
|
A compilation of a covered work with other separate and independent
|
||||||
|
works, which are not by their nature extensions of the covered work,
|
||||||
|
and which are not combined with it such as to form a larger program,
|
||||||
|
in or on a volume of a storage or distribution medium, is called an
|
||||||
|
"aggregate" if the compilation and its resulting copyright are not
|
||||||
|
used to limit the access or legal rights of the compilation's users
|
||||||
|
beyond what the individual works permit. Inclusion of a covered work
|
||||||
|
in an aggregate does not cause this License to apply to the other
|
||||||
|
parts of the aggregate.
|
||||||
|
|
||||||
|
6. Conveying Non-Source Forms.
|
||||||
|
|
||||||
|
You may convey a covered work in object code form under the terms
|
||||||
|
of sections 4 and 5, provided that you also convey the
|
||||||
|
machine-readable Corresponding Source under the terms of this License,
|
||||||
|
in one of these ways:
|
||||||
|
|
||||||
|
a) Convey the object code in, or embodied in, a physical product
|
||||||
|
(including a physical distribution medium), accompanied by the
|
||||||
|
Corresponding Source fixed on a durable physical medium
|
||||||
|
customarily used for software interchange.
|
||||||
|
|
||||||
|
b) Convey the object code in, or embodied in, a physical product
|
||||||
|
(including a physical distribution medium), accompanied by a
|
||||||
|
written offer, valid for at least three years and valid for as
|
||||||
|
long as you offer spare parts or customer support for that product
|
||||||
|
model, to give anyone who possesses the object code either (1) a
|
||||||
|
copy of the Corresponding Source for all the software in the
|
||||||
|
product that is covered by this License, on a durable physical
|
||||||
|
medium customarily used for software interchange, for a price no
|
||||||
|
more than your reasonable cost of physically performing this
|
||||||
|
conveying of source, or (2) access to copy the
|
||||||
|
Corresponding Source from a network server at no charge.
|
||||||
|
|
||||||
|
c) Convey individual copies of the object code with a copy of the
|
||||||
|
written offer to provide the Corresponding Source. This
|
||||||
|
alternative is allowed only occasionally and noncommercially, and
|
||||||
|
only if you received the object code with such an offer, in accord
|
||||||
|
with subsection 6b.
|
||||||
|
|
||||||
|
d) Convey the object code by offering access from a designated
|
||||||
|
place (gratis or for a charge), and offer equivalent access to the
|
||||||
|
Corresponding Source in the same way through the same place at no
|
||||||
|
further charge. You need not require recipients to copy the
|
||||||
|
Corresponding Source along with the object code. If the place to
|
||||||
|
copy the object code is a network server, the Corresponding Source
|
||||||
|
may be on a different server (operated by you or a third party)
|
||||||
|
that supports equivalent copying facilities, provided you maintain
|
||||||
|
clear directions next to the object code saying where to find the
|
||||||
|
Corresponding Source. Regardless of what server hosts the
|
||||||
|
Corresponding Source, you remain obligated to ensure that it is
|
||||||
|
available for as long as needed to satisfy these requirements.
|
||||||
|
|
||||||
|
e) Convey the object code using peer-to-peer transmission, provided
|
||||||
|
you inform other peers where the object code and Corresponding
|
||||||
|
Source of the work are being offered to the general public at no
|
||||||
|
charge under subsection 6d.
|
||||||
|
|
||||||
|
A separable portion of the object code, whose source code is excluded
|
||||||
|
from the Corresponding Source as a System Library, need not be
|
||||||
|
included in conveying the object code work.
|
||||||
|
|
||||||
|
A "User Product" is either (1) a "consumer product", which means any
|
||||||
|
tangible personal property which is normally used for personal, family,
|
||||||
|
or household purposes, or (2) anything designed or sold for incorporation
|
||||||
|
into a dwelling. In determining whether a product is a consumer product,
|
||||||
|
doubtful cases shall be resolved in favor of coverage. For a particular
|
||||||
|
product received by a particular user, "normally used" refers to a
|
||||||
|
typical or common use of that class of product, regardless of the status
|
||||||
|
of the particular user or of the way in which the particular user
|
||||||
|
actually uses, or expects or is expected to use, the product. A product
|
||||||
|
is a consumer product regardless of whether the product has substantial
|
||||||
|
commercial, industrial or non-consumer uses, unless such uses represent
|
||||||
|
the only significant mode of use of the product.
|
||||||
|
|
||||||
|
"Installation Information" for a User Product means any methods,
|
||||||
|
procedures, authorization keys, or other information required to install
|
||||||
|
and execute modified versions of a covered work in that User Product from
|
||||||
|
a modified version of its Corresponding Source. The information must
|
||||||
|
suffice to ensure that the continued functioning of the modified object
|
||||||
|
code is in no case prevented or interfered with solely because
|
||||||
|
modification has been made.
|
||||||
|
|
||||||
|
If you convey an object code work under this section in, or with, or
|
||||||
|
specifically for use in, a User Product, and the conveying occurs as
|
||||||
|
part of a transaction in which the right of possession and use of the
|
||||||
|
User Product is transferred to the recipient in perpetuity or for a
|
||||||
|
fixed term (regardless of how the transaction is characterized), the
|
||||||
|
Corresponding Source conveyed under this section must be accompanied
|
||||||
|
by the Installation Information. But this requirement does not apply
|
||||||
|
if neither you nor any third party retains the ability to install
|
||||||
|
modified object code on the User Product (for example, the work has
|
||||||
|
been installed in ROM).
|
||||||
|
|
||||||
|
The requirement to provide Installation Information does not include a
|
||||||
|
requirement to continue to provide support service, warranty, or updates
|
||||||
|
for a work that has been modified or installed by the recipient, or for
|
||||||
|
the User Product in which it has been modified or installed. Access to a
|
||||||
|
network may be denied when the modification itself materially and
|
||||||
|
adversely affects the operation of the network or violates the rules and
|
||||||
|
protocols for communication across the network.
|
||||||
|
|
||||||
|
Corresponding Source conveyed, and Installation Information provided,
|
||||||
|
in accord with this section must be in a format that is publicly
|
||||||
|
documented (and with an implementation available to the public in
|
||||||
|
source code form), and must require no special password or key for
|
||||||
|
unpacking, reading or copying.
|
||||||
|
|
||||||
|
7. Additional Terms.
|
||||||
|
|
||||||
|
"Additional permissions" are terms that supplement the terms of this
|
||||||
|
License by making exceptions from one or more of its conditions.
|
||||||
|
Additional permissions that are applicable to the entire Program shall
|
||||||
|
be treated as though they were included in this License, to the extent
|
||||||
|
that they are valid under applicable law. If additional permissions
|
||||||
|
apply only to part of the Program, that part may be used separately
|
||||||
|
under those permissions, but the entire Program remains governed by
|
||||||
|
this License without regard to the additional permissions.
|
||||||
|
|
||||||
|
When you convey a copy of a covered work, you may at your option
|
||||||
|
remove any additional permissions from that copy, or from any part of
|
||||||
|
it. (Additional permissions may be written to require their own
|
||||||
|
removal in certain cases when you modify the work.) You may place
|
||||||
|
additional permissions on material, added by you to a covered work,
|
||||||
|
for which you have or can give appropriate copyright permission.
|
||||||
|
|
||||||
|
Notwithstanding any other provision of this License, for material you
|
||||||
|
add to a covered work, you may (if authorized by the copyright holders of
|
||||||
|
that material) supplement the terms of this License with terms:
|
||||||
|
|
||||||
|
a) Disclaiming warranty or limiting liability differently from the
|
||||||
|
terms of sections 15 and 16 of this License; or
|
||||||
|
|
||||||
|
b) Requiring preservation of specified reasonable legal notices or
|
||||||
|
author attributions in that material or in the Appropriate Legal
|
||||||
|
Notices displayed by works containing it; or
|
||||||
|
|
||||||
|
c) Prohibiting misrepresentation of the origin of that material, or
|
||||||
|
requiring that modified versions of such material be marked in
|
||||||
|
reasonable ways as different from the original version; or
|
||||||
|
|
||||||
|
d) Limiting the use for publicity purposes of names of licensors or
|
||||||
|
authors of the material; or
|
||||||
|
|
||||||
|
e) Declining to grant rights under trademark law for use of some
|
||||||
|
trade names, trademarks, or service marks; or
|
||||||
|
|
||||||
|
f) Requiring indemnification of licensors and authors of that
|
||||||
|
material by anyone who conveys the material (or modified versions of
|
||||||
|
it) with contractual assumptions of liability to the recipient, for
|
||||||
|
any liability that these contractual assumptions directly impose on
|
||||||
|
those licensors and authors.
|
||||||
|
|
||||||
|
All other non-permissive additional terms are considered "further
|
||||||
|
restrictions" within the meaning of section 10. If the Program as you
|
||||||
|
received it, or any part of it, contains a notice stating that it is
|
||||||
|
governed by this License along with a term that is a further
|
||||||
|
restriction, you may remove that term. If a license document contains
|
||||||
|
a further restriction but permits relicensing or conveying under this
|
||||||
|
License, you may add to a covered work material governed by the terms
|
||||||
|
of that license document, provided that the further restriction does
|
||||||
|
not survive such relicensing or conveying.
|
||||||
|
|
||||||
|
If you add terms to a covered work in accord with this section, you
|
||||||
|
must place, in the relevant source files, a statement of the
|
||||||
|
additional terms that apply to those files, or a notice indicating
|
||||||
|
where to find the applicable terms.
|
||||||
|
|
||||||
|
Additional terms, permissive or non-permissive, may be stated in the
|
||||||
|
form of a separately written license, or stated as exceptions;
|
||||||
|
the above requirements apply either way.
|
||||||
|
|
||||||
|
8. Termination.
|
||||||
|
|
||||||
|
You may not propagate or modify a covered work except as expressly
|
||||||
|
provided under this License. Any attempt otherwise to propagate or
|
||||||
|
modify it is void, and will automatically terminate your rights under
|
||||||
|
this License (including any patent licenses granted under the third
|
||||||
|
paragraph of section 11).
|
||||||
|
|
||||||
|
However, if you cease all violation of this License, then your
|
||||||
|
license from a particular copyright holder is reinstated (a)
|
||||||
|
provisionally, unless and until the copyright holder explicitly and
|
||||||
|
finally terminates your license, and (b) permanently, if the copyright
|
||||||
|
holder fails to notify you of the violation by some reasonable means
|
||||||
|
prior to 60 days after the cessation.
|
||||||
|
|
||||||
|
Moreover, your license from a particular copyright holder is
|
||||||
|
reinstated permanently if the copyright holder notifies you of the
|
||||||
|
violation by some reasonable means, this is the first time you have
|
||||||
|
received notice of violation of this License (for any work) from that
|
||||||
|
copyright holder, and you cure the violation prior to 30 days after
|
||||||
|
your receipt of the notice.
|
||||||
|
|
||||||
|
Termination of your rights under this section does not terminate the
|
||||||
|
licenses of parties who have received copies or rights from you under
|
||||||
|
this License. If your rights have been terminated and not permanently
|
||||||
|
reinstated, you do not qualify to receive new licenses for the same
|
||||||
|
material under section 10.
|
||||||
|
|
||||||
|
9. Acceptance Not Required for Having Copies.
|
||||||
|
|
||||||
|
You are not required to accept this License in order to receive or
|
||||||
|
run a copy of the Program. Ancillary propagation of a covered work
|
||||||
|
occurring solely as a consequence of using peer-to-peer transmission
|
||||||
|
to receive a copy likewise does not require acceptance. However,
|
||||||
|
nothing other than this License grants you permission to propagate or
|
||||||
|
modify any covered work. These actions infringe copyright if you do
|
||||||
|
not accept this License. Therefore, by modifying or propagating a
|
||||||
|
covered work, you indicate your acceptance of this License to do so.
|
||||||
|
|
||||||
|
10. Automatic Licensing of Downstream Recipients.
|
||||||
|
|
||||||
|
Each time you convey a covered work, the recipient automatically
|
||||||
|
receives a license from the original licensors, to run, modify and
|
||||||
|
propagate that work, subject to this License. You are not responsible
|
||||||
|
for enforcing compliance by third parties with this License.
|
||||||
|
|
||||||
|
An "entity transaction" is a transaction transferring control of an
|
||||||
|
organization, or substantially all assets of one, or subdividing an
|
||||||
|
organization, or merging organizations. If propagation of a covered
|
||||||
|
work results from an entity transaction, each party to that
|
||||||
|
transaction who receives a copy of the work also receives whatever
|
||||||
|
licenses to the work the party's predecessor in interest had or could
|
||||||
|
give under the previous paragraph, plus a right to possession of the
|
||||||
|
Corresponding Source of the work from the predecessor in interest, if
|
||||||
|
the predecessor has it or can get it with reasonable efforts.
|
||||||
|
|
||||||
|
You may not impose any further restrictions on the exercise of the
|
||||||
|
rights granted or affirmed under this License. For example, you may
|
||||||
|
not impose a license fee, royalty, or other charge for exercise of
|
||||||
|
rights granted under this License, and you may not initiate litigation
|
||||||
|
(including a cross-claim or counterclaim in a lawsuit) alleging that
|
||||||
|
any patent claim is infringed by making, using, selling, offering for
|
||||||
|
sale, or importing the Program or any portion of it.
|
||||||
|
|
||||||
|
11. Patents.
|
||||||
|
|
||||||
|
A "contributor" is a copyright holder who authorizes use under this
|
||||||
|
License of the Program or a work on which the Program is based. The
|
||||||
|
work thus licensed is called the contributor's "contributor version".
|
||||||
|
|
||||||
|
A contributor's "essential patent claims" are all patent claims
|
||||||
|
owned or controlled by the contributor, whether already acquired or
|
||||||
|
hereafter acquired, that would be infringed by some manner, permitted
|
||||||
|
by this License, of making, using, or selling its contributor version,
|
||||||
|
but do not include claims that would be infringed only as a
|
||||||
|
consequence of further modification of the contributor version. For
|
||||||
|
purposes of this definition, "control" includes the right to grant
|
||||||
|
patent sublicenses in a manner consistent with the requirements of
|
||||||
|
this License.
|
||||||
|
|
||||||
|
Each contributor grants you a non-exclusive, worldwide, royalty-free
|
||||||
|
patent license under the contributor's essential patent claims, to
|
||||||
|
make, use, sell, offer to sale, import and otherwise run, modify and
|
||||||
|
propagate the contents of its contributor version.
|
||||||
|
|
||||||
|
In the following three paragraphs, a "patent license" is any express
|
||||||
|
agreement or commitment, however denominated, not to enforce a patent
|
||||||
|
(such as an express permission to practice a patent or covenant not to
|
||||||
|
sue for patent infringement). To "grant" such a patent license to a
|
||||||
|
party means to make such an agreement or commitment not to enforce a
|
||||||
|
patent against the party.
|
||||||
|
|
||||||
|
If you convey a covered work, knowingly relying on a patent license,
|
||||||
|
and the Corresponding Source of the work is not available for anyone
|
||||||
|
to copy, free of charge and under the terms of this License, through a
|
||||||
|
publicly available network server or other readily accessible means,
|
||||||
|
then you must either (1) cause the Corresponding Source to be so
|
||||||
|
available, or (2) arrange to deprive yourself of the benefit of the
|
||||||
|
patent license for this particular work, or (3) arrange, in a manner
|
||||||
|
consistent with the requirements of this License, to extend the patent
|
||||||
|
license to downstream recipients. "Knowingly relying" means you have
|
||||||
|
actual knowledge that, but for the patent license, your conveying the
|
||||||
|
covered work in a country, or your recipient's use of the covered work
|
||||||
|
in a country, would infringe one or more identifiable patents in that
|
||||||
|
country that you have reason to believe are valid.
|
||||||
|
|
||||||
|
If, pursuant to or in connection with a single transaction or
|
||||||
|
arrangement, you convey, or propagate by procuring conveyance of, a
|
||||||
|
covered work, and grant a patent license to some of the parties
|
||||||
|
receiving the covered work authorizing them to use, propagate, modify
|
||||||
|
or convey a specific copy of the covered work, then the patent license
|
||||||
|
you grant is automatically extended to all recipients of the covered
|
||||||
|
work and works based on it.
|
||||||
|
|
||||||
|
A patent license is "discriminatory" if it does not include within
|
||||||
|
the scope of its coverage, prohibits the exercise of, or is
|
||||||
|
conditioned on the non-exercise of one or more of the rights that are
|
||||||
|
specifically granted under this License. You may not convey a covered
|
||||||
|
work if you are a party to an arrangement with a third party that is
|
||||||
|
in the business of distributing software, under which you make payment
|
||||||
|
to the third party based on the extent of your activity of conveying
|
||||||
|
the work, and under which the third party grants, to any of the
|
||||||
|
parties who would receive the covered work from you, a discriminatory
|
||||||
|
patent license (a) in connection with copies of the covered work
|
||||||
|
conveyed by you (or copies made from those copies), or (b) primarily
|
||||||
|
for and in connection with specific products or compilations that
|
||||||
|
contain the covered work, unless you entered into that arrangement,
|
||||||
|
or that patent license was granted, prior to 28 March 2007.
|
||||||
|
|
||||||
|
Nothing in this License shall be construed as excluding or limiting
|
||||||
|
any implied license or other defenses to infringement that may
|
||||||
|
otherwise be available to you under applicable patent law.
|
||||||
|
|
||||||
|
12. No Surrender of Others' Freedom.
|
||||||
|
|
||||||
|
If conditions are imposed on you (whether by court order, agreement or
|
||||||
|
otherwise) that contradict the conditions of this License, they do not
|
||||||
|
excuse you from the conditions of this License. If you cannot convey a
|
||||||
|
covered work so as to satisfy simultaneously your obligations under this
|
||||||
|
License and any other pertinent obligations, then as a consequence you may
|
||||||
|
not convey it at all. For example, if you agree to terms that obligate you
|
||||||
|
to collect a royalty for further conveying from those to whom you convey
|
||||||
|
the Program, the only way you could satisfy both those terms and this
|
||||||
|
License would be to refrain entirely from conveying the Program.
|
||||||
|
|
||||||
|
13. Use with the GNU Affero General Public License.
|
||||||
|
|
||||||
|
Notwithstanding any other provision of this License, you have
|
||||||
|
permission to link or combine any covered work with a work licensed
|
||||||
|
under version 3 of the GNU Affero General Public License into a single
|
||||||
|
combined work, and to convey the resulting work. The terms of this
|
||||||
|
License will continue to apply to the part which is the covered work,
|
||||||
|
but the special requirements of the GNU Affero General Public License,
|
||||||
|
section 13, concerning interaction through a network will apply to the
|
||||||
|
combination as such.
|
||||||
|
|
||||||
|
14. Revised Versions of this License.
|
||||||
|
|
||||||
|
The Free Software Foundation may publish revised and/or new versions of
|
||||||
|
the GNU General Public License from time to time. Such new versions will
|
||||||
|
be similar in spirit to the present version, but may differ in detail to
|
||||||
|
address new problems or concerns.
|
||||||
|
|
||||||
|
Each version is given a distinguishing version number. If the
|
||||||
|
Program specifies that a certain numbered version of the GNU General
|
||||||
|
Public License "or any later version" applies to it, you have the
|
||||||
|
option of following the terms and conditions either of that numbered
|
||||||
|
version or of any later version published by the Free Software
|
||||||
|
Foundation. If the Program does not specify a version number of the
|
||||||
|
GNU General Public License, you may choose any version ever published
|
||||||
|
by the Free Software Foundation.
|
||||||
|
|
||||||
|
If the Program specifies that a proxy can decide which future
|
||||||
|
versions of the GNU General Public License can be used, that proxy's
|
||||||
|
public statement of acceptance of a version permanently authorizes you
|
||||||
|
to choose that version for the Program.
|
||||||
|
|
||||||
|
Later license versions may give you additional or different
|
||||||
|
permissions. However, no additional obligations are imposed on any
|
||||||
|
author or copyright holder as a result of your choosing to follow a
|
||||||
|
later version.
|
||||||
|
|
||||||
|
15. Disclaimer of Warranty.
|
||||||
|
|
||||||
|
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
|
||||||
|
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
|
||||||
|
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
|
||||||
|
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
|
||||||
|
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
|
||||||
|
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
|
||||||
|
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
|
||||||
|
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
|
||||||
|
|
||||||
|
16. Limitation of Liability.
|
||||||
|
|
||||||
|
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
|
||||||
|
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
|
||||||
|
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
|
||||||
|
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
|
||||||
|
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
|
||||||
|
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
|
||||||
|
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
|
||||||
|
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
|
||||||
|
SUCH DAMAGES.
|
||||||
|
|
||||||
|
17. Interpretation of Sections 15 and 16.
|
||||||
|
|
||||||
|
If the disclaimer of warranty and limitation of liability provided
|
||||||
|
above cannot be given local legal effect according to their terms,
|
||||||
|
reviewing courts shall apply local law that most closely approximates
|
||||||
|
an absolute waiver of all civil liability in connection with the
|
||||||
|
Program, unless a warranty or assumption of liability accompanies a
|
||||||
|
copy of the Program in return for a fee.
|
||||||
|
|
||||||
|
END OF TERMS AND CONDITIONS
|
||||||
|
|
||||||
|
How to Apply These Terms to Your New Programs
|
||||||
|
|
||||||
|
If you develop a new program, and you want it to be of the greatest
|
||||||
|
possible use to the public, the best way to achieve this is to make it
|
||||||
|
free software which everyone can redistribute and change under these terms.
|
||||||
|
|
||||||
|
To do so, attach the following notices to the program. It is safest
|
||||||
|
to attach them to the start of each source file to most effectively
|
||||||
|
state the exclusion of warranty; and each file should have at least
|
||||||
|
the "copyright" line and a pointer to where the full notice is found.
|
||||||
|
|
||||||
|
<one line to give the program's name and a brief idea of what it does.>
|
||||||
|
Copyright (C) <year> <name of author>
|
||||||
|
|
||||||
|
This program is free software: you can redistribute it and/or modify
|
||||||
|
it under the terms of the GNU General Public License as published by
|
||||||
|
the Free Software Foundation, either version 3 of the License, or
|
||||||
|
(at your option) any later version.
|
||||||
|
|
||||||
|
This program is distributed in the hope that it will be useful,
|
||||||
|
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||||
|
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||||
|
GNU General Public License for more details.
|
||||||
|
|
||||||
|
You should have received a copy of the GNU General Public License
|
||||||
|
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||||
|
|
||||||
|
Also add information on how to contact you by electronic and paper mail.
|
||||||
|
|
||||||
|
If the program does terminal interaction, make it output a short
|
||||||
|
notice like this when it starts in an interactive mode:
|
||||||
|
|
||||||
|
<program> Copyright (C) <year> <name of author>
|
||||||
|
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
|
||||||
|
This is free software, and you are welcome to redistribute it
|
||||||
|
under certain conditions; type `show c' for details.
|
||||||
|
|
||||||
|
The hypothetical commands `show w' and `show c' should show the appropriate
|
||||||
|
parts of the General Public License. Of course, your program's commands
|
||||||
|
might be different; for a GUI interface, you would use an "about box".
|
||||||
|
|
||||||
|
You should also get your employer (if you work as a programmer) or school,
|
||||||
|
if any, to sign a "copyright disclaimer" for the program, if necessary.
|
||||||
|
For more information on this, and how to apply and follow the GNU GPL, see
|
||||||
|
<https://www.gnu.org/licenses/>.
|
||||||
|
|
||||||
|
The GNU General Public License does not permit incorporating your program
|
||||||
|
into proprietary programs. If your program is a subroutine library, you
|
||||||
|
may consider it more useful to permit linking proprietary applications with
|
||||||
|
the library. If this is what you want to do, use the GNU Lesser General
|
||||||
|
Public License instead of this License. But first, please read
|
||||||
|
<https://www.gnu.org/licenses/why-not-lgpl.html>.
|
||||||
|
|||||||
@@ -0,0 +1,201 @@
|
|||||||
|
Apache License
|
||||||
|
Version 2.0, January 2004
|
||||||
|
http://www.apache.org/licenses/
|
||||||
|
|
||||||
|
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
||||||
|
|
||||||
|
1. Definitions.
|
||||||
|
|
||||||
|
"License" shall mean the terms and conditions for use, reproduction,
|
||||||
|
and distribution as defined by Sections 1 through 9 of this document.
|
||||||
|
|
||||||
|
"Licensor" shall mean the copyright owner or entity authorized by
|
||||||
|
the copyright owner that is granting the License.
|
||||||
|
|
||||||
|
"Legal Entity" shall mean the union of the acting entity and all
|
||||||
|
other entities that control, are controlled by, or are under common
|
||||||
|
control with that entity. For the purposes of this definition,
|
||||||
|
"control" means (i) the power, direct or indirect, to cause the
|
||||||
|
direction or management of such entity, whether by contract or
|
||||||
|
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
||||||
|
outstanding shares, or (iii) beneficial ownership of such entity.
|
||||||
|
|
||||||
|
"You" (or "Your") shall mean an individual or Legal Entity
|
||||||
|
exercising permissions granted by this License.
|
||||||
|
|
||||||
|
"Source" form shall mean the preferred form for making modifications,
|
||||||
|
including but not limited to software source code, documentation
|
||||||
|
source, and configuration files.
|
||||||
|
|
||||||
|
"Object" form shall mean any form resulting from mechanical
|
||||||
|
transformation or translation of a Source form, including but
|
||||||
|
not limited to compiled object code, generated documentation,
|
||||||
|
and conversions to other media types.
|
||||||
|
|
||||||
|
"Work" shall mean the work of authorship, whether in Source or
|
||||||
|
Object form, made available under the License, as indicated by a
|
||||||
|
copyright notice that is included in or attached to the work
|
||||||
|
(an example is provided in the Appendix below).
|
||||||
|
|
||||||
|
"Derivative Works" shall mean any work, whether in Source or Object
|
||||||
|
form, that is based on (or derived from) the Work and for which the
|
||||||
|
editorial revisions, annotations, elaborations, or other modifications
|
||||||
|
represent, as a whole, an original work of authorship. For the purposes
|
||||||
|
of this License, Derivative Works shall not include works that remain
|
||||||
|
separable from, or merely link (or bind by name) to the interfaces of,
|
||||||
|
the Work and Derivative Works thereof.
|
||||||
|
|
||||||
|
"Contribution" shall mean any work of authorship, including
|
||||||
|
the original version of the Work and any modifications or additions
|
||||||
|
to that Work or Derivative Works thereof, that is intentionally
|
||||||
|
submitted to Licensor for inclusion in the Work by the copyright owner
|
||||||
|
or by an individual or Legal Entity authorized to submit on behalf of
|
||||||
|
the copyright owner. For the purposes of this definition, "submitted"
|
||||||
|
means any form of electronic, verbal, or written communication sent
|
||||||
|
to the Licensor or its representatives, including but not limited to
|
||||||
|
communication on electronic mailing lists, source code control systems,
|
||||||
|
and issue tracking systems that are managed by, or on behalf of, the
|
||||||
|
Licensor for the purpose of discussing and improving the Work, but
|
||||||
|
excluding communication that is conspicuously marked or otherwise
|
||||||
|
designated in writing by the copyright owner as "Not a Contribution."
|
||||||
|
|
||||||
|
"Contributor" shall mean Licensor and any individual or Legal Entity
|
||||||
|
on behalf of whom a Contribution has been received by Licensor and
|
||||||
|
subsequently incorporated within the Work.
|
||||||
|
|
||||||
|
2. Grant of Copyright License. Subject to the terms and conditions of
|
||||||
|
this License, each Contributor hereby grants to You a perpetual,
|
||||||
|
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||||
|
copyright license to reproduce, prepare Derivative Works of,
|
||||||
|
publicly display, publicly perform, sublicense, and distribute the
|
||||||
|
Work and such Derivative Works in Source or Object form.
|
||||||
|
|
||||||
|
3. Grant of Patent License. Subject to the terms and conditions of
|
||||||
|
this License, each Contributor hereby grants to You a perpetual,
|
||||||
|
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||||
|
(except as stated in this section) patent license to make, have made,
|
||||||
|
use, offer to sell, sell, import, and otherwise transfer the Work,
|
||||||
|
where such license applies only to those patent claims licensable
|
||||||
|
by such Contributor that are necessarily infringed by their
|
||||||
|
Contribution(s) alone or by combination of their Contribution(s)
|
||||||
|
with the Work to which such Contribution(s) was submitted. If You
|
||||||
|
institute patent litigation against any entity (including a
|
||||||
|
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
||||||
|
or a Contribution incorporated within the Work constitutes direct
|
||||||
|
or contributory patent infringement, then any patent licenses
|
||||||
|
granted to You under this License for that Work shall terminate
|
||||||
|
as of the date such litigation is filed.
|
||||||
|
|
||||||
|
4. Redistribution. You may reproduce and distribute copies of the
|
||||||
|
Work or Derivative Works thereof in any medium, with or without
|
||||||
|
modifications, and in Source or Object form, provided that You
|
||||||
|
meet the following conditions:
|
||||||
|
|
||||||
|
(a) You must give any other recipients of the Work or
|
||||||
|
Derivative Works a copy of this License; and
|
||||||
|
|
||||||
|
(b) You must cause any modified files to carry prominent notices
|
||||||
|
stating that You changed the files; and
|
||||||
|
|
||||||
|
(c) You must retain, in the Source form of any Derivative Works
|
||||||
|
that You distribute, all copyright, patent, trademark, and
|
||||||
|
attribution notices from the Source form of the Work,
|
||||||
|
excluding those notices that do not pertain to any part of
|
||||||
|
the Derivative Works; and
|
||||||
|
|
||||||
|
(d) If the Work includes a "NOTICE" text file as part of its
|
||||||
|
distribution, then any Derivative Works that You distribute must
|
||||||
|
include a readable copy of the attribution notices contained
|
||||||
|
within such NOTICE file, excluding those notices that do not
|
||||||
|
pertain to any part of the Derivative Works, in at least one
|
||||||
|
of the following places: within a NOTICE text file distributed
|
||||||
|
as part of the Derivative Works; within the Source form or
|
||||||
|
documentation, if provided along with the Derivative Works; or,
|
||||||
|
within a display generated by the Derivative Works, if and
|
||||||
|
wherever such third-party notices normally appear. The contents
|
||||||
|
of the NOTICE file are for informational purposes only and
|
||||||
|
do not modify the License. You may add Your own attribution
|
||||||
|
notices within Derivative Works that You distribute, alongside
|
||||||
|
or as an addendum to the NOTICE text from the Work, provided
|
||||||
|
that such additional attribution notices cannot be construed
|
||||||
|
as modifying the License.
|
||||||
|
|
||||||
|
You may add Your own copyright statement to Your modifications and
|
||||||
|
may provide additional or different license terms and conditions
|
||||||
|
for use, reproduction, or distribution of Your modifications, or
|
||||||
|
for any such Derivative Works as a whole, provided Your use,
|
||||||
|
reproduction, and distribution of the Work otherwise complies with
|
||||||
|
the conditions stated in this License.
|
||||||
|
|
||||||
|
5. Submission of Contributions. Unless You explicitly state otherwise,
|
||||||
|
any Contribution intentionally submitted for inclusion in the Work
|
||||||
|
by You to the Licensor shall be under the terms and conditions of
|
||||||
|
this License, without any additional terms or conditions.
|
||||||
|
Notwithstanding the above, nothing herein shall supersede or modify
|
||||||
|
the terms of any separate license agreement you may have executed
|
||||||
|
with Licensor regarding such Contributions.
|
||||||
|
|
||||||
|
6. Trademarks. This License does not grant permission to use the trade
|
||||||
|
names, trademarks, service marks, or product names of the Licensor,
|
||||||
|
except as required for reasonable and customary use in describing the
|
||||||
|
origin of the Work and reproducing the content of the NOTICE file.
|
||||||
|
|
||||||
|
7. Disclaimer of Warranty. Unless required by applicable law or
|
||||||
|
agreed to in writing, Licensor provides the Work (and each
|
||||||
|
Contributor provides its Contributions) on an "AS IS" BASIS,
|
||||||
|
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
||||||
|
implied, including, without limitation, any warranties or conditions
|
||||||
|
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
||||||
|
PARTICULAR PURPOSE. You are solely responsible for determining the
|
||||||
|
appropriateness of using or redistributing the Work and assume any
|
||||||
|
risks associated with Your exercise of permissions under this License.
|
||||||
|
|
||||||
|
8. Limitation of Liability. In no event and under no legal theory,
|
||||||
|
whether in tort (including negligence), contract, or otherwise,
|
||||||
|
unless required by applicable law (such as deliberate and grossly
|
||||||
|
negligent acts) or agreed to in writing, shall any Contributor be
|
||||||
|
liable to You for damages, including any direct, indirect, special,
|
||||||
|
incidental, or consequential damages of any character arising as a
|
||||||
|
result of this License or out of the use or inability to use the
|
||||||
|
Work (including but not limited to damages for loss of goodwill,
|
||||||
|
work stoppage, computer failure or malfunction, or any and all
|
||||||
|
other commercial damages or losses), even if such Contributor
|
||||||
|
has been advised of the possibility of such damages.
|
||||||
|
|
||||||
|
9. Accepting Warranty or Additional Liability. While redistributing
|
||||||
|
the Work or Derivative Works thereof, You may choose to offer,
|
||||||
|
and charge a fee for, acceptance of support, warranty, indemnity,
|
||||||
|
or other liability obligations and/or rights consistent with this
|
||||||
|
License. However, in accepting such obligations, You may act only
|
||||||
|
on Your own behalf and on Your sole responsibility, not on behalf
|
||||||
|
of any other Contributor, and only if You agree to indemnify,
|
||||||
|
defend, and hold each Contributor harmless for any liability
|
||||||
|
incurred by, or claims asserted against, such Contributor by reason
|
||||||
|
of your accepting any such warranty or additional liability.
|
||||||
|
|
||||||
|
END OF TERMS AND CONDITIONS
|
||||||
|
|
||||||
|
APPENDIX: How to apply the Apache License to your work.
|
||||||
|
|
||||||
|
To apply the Apache License to your work, attach the following
|
||||||
|
boilerplate notice, with the fields enclosed by brackets "[]"
|
||||||
|
replaced with your own identifying information. (Don't include
|
||||||
|
the brackets!) The text should be enclosed in the appropriate
|
||||||
|
comment syntax for the file format. We also recommend that a
|
||||||
|
file or class name and description of purpose be included on the
|
||||||
|
same "printed page" as the copyright notice for easier
|
||||||
|
identification within third-party archives.
|
||||||
|
|
||||||
|
Copyright [yyyy] [name of copyright owner]
|
||||||
|
|
||||||
|
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.
|
||||||
@@ -0,0 +1,19 @@
|
|||||||
|
FLVX
|
||||||
|
Copyright 2026 Sagit-chu
|
||||||
|
|
||||||
|
This product includes software developed at
|
||||||
|
flux-panel (https://github.com/bqlpfy/flux-panel)
|
||||||
|
Copyright 2024-2026 bqlpfy
|
||||||
|
|
||||||
|
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
|
||||||
|
|
||||||
|
-------------------------------------------------------------------------
|
||||||
|
This project is a derivative work based on flux-panel.
|
||||||
|
Modifications and new components (backend, agents, frontend updates)
|
||||||
|
are licensed under the GNU General Public License v3.0 (GPLv3).
|
||||||
|
See the LICENSE file for the full GPLv3 text.
|
||||||
|
-------------------------------------------------------------------------
|
||||||
@@ -1,6 +1,35 @@
|
|||||||
# flux-panel转发面板 哆啦A梦转发面板
|
# FLVX
|
||||||
|
|
||||||
|
> **联系我们**: [Telegram群组](https://t.me/flvxpanel)
|
||||||
|
|
||||||
|
## Original Project
|
||||||
|
- **Name**: flux-panel
|
||||||
|
- **Source**: https://github.com/bqlpfy/flux-panel
|
||||||
|
- **License**: Apache License 2.0
|
||||||
|
|
||||||
|
## Modifications
|
||||||
|
The following major changes and additions have been made in this fork (FLVX):
|
||||||
|
|
||||||
|
### 1. Backend Architecture (Replaced)
|
||||||
|
- **Removed**: The original `springboot-backend/` (Java/Spring Boot) has been entirely removed.
|
||||||
|
- **Added**: A new `go-backend/` (Go/SQLite) implementation replaces the original backend.
|
||||||
|
|
||||||
|
### 2. Forwarding Agent (Modified)
|
||||||
|
- **Modified**: `go-gost/` - Modified forwarding agent wrapper.
|
||||||
|
- **Modified**: `go-gost/x/` - Modified local fork of the `gost` extensions library.
|
||||||
|
|
||||||
|
### 3. Frontend (Modified)
|
||||||
|
- **Modified**: `vite-frontend/` - Significant updates to the React/Vite dashboard to compatible with the new Go backend, including UI/UX improvements (HeroUI + Tailwind).
|
||||||
|
|
||||||
|
### 4. Mobile Applications (Removed)
|
||||||
|
- **Removed**: `android-app/` - Source code for the Android client.
|
||||||
|
- **Removed**: `ios-app/` - Source code for the iOS client.
|
||||||
|
|
||||||
|
### 5. Infrastructure & Scripts
|
||||||
|
- **Modified**: `docker-compose-v4.yml`, `docker-compose-v6.yml` (Updated for Go backend).
|
||||||
|
- **Modified**: `install.sh`, `panel_install.sh` (Updated installation logic).
|
||||||
|
- **Added**: `AGENTS.md` (Project documentation).
|
||||||
|
|
||||||
本项目基于 [go-gost/gost](https://github.com/go-gost/gost) 和 [go-gost/x](https://github.com/go-gost/x) 两个开源库,实现了转发面板。
|
|
||||||
---
|
---
|
||||||
## 特性
|
## 特性
|
||||||
|
|
||||||
@@ -15,7 +44,7 @@
|
|||||||
## 部署流程
|
## 部署流程
|
||||||
---
|
---
|
||||||
### Docker Compose部署
|
### Docker Compose部署
|
||||||
#### 快速部署
|
#### 快速部署(安装最新版)
|
||||||
面板端:
|
面板端:
|
||||||
```bash
|
```bash
|
||||||
curl -L https://raw.githubusercontent.com/Sagit-chu/flux-panel/main/panel_install.sh -o panel_install.sh && chmod +x panel_install.sh && ./panel_install.sh
|
curl -L https://raw.githubusercontent.com/Sagit-chu/flux-panel/main/panel_install.sh -o panel_install.sh && chmod +x panel_install.sh && ./panel_install.sh
|
||||||
@@ -25,6 +54,18 @@ curl -L https://raw.githubusercontent.com/Sagit-chu/flux-panel/main/panel_instal
|
|||||||
curl -L https://raw.githubusercontent.com/Sagit-chu/flux-panel/main/install.sh -o install.sh && chmod +x install.sh && ./install.sh
|
curl -L https://raw.githubusercontent.com/Sagit-chu/flux-panel/main/install.sh -o install.sh && chmod +x install.sh && ./install.sh
|
||||||
```
|
```
|
||||||
|
|
||||||
|
#### 安装特定版本
|
||||||
|
从 [Releases](https://github.com/Sagit-chu/flux-panel/releases) 页面复制对应版本的安装命令,脚本会自动安装该版本而非最新版。
|
||||||
|
|
||||||
|
面板端(以 2.1.0 为例):
|
||||||
|
```bash
|
||||||
|
curl -L https://github.com/Sagit-chu/flux-panel/releases/download/2.1.0/panel_install.sh -o panel_install.sh && chmod +x panel_install.sh && ./panel_install.sh
|
||||||
|
```
|
||||||
|
节点端(以 2.1.0 为例):
|
||||||
|
```bash
|
||||||
|
curl -L https://github.com/Sagit-chu/flux-panel/releases/download/2.1.0/install.sh -o install.sh && chmod +x install.sh && ./install.sh
|
||||||
|
```
|
||||||
|
|
||||||
#### 默认管理员账号
|
#### 默认管理员账号
|
||||||
|
|
||||||
- **账号**: admin_user
|
- **账号**: admin_user
|
||||||
|
|||||||
@@ -1,15 +0,0 @@
|
|||||||
*.iml
|
|
||||||
.gradle
|
|
||||||
/local.properties
|
|
||||||
/.idea/caches
|
|
||||||
/.idea/libraries
|
|
||||||
/.idea/modules.xml
|
|
||||||
/.idea/workspace.xml
|
|
||||||
/.idea/navEditor.xml
|
|
||||||
/.idea/assetWizardSettings.xml
|
|
||||||
.DS_Store
|
|
||||||
/build
|
|
||||||
/captures
|
|
||||||
.externalNativeBuild
|
|
||||||
.cxx
|
|
||||||
local.properties
|
|
||||||
@@ -1 +0,0 @@
|
|||||||
/build
|
|
||||||
@@ -1,45 +0,0 @@
|
|||||||
plugins {
|
|
||||||
id 'com.android.application'
|
|
||||||
id 'org.jetbrains.kotlin.android'
|
|
||||||
}
|
|
||||||
|
|
||||||
android {
|
|
||||||
namespace 'com.flux'
|
|
||||||
compileSdk 34
|
|
||||||
|
|
||||||
defaultConfig {
|
|
||||||
applicationId "com.flux"
|
|
||||||
minSdk 24
|
|
||||||
targetSdk 34
|
|
||||||
versionCode 1
|
|
||||||
versionName "1.0.1"
|
|
||||||
|
|
||||||
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
|
|
||||||
}
|
|
||||||
|
|
||||||
buildTypes {
|
|
||||||
release {
|
|
||||||
minifyEnabled false
|
|
||||||
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
|
|
||||||
}
|
|
||||||
}
|
|
||||||
compileOptions {
|
|
||||||
sourceCompatibility JavaVersion.VERSION_1_8
|
|
||||||
targetCompatibility JavaVersion.VERSION_1_8
|
|
||||||
}
|
|
||||||
kotlinOptions {
|
|
||||||
jvmTarget = '1.8'
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
dependencies {
|
|
||||||
|
|
||||||
implementation 'androidx.core:core-ktx:1.9.0'
|
|
||||||
implementation 'androidx.appcompat:appcompat:1.7.1'
|
|
||||||
implementation 'com.google.android.material:material:1.12.0'
|
|
||||||
implementation 'androidx.constraintlayout:constraintlayout:2.2.1'
|
|
||||||
implementation 'androidx.webkit:webkit:1.8.0'
|
|
||||||
testImplementation 'junit:junit:4.13.2'
|
|
||||||
androidTestImplementation 'androidx.test.ext:junit:1.3.0'
|
|
||||||
androidTestImplementation 'androidx.test.espresso:espresso-core:3.7.0'
|
|
||||||
}
|
|
||||||
@@ -1,21 +0,0 @@
|
|||||||
# Add project specific ProGuard rules here.
|
|
||||||
# You can control the set of applied configuration files using the
|
|
||||||
# proguardFiles setting in build.gradle.
|
|
||||||
#
|
|
||||||
# For more details, see
|
|
||||||
# http://developer.android.com/guide/developing/tools/proguard.html
|
|
||||||
|
|
||||||
# If your project uses WebView with JS, uncomment the following
|
|
||||||
# and specify the fully qualified class name to the JavaScript interface
|
|
||||||
# class:
|
|
||||||
#-keepclassmembers class fqcn.of.javascript.interface.for.webview {
|
|
||||||
# public *;
|
|
||||||
#}
|
|
||||||
|
|
||||||
# Uncomment this to preserve the line number information for
|
|
||||||
# debugging stack traces.
|
|
||||||
#-keepattributes SourceFile,LineNumberTable
|
|
||||||
|
|
||||||
# If you keep the line number information, uncomment this to
|
|
||||||
# hide the original source file name.
|
|
||||||
#-renamesourcefileattribute SourceFile
|
|
||||||
@@ -1,20 +0,0 @@
|
|||||||
{
|
|
||||||
"version": 3,
|
|
||||||
"artifactType": {
|
|
||||||
"type": "APK",
|
|
||||||
"kind": "Directory"
|
|
||||||
},
|
|
||||||
"applicationId": "com.flux",
|
|
||||||
"variantName": "release",
|
|
||||||
"elements": [
|
|
||||||
{
|
|
||||||
"type": "SINGLE",
|
|
||||||
"filters": [],
|
|
||||||
"attributes": [],
|
|
||||||
"versionCode": 1,
|
|
||||||
"versionName": "1.0.1",
|
|
||||||
"outputFile": "app-release.apk"
|
|
||||||
}
|
|
||||||
],
|
|
||||||
"elementType": "File"
|
|
||||||
}
|
|
||||||
@@ -1,24 +0,0 @@
|
|||||||
package com.flux
|
|
||||||
|
|
||||||
import androidx.test.platform.app.InstrumentationRegistry
|
|
||||||
import androidx.test.ext.junit.runners.AndroidJUnit4
|
|
||||||
|
|
||||||
import org.junit.Test
|
|
||||||
import org.junit.runner.RunWith
|
|
||||||
|
|
||||||
import org.junit.Assert.*
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Instrumented test, which will execute on an Android device.
|
|
||||||
*
|
|
||||||
* See [testing documentation](http://d.android.com/tools/testing).
|
|
||||||
*/
|
|
||||||
@RunWith(AndroidJUnit4::class)
|
|
||||||
class ExampleInstrumentedTest {
|
|
||||||
@Test
|
|
||||||
fun useAppContext() {
|
|
||||||
// Context of the app under test.
|
|
||||||
val appContext = InstrumentationRegistry.getInstrumentation().targetContext
|
|
||||||
assertEquals("com.flux", appContext.packageName)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,32 +0,0 @@
|
|||||||
<?xml version="1.0" encoding="utf-8"?>
|
|
||||||
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
|
|
||||||
xmlns:tools="http://schemas.android.com/tools"
|
|
||||||
package="com.flux" >
|
|
||||||
|
|
||||||
<uses-permission android:name="android.permission.INTERNET" />
|
|
||||||
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
|
|
||||||
|
|
||||||
<application
|
|
||||||
android:allowBackup="true"
|
|
||||||
android:dataExtractionRules="@xml/data_extraction_rules"
|
|
||||||
android:fullBackupContent="@xml/backup_rules"
|
|
||||||
android:icon="@mipmap/ic_launcher"
|
|
||||||
android:label="@string/app_name"
|
|
||||||
android:roundIcon="@mipmap/ic_launcher_round"
|
|
||||||
android:supportsRtl="true"
|
|
||||||
android:theme="@style/Theme.Flux"
|
|
||||||
android:usesCleartextTraffic="true"
|
|
||||||
tools:targetApi="31" >
|
|
||||||
<activity
|
|
||||||
android:name="com.flux.MainActivity"
|
|
||||||
android:exported="true"
|
|
||||||
android:configChanges="uiMode|orientation|screenSize" >
|
|
||||||
<intent-filter>
|
|
||||||
<action android:name="android.intent.action.MAIN" />
|
|
||||||
|
|
||||||
<category android:name="android.intent.category.LAUNCHER" />
|
|
||||||
</intent-filter>
|
|
||||||
</activity>
|
|
||||||
</application>
|
|
||||||
|
|
||||||
</manifest>
|
|
||||||
|
Before Width: | Height: | Size: 406 KiB |
@@ -1,214 +0,0 @@
|
|||||||
package com.flux
|
|
||||||
|
|
||||||
import androidx.core.content.edit
|
|
||||||
import android.graphics.Color
|
|
||||||
import android.os.Build
|
|
||||||
import android.os.Bundle
|
|
||||||
import android.view.View
|
|
||||||
import android.view.WindowInsetsController
|
|
||||||
import androidx.appcompat.app.AppCompatActivity
|
|
||||||
import android.webkit.*
|
|
||||||
import android.content.res.Configuration
|
|
||||||
import org.json.JSONArray
|
|
||||||
import org.json.JSONObject
|
|
||||||
|
|
||||||
|
|
||||||
class MainActivity : AppCompatActivity() {
|
|
||||||
|
|
||||||
private lateinit var webView: WebView
|
|
||||||
|
|
||||||
override fun onCreate(savedInstanceState: Bundle?) {
|
|
||||||
super.onCreate(savedInstanceState)
|
|
||||||
setContentView(R.layout.activity_main)
|
|
||||||
|
|
||||||
webView = findViewById(R.id.webView)
|
|
||||||
WebView.setWebContentsDebuggingEnabled(true)
|
|
||||||
setupWebView()
|
|
||||||
loadUrl()
|
|
||||||
|
|
||||||
setupSystemBars()
|
|
||||||
setupRootBackground()
|
|
||||||
}
|
|
||||||
|
|
||||||
private fun setupWebView() {
|
|
||||||
val settings = webView.settings
|
|
||||||
settings.javaScriptEnabled = true
|
|
||||||
settings.domStorageEnabled = true
|
|
||||||
settings.databaseEnabled = true
|
|
||||||
settings.loadWithOverviewMode = true
|
|
||||||
settings.useWideViewPort = true
|
|
||||||
settings.setSupportZoom(true)
|
|
||||||
settings.builtInZoomControls = true
|
|
||||||
settings.displayZoomControls = false
|
|
||||||
|
|
||||||
// 隐藏滚动条但不影响滚动
|
|
||||||
webView.isVerticalScrollBarEnabled = false
|
|
||||||
webView.isHorizontalScrollBarEnabled = false
|
|
||||||
webView.scrollBarStyle = View.SCROLLBARS_INSIDE_OVERLAY
|
|
||||||
webView.overScrollMode = View.OVER_SCROLL_NEVER
|
|
||||||
|
|
||||||
|
|
||||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
|
|
||||||
settings.mixedContentMode = WebSettings.MIXED_CONTENT_ALWAYS_ALLOW
|
|
||||||
}
|
|
||||||
|
|
||||||
val isDarkTheme = resources.configuration.uiMode and
|
|
||||||
Configuration.UI_MODE_NIGHT_MASK ==
|
|
||||||
Configuration.UI_MODE_NIGHT_YES
|
|
||||||
|
|
||||||
webView.setBackgroundColor(if (isDarkTheme) Color.BLACK else Color.WHITE)
|
|
||||||
|
|
||||||
|
|
||||||
// 添加JavaScript接口
|
|
||||||
webView.addJavascriptInterface(object {
|
|
||||||
|
|
||||||
@android.webkit.JavascriptInterface
|
|
||||||
fun getPanelAddresses(callback: String) {
|
|
||||||
val sharedPrefs = getSharedPreferences("panel_config", MODE_PRIVATE)
|
|
||||||
val addresses = sharedPrefs.getString("panel_addresses", "[]")
|
|
||||||
webView.post {
|
|
||||||
webView.evaluateJavascript("window.$callback($addresses);", null)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
@android.webkit.JavascriptInterface
|
|
||||||
fun savePanelAddress(name: String, address: String) {
|
|
||||||
val json = JSONObject()
|
|
||||||
json.put("name", name)
|
|
||||||
json.put("address", address)
|
|
||||||
json.put("inx", false)
|
|
||||||
val sharedPrefs = getSharedPreferences("panel_config", MODE_PRIVATE)
|
|
||||||
val addresses = sharedPrefs.getString("panel_addresses", "[]")
|
|
||||||
val jsonArray = JSONArray(addresses)
|
|
||||||
jsonArray.put(json)
|
|
||||||
sharedPrefs.edit {
|
|
||||||
putString("panel_addresses", jsonArray.toString())
|
|
||||||
}
|
|
||||||
webView.post {
|
|
||||||
webView.evaluateJavascript("window.setPanelAddresses(${jsonArray.toString()});", null)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
@android.webkit.JavascriptInterface
|
|
||||||
fun setCurrentPanelAddress(name: String) {
|
|
||||||
|
|
||||||
val sharedPrefs = getSharedPreferences("panel_config", MODE_PRIVATE)
|
|
||||||
val addresses = sharedPrefs.getString("panel_addresses", "[]")
|
|
||||||
val jsonArray = JSONArray(addresses)
|
|
||||||
for (i in 0 until jsonArray.length()) {
|
|
||||||
val obj = jsonArray.getJSONObject(i)
|
|
||||||
if (name == obj.getString("name")) {
|
|
||||||
obj.put("inx", true)
|
|
||||||
}else{
|
|
||||||
obj.put("inx", false)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
sharedPrefs.edit {
|
|
||||||
putString("panel_addresses", jsonArray.toString())
|
|
||||||
}
|
|
||||||
webView.post {
|
|
||||||
webView.evaluateJavascript("window.setPanelAddresses(${jsonArray.toString()});", null)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
@android.webkit.JavascriptInterface
|
|
||||||
fun deletePanelAddress(name: String) {
|
|
||||||
val jsonArray = JSONArray()
|
|
||||||
val sharedPrefs = getSharedPreferences("panel_config", MODE_PRIVATE)
|
|
||||||
val addresses = sharedPrefs.getString("panel_addresses", "[]")
|
|
||||||
val jsonArraya = JSONArray(addresses)
|
|
||||||
for (i in 0 until jsonArraya.length()) {
|
|
||||||
val obj = jsonArraya.getJSONObject(i)
|
|
||||||
if (name != obj.getString("name")) {
|
|
||||||
jsonArray.put(obj)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
sharedPrefs.edit {
|
|
||||||
putString("panel_addresses", jsonArray.toString())
|
|
||||||
}
|
|
||||||
webView.post {
|
|
||||||
webView.evaluateJavascript("window.setPanelAddresses(${jsonArray.toString()});", null)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}, "JsInterface")
|
|
||||||
|
|
||||||
}
|
|
||||||
|
|
||||||
private fun loadUrl() {
|
|
||||||
//webView.loadUrl("http://192.168.100.9:3000")
|
|
||||||
webView.loadUrl("file:///android_asset/index.html")
|
|
||||||
}
|
|
||||||
|
|
||||||
private fun setupSystemBars() {
|
|
||||||
val isDarkTheme = resources.configuration.uiMode and
|
|
||||||
Configuration.UI_MODE_NIGHT_MASK ==
|
|
||||||
Configuration.UI_MODE_NIGHT_YES
|
|
||||||
|
|
||||||
if (isDarkTheme) {
|
|
||||||
window.statusBarColor = Color.BLACK
|
|
||||||
window.navigationBarColor = Color.BLACK
|
|
||||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
|
|
||||||
window.insetsController?.setSystemBarsAppearance(
|
|
||||||
0,
|
|
||||||
WindowInsetsController.APPEARANCE_LIGHT_STATUS_BARS or
|
|
||||||
WindowInsetsController.APPEARANCE_LIGHT_NAVIGATION_BARS
|
|
||||||
)
|
|
||||||
} else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
|
|
||||||
@Suppress("DEPRECATION")
|
|
||||||
window.decorView.systemUiVisibility =
|
|
||||||
window.decorView.systemUiVisibility and View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR.inv()
|
|
||||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
|
|
||||||
@Suppress("DEPRECATION")
|
|
||||||
window.decorView.systemUiVisibility =
|
|
||||||
window.decorView.systemUiVisibility and View.SYSTEM_UI_FLAG_LIGHT_NAVIGATION_BAR.inv()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
window.statusBarColor = Color.WHITE
|
|
||||||
window.navigationBarColor = Color.WHITE
|
|
||||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
|
|
||||||
window.insetsController?.setSystemBarsAppearance(
|
|
||||||
WindowInsetsController.APPEARANCE_LIGHT_STATUS_BARS or
|
|
||||||
WindowInsetsController.APPEARANCE_LIGHT_NAVIGATION_BARS,
|
|
||||||
WindowInsetsController.APPEARANCE_LIGHT_STATUS_BARS or
|
|
||||||
WindowInsetsController.APPEARANCE_LIGHT_NAVIGATION_BARS
|
|
||||||
)
|
|
||||||
} else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
|
|
||||||
@Suppress("DEPRECATION")
|
|
||||||
window.decorView.systemUiVisibility =
|
|
||||||
window.decorView.systemUiVisibility or View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR
|
|
||||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
|
|
||||||
@Suppress("DEPRECATION")
|
|
||||||
window.decorView.systemUiVisibility =
|
|
||||||
window.decorView.systemUiVisibility or View.SYSTEM_UI_FLAG_LIGHT_NAVIGATION_BAR
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
override fun onBackPressed() {
|
|
||||||
if (webView.canGoBack()) webView.goBack() else super.onBackPressed()
|
|
||||||
}
|
|
||||||
|
|
||||||
override fun onConfigurationChanged(newConfig: Configuration) {
|
|
||||||
super.onConfigurationChanged(newConfig)
|
|
||||||
setupSystemBars()
|
|
||||||
setupWebViewBackground()
|
|
||||||
setupRootBackground()
|
|
||||||
}
|
|
||||||
|
|
||||||
private fun setupWebViewBackground() {
|
|
||||||
val isDarkTheme = resources.configuration.uiMode and
|
|
||||||
Configuration.UI_MODE_NIGHT_MASK ==
|
|
||||||
Configuration.UI_MODE_NIGHT_YES
|
|
||||||
webView.setBackgroundColor(if (isDarkTheme) Color.BLACK else Color.WHITE)
|
|
||||||
}
|
|
||||||
|
|
||||||
private fun setupRootBackground() {
|
|
||||||
val isDarkTheme = resources.configuration.uiMode and
|
|
||||||
Configuration.UI_MODE_NIGHT_MASK ==
|
|
||||||
Configuration.UI_MODE_NIGHT_YES
|
|
||||||
val rootView = findViewById<View>(android.R.id.content)
|
|
||||||
rootView.setBackgroundColor(if (isDarkTheme) Color.BLACK else Color.WHITE)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,74 +0,0 @@
|
|||||||
<?xml version="1.0" encoding="utf-8"?>
|
|
||||||
<vector
|
|
||||||
android:height="108dp"
|
|
||||||
android:width="108dp"
|
|
||||||
android:viewportHeight="108"
|
|
||||||
android:viewportWidth="108"
|
|
||||||
xmlns:android="http://schemas.android.com/apk/res/android">
|
|
||||||
<path android:fillColor="#3DDC84"
|
|
||||||
android:pathData="M0,0h108v108h-108z"/>
|
|
||||||
<path android:fillColor="#00000000" android:pathData="M9,0L9,108"
|
|
||||||
android:strokeColor="#33FFFFFF" android:strokeWidth="0.8"/>
|
|
||||||
<path android:fillColor="#00000000" android:pathData="M19,0L19,108"
|
|
||||||
android:strokeColor="#33FFFFFF" android:strokeWidth="0.8"/>
|
|
||||||
<path android:fillColor="#00000000" android:pathData="M29,0L29,108"
|
|
||||||
android:strokeColor="#33FFFFFF" android:strokeWidth="0.8"/>
|
|
||||||
<path android:fillColor="#00000000" android:pathData="M39,0L39,108"
|
|
||||||
android:strokeColor="#33FFFFFF" android:strokeWidth="0.8"/>
|
|
||||||
<path android:fillColor="#00000000" android:pathData="M49,0L49,108"
|
|
||||||
android:strokeColor="#33FFFFFF" android:strokeWidth="0.8"/>
|
|
||||||
<path android:fillColor="#00000000" android:pathData="M59,0L59,108"
|
|
||||||
android:strokeColor="#33FFFFFF" android:strokeWidth="0.8"/>
|
|
||||||
<path android:fillColor="#00000000" android:pathData="M69,0L69,108"
|
|
||||||
android:strokeColor="#33FFFFFF" android:strokeWidth="0.8"/>
|
|
||||||
<path android:fillColor="#00000000" android:pathData="M79,0L79,108"
|
|
||||||
android:strokeColor="#33FFFFFF" android:strokeWidth="0.8"/>
|
|
||||||
<path android:fillColor="#00000000" android:pathData="M89,0L89,108"
|
|
||||||
android:strokeColor="#33FFFFFF" android:strokeWidth="0.8"/>
|
|
||||||
<path android:fillColor="#00000000" android:pathData="M99,0L99,108"
|
|
||||||
android:strokeColor="#33FFFFFF" android:strokeWidth="0.8"/>
|
|
||||||
<path android:fillColor="#00000000" android:pathData="M0,9L108,9"
|
|
||||||
android:strokeColor="#33FFFFFF" android:strokeWidth="0.8"/>
|
|
||||||
<path android:fillColor="#00000000" android:pathData="M0,19L108,19"
|
|
||||||
android:strokeColor="#33FFFFFF" android:strokeWidth="0.8"/>
|
|
||||||
<path android:fillColor="#00000000" android:pathData="M0,29L108,29"
|
|
||||||
android:strokeColor="#33FFFFFF" android:strokeWidth="0.8"/>
|
|
||||||
<path android:fillColor="#00000000" android:pathData="M0,39L108,39"
|
|
||||||
android:strokeColor="#33FFFFFF" android:strokeWidth="0.8"/>
|
|
||||||
<path android:fillColor="#00000000" android:pathData="M0,49L108,49"
|
|
||||||
android:strokeColor="#33FFFFFF" android:strokeWidth="0.8"/>
|
|
||||||
<path android:fillColor="#00000000" android:pathData="M0,59L108,59"
|
|
||||||
android:strokeColor="#33FFFFFF" android:strokeWidth="0.8"/>
|
|
||||||
<path android:fillColor="#00000000" android:pathData="M0,69L108,69"
|
|
||||||
android:strokeColor="#33FFFFFF" android:strokeWidth="0.8"/>
|
|
||||||
<path android:fillColor="#00000000" android:pathData="M0,79L108,79"
|
|
||||||
android:strokeColor="#33FFFFFF" android:strokeWidth="0.8"/>
|
|
||||||
<path android:fillColor="#00000000" android:pathData="M0,89L108,89"
|
|
||||||
android:strokeColor="#33FFFFFF" android:strokeWidth="0.8"/>
|
|
||||||
<path android:fillColor="#00000000" android:pathData="M0,99L108,99"
|
|
||||||
android:strokeColor="#33FFFFFF" android:strokeWidth="0.8"/>
|
|
||||||
<path android:fillColor="#00000000" android:pathData="M19,29L89,29"
|
|
||||||
android:strokeColor="#33FFFFFF" android:strokeWidth="0.8"/>
|
|
||||||
<path android:fillColor="#00000000" android:pathData="M19,39L89,39"
|
|
||||||
android:strokeColor="#33FFFFFF" android:strokeWidth="0.8"/>
|
|
||||||
<path android:fillColor="#00000000" android:pathData="M19,49L89,49"
|
|
||||||
android:strokeColor="#33FFFFFF" android:strokeWidth="0.8"/>
|
|
||||||
<path android:fillColor="#00000000" android:pathData="M19,59L89,59"
|
|
||||||
android:strokeColor="#33FFFFFF" android:strokeWidth="0.8"/>
|
|
||||||
<path android:fillColor="#00000000" android:pathData="M19,69L89,69"
|
|
||||||
android:strokeColor="#33FFFFFF" android:strokeWidth="0.8"/>
|
|
||||||
<path android:fillColor="#00000000" android:pathData="M19,79L89,79"
|
|
||||||
android:strokeColor="#33FFFFFF" android:strokeWidth="0.8"/>
|
|
||||||
<path android:fillColor="#00000000" android:pathData="M29,19L29,89"
|
|
||||||
android:strokeColor="#33FFFFFF" android:strokeWidth="0.8"/>
|
|
||||||
<path android:fillColor="#00000000" android:pathData="M39,19L39,89"
|
|
||||||
android:strokeColor="#33FFFFFF" android:strokeWidth="0.8"/>
|
|
||||||
<path android:fillColor="#00000000" android:pathData="M49,19L49,89"
|
|
||||||
android:strokeColor="#33FFFFFF" android:strokeWidth="0.8"/>
|
|
||||||
<path android:fillColor="#00000000" android:pathData="M59,19L59,89"
|
|
||||||
android:strokeColor="#33FFFFFF" android:strokeWidth="0.8"/>
|
|
||||||
<path android:fillColor="#00000000" android:pathData="M69,19L69,89"
|
|
||||||
android:strokeColor="#33FFFFFF" android:strokeWidth="0.8"/>
|
|
||||||
<path android:fillColor="#00000000" android:pathData="M79,19L79,89"
|
|
||||||
android:strokeColor="#33FFFFFF" android:strokeWidth="0.8"/>
|
|
||||||
</vector>
|
|
||||||
@@ -1,30 +0,0 @@
|
|||||||
<vector xmlns:android="http://schemas.android.com/apk/res/android"
|
|
||||||
xmlns:aapt="http://schemas.android.com/aapt"
|
|
||||||
android:width="108dp"
|
|
||||||
android:height="108dp"
|
|
||||||
android:viewportWidth="108"
|
|
||||||
android:viewportHeight="108">
|
|
||||||
<path android:pathData="M31,63.928c0,0 6.4,-11 12.1,-13.1c7.2,-2.6 26,-1.4 26,-1.4l38.1,38.1L107,108.928l-32,-1L31,63.928z">
|
|
||||||
<aapt:attr name="android:fillColor">
|
|
||||||
<gradient
|
|
||||||
android:endX="85.84757"
|
|
||||||
android:endY="92.4963"
|
|
||||||
android:startX="42.9492"
|
|
||||||
android:startY="49.59793"
|
|
||||||
android:type="linear">
|
|
||||||
<item
|
|
||||||
android:color="#44000000"
|
|
||||||
android:offset="0.0" />
|
|
||||||
<item
|
|
||||||
android:color="#00000000"
|
|
||||||
android:offset="1.0" />
|
|
||||||
</gradient>
|
|
||||||
</aapt:attr>
|
|
||||||
</path>
|
|
||||||
<path
|
|
||||||
android:fillColor="#FFFFFF"
|
|
||||||
android:fillType="nonZero"
|
|
||||||
android:pathData="M65.3,45.828l3.8,-6.6c0.2,-0.4 0.1,-0.9 -0.3,-1.1c-0.4,-0.2 -0.9,-0.1 -1.1,0.3l-3.9,6.7c-6.3,-2.8 -13.4,-2.8 -19.7,0l-3.9,-6.7c-0.2,-0.4 -0.7,-0.5 -1.1,-0.3C38.8,38.328 38.7,38.828 38.9,39.228l3.8,6.6C36.2,49.428 31.7,56.028 31,63.928h46C76.3,56.028 71.8,49.428 65.3,45.828zM43.4,57.328c-0.8,0 -1.5,-0.5 -1.8,-1.2c-0.3,-0.7 -0.1,-1.5 0.4,-2.1c0.5,-0.5 1.4,-0.7 2.1,-0.4c0.7,0.3 1.2,1 1.2,1.8C45.3,56.528 44.5,57.328 43.4,57.328L43.4,57.328zM64.6,57.328c-0.8,0 -1.5,-0.5 -1.8,-1.2s-0.1,-1.5 0.4,-2.1c0.5,-0.5 1.4,-0.7 2.1,-0.4c0.7,0.3 1.2,1 1.2,1.8C66.5,56.528 65.6,57.328 64.6,57.328L64.6,57.328z"
|
|
||||||
android:strokeWidth="1"
|
|
||||||
android:strokeColor="#00000000" />
|
|
||||||
</vector>
|
|
||||||
@@ -1,19 +0,0 @@
|
|||||||
<?xml version="1.0" encoding="utf-8"?>
|
|
||||||
<androidx.constraintlayout.widget.ConstraintLayout
|
|
||||||
xmlns:android="http://schemas.android.com/apk/res/android"
|
|
||||||
xmlns:tools="http://schemas.android.com/tools"
|
|
||||||
xmlns:app="http://schemas.android.com/apk/res-auto"
|
|
||||||
android:layout_width="match_parent"
|
|
||||||
android:layout_height="match_parent"
|
|
||||||
tools:context=".MainActivity">
|
|
||||||
|
|
||||||
<WebView
|
|
||||||
android:id="@+id/webView"
|
|
||||||
android:layout_width="0dp"
|
|
||||||
android:layout_height="0dp"
|
|
||||||
app:layout_constraintBottom_toBottomOf="parent"
|
|
||||||
app:layout_constraintStart_toStartOf="parent"
|
|
||||||
app:layout_constraintEnd_toEndOf="parent"
|
|
||||||
app:layout_constraintTop_toTopOf="parent" />
|
|
||||||
|
|
||||||
</androidx.constraintlayout.widget.ConstraintLayout>
|
|
||||||
@@ -1,5 +0,0 @@
|
|||||||
<?xml version="1.0" encoding="utf-8"?>
|
|
||||||
<adaptive-icon xmlns:android="http://schemas.android.com/apk/res/android">
|
|
||||||
<background android:drawable="@drawable/ic_launcher_background"/>
|
|
||||||
<foreground android:drawable="@mipmap/ic_launcher_foreground"/>
|
|
||||||
</adaptive-icon>
|
|
||||||
@@ -1,5 +0,0 @@
|
|||||||
<?xml version="1.0" encoding="utf-8"?>
|
|
||||||
<adaptive-icon xmlns:android="http://schemas.android.com/apk/res/android">
|
|
||||||
<background android:drawable="@drawable/ic_launcher_background"/>
|
|
||||||
<foreground android:drawable="@mipmap/ic_launcher_foreground"/>
|
|
||||||
</adaptive-icon>
|
|
||||||
|
Before Width: | Height: | Size: 6.3 KiB |
|
Before Width: | Height: | Size: 19 KiB |
|
Before Width: | Height: | Size: 7.5 KiB |
|
Before Width: | Height: | Size: 3.7 KiB |
|
Before Width: | Height: | Size: 10 KiB |
|
Before Width: | Height: | Size: 4.2 KiB |
|
Before Width: | Height: | Size: 10 KiB |
|
Before Width: | Height: | Size: 30 KiB |
|
Before Width: | Height: | Size: 12 KiB |
|
Before Width: | Height: | Size: 20 KiB |
|
Before Width: | Height: | Size: 54 KiB |
|
Before Width: | Height: | Size: 22 KiB |
|
Before Width: | Height: | Size: 30 KiB |
|
Before Width: | Height: | Size: 86 KiB |
|
Before Width: | Height: | Size: 34 KiB |
@@ -1,9 +0,0 @@
|
|||||||
<resources xmlns:tools="http://schemas.android.com/tools">
|
|
||||||
<!-- Base application theme. -->
|
|
||||||
<style name="Base.Theme.Flux" parent="Theme.Material3.DayNight.NoActionBar">
|
|
||||||
<!-- Customize your dark theme here. -->
|
|
||||||
<!-- <item name="colorPrimary">@color/my_dark_primary</item> -->
|
|
||||||
<item name="android:statusBarColor">@android:color/transparent</item>
|
|
||||||
<item name="android:navigationBarColor">@android:color/transparent</item>
|
|
||||||
</style>
|
|
||||||
</resources>
|
|
||||||
@@ -1,6 +0,0 @@
|
|||||||
<?xml version="1.0" encoding="utf-8"?>
|
|
||||||
<resources>
|
|
||||||
<color name="black">#FF000000</color>
|
|
||||||
<color name="white">#FFFFFFFF</color>
|
|
||||||
|
|
||||||
</resources>
|
|
||||||
@@ -1,3 +0,0 @@
|
|||||||
<resources>
|
|
||||||
<string name="app_name">Flux</string>
|
|
||||||
</resources>
|
|
||||||
@@ -1,11 +0,0 @@
|
|||||||
<resources xmlns:tools="http://schemas.android.com/tools">
|
|
||||||
<!-- Base application theme. -->
|
|
||||||
<style name="Base.Theme.Flux" parent="Theme.Material3.DayNight.NoActionBar">
|
|
||||||
<!-- Customize your light theme here. -->
|
|
||||||
<!-- <item name="colorPrimary">@color/my_light_primary</item> -->
|
|
||||||
<item name="android:statusBarColor">@android:color/transparent</item>
|
|
||||||
<item name="android:navigationBarColor">@android:color/transparent</item>
|
|
||||||
</style>
|
|
||||||
|
|
||||||
<style name="Theme.Flux" parent="Base.Theme.Flux" />
|
|
||||||
</resources>
|
|
||||||
@@ -1,13 +0,0 @@
|
|||||||
<?xml version="1.0" encoding="utf-8"?><!--
|
|
||||||
Sample backup rules file; uncomment and customize as necessary.
|
|
||||||
See https://developer.android.com/guide/topics/data/autobackup
|
|
||||||
for details.
|
|
||||||
Note: This file is ignored for devices older that API 31
|
|
||||||
See https://developer.android.com/about/versions/12/backup-restore
|
|
||||||
-->
|
|
||||||
<full-backup-content>
|
|
||||||
<!--
|
|
||||||
<include domain="sharedpref" path="."/>
|
|
||||||
<exclude domain="sharedpref" path="device.xml"/>
|
|
||||||
-->
|
|
||||||
</full-backup-content>
|
|
||||||
@@ -1,19 +0,0 @@
|
|||||||
<?xml version="1.0" encoding="utf-8"?><!--
|
|
||||||
Sample data extraction rules file; uncomment and customize as necessary.
|
|
||||||
See https://developer.android.com/about/versions/12/backup-restore#xml-changes
|
|
||||||
for details.
|
|
||||||
-->
|
|
||||||
<data-extraction-rules>
|
|
||||||
<cloud-backup>
|
|
||||||
<!-- TODO: Use <include> and <exclude> to control what is backed up.
|
|
||||||
<include .../>
|
|
||||||
<exclude .../>
|
|
||||||
-->
|
|
||||||
</cloud-backup>
|
|
||||||
<!--
|
|
||||||
<device-transfer>
|
|
||||||
<include .../>
|
|
||||||
<exclude .../>
|
|
||||||
</device-transfer>
|
|
||||||
-->
|
|
||||||
</data-extraction-rules>
|
|
||||||
@@ -1,17 +0,0 @@
|
|||||||
package com.flux
|
|
||||||
|
|
||||||
import org.junit.Test
|
|
||||||
|
|
||||||
import org.junit.Assert.*
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Example local unit test, which will execute on the development machine (host).
|
|
||||||
*
|
|
||||||
* See [testing documentation](http://d.android.com/tools/testing).
|
|
||||||
*/
|
|
||||||
class ExampleUnitTest {
|
|
||||||
@Test
|
|
||||||
fun addition_isCorrect() {
|
|
||||||
assertEquals(4, 2 + 2)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,5 +0,0 @@
|
|||||||
// Top-level build file where you can add configuration options common to all sub-projects/modules.
|
|
||||||
plugins {
|
|
||||||
id 'com.android.application' version '8.2.2' apply false
|
|
||||||
id 'org.jetbrains.kotlin.android' version '1.8.0' apply false
|
|
||||||
}
|
|
||||||
@@ -1,23 +0,0 @@
|
|||||||
# Project-wide Gradle settings.
|
|
||||||
# IDE (e.g. Android Studio) users:
|
|
||||||
# Gradle settings configured through the IDE *will override*
|
|
||||||
# any settings specified in this file.
|
|
||||||
# For more details on how to configure your build environment visit
|
|
||||||
# http://www.gradle.org/docs/current/userguide/build_environment.html
|
|
||||||
# Specifies the JVM arguments used for the daemon process.
|
|
||||||
# The setting is particularly useful for tweaking memory settings.
|
|
||||||
org.gradle.jvmargs=-Xmx2048m -Dfile.encoding=UTF-8
|
|
||||||
# When configured, Gradle will run in incubating parallel mode.
|
|
||||||
# This option should only be used with decoupled projects. More details, visit
|
|
||||||
# http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects
|
|
||||||
# org.gradle.parallel=true
|
|
||||||
# AndroidX package structure to make it clearer which packages are bundled with the
|
|
||||||
# Android operating system, and which are packaged with your app's APK
|
|
||||||
# https://developer.android.com/topic/libraries/support-library/androidx-rn
|
|
||||||
android.useAndroidX=true
|
|
||||||
# Kotlin code style for this project: "official" or "obsolete":
|
|
||||||
kotlin.code.style=official
|
|
||||||
# Enables namespacing of each library's R class so that its R class includes only the
|
|
||||||
# resources declared in the library itself and none from the library's dependencies,
|
|
||||||
# thereby reducing the size of the R class for that library
|
|
||||||
android.nonTransitiveRClass=true
|
|
||||||
@@ -1,6 +0,0 @@
|
|||||||
#Wed Aug 20 09:15:27 CST 2025
|
|
||||||
distributionBase=GRADLE_USER_HOME
|
|
||||||
distributionPath=wrapper/dists
|
|
||||||
distributionUrl=https\://services.gradle.org/distributions/gradle-8.2.1-bin.zip
|
|
||||||
zipStoreBase=GRADLE_USER_HOME
|
|
||||||
zipStorePath=wrapper/dists
|
|
||||||
@@ -1,185 +0,0 @@
|
|||||||
#!/usr/bin/env sh
|
|
||||||
|
|
||||||
#
|
|
||||||
# Copyright 2015 the original author or authors.
|
|
||||||
#
|
|
||||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
|
||||||
# you may not use this file except in compliance with the License.
|
|
||||||
# You may obtain a copy of the License at
|
|
||||||
#
|
|
||||||
# https://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.
|
|
||||||
#
|
|
||||||
|
|
||||||
##############################################################################
|
|
||||||
##
|
|
||||||
## Gradle start up script for UN*X
|
|
||||||
##
|
|
||||||
##############################################################################
|
|
||||||
|
|
||||||
# Attempt to set APP_HOME
|
|
||||||
# Resolve links: $0 may be a link
|
|
||||||
PRG="$0"
|
|
||||||
# Need this for relative symlinks.
|
|
||||||
while [ -h "$PRG" ] ; do
|
|
||||||
ls=`ls -ld "$PRG"`
|
|
||||||
link=`expr "$ls" : '.*-> \(.*\)$'`
|
|
||||||
if expr "$link" : '/.*' > /dev/null; then
|
|
||||||
PRG="$link"
|
|
||||||
else
|
|
||||||
PRG=`dirname "$PRG"`"/$link"
|
|
||||||
fi
|
|
||||||
done
|
|
||||||
SAVED="`pwd`"
|
|
||||||
cd "`dirname \"$PRG\"`/" >/dev/null
|
|
||||||
APP_HOME="`pwd -P`"
|
|
||||||
cd "$SAVED" >/dev/null
|
|
||||||
|
|
||||||
APP_NAME="Gradle"
|
|
||||||
APP_BASE_NAME=`basename "$0"`
|
|
||||||
|
|
||||||
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
|
|
||||||
DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
|
|
||||||
|
|
||||||
# Use the maximum available, or set MAX_FD != -1 to use that value.
|
|
||||||
MAX_FD="maximum"
|
|
||||||
|
|
||||||
warn () {
|
|
||||||
echo "$*"
|
|
||||||
}
|
|
||||||
|
|
||||||
die () {
|
|
||||||
echo
|
|
||||||
echo "$*"
|
|
||||||
echo
|
|
||||||
exit 1
|
|
||||||
}
|
|
||||||
|
|
||||||
# OS specific support (must be 'true' or 'false').
|
|
||||||
cygwin=false
|
|
||||||
msys=false
|
|
||||||
darwin=false
|
|
||||||
nonstop=false
|
|
||||||
case "`uname`" in
|
|
||||||
CYGWIN* )
|
|
||||||
cygwin=true
|
|
||||||
;;
|
|
||||||
Darwin* )
|
|
||||||
darwin=true
|
|
||||||
;;
|
|
||||||
MINGW* )
|
|
||||||
msys=true
|
|
||||||
;;
|
|
||||||
NONSTOP* )
|
|
||||||
nonstop=true
|
|
||||||
;;
|
|
||||||
esac
|
|
||||||
|
|
||||||
CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
|
|
||||||
|
|
||||||
|
|
||||||
# Determine the Java command to use to start the JVM.
|
|
||||||
if [ -n "$JAVA_HOME" ] ; then
|
|
||||||
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
|
|
||||||
# IBM's JDK on AIX uses strange locations for the executables
|
|
||||||
JAVACMD="$JAVA_HOME/jre/sh/java"
|
|
||||||
else
|
|
||||||
JAVACMD="$JAVA_HOME/bin/java"
|
|
||||||
fi
|
|
||||||
if [ ! -x "$JAVACMD" ] ; then
|
|
||||||
die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
|
|
||||||
|
|
||||||
Please set the JAVA_HOME variable in your environment to match the
|
|
||||||
location of your Java installation."
|
|
||||||
fi
|
|
||||||
else
|
|
||||||
JAVACMD="java"
|
|
||||||
which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
|
|
||||||
|
|
||||||
Please set the JAVA_HOME variable in your environment to match the
|
|
||||||
location of your Java installation."
|
|
||||||
fi
|
|
||||||
|
|
||||||
# Increase the maximum file descriptors if we can.
|
|
||||||
if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then
|
|
||||||
MAX_FD_LIMIT=`ulimit -H -n`
|
|
||||||
if [ $? -eq 0 ] ; then
|
|
||||||
if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
|
|
||||||
MAX_FD="$MAX_FD_LIMIT"
|
|
||||||
fi
|
|
||||||
ulimit -n $MAX_FD
|
|
||||||
if [ $? -ne 0 ] ; then
|
|
||||||
warn "Could not set maximum file descriptor limit: $MAX_FD"
|
|
||||||
fi
|
|
||||||
else
|
|
||||||
warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
|
|
||||||
fi
|
|
||||||
fi
|
|
||||||
|
|
||||||
# For Darwin, add options to specify how the application appears in the dock
|
|
||||||
if $darwin; then
|
|
||||||
GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
|
|
||||||
fi
|
|
||||||
|
|
||||||
# For Cygwin or MSYS, switch paths to Windows format before running java
|
|
||||||
if [ "$cygwin" = "true" -o "$msys" = "true" ] ; then
|
|
||||||
APP_HOME=`cygpath --path --mixed "$APP_HOME"`
|
|
||||||
CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
|
|
||||||
|
|
||||||
JAVACMD=`cygpath --unix "$JAVACMD"`
|
|
||||||
|
|
||||||
# We build the pattern for arguments to be converted via cygpath
|
|
||||||
ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
|
|
||||||
SEP=""
|
|
||||||
for dir in $ROOTDIRSRAW ; do
|
|
||||||
ROOTDIRS="$ROOTDIRS$SEP$dir"
|
|
||||||
SEP="|"
|
|
||||||
done
|
|
||||||
OURCYGPATTERN="(^($ROOTDIRS))"
|
|
||||||
# Add a user-defined pattern to the cygpath arguments
|
|
||||||
if [ "$GRADLE_CYGPATTERN" != "" ] ; then
|
|
||||||
OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
|
|
||||||
fi
|
|
||||||
# Now convert the arguments - kludge to limit ourselves to /bin/sh
|
|
||||||
i=0
|
|
||||||
for arg in "$@" ; do
|
|
||||||
CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
|
|
||||||
CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option
|
|
||||||
|
|
||||||
if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition
|
|
||||||
eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
|
|
||||||
else
|
|
||||||
eval `echo args$i`="\"$arg\""
|
|
||||||
fi
|
|
||||||
i=`expr $i + 1`
|
|
||||||
done
|
|
||||||
case $i in
|
|
||||||
0) set -- ;;
|
|
||||||
1) set -- "$args0" ;;
|
|
||||||
2) set -- "$args0" "$args1" ;;
|
|
||||||
3) set -- "$args0" "$args1" "$args2" ;;
|
|
||||||
4) set -- "$args0" "$args1" "$args2" "$args3" ;;
|
|
||||||
5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
|
|
||||||
6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
|
|
||||||
7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
|
|
||||||
8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
|
|
||||||
9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
|
|
||||||
esac
|
|
||||||
fi
|
|
||||||
|
|
||||||
# Escape application args
|
|
||||||
save () {
|
|
||||||
for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done
|
|
||||||
echo " "
|
|
||||||
}
|
|
||||||
APP_ARGS=`save "$@"`
|
|
||||||
|
|
||||||
# Collect all arguments for the java command, following the shell quoting and substitution rules
|
|
||||||
eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS"
|
|
||||||
|
|
||||||
exec "$JAVACMD" "$@"
|
|
||||||
@@ -1,89 +0,0 @@
|
|||||||
@rem
|
|
||||||
@rem Copyright 2015 the original author or authors.
|
|
||||||
@rem
|
|
||||||
@rem Licensed under the Apache License, Version 2.0 (the "License");
|
|
||||||
@rem you may not use this file except in compliance with the License.
|
|
||||||
@rem You may obtain a copy of the License at
|
|
||||||
@rem
|
|
||||||
@rem https://www.apache.org/licenses/LICENSE-2.0
|
|
||||||
@rem
|
|
||||||
@rem Unless required by applicable law or agreed to in writing, software
|
|
||||||
@rem distributed under the License is distributed on an "AS IS" BASIS,
|
|
||||||
@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
||||||
@rem See the License for the specific language governing permissions and
|
|
||||||
@rem limitations under the License.
|
|
||||||
@rem
|
|
||||||
|
|
||||||
@if "%DEBUG%" == "" @echo off
|
|
||||||
@rem ##########################################################################
|
|
||||||
@rem
|
|
||||||
@rem Gradle startup script for Windows
|
|
||||||
@rem
|
|
||||||
@rem ##########################################################################
|
|
||||||
|
|
||||||
@rem Set local scope for the variables with windows NT shell
|
|
||||||
if "%OS%"=="Windows_NT" setlocal
|
|
||||||
|
|
||||||
set DIRNAME=%~dp0
|
|
||||||
if "%DIRNAME%" == "" set DIRNAME=.
|
|
||||||
set APP_BASE_NAME=%~n0
|
|
||||||
set APP_HOME=%DIRNAME%
|
|
||||||
|
|
||||||
@rem Resolve any "." and ".." in APP_HOME to make it shorter.
|
|
||||||
for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi
|
|
||||||
|
|
||||||
@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
|
|
||||||
set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m"
|
|
||||||
|
|
||||||
@rem Find java.exe
|
|
||||||
if defined JAVA_HOME goto findJavaFromJavaHome
|
|
||||||
|
|
||||||
set JAVA_EXE=java.exe
|
|
||||||
%JAVA_EXE% -version >NUL 2>&1
|
|
||||||
if "%ERRORLEVEL%" == "0" goto execute
|
|
||||||
|
|
||||||
echo.
|
|
||||||
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
|
|
||||||
echo.
|
|
||||||
echo Please set the JAVA_HOME variable in your environment to match the
|
|
||||||
echo location of your Java installation.
|
|
||||||
|
|
||||||
goto fail
|
|
||||||
|
|
||||||
:findJavaFromJavaHome
|
|
||||||
set JAVA_HOME=%JAVA_HOME:"=%
|
|
||||||
set JAVA_EXE=%JAVA_HOME%/bin/java.exe
|
|
||||||
|
|
||||||
if exist "%JAVA_EXE%" goto execute
|
|
||||||
|
|
||||||
echo.
|
|
||||||
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
|
|
||||||
echo.
|
|
||||||
echo Please set the JAVA_HOME variable in your environment to match the
|
|
||||||
echo location of your Java installation.
|
|
||||||
|
|
||||||
goto fail
|
|
||||||
|
|
||||||
:execute
|
|
||||||
@rem Setup the command line
|
|
||||||
|
|
||||||
set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
|
|
||||||
|
|
||||||
|
|
||||||
@rem Execute Gradle
|
|
||||||
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %*
|
|
||||||
|
|
||||||
:end
|
|
||||||
@rem End local scope for the variables with windows NT shell
|
|
||||||
if "%ERRORLEVEL%"=="0" goto mainEnd
|
|
||||||
|
|
||||||
:fail
|
|
||||||
rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
|
|
||||||
rem the _cmd.exe /c_ return code!
|
|
||||||
if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
|
|
||||||
exit /b 1
|
|
||||||
|
|
||||||
:mainEnd
|
|
||||||
if "%OS%"=="Windows_NT" endlocal
|
|
||||||
|
|
||||||
:omega
|
|
||||||
@@ -1,17 +0,0 @@
|
|||||||
pluginManagement {
|
|
||||||
repositories {
|
|
||||||
google()
|
|
||||||
mavenCentral()
|
|
||||||
gradlePluginPortal()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
dependencyResolutionManagement {
|
|
||||||
repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS)
|
|
||||||
repositories {
|
|
||||||
google()
|
|
||||||
mavenCentral()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
rootProject.name = "Flux"
|
|
||||||
include ':app'
|
|
||||||
|
Before Width: | Height: | Size: 14 KiB |
@@ -0,0 +1,24 @@
|
|||||||
|
# 常见问题 (FAQ)
|
||||||
|
|
||||||
|
### Q1: 安装脚本提示 "Docker command not found"?
|
||||||
|
**A**: 请确保您的系统已安装 Docker 和 Docker Compose。
|
||||||
|
- Ubuntu/Debian 安装 Docker: `curl -fsSL https://get.docker.com | bash`
|
||||||
|
|
||||||
|
### Q2: 面板无法访问 (Connection Refused)?
|
||||||
|
**A**:
|
||||||
|
1. 检查防火墙是否放行了前端端口(默认 `6366`)。
|
||||||
|
2. 检查容器是否正常运行: `docker ps`。
|
||||||
|
3. 查看容器日志: `docker logs flux-panel-backend` 或 `docker logs vite-frontend`。
|
||||||
|
|
||||||
|
### Q3: 节点显示离线?
|
||||||
|
**A**:
|
||||||
|
1. 检查节点服务器与面板服务器之间的网络连通性。
|
||||||
|
2. 确认在节点端安装时输入的 **面板地址** 和 **密钥** 是否正确。
|
||||||
|
3. 检查节点端服务状态: `systemctl status flux_agent`。
|
||||||
|
4. 查看节点端日志: `journalctl -u flux_agent -f`。
|
||||||
|
|
||||||
|
### Q4: 只有 TCP 能通,UDP 不通?
|
||||||
|
**A**: 请检查服务器防火墙和安全组(AWS/阿里云/腾讯云等)是否同时放行了对应端口的 **TCP 和 UDP** 协议。
|
||||||
|
|
||||||
|
### Q5: IPv6 无法使用?
|
||||||
|
**A**: 面板安装脚本会自动尝试配置 Docker 的 IPv6。如果失败,请手动检查 `/etc/docker/daemon.json` 配置,确保 `ipv6: true` 且分配了正确的 `fixed-cidr-v6` 子网。
|
||||||
@@ -0,0 +1,37 @@
|
|||||||
|
# FLVX 官方文档
|
||||||
|
|
||||||
|
**FLVX** 是一个基于 [go-gost/gost](https://github.com/go-gost/gost) 和 [go-gost/x](https://github.com/go-gost/x) 开发的高性能流量转发管理系统。
|
||||||
|
|
||||||
|
> 📞 **联系我们**: [Telegram群组](https://t.me/flvxpanel)
|
||||||
|
|
||||||
|
## 核心特性
|
||||||
|
|
||||||
|
- **多协议支持**: 完美支持 TCP 和 UDP 协议转发。
|
||||||
|
- **灵活转发**: 支持 **端口转发** 与 **隧道转发** 两种模式。
|
||||||
|
- **流量控制**: 支持按 **隧道账号级别** 管理流量转发数量,用于用户/隧道配额控制。
|
||||||
|
- **限速管理**: 可针对 **指定用户的指定隧道进行限速** 设置。
|
||||||
|
- **计费策略**: 支持配置 **单向或双向流量计费方式**,灵活适配不同计费模型。
|
||||||
|
- **策略配置**: 提供灵活的转发策略配置,适用于多种网络场景。
|
||||||
|
|
||||||
|
## 快速开始
|
||||||
|
|
||||||
|
- [安装部署](./install.md)
|
||||||
|
- [使用指南](./usage.md)
|
||||||
|
- [常见问题](./faq.md)
|
||||||
|
|
||||||
|
## 免责声明
|
||||||
|
|
||||||
|
本项目仅供个人学习与研究使用,基于开源项目进行二次开发。
|
||||||
|
使用本项目所带来的任何风险均由使用者自行承担。本项目为开源的流量转发工具,仅限合法、合规用途。
|
||||||
|
**禁止将本项目用于任何违法或未经授权的行为,包括但不限于网络攻击、数据窃取、非法访问等。**
|
||||||
|
|
||||||
|
## 捐赠支持
|
||||||
|
|
||||||
|
如果您觉得本项目对您有帮助,欢迎请作者喝杯咖啡!
|
||||||
|
|
||||||
|
| 网络 | 地址 |
|
||||||
|
|------------|----------------------------------------------------------------------|
|
||||||
|
| BNB(BEP20) | `0xa608708fdc6279a2433fd4b82f0b72b8cbe97ed5` |
|
||||||
|
| TRC20 | `TM8VYdU3s3gSX5PC8swjAJrAzZFCHKqG2k` |
|
||||||
|
| Aptos | `0x49427bfcba1006a346447430689b2307ac156316bb34850d1d3029ff9d118da5` |
|
||||||
|
| Polygon | `0xa608708fdc6279a2433fd4b82f0b72b8cbe97ed5` |
|
||||||
@@ -0,0 +1,79 @@
|
|||||||
|
# 安装部署指南
|
||||||
|
|
||||||
|
本文档介绍如何部署 FLVX 面板端及节点端。
|
||||||
|
|
||||||
|
## 一、面板端部署
|
||||||
|
|
||||||
|
面板端负责管理用户、节点和转发规则。
|
||||||
|
|
||||||
|
### 1. 环境要求
|
||||||
|
- 操作系统:Linux (推荐 Debian 10+ / Ubuntu 20.04+)
|
||||||
|
- 必须安装 Docker 和 Docker Compose
|
||||||
|
|
||||||
|
### 2. 一键安装脚本
|
||||||
|
|
||||||
|
使用以下命令即可快速安装面板:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
curl -L https://raw.githubusercontent.com/Sagit-chu/flux-panel/main/panel_install.sh -o panel_install.sh && chmod +x panel_install.sh && ./panel_install.sh
|
||||||
|
```
|
||||||
|
|
||||||
|
**安装过程中会提示输入以下信息:**
|
||||||
|
- **前端端口**: 默认为 `6366`
|
||||||
|
- **后端端口**: 默认为 `6365`
|
||||||
|
|
||||||
|
脚本会自动检测系统是否支持 IPv6,并自动配置 Docker 的 IPv6 支持。
|
||||||
|
|
||||||
|
### 3. 访问面板
|
||||||
|
|
||||||
|
安装完成后,访问:
|
||||||
|
`http://<服务器IP>:<前端端口>` (默认: `http://<服务器IP>:6366`)
|
||||||
|
|
||||||
|
**默认管理员账号:**
|
||||||
|
- 用户名: `admin_user`
|
||||||
|
- 密码: `admin_user`
|
||||||
|
|
||||||
|
> ⚠️ **注意**: 首次登录后,请务必在“个人中心”或“设置”中修改默认密码!
|
||||||
|
|
||||||
|
### 4. 维护命令
|
||||||
|
|
||||||
|
再次运行 `./panel_install.sh` 脚本可以看到管理菜单:
|
||||||
|
1. 安装面板
|
||||||
|
2. 更新面板
|
||||||
|
3. 卸载面板
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 二、节点端部署
|
||||||
|
|
||||||
|
节点端运行在实际进行流量转发的服务器上,需要连接到面板端进行管理。
|
||||||
|
|
||||||
|
### 1. 获取接入密钥
|
||||||
|
1. 登录面板端。
|
||||||
|
2. 进入 **节点管理 (Node)** 页面。
|
||||||
|
3. 点击 **添加节点**。
|
||||||
|
4. 获取该节点的 **接入密钥 (Secret)**。
|
||||||
|
|
||||||
|
### 2. 一键安装脚本
|
||||||
|
|
||||||
|
在节点服务器上运行:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
curl -L https://raw.githubusercontent.com/Sagit-chu/flux-panel/main/install.sh -o install.sh && chmod +x install.sh && ./install.sh
|
||||||
|
```
|
||||||
|
|
||||||
|
**安装过程中会提示输入:**
|
||||||
|
- **服务器地址**: 面板端的通信地址(通常是 `http://<面板IP>:<后端端口>`,例如 `http://1.2.3.4:6365`)。
|
||||||
|
- **密钥**: 刚才在面板中获取的节点密钥。
|
||||||
|
|
||||||
|
或者直接使用带参数的命令(适用于自动化部署):
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# 替换 <面板地址> 和 <密钥>
|
||||||
|
./install.sh -a "http://1.2.3.4:6365" -s "your_node_secret"
|
||||||
|
```
|
||||||
|
|
||||||
|
### 3. 验证安装
|
||||||
|
安装完成后,服务会自动启动。
|
||||||
|
- 查看状态: `systemctl status flux_agent`
|
||||||
|
- 回到面板 **节点管理** 页面,该节点状态应显示为 **在线**。
|
||||||
@@ -0,0 +1,35 @@
|
|||||||
|
# 使用指南
|
||||||
|
|
||||||
|
## 1. 仪表盘 (Dashboard)
|
||||||
|
登录系统后首先看到的是仪表盘,这里展示了系统的整体运行状态,包括:
|
||||||
|
- 在线节点数量
|
||||||
|
- 用户总数
|
||||||
|
- 流量统计信息
|
||||||
|
|
||||||
|
## 2. 节点管理 (Node)
|
||||||
|
节点是实际承载流量转发的服务器。
|
||||||
|
- **添加节点**: 点击“添加”,获取密钥用于节点端安装。
|
||||||
|
- **管理**: 可以查看节点在线状态、版本信息,以及对节点进行编辑或删除。
|
||||||
|
|
||||||
|
## 3. 用户管理 (User)
|
||||||
|
管理员可以创建和管理普通用户。
|
||||||
|
- **创建用户**: 设置用户名、密码、流量配额等。
|
||||||
|
- **用户组**: 可以将用户分配到不同的组 (Group),便于统一管理权限或策略。
|
||||||
|
|
||||||
|
## 4. 转发管理 (Forward)
|
||||||
|
这是核心功能区,用于设置端口转发规则。
|
||||||
|
- **端口转发**: 将节点服务器的某个端口流量转发到目标地址。
|
||||||
|
- **协议**: 支持 TCP / UDP。
|
||||||
|
- **入口**: 选择入口节点和监听端口。
|
||||||
|
- **出口**: 设置目标 IP 和端口。
|
||||||
|
- **隧道转发**: 用于更复杂的网络穿透场景(具体配置视业务需求而定)。
|
||||||
|
|
||||||
|
## 5. 限制与策略 (Limit)
|
||||||
|
- **限速**: 可以对指定用户或指定隧道进行带宽限制,防止资源滥用。
|
||||||
|
- **计费模式**: 支持配置流量计算方式(单向或双向),适合运营场景。
|
||||||
|
|
||||||
|
## 6. 系统配置 (Config)
|
||||||
|
在此页面进行系统的全局设置。
|
||||||
|
|
||||||
|
## 7. 个人设置 (Profile)
|
||||||
|
- **修改密码**: 为了安全,建议定期修改管理员密码。
|
||||||
|
Before Width: | Height: | Size: 1.3 MiB |
@@ -1,7 +1,7 @@
|
|||||||
services:
|
services:
|
||||||
backend:
|
backend:
|
||||||
image: ghcr.io/sagit-chu/go-backend:${FLUX_VERSION:-latest}
|
image: ghcr.io/sagit-chu/flux-panel-backend:${FLUX_VERSION:-latest}
|
||||||
container_name: go-backend
|
container_name: flux-panel-backend
|
||||||
restart: unless-stopped
|
restart: unless-stopped
|
||||||
logging:
|
logging:
|
||||||
driver: json-file
|
driver: json-file
|
||||||
@@ -12,6 +12,7 @@ services:
|
|||||||
JWT_SECRET: ${JWT_SECRET}
|
JWT_SECRET: ${JWT_SECRET}
|
||||||
LOG_DIR: /app/logs
|
LOG_DIR: /app/logs
|
||||||
SERVER_ADDR: :6365
|
SERVER_ADDR: :6365
|
||||||
|
TZ: Asia/Shanghai
|
||||||
ports:
|
ports:
|
||||||
- "${BACKEND_PORT}:6365"
|
- "${BACKEND_PORT}:6365"
|
||||||
volumes:
|
volumes:
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
services:
|
services:
|
||||||
backend:
|
backend:
|
||||||
image: ghcr.io/sagit-chu/go-backend:${FLUX_VERSION:-latest}
|
image: ghcr.io/sagit-chu/flux-panel-backend:${FLUX_VERSION:-latest}
|
||||||
container_name: go-backend
|
container_name: flux-panel-backend
|
||||||
restart: unless-stopped
|
restart: unless-stopped
|
||||||
logging:
|
logging:
|
||||||
driver: json-file
|
driver: json-file
|
||||||
@@ -12,6 +12,7 @@ services:
|
|||||||
JWT_SECRET: ${JWT_SECRET}
|
JWT_SECRET: ${JWT_SECRET}
|
||||||
LOG_DIR: /app/logs
|
LOG_DIR: /app/logs
|
||||||
SERVER_ADDR: :6365
|
SERVER_ADDR: :6365
|
||||||
|
TZ: Asia/Shanghai
|
||||||
ports:
|
ports:
|
||||||
- "${BACKEND_PORT}:6365"
|
- "${BACKEND_PORT}:6365"
|
||||||
volumes:
|
volumes:
|
||||||
|
|||||||
@@ -0,0 +1,47 @@
|
|||||||
|
# GO BACKEND KNOWLEDGE BASE
|
||||||
|
|
||||||
|
## OVERVIEW
|
||||||
|
Go-based Admin API for FLVX (formerly Flux Panel). Replaces the legacy Spring Boot backend.
|
||||||
|
**Stack:** Go 1.23, net/http (std lib), SQLite (modernc.org/sqlite).
|
||||||
|
|
||||||
|
## STRUCTURE
|
||||||
|
```
|
||||||
|
go-backend/
|
||||||
|
├── cmd/paneld/main.go # Entry point; starts HTTP server + WebSocket
|
||||||
|
├── internal/
|
||||||
|
│ ├── http/ # HTTP layer
|
||||||
|
│ │ ├── router.go # Routes (NewServeMux) + Middleware chain
|
||||||
|
│ │ ├── handler/ # API Handlers (User, Tunnel, Node, etc.)
|
||||||
|
│ │ ├── middleware/ # JWT, CORS, Logging, Recover
|
||||||
|
│ │ └── response/ # JSON response helpers
|
||||||
|
│ ├── store/sqlite/ # Data Access Layer (Repository pattern)
|
||||||
|
│ │ ├── repository.go # SQL queries & Struct definitions
|
||||||
|
│ │ └── sql/ # Embedded schema.sql & data.sql
|
||||||
|
│ └── auth/ # Auth logic
|
||||||
|
├── tests/ # Integration/Contract tests
|
||||||
|
├── Dockerfile # Multi-stage build (alpine)
|
||||||
|
└── Makefile # Build commands
|
||||||
|
```
|
||||||
|
|
||||||
|
## WHERE TO LOOK
|
||||||
|
| Task | Location | Notes |
|
||||||
|
|------|----------|-------|
|
||||||
|
| **API Routes** | `go-backend/internal/http/router.go` | Registers handlers to `http.ServeMux` |
|
||||||
|
| **DB Schema** | `go-backend/internal/store/sqlite/sql/schema.sql` | Embedded in binary |
|
||||||
|
| **SQL Queries** | `go-backend/internal/store/sqlite/repository.go` | Raw SQL, no ORM |
|
||||||
|
| **Auth Middleware** | `go-backend/internal/http/middleware/jwt.go` | Extracts `Authorization` header |
|
||||||
|
| **WebSocket** | `go-backend/internal/ws/` | Real-time updates (traffic, status) |
|
||||||
|
|
||||||
|
## CONVENTIONS
|
||||||
|
- **No ORM**: Uses raw SQL with `database/sql` and `modernc.org/sqlite`.
|
||||||
|
- **Standard Lib**: Uses `net/http` for routing (Go 1.22+ patterns).
|
||||||
|
- **Auth**: Expects raw JWT in `Authorization` header (no `Bearer` prefix).
|
||||||
|
- **Config**: Loaded from environment variables (see `cmd/paneld/main.go`).
|
||||||
|
|
||||||
|
## COMMANDS
|
||||||
|
```bash
|
||||||
|
cd go-backend
|
||||||
|
go run ./cmd/paneld
|
||||||
|
go test ./...
|
||||||
|
make build
|
||||||
|
```
|
||||||
@@ -5,7 +5,9 @@ COPY go.mod ./
|
|||||||
RUN go mod download
|
RUN go mod download
|
||||||
|
|
||||||
COPY . .
|
COPY . .
|
||||||
RUN CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build -o /out/paneld ./cmd/paneld
|
ARG TARGETOS
|
||||||
|
ARG TARGETARCH
|
||||||
|
RUN CGO_ENABLED=0 GOOS=${TARGETOS:-linux} env ${TARGETARCH:+GOARCH=${TARGETARCH}} go build -o /out/paneld ./cmd/paneld
|
||||||
|
|
||||||
FROM debian:bookworm-slim
|
FROM debian:bookworm-slim
|
||||||
WORKDIR /app
|
WORKDIR /app
|
||||||
|
|||||||
@@ -0,0 +1,327 @@
|
|||||||
|
package client
|
||||||
|
|
||||||
|
import (
|
||||||
|
"encoding/json"
|
||||||
|
"fmt"
|
||||||
|
"io"
|
||||||
|
"net/http"
|
||||||
|
"strings"
|
||||||
|
"time"
|
||||||
|
)
|
||||||
|
|
||||||
|
type FederationClient struct {
|
||||||
|
client *http.Client
|
||||||
|
}
|
||||||
|
|
||||||
|
type RemoteNodeInfo struct {
|
||||||
|
ShareID int64 `json:"shareId"`
|
||||||
|
ShareName string `json:"shareName"`
|
||||||
|
NodeID int64 `json:"nodeId"`
|
||||||
|
NodeName string `json:"nodeName"`
|
||||||
|
ServerIP string `json:"serverIp"`
|
||||||
|
Status int `json:"status"`
|
||||||
|
MaxBandwidth int64 `json:"maxBandwidth"`
|
||||||
|
CurrentFlow int64 `json:"currentFlow"`
|
||||||
|
ExpiryTime int64 `json:"expiryTime"`
|
||||||
|
PortRangeStart int `json:"portRangeStart"`
|
||||||
|
PortRangeEnd int `json:"portRangeEnd"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type RemoteTunnelResponse struct {
|
||||||
|
TunnelID int64 `json:"tunnelId"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type RuntimeReservePortRequest struct {
|
||||||
|
ResourceKey string `json:"resourceKey"`
|
||||||
|
Protocol string `json:"protocol"`
|
||||||
|
RequestedPort int `json:"requestedPort"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type RuntimeReservePortResponse struct {
|
||||||
|
ReservationID string `json:"reservationId"`
|
||||||
|
BindingID string `json:"bindingId"`
|
||||||
|
AllocatedPort int `json:"allocatedPort"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type RuntimeTarget struct {
|
||||||
|
Host string `json:"host"`
|
||||||
|
Port int `json:"port"`
|
||||||
|
Protocol string `json:"protocol"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type RuntimeApplyRoleRequest struct {
|
||||||
|
ReservationID string `json:"reservationId"`
|
||||||
|
ResourceKey string `json:"resourceKey"`
|
||||||
|
Role string `json:"role"`
|
||||||
|
Protocol string `json:"protocol"`
|
||||||
|
Strategy string `json:"strategy"`
|
||||||
|
Targets []RuntimeTarget `json:"targets"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type RuntimeApplyRoleResponse struct {
|
||||||
|
BindingID string `json:"bindingId"`
|
||||||
|
ReservationID string `json:"reservationId"`
|
||||||
|
AllocatedPort int `json:"allocatedPort"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type RuntimeReleaseRoleRequest struct {
|
||||||
|
BindingID string `json:"bindingId"`
|
||||||
|
ReservationID string `json:"reservationId"`
|
||||||
|
ResourceKey string `json:"resourceKey"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type RuntimeDiagnoseRequest struct {
|
||||||
|
IP string `json:"ip"`
|
||||||
|
Port int `json:"port"`
|
||||||
|
Count int `json:"count"`
|
||||||
|
Timeout int `json:"timeout"`
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewFederationClient() *FederationClient {
|
||||||
|
return &FederationClient{
|
||||||
|
client: &http.Client{
|
||||||
|
Timeout: 10 * time.Second,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *FederationClient) Connect(url, token, localDomain string) (*RemoteNodeInfo, error) {
|
||||||
|
url = strings.TrimSuffix(url, "/")
|
||||||
|
req, err := http.NewRequest("POST", url+"/api/v1/federation/connect", nil)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
req.Header.Set("Authorization", "Bearer "+token)
|
||||||
|
if localDomain != "" {
|
||||||
|
req.Header.Set("X-Panel-Domain", localDomain)
|
||||||
|
}
|
||||||
|
req.Header.Set("Content-Type", "application/json")
|
||||||
|
|
||||||
|
resp, err := c.client.Do(req)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
defer resp.Body.Close()
|
||||||
|
|
||||||
|
if resp.StatusCode != 200 {
|
||||||
|
body, _ := io.ReadAll(resp.Body)
|
||||||
|
return nil, fmt.Errorf("remote error %d: %s", resp.StatusCode, string(body))
|
||||||
|
}
|
||||||
|
|
||||||
|
var res struct {
|
||||||
|
Code int `json:"code"`
|
||||||
|
Msg string `json:"msg"`
|
||||||
|
Data RemoteNodeInfo `json:"data"`
|
||||||
|
}
|
||||||
|
if err := json.NewDecoder(resp.Body).Decode(&res); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
if res.Code != 0 {
|
||||||
|
return nil, fmt.Errorf("remote api error: %s", res.Msg)
|
||||||
|
}
|
||||||
|
|
||||||
|
return &res.Data, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *FederationClient) CreateTunnel(url, token, localDomain, protocol string, remotePort int, target string) (*RemoteTunnelResponse, error) {
|
||||||
|
url = strings.TrimSuffix(url, "/")
|
||||||
|
payload := map[string]interface{}{
|
||||||
|
"protocol": protocol,
|
||||||
|
"remotePort": remotePort,
|
||||||
|
"target": target,
|
||||||
|
}
|
||||||
|
bodyBytes, _ := json.Marshal(payload)
|
||||||
|
req, err := http.NewRequest("POST", url+"/api/v1/federation/tunnel/create", strings.NewReader(string(bodyBytes)))
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
req.Header.Set("Authorization", "Bearer "+token)
|
||||||
|
if localDomain != "" {
|
||||||
|
req.Header.Set("X-Panel-Domain", localDomain)
|
||||||
|
}
|
||||||
|
req.Header.Set("Content-Type", "application/json")
|
||||||
|
|
||||||
|
resp, err := c.client.Do(req)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
defer resp.Body.Close()
|
||||||
|
|
||||||
|
if resp.StatusCode != 200 {
|
||||||
|
body, _ := io.ReadAll(resp.Body)
|
||||||
|
return nil, fmt.Errorf("remote error %d: %s", resp.StatusCode, string(body))
|
||||||
|
}
|
||||||
|
|
||||||
|
var res struct {
|
||||||
|
Code int `json:"code"`
|
||||||
|
Msg string `json:"msg"`
|
||||||
|
Data RemoteTunnelResponse `json:"data"`
|
||||||
|
}
|
||||||
|
if err := json.NewDecoder(resp.Body).Decode(&res); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
if res.Code != 0 {
|
||||||
|
return nil, fmt.Errorf("remote api error: %s", res.Msg)
|
||||||
|
}
|
||||||
|
|
||||||
|
return &res.Data, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *FederationClient) ReservePort(url, token, localDomain string, reqData RuntimeReservePortRequest) (*RuntimeReservePortResponse, error) {
|
||||||
|
url = strings.TrimSuffix(url, "/")
|
||||||
|
bodyBytes, _ := json.Marshal(reqData)
|
||||||
|
req, err := http.NewRequest("POST", url+"/api/v1/federation/runtime/reserve-port", strings.NewReader(string(bodyBytes)))
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
req.Header.Set("Authorization", "Bearer "+token)
|
||||||
|
if localDomain != "" {
|
||||||
|
req.Header.Set("X-Panel-Domain", localDomain)
|
||||||
|
}
|
||||||
|
req.Header.Set("Content-Type", "application/json")
|
||||||
|
|
||||||
|
resp, err := c.client.Do(req)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
defer resp.Body.Close()
|
||||||
|
|
||||||
|
if resp.StatusCode != 200 {
|
||||||
|
body, _ := io.ReadAll(resp.Body)
|
||||||
|
return nil, fmt.Errorf("remote error %d: %s", resp.StatusCode, string(body))
|
||||||
|
}
|
||||||
|
|
||||||
|
var res struct {
|
||||||
|
Code int `json:"code"`
|
||||||
|
Msg string `json:"msg"`
|
||||||
|
Data RuntimeReservePortResponse `json:"data"`
|
||||||
|
}
|
||||||
|
if err := json.NewDecoder(resp.Body).Decode(&res); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
if res.Code != 0 {
|
||||||
|
return nil, fmt.Errorf("remote api error: %s", res.Msg)
|
||||||
|
}
|
||||||
|
|
||||||
|
return &res.Data, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *FederationClient) ApplyRole(url, token, localDomain string, reqData RuntimeApplyRoleRequest) (*RuntimeApplyRoleResponse, error) {
|
||||||
|
url = strings.TrimSuffix(url, "/")
|
||||||
|
bodyBytes, _ := json.Marshal(reqData)
|
||||||
|
req, err := http.NewRequest("POST", url+"/api/v1/federation/runtime/apply-role", strings.NewReader(string(bodyBytes)))
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
req.Header.Set("Authorization", "Bearer "+token)
|
||||||
|
if localDomain != "" {
|
||||||
|
req.Header.Set("X-Panel-Domain", localDomain)
|
||||||
|
}
|
||||||
|
req.Header.Set("Content-Type", "application/json")
|
||||||
|
|
||||||
|
resp, err := c.client.Do(req)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
defer resp.Body.Close()
|
||||||
|
|
||||||
|
if resp.StatusCode != 200 {
|
||||||
|
body, _ := io.ReadAll(resp.Body)
|
||||||
|
return nil, fmt.Errorf("remote error %d: %s", resp.StatusCode, string(body))
|
||||||
|
}
|
||||||
|
|
||||||
|
var res struct {
|
||||||
|
Code int `json:"code"`
|
||||||
|
Msg string `json:"msg"`
|
||||||
|
Data RuntimeApplyRoleResponse `json:"data"`
|
||||||
|
}
|
||||||
|
if err := json.NewDecoder(resp.Body).Decode(&res); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
if res.Code != 0 {
|
||||||
|
return nil, fmt.Errorf("remote api error: %s", res.Msg)
|
||||||
|
}
|
||||||
|
|
||||||
|
return &res.Data, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *FederationClient) ReleaseRole(url, token, localDomain string, reqData RuntimeReleaseRoleRequest) error {
|
||||||
|
url = strings.TrimSuffix(url, "/")
|
||||||
|
bodyBytes, _ := json.Marshal(reqData)
|
||||||
|
req, err := http.NewRequest("POST", url+"/api/v1/federation/runtime/release-role", strings.NewReader(string(bodyBytes)))
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
req.Header.Set("Authorization", "Bearer "+token)
|
||||||
|
if localDomain != "" {
|
||||||
|
req.Header.Set("X-Panel-Domain", localDomain)
|
||||||
|
}
|
||||||
|
req.Header.Set("Content-Type", "application/json")
|
||||||
|
|
||||||
|
resp, err := c.client.Do(req)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
defer resp.Body.Close()
|
||||||
|
|
||||||
|
if resp.StatusCode != 200 {
|
||||||
|
body, _ := io.ReadAll(resp.Body)
|
||||||
|
return fmt.Errorf("remote error %d: %s", resp.StatusCode, string(body))
|
||||||
|
}
|
||||||
|
|
||||||
|
var res struct {
|
||||||
|
Code int `json:"code"`
|
||||||
|
Msg string `json:"msg"`
|
||||||
|
}
|
||||||
|
if err := json.NewDecoder(resp.Body).Decode(&res); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if res.Code != 0 {
|
||||||
|
return fmt.Errorf("remote api error: %s", res.Msg)
|
||||||
|
}
|
||||||
|
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *FederationClient) Diagnose(url, token, localDomain string, reqData RuntimeDiagnoseRequest) (map[string]interface{}, error) {
|
||||||
|
url = strings.TrimSuffix(url, "/")
|
||||||
|
bodyBytes, _ := json.Marshal(reqData)
|
||||||
|
req, err := http.NewRequest("POST", url+"/api/v1/federation/runtime/diagnose", strings.NewReader(string(bodyBytes)))
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
req.Header.Set("Authorization", "Bearer "+token)
|
||||||
|
if localDomain != "" {
|
||||||
|
req.Header.Set("X-Panel-Domain", localDomain)
|
||||||
|
}
|
||||||
|
req.Header.Set("Content-Type", "application/json")
|
||||||
|
|
||||||
|
resp, err := c.client.Do(req)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
defer resp.Body.Close()
|
||||||
|
|
||||||
|
if resp.StatusCode != 200 {
|
||||||
|
body, _ := io.ReadAll(resp.Body)
|
||||||
|
return nil, fmt.Errorf("remote error %d: %s", resp.StatusCode, string(body))
|
||||||
|
}
|
||||||
|
|
||||||
|
var res struct {
|
||||||
|
Code int `json:"code"`
|
||||||
|
Msg string `json:"msg"`
|
||||||
|
Data map[string]interface{} `json:"data"`
|
||||||
|
}
|
||||||
|
if err := json.NewDecoder(resp.Body).Decode(&res); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
if res.Code != 0 {
|
||||||
|
return nil, fmt.Errorf("remote api error: %s", res.Msg)
|
||||||
|
}
|
||||||
|
|
||||||
|
if res.Data == nil {
|
||||||
|
return nil, fmt.Errorf("remote api error: empty diagnosis payload")
|
||||||
|
}
|
||||||
|
|
||||||
|
return res.Data, nil
|
||||||
|
}
|
||||||
@@ -1,67 +0,0 @@
|
|||||||
package handler
|
|
||||||
|
|
||||||
import "time"
|
|
||||||
|
|
||||||
const captchaTokenTTL = 5 * time.Minute
|
|
||||||
|
|
||||||
func (h *Handler) storeCaptchaToken(token string) {
|
|
||||||
if h == nil {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
token = normalizeCaptchaToken(token)
|
|
||||||
if token == "" {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
h.captchaMu.Lock()
|
|
||||||
defer h.captchaMu.Unlock()
|
|
||||||
|
|
||||||
now := time.Now().UnixMilli()
|
|
||||||
h.pruneExpiredCaptchaTokensLocked(now)
|
|
||||||
h.captchaTokens[token] = now + int64(captchaTokenTTL/time.Millisecond)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (h *Handler) consumeCaptchaToken(token string) bool {
|
|
||||||
if h == nil {
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
token = normalizeCaptchaToken(token)
|
|
||||||
if token == "" {
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
|
|
||||||
h.captchaMu.Lock()
|
|
||||||
defer h.captchaMu.Unlock()
|
|
||||||
|
|
||||||
now := time.Now().UnixMilli()
|
|
||||||
h.pruneExpiredCaptchaTokensLocked(now)
|
|
||||||
expiresAt, ok := h.captchaTokens[token]
|
|
||||||
if !ok || expiresAt <= now {
|
|
||||||
delete(h.captchaTokens, token)
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
delete(h.captchaTokens, token)
|
|
||||||
return true
|
|
||||||
}
|
|
||||||
|
|
||||||
func (h *Handler) pruneExpiredCaptchaTokensLocked(now int64) {
|
|
||||||
for token, expiresAt := range h.captchaTokens {
|
|
||||||
if expiresAt <= now {
|
|
||||||
delete(h.captchaTokens, token)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func normalizeCaptchaToken(token string) string {
|
|
||||||
return trimToken(token)
|
|
||||||
}
|
|
||||||
|
|
||||||
func trimToken(token string) string {
|
|
||||||
for len(token) > 0 && (token[0] == ' ' || token[0] == '\t' || token[0] == '\n' || token[0] == '\r') {
|
|
||||||
token = token[1:]
|
|
||||||
}
|
|
||||||
for len(token) > 0 && (token[len(token)-1] == ' ' || token[len(token)-1] == '\t' || token[len(token)-1] == '\n' || token[len(token)-1] == '\r') {
|
|
||||||
token = token[:len(token)-1]
|
|
||||||
}
|
|
||||||
return token
|
|
||||||
}
|
|
||||||
@@ -11,6 +11,7 @@ import (
|
|||||||
"strings"
|
"strings"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
|
"go-backend/internal/http/client"
|
||||||
"go-backend/internal/ws"
|
"go-backend/internal/ws"
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -51,6 +52,10 @@ type nodeRecord struct {
|
|||||||
TCPListenAddr string
|
TCPListenAddr string
|
||||||
UDPListenAddr string
|
UDPListenAddr string
|
||||||
InterfaceName string
|
InterfaceName string
|
||||||
|
IsRemote int
|
||||||
|
RemoteURL string
|
||||||
|
RemoteToken string
|
||||||
|
RemoteConfig string
|
||||||
}
|
}
|
||||||
|
|
||||||
type chainNodeRecord struct {
|
type chainNodeRecord struct {
|
||||||
@@ -59,6 +64,8 @@ type chainNodeRecord struct {
|
|||||||
NodeID int64
|
NodeID int64
|
||||||
Port int
|
Port int
|
||||||
NodeName string
|
NodeName string
|
||||||
|
Protocol string
|
||||||
|
Strategy string
|
||||||
}
|
}
|
||||||
|
|
||||||
type diagnosisTarget struct {
|
type diagnosisTarget struct {
|
||||||
@@ -195,7 +202,7 @@ func (h *Handler) listForwardPorts(forwardID int64) ([]forwardPortRecord, error)
|
|||||||
|
|
||||||
func (h *Handler) getNodeRecord(nodeID int64) (*nodeRecord, error) {
|
func (h *Handler) getNodeRecord(nodeID int64) (*nodeRecord, error) {
|
||||||
row := h.repo.DB().QueryRow(`
|
row := h.repo.DB().QueryRow(`
|
||||||
SELECT id, name, server_ip, server_ip_v4, server_ip_v6, status, port, tcp_listen_addr, udp_listen_addr, interface_name
|
SELECT id, name, server_ip, server_ip_v4, server_ip_v6, status, port, tcp_listen_addr, udp_listen_addr, interface_name, is_remote, remote_url, remote_token, remote_config
|
||||||
FROM node
|
FROM node
|
||||||
WHERE id = ?
|
WHERE id = ?
|
||||||
LIMIT 1
|
LIMIT 1
|
||||||
@@ -207,7 +214,10 @@ func (h *Handler) getNodeRecord(nodeID int64) (*nodeRecord, error) {
|
|||||||
var tcpListen sql.NullString
|
var tcpListen sql.NullString
|
||||||
var udpListen sql.NullString
|
var udpListen sql.NullString
|
||||||
var iface sql.NullString
|
var iface sql.NullString
|
||||||
err := row.Scan(&n.ID, &n.Name, &n.ServerIP, &serverIPv4, &serverIPv6, &n.Status, &portRange, &tcpListen, &udpListen, &iface)
|
var remoteURL sql.NullString
|
||||||
|
var remoteToken sql.NullString
|
||||||
|
var remoteConfig sql.NullString
|
||||||
|
err := row.Scan(&n.ID, &n.Name, &n.ServerIP, &serverIPv4, &serverIPv6, &n.Status, &portRange, &tcpListen, &udpListen, &iface, &n.IsRemote, &remoteURL, &remoteToken, &remoteConfig)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
if errors.Is(err, sql.ErrNoRows) {
|
if errors.Is(err, sql.ErrNoRows) {
|
||||||
return nil, errors.New("节点不存在")
|
return nil, errors.New("节点不存在")
|
||||||
@@ -220,6 +230,9 @@ func (h *Handler) getNodeRecord(nodeID int64) (*nodeRecord, error) {
|
|||||||
n.TCPListenAddr = strings.TrimSpace(tcpListen.String)
|
n.TCPListenAddr = strings.TrimSpace(tcpListen.String)
|
||||||
n.UDPListenAddr = strings.TrimSpace(udpListen.String)
|
n.UDPListenAddr = strings.TrimSpace(udpListen.String)
|
||||||
n.InterfaceName = strings.TrimSpace(iface.String)
|
n.InterfaceName = strings.TrimSpace(iface.String)
|
||||||
|
n.RemoteURL = strings.TrimSpace(remoteURL.String)
|
||||||
|
n.RemoteToken = strings.TrimSpace(remoteToken.String)
|
||||||
|
n.RemoteConfig = strings.TrimSpace(remoteConfig.String)
|
||||||
if n.TCPListenAddr == "" {
|
if n.TCPListenAddr == "" {
|
||||||
n.TCPListenAddr = "[::]"
|
n.TCPListenAddr = "[::]"
|
||||||
}
|
}
|
||||||
@@ -232,28 +245,83 @@ func (h *Handler) getNodeRecord(nodeID int64) (*nodeRecord, error) {
|
|||||||
return &n, nil
|
return &n, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func (h *Handler) resolveUserTunnelAndLimiter(userID, tunnelID int64) (int64, *int, error) {
|
func (h *Handler) resolveUserTunnelAndLimiter(userID, tunnelID int64) (int64, *int64, *int, error) {
|
||||||
row := h.repo.DB().QueryRow(`
|
row := h.repo.DB().QueryRow(`
|
||||||
SELECT ut.id, sl.speed
|
SELECT ut.id, sl.id, sl.speed
|
||||||
FROM user_tunnel ut
|
FROM user_tunnel ut
|
||||||
LEFT JOIN speed_limit sl ON sl.id = ut.speed_id
|
LEFT JOIN speed_limit sl ON sl.id = ut.speed_id
|
||||||
WHERE ut.user_id = ? AND ut.tunnel_id = ?
|
WHERE ut.user_id = ? AND ut.tunnel_id = ?
|
||||||
|
ORDER BY ut.id ASC
|
||||||
LIMIT 1
|
LIMIT 1
|
||||||
`, userID, tunnelID)
|
`, userID, tunnelID)
|
||||||
var userTunnelID int64
|
var userTunnelID int64
|
||||||
|
var limiterID sql.NullInt64
|
||||||
var speed sql.NullInt64
|
var speed sql.NullInt64
|
||||||
err := row.Scan(&userTunnelID, &speed)
|
err := row.Scan(&userTunnelID, &limiterID, &speed)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
if errors.Is(err, sql.ErrNoRows) {
|
if errors.Is(err, sql.ErrNoRows) {
|
||||||
return 0, nil, nil
|
return 0, nil, nil, nil
|
||||||
}
|
}
|
||||||
return 0, nil, err
|
return 0, nil, nil, err
|
||||||
}
|
}
|
||||||
if !speed.Valid || speed.Int64 <= 0 {
|
if !limiterID.Valid || limiterID.Int64 <= 0 {
|
||||||
return userTunnelID, nil, nil
|
return userTunnelID, nil, nil, nil
|
||||||
}
|
}
|
||||||
v := int(speed.Int64)
|
v := limiterID.Int64
|
||||||
return userTunnelID, &v, nil
|
s := int(speed.Int64)
|
||||||
|
return userTunnelID, &v, &s, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (h *Handler) listUserTunnelIDs(userID, tunnelID int64) ([]int64, error) {
|
||||||
|
rows, err := h.repo.DB().Query(`
|
||||||
|
SELECT id
|
||||||
|
FROM user_tunnel
|
||||||
|
WHERE user_id = ? AND tunnel_id = ?
|
||||||
|
ORDER BY id ASC
|
||||||
|
`, userID, tunnelID)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
defer rows.Close()
|
||||||
|
|
||||||
|
out := make([]int64, 0)
|
||||||
|
for rows.Next() {
|
||||||
|
var id int64
|
||||||
|
if err := rows.Scan(&id); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
out = append(out, id)
|
||||||
|
}
|
||||||
|
if err := rows.Err(); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return out, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (h *Handler) listUserTunnelIDsByUser(userID int64) ([]int64, error) {
|
||||||
|
rows, err := h.repo.DB().Query(`
|
||||||
|
SELECT id
|
||||||
|
FROM user_tunnel
|
||||||
|
WHERE user_id = ?
|
||||||
|
ORDER BY id ASC
|
||||||
|
`, userID)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
defer rows.Close()
|
||||||
|
|
||||||
|
out := make([]int64, 0)
|
||||||
|
for rows.Next() {
|
||||||
|
var id int64
|
||||||
|
if err := rows.Scan(&id); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
out = append(out, id)
|
||||||
|
}
|
||||||
|
if err := rows.Err(); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return out, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func (h *Handler) syncForwardServices(forward *forwardRecord, method string, allowFallbackAdd bool) error {
|
func (h *Handler) syncForwardServices(forward *forwardRecord, method string, allowFallbackAdd bool) error {
|
||||||
@@ -273,18 +341,22 @@ func (h *Handler) syncForwardServices(forward *forwardRecord, method string, all
|
|||||||
return errors.New("转发入口端口不存在")
|
return errors.New("转发入口端口不存在")
|
||||||
}
|
}
|
||||||
|
|
||||||
userTunnelID, limiter, err := h.resolveUserTunnelAndLimiter(forward.UserID, forward.TunnelID)
|
userTunnelID, limiterID, speed, err := h.resolveUserTunnelAndLimiter(forward.UserID, forward.TunnelID)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
serviceBase := buildForwardServiceBase(forward.ID, forward.UserID, userTunnelID)
|
serviceBase := buildForwardServiceBase(forward.ID, forward.UserID, userTunnelID)
|
||||||
|
|
||||||
for _, fp := range ports {
|
for _, fp := range ports {
|
||||||
|
if limiterID != nil && speed != nil {
|
||||||
|
h.ensureLimiterOnNode(fp.NodeID, *limiterID, *speed)
|
||||||
|
}
|
||||||
|
|
||||||
node, err := h.getNodeRecord(fp.NodeID)
|
node, err := h.getNodeRecord(fp.NodeID)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
services := buildForwardServiceConfigs(serviceBase, forward, tunnel, node, fp.Port, limiter)
|
services := buildForwardServiceConfigs(serviceBase, forward, tunnel, node, fp.Port, limiterID)
|
||||||
_, err = h.sendNodeCommand(node.ID, method, services, true, false)
|
_, err = h.sendNodeCommand(node.ID, method, services, true, false)
|
||||||
if err != nil && allowFallbackAdd && method == "UpdateService" {
|
if err != nil && allowFallbackAdd && method == "UpdateService" {
|
||||||
_, err = h.sendNodeCommand(node.ID, "AddService", services, true, false)
|
_, err = h.sendNodeCommand(node.ID, "AddService", services, true, false)
|
||||||
@@ -307,24 +379,70 @@ func (h *Handler) controlForwardServices(forward *forwardRecord, commandType str
|
|||||||
if len(ports) == 0 {
|
if len(ports) == 0 {
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
userTunnelID, _, err := h.resolveUserTunnelAndLimiter(forward.UserID, forward.TunnelID)
|
userTunnelID, _, _, err := h.resolveUserTunnelAndLimiter(forward.UserID, forward.TunnelID)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
base := buildForwardServiceBase(forward.ID, forward.UserID, userTunnelID)
|
userTunnelIDs, err := h.listUserTunnelIDs(forward.UserID, forward.TunnelID)
|
||||||
payload := map[string]interface{}{
|
if err != nil {
|
||||||
"services": buildForwardControlServiceNames(base, commandType),
|
return err
|
||||||
}
|
}
|
||||||
|
allUserTunnelIDs, err := h.listUserTunnelIDsByUser(forward.UserID)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
candidateTunnelIDs := make([]int64, 0, len(userTunnelIDs)+len(allUserTunnelIDs))
|
||||||
|
candidateTunnelIDs = append(candidateTunnelIDs, userTunnelIDs...)
|
||||||
|
candidateTunnelIDs = append(candidateTunnelIDs, allUserTunnelIDs...)
|
||||||
|
bases := buildForwardServiceBaseCandidates(forward.ID, forward.UserID, userTunnelID, candidateTunnelIDs)
|
||||||
seen := map[int64]struct{}{}
|
seen := map[int64]struct{}{}
|
||||||
for _, fp := range ports {
|
for _, fp := range ports {
|
||||||
if _, ok := seen[fp.NodeID]; ok {
|
if _, ok := seen[fp.NodeID]; ok {
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
seen[fp.NodeID] = struct{}{}
|
seen[fp.NodeID] = struct{}{}
|
||||||
_, err := h.sendNodeCommand(fp.NodeID, commandType, payload, false, tolerateNotFound)
|
|
||||||
if err != nil {
|
var lastNotFoundErr error
|
||||||
return err
|
nodeHandled := false
|
||||||
|
|
||||||
|
for _, base := range bases {
|
||||||
|
variants := []string{base + "_tcp", base + "_udp"}
|
||||||
|
if shouldTryLegacySingleService(commandType) || strings.EqualFold(strings.TrimSpace(commandType), "DeleteService") {
|
||||||
|
variants = append(variants, base)
|
||||||
|
}
|
||||||
|
|
||||||
|
candidateHandled := false
|
||||||
|
for _, name := range variants {
|
||||||
|
payload := map[string]interface{}{
|
||||||
|
"services": []string{name},
|
||||||
|
}
|
||||||
|
_, err := h.sendNodeCommand(fp.NodeID, commandType, payload, false, false)
|
||||||
|
if err == nil {
|
||||||
|
candidateHandled = true
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if !isNotFoundError(err) {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
lastNotFoundErr = err
|
||||||
|
}
|
||||||
|
|
||||||
|
if candidateHandled {
|
||||||
|
nodeHandled = true
|
||||||
|
break
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if nodeHandled {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if tolerateNotFound {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if lastNotFoundErr != nil {
|
||||||
|
return lastNotFoundErr
|
||||||
|
}
|
||||||
|
return errors.New("service control failed")
|
||||||
}
|
}
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
@@ -674,7 +792,15 @@ func (h *Handler) appendPathDiagnosis(results *[]map[string]interface{}, nodeCac
|
|||||||
}
|
}
|
||||||
item["nodeName"] = fromNode.Name
|
item["nodeName"] = fromNode.Name
|
||||||
|
|
||||||
pingData, pingErr := h.tcpPingViaNode(fromNodeID, targetIP, targetPort)
|
var (
|
||||||
|
pingData map[string]interface{}
|
||||||
|
pingErr error
|
||||||
|
)
|
||||||
|
if fromNode.IsRemote == 1 {
|
||||||
|
pingData, pingErr = h.tcpPingViaRemoteNode(fromNode, targetIP, targetPort)
|
||||||
|
} else {
|
||||||
|
pingData, pingErr = h.tcpPingViaNode(fromNodeID, targetIP, targetPort)
|
||||||
|
}
|
||||||
if pingErr != nil {
|
if pingErr != nil {
|
||||||
item["success"] = false
|
item["success"] = false
|
||||||
item["message"] = pingErr.Error()
|
item["message"] = pingErr.Error()
|
||||||
@@ -763,7 +889,7 @@ func firstPortFromRange(portRange string) int {
|
|||||||
|
|
||||||
func (h *Handler) listChainNodesForTunnel(tunnelID int64) ([]chainNodeRecord, error) {
|
func (h *Handler) listChainNodesForTunnel(tunnelID int64) ([]chainNodeRecord, error) {
|
||||||
rows, err := h.repo.DB().Query(`
|
rows, err := h.repo.DB().Query(`
|
||||||
SELECT ct.chain_type, COALESCE(ct.inx, 0), ct.node_id, COALESCE(ct.port, 0), n.name
|
SELECT ct.chain_type, COALESCE(ct.inx, 0), ct.node_id, COALESCE(ct.port, 0), n.name, ct.protocol, ct.strategy
|
||||||
FROM chain_tunnel ct
|
FROM chain_tunnel ct
|
||||||
LEFT JOIN node n ON n.id = ct.node_id
|
LEFT JOIN node n ON n.id = ct.node_id
|
||||||
WHERE ct.tunnel_id = ?
|
WHERE ct.tunnel_id = ?
|
||||||
@@ -778,7 +904,9 @@ func (h *Handler) listChainNodesForTunnel(tunnelID int64) ([]chainNodeRecord, er
|
|||||||
for rows.Next() {
|
for rows.Next() {
|
||||||
var item chainNodeRecord
|
var item chainNodeRecord
|
||||||
var name sql.NullString
|
var name sql.NullString
|
||||||
if err := rows.Scan(&item.ChainType, &item.Inx, &item.NodeID, &item.Port, &name); err != nil {
|
var protocol sql.NullString
|
||||||
|
var strategy sql.NullString
|
||||||
|
if err := rows.Scan(&item.ChainType, &item.Inx, &item.NodeID, &item.Port, &name, &protocol, &strategy); err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
if strings.TrimSpace(name.String) == "" {
|
if strings.TrimSpace(name.String) == "" {
|
||||||
@@ -786,6 +914,8 @@ func (h *Handler) listChainNodesForTunnel(tunnelID int64) ([]chainNodeRecord, er
|
|||||||
} else {
|
} else {
|
||||||
item.NodeName = name.String
|
item.NodeName = name.String
|
||||||
}
|
}
|
||||||
|
item.Protocol = defaultString(protocol.String, "tls")
|
||||||
|
item.Strategy = defaultString(strategy.String, "round")
|
||||||
result = append(result, item)
|
result = append(result, item)
|
||||||
}
|
}
|
||||||
if err := rows.Err(); err != nil {
|
if err := rows.Err(); err != nil {
|
||||||
@@ -810,6 +940,25 @@ func (h *Handler) tcpPingViaNode(nodeID int64, ip string, port int) (map[string]
|
|||||||
return res.Data, nil
|
return res.Data, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func (h *Handler) tcpPingViaRemoteNode(node *nodeRecord, ip string, port int) (map[string]interface{}, error) {
|
||||||
|
if node == nil {
|
||||||
|
return nil, errors.New("节点不存在")
|
||||||
|
}
|
||||||
|
remoteURL := strings.TrimSpace(node.RemoteURL)
|
||||||
|
remoteToken := strings.TrimSpace(node.RemoteToken)
|
||||||
|
if remoteURL == "" || remoteToken == "" {
|
||||||
|
return nil, errors.New("远程节点缺少共享配置")
|
||||||
|
}
|
||||||
|
|
||||||
|
fc := client.NewFederationClient()
|
||||||
|
return fc.Diagnose(remoteURL, remoteToken, h.federationLocalDomain(), client.RuntimeDiagnoseRequest{
|
||||||
|
IP: strings.TrimSpace(ip),
|
||||||
|
Port: port,
|
||||||
|
Count: 4,
|
||||||
|
Timeout: 5000,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
func splitRemoteTargets(remoteAddr string) []string {
|
func splitRemoteTargets(remoteAddr string) []string {
|
||||||
parts := strings.Split(remoteAddr, ",")
|
parts := strings.Split(remoteAddr, ",")
|
||||||
out := make([]string, 0, len(parts))
|
out := make([]string, 0, len(parts))
|
||||||
@@ -852,6 +1001,31 @@ func buildForwardServiceBase(forwardID, userID, userTunnelID int64) string {
|
|||||||
return fmt.Sprintf("%d_%d_%d", forwardID, userID, userTunnelID)
|
return fmt.Sprintf("%d_%d_%d", forwardID, userID, userTunnelID)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func buildForwardServiceBaseCandidates(forwardID, userID, preferredUserTunnelID int64, userTunnelIDs []int64) []string {
|
||||||
|
orderedIDs := make([]int64, 0, len(userTunnelIDs)+2)
|
||||||
|
seen := make(map[int64]struct{}, len(userTunnelIDs)+2)
|
||||||
|
|
||||||
|
appendID := func(id int64) {
|
||||||
|
if _, ok := seen[id]; ok {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
seen[id] = struct{}{}
|
||||||
|
orderedIDs = append(orderedIDs, id)
|
||||||
|
}
|
||||||
|
|
||||||
|
appendID(preferredUserTunnelID)
|
||||||
|
for _, id := range userTunnelIDs {
|
||||||
|
appendID(id)
|
||||||
|
}
|
||||||
|
appendID(0)
|
||||||
|
|
||||||
|
bases := make([]string, 0, len(orderedIDs))
|
||||||
|
for _, id := range orderedIDs {
|
||||||
|
bases = append(bases, buildForwardServiceBase(forwardID, userID, id))
|
||||||
|
}
|
||||||
|
return bases
|
||||||
|
}
|
||||||
|
|
||||||
func buildForwardControlServiceNames(base, commandType string) []string {
|
func buildForwardControlServiceNames(base, commandType string) []string {
|
||||||
names := []string{base + "_tcp", base + "_udp"}
|
names := []string{base + "_tcp", base + "_udp"}
|
||||||
if strings.EqualFold(strings.TrimSpace(commandType), "DeleteService") {
|
if strings.EqualFold(strings.TrimSpace(commandType), "DeleteService") {
|
||||||
@@ -860,7 +1034,20 @@ func buildForwardControlServiceNames(base, commandType string) []string {
|
|||||||
return names
|
return names
|
||||||
}
|
}
|
||||||
|
|
||||||
func buildForwardServiceConfigs(baseName string, forward *forwardRecord, tunnel *tunnelRecord, node *nodeRecord, port int, limiter *int) []map[string]interface{} {
|
func shouldTryLegacySingleService(commandType string) bool {
|
||||||
|
cmd := strings.ToLower(strings.TrimSpace(commandType))
|
||||||
|
return cmd == "pauseservice" || cmd == "resumeservice"
|
||||||
|
}
|
||||||
|
|
||||||
|
func isNotFoundError(err error) bool {
|
||||||
|
if err == nil {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
msg := strings.ToLower(strings.TrimSpace(err.Error()))
|
||||||
|
return strings.Contains(msg, "not found") || strings.Contains(msg, "不存在")
|
||||||
|
}
|
||||||
|
|
||||||
|
func buildForwardServiceConfigs(baseName string, forward *forwardRecord, tunnel *tunnelRecord, node *nodeRecord, port int, limiterID *int64) []map[string]interface{} {
|
||||||
protocols := []string{"tcp", "udp"}
|
protocols := []string{"tcp", "udp"}
|
||||||
services := make([]map[string]interface{}, 0, 2)
|
services := make([]map[string]interface{}, 0, 2)
|
||||||
targets := splitRemoteTargets(forward.RemoteAddr)
|
targets := splitRemoteTargets(forward.RemoteAddr)
|
||||||
@@ -901,8 +1088,8 @@ func buildForwardServiceConfigs(baseName string, forward *forwardRecord, tunnel
|
|||||||
if tunnel != nil && tunnel.Type == 1 && strings.TrimSpace(node.InterfaceName) != "" {
|
if tunnel != nil && tunnel.Type == 1 && strings.TrimSpace(node.InterfaceName) != "" {
|
||||||
service["metadata"] = map[string]interface{}{"interface": node.InterfaceName}
|
service["metadata"] = map[string]interface{}{"interface": node.InterfaceName}
|
||||||
}
|
}
|
||||||
if limiter != nil && *limiter > 0 {
|
if limiterID != nil && *limiterID > 0 {
|
||||||
service["limiter"] = strconv.Itoa(*limiter)
|
service["limiter"] = strconv.FormatInt(*limiterID, 10)
|
||||||
}
|
}
|
||||||
services = append(services, service)
|
services = append(services, service)
|
||||||
}
|
}
|
||||||
@@ -965,3 +1152,49 @@ func asBool(v interface{}, def bool) bool {
|
|||||||
return def
|
return def
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func (h *Handler) sendLimiterConfig(limiterID int64, speedMbps int, tunnelID int64) error {
|
||||||
|
rate := float64(speedMbps) / 8.0
|
||||||
|
limitStr := fmt.Sprintf("$ %.1fMB %.1fMB", rate, rate)
|
||||||
|
|
||||||
|
payload := map[string]interface{}{
|
||||||
|
"name": strconv.FormatInt(limiterID, 10),
|
||||||
|
"limits": []string{limitStr},
|
||||||
|
}
|
||||||
|
|
||||||
|
nodes, err := h.tunnelEntryNodeIDs(tunnelID)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, nodeID := range nodes {
|
||||||
|
_, _ = h.sendNodeCommand(nodeID, "AddLimiters", payload, false, false)
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (h *Handler) sendDeleteLimiterConfig(limiterID int64, tunnelID int64) error {
|
||||||
|
payload := map[string]interface{}{
|
||||||
|
"limiter": strconv.FormatInt(limiterID, 10),
|
||||||
|
}
|
||||||
|
|
||||||
|
nodes, err := h.tunnelEntryNodeIDs(tunnelID)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, nodeID := range nodes {
|
||||||
|
_, _ = h.sendNodeCommand(nodeID, "DeleteLimiters", payload, false, true)
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (h *Handler) ensureLimiterOnNode(nodeID int64, limiterID int64, speed int) {
|
||||||
|
rate := float64(speed) / 8.0
|
||||||
|
limitStr := fmt.Sprintf("$ %.1fMB %.1fMB", rate, rate)
|
||||||
|
payload := map[string]interface{}{
|
||||||
|
"name": strconv.FormatInt(limiterID, 10),
|
||||||
|
"limits": []string{limitStr},
|
||||||
|
}
|
||||||
|
_, _ = h.sendNodeCommand(nodeID, "AddLimiters", payload, false, false)
|
||||||
|
}
|
||||||
|
|||||||
@@ -25,3 +25,31 @@ func TestBuildForwardControlServiceNamesDelete(t *testing.T) {
|
|||||||
t.Fatalf("expected %v, got %v", want, got)
|
t.Fatalf("expected %v, got %v", want, got)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TestBuildForwardServiceBaseCandidates(t *testing.T) {
|
||||||
|
got := buildForwardServiceBaseCandidates(12, 34, 56, []int64{56, 78, 90})
|
||||||
|
want := []string{"12_34_56", "12_34_78", "12_34_90", "12_34_0"}
|
||||||
|
if !reflect.DeepEqual(got, want) {
|
||||||
|
t.Fatalf("expected %v, got %v", want, got)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestBuildForwardServiceBaseCandidatesWithZeroPreferred(t *testing.T) {
|
||||||
|
got := buildForwardServiceBaseCandidates(12, 34, 0, []int64{78, 0, 90})
|
||||||
|
want := []string{"12_34_0", "12_34_78", "12_34_90"}
|
||||||
|
if !reflect.DeepEqual(got, want) {
|
||||||
|
t.Fatalf("expected %v, got %v", want, got)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestShouldTryLegacySingleService(t *testing.T) {
|
||||||
|
if !shouldTryLegacySingleService("PauseService") {
|
||||||
|
t.Fatalf("PauseService should require legacy fallback")
|
||||||
|
}
|
||||||
|
if !shouldTryLegacySingleService("resumeService") {
|
||||||
|
t.Fatalf("ResumeService should require legacy fallback")
|
||||||
|
}
|
||||||
|
if shouldTryLegacySingleService("DeleteService") {
|
||||||
|
t.Fatalf("DeleteService should not require legacy fallback")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
@@ -0,0 +1,210 @@
|
|||||||
|
package handler
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bytes"
|
||||||
|
"encoding/json"
|
||||||
|
"net/http"
|
||||||
|
"net/http/httptest"
|
||||||
|
"path/filepath"
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"go-backend/internal/http/response"
|
||||||
|
"go-backend/internal/store/sqlite"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestPickPeerSharePortUsesRuntimeReservations(t *testing.T) {
|
||||||
|
repo, err := sqlite.Open(filepath.Join(t.TempDir(), "panel.db"))
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("open repo: %v", err)
|
||||||
|
}
|
||||||
|
defer repo.Close()
|
||||||
|
|
||||||
|
h := &Handler{repo: repo}
|
||||||
|
now := time.Now().UnixMilli()
|
||||||
|
|
||||||
|
if _, err := repo.DB().Exec(`INSERT INTO chain_tunnel(tunnel_id, chain_type, node_id, port, strategy, inx, protocol) VALUES(?, ?, ?, ?, ?, ?, ?)`, 1, 2, 1, 3000, "round", 1, "tls"); err != nil {
|
||||||
|
t.Fatalf("insert chain_tunnel: %v", err)
|
||||||
|
}
|
||||||
|
if _, err := repo.DB().Exec(`INSERT INTO forward_port(forward_id, node_id, port) VALUES(?, ?, ?)`, 1, 1, 3001); err != nil {
|
||||||
|
t.Fatalf("insert forward_port: %v", err)
|
||||||
|
}
|
||||||
|
if _, err := repo.DB().Exec(`
|
||||||
|
INSERT INTO peer_share_runtime(share_id, node_id, reservation_id, resource_key, binding_id, role, chain_name, service_name, protocol, strategy, port, target, applied, status, created_time, updated_time)
|
||||||
|
VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
||||||
|
`, 77, 1, "res-1", "rk-1", "b-1", "exit", "", "fed_svc_1", "tls", "round", 3002, "", 1, 1, now, now); err != nil {
|
||||||
|
t.Fatalf("insert peer_share_runtime: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
share := &sqlite.PeerShare{
|
||||||
|
ID: 77,
|
||||||
|
NodeID: 1,
|
||||||
|
PortRangeStart: 3000,
|
||||||
|
PortRangeEnd: 3004,
|
||||||
|
}
|
||||||
|
|
||||||
|
port, err := h.pickPeerSharePort(share, 0)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("pick auto port: %v", err)
|
||||||
|
}
|
||||||
|
if port != 3003 {
|
||||||
|
t.Fatalf("expected port 3003, got %d", port)
|
||||||
|
}
|
||||||
|
|
||||||
|
if _, err := h.pickPeerSharePort(share, 3001); err == nil {
|
||||||
|
t.Fatalf("expected requested busy port to fail")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestApplyTunnelRuntimeSkipsRemoteNodes(t *testing.T) {
|
||||||
|
h := &Handler{}
|
||||||
|
state := &tunnelCreateState{
|
||||||
|
TunnelID: 1,
|
||||||
|
Type: 2,
|
||||||
|
InNodes: []tunnelRuntimeNode{
|
||||||
|
{NodeID: 11, ChainType: 1, Protocol: "tls"},
|
||||||
|
},
|
||||||
|
ChainHops: [][]tunnelRuntimeNode{
|
||||||
|
{
|
||||||
|
{NodeID: 12, ChainType: 2, Inx: 1, Port: 41000, Protocol: "tls", Strategy: "round"},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
OutNodes: []tunnelRuntimeNode{
|
||||||
|
{NodeID: 13, ChainType: 3, Port: 42000, Protocol: "tls", Strategy: "round"},
|
||||||
|
},
|
||||||
|
Nodes: map[int64]*nodeRecord{
|
||||||
|
11: {ID: 11, Name: "remote-in", IsRemote: 1},
|
||||||
|
12: {ID: 12, Name: "remote-chain", IsRemote: 1},
|
||||||
|
13: {ID: 13, Name: "remote-out", IsRemote: 1},
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
chains, services, err := h.applyTunnelRuntime(state)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("apply runtime: %v", err)
|
||||||
|
}
|
||||||
|
if len(chains) != 0 {
|
||||||
|
t.Fatalf("expected no local chains created, got %d", len(chains))
|
||||||
|
}
|
||||||
|
if len(services) != 0 {
|
||||||
|
t.Fatalf("expected no local services created, got %d", len(services))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestPrepareTunnelCreateStateRemoteAutoPortDefersToFederation(t *testing.T) {
|
||||||
|
repo, err := sqlite.Open(filepath.Join(t.TempDir(), "panel.db"))
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("open repo: %v", err)
|
||||||
|
}
|
||||||
|
defer repo.Close()
|
||||||
|
|
||||||
|
h := &Handler{repo: repo}
|
||||||
|
now := time.Now().UnixMilli()
|
||||||
|
|
||||||
|
insertNode := func(name string, status int, portRange string, isRemote int) int64 {
|
||||||
|
res, execErr := repo.DB().Exec(`
|
||||||
|
INSERT INTO node(name, secret, server_ip, server_ip_v4, server_ip_v6, port, interface_name, version, http, tls, socks, created_time, updated_time, status, tcp_listen_addr, udp_listen_addr, inx, is_remote, remote_url, remote_token, remote_config)
|
||||||
|
VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
||||||
|
`, name, name+"-secret", "10.0.0.1", "10.0.0.1", "", portRange, "", "v1", 1, 1, 1, now, now, status, "[::]", "[::]", 0, isRemote, "http://peer", "peer-token", `{"shareId":1}`)
|
||||||
|
if execErr != nil {
|
||||||
|
t.Fatalf("insert node %s: %v", name, execErr)
|
||||||
|
}
|
||||||
|
id, idErr := res.LastInsertId()
|
||||||
|
if idErr != nil {
|
||||||
|
t.Fatalf("node id %s: %v", name, idErr)
|
||||||
|
}
|
||||||
|
return id
|
||||||
|
}
|
||||||
|
|
||||||
|
entryID := insertNode("entry", 1, "31000-31010", 0)
|
||||||
|
remoteOutID := insertNode("remote-out", 1, "30000", 1)
|
||||||
|
|
||||||
|
if _, err := repo.DB().Exec(`INSERT INTO forward_port(forward_id, node_id, port) VALUES(?, ?, ?)`, 1, remoteOutID, 30000); err != nil {
|
||||||
|
t.Fatalf("insert forward_port: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
tx, err := repo.DB().Begin()
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("begin tx: %v", err)
|
||||||
|
}
|
||||||
|
defer tx.Rollback()
|
||||||
|
|
||||||
|
req := map[string]interface{}{
|
||||||
|
"name": "test-tunnel",
|
||||||
|
"inNodeId": []interface{}{
|
||||||
|
map[string]interface{}{"nodeId": float64(entryID), "protocol": "tls", "strategy": "round"},
|
||||||
|
},
|
||||||
|
"outNodeId": []interface{}{
|
||||||
|
map[string]interface{}{"nodeId": float64(remoteOutID), "protocol": "tls", "strategy": "round", "port": float64(0)},
|
||||||
|
},
|
||||||
|
"chainNodes": []interface{}{},
|
||||||
|
}
|
||||||
|
|
||||||
|
state, err := h.prepareTunnelCreateState(tx, req, 2, 0)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("prepare state should not fail for remote auto-port: %v", err)
|
||||||
|
}
|
||||||
|
if len(state.OutNodes) != 1 {
|
||||||
|
t.Fatalf("expected 1 out node, got %d", len(state.OutNodes))
|
||||||
|
}
|
||||||
|
if state.OutNodes[0].Port != 0 {
|
||||||
|
t.Fatalf("expected remote out port to remain 0 before federation reserve, got %d", state.OutNodes[0].Port)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestFederationRuntimeReservePortRejectsWhenShareFlowExceeded(t *testing.T) {
|
||||||
|
repo, err := sqlite.Open(filepath.Join(t.TempDir(), "panel.db"))
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("open repo: %v", err)
|
||||||
|
}
|
||||||
|
defer repo.Close()
|
||||||
|
|
||||||
|
h := &Handler{repo: repo}
|
||||||
|
now := time.Now().UnixMilli()
|
||||||
|
|
||||||
|
if err := repo.CreatePeerShare(&sqlite.PeerShare{
|
||||||
|
Name: "limited-share",
|
||||||
|
NodeID: 1,
|
||||||
|
Token: "limited-token",
|
||||||
|
MaxBandwidth: 2048,
|
||||||
|
CurrentFlow: 2048,
|
||||||
|
PortRangeStart: 30000,
|
||||||
|
PortRangeEnd: 30010,
|
||||||
|
IsActive: 1,
|
||||||
|
CreatedTime: now,
|
||||||
|
UpdatedTime: now,
|
||||||
|
}); err != nil {
|
||||||
|
t.Fatalf("create share: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
body, err := json.Marshal(map[string]interface{}{
|
||||||
|
"resourceKey": "tunnel:1:node:1:type:3:hop:0",
|
||||||
|
"protocol": "tls",
|
||||||
|
"requestedPort": 0,
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("marshal request: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
req := httptest.NewRequest(http.MethodPost, "/api/v1/federation/runtime/reserve-port", bytes.NewReader(body))
|
||||||
|
req.Header.Set("Authorization", "Bearer limited-token")
|
||||||
|
req.Header.Set("Content-Type", "application/json")
|
||||||
|
res := httptest.NewRecorder()
|
||||||
|
|
||||||
|
h.federationRuntimeReservePort(res, req)
|
||||||
|
|
||||||
|
if res.Code != http.StatusOK {
|
||||||
|
t.Fatalf("expected status %d, got %d", http.StatusOK, res.Code)
|
||||||
|
}
|
||||||
|
|
||||||
|
var payload response.R
|
||||||
|
if err := json.NewDecoder(res.Body).Decode(&payload); err != nil {
|
||||||
|
t.Fatalf("decode response: %v", err)
|
||||||
|
}
|
||||||
|
if payload.Code != 403 {
|
||||||
|
t.Fatalf("expected response code 403, got %d (%s)", payload.Code, payload.Msg)
|
||||||
|
}
|
||||||
|
if payload.Msg != "Share traffic limit exceeded" {
|
||||||
|
t.Fatalf("unexpected response message: %q", payload.Msg)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,637 @@
|
|||||||
|
package handler
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bytes"
|
||||||
|
"encoding/json"
|
||||||
|
"fmt"
|
||||||
|
"net/http"
|
||||||
|
"net/http/httptest"
|
||||||
|
"path/filepath"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"go-backend/internal/http/response"
|
||||||
|
"go-backend/internal/store/sqlite"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestFederationShareCreateRejectsRemoteNode(t *testing.T) {
|
||||||
|
repo, err := sqlite.Open(filepath.Join(t.TempDir(), "panel.db"))
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("open sqlite: %v", err)
|
||||||
|
}
|
||||||
|
t.Cleanup(func() { _ = repo.Close() })
|
||||||
|
|
||||||
|
h := New(repo, "test-jwt-secret")
|
||||||
|
now := time.Now().UnixMilli()
|
||||||
|
|
||||||
|
insertRes, err := repo.DB().Exec(`
|
||||||
|
INSERT INTO node(name, secret, server_ip, server_ip_v4, server_ip_v6, port, interface_name, version, http, tls, socks, created_time, updated_time, status, tcp_listen_addr, udp_listen_addr, inx, is_remote, remote_url, remote_token, remote_config)
|
||||||
|
VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
||||||
|
`, "remote-share-node", "remote-share-secret", "10.10.10.1", "10.10.10.1", "", "20000-20010", "", "v1", 1, 1, 1, now, now, 1, "[::]", "[::]", 0, 1, "http://peer.example", "peer-token", `{"shareId":1}`)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("insert remote node: %v", err)
|
||||||
|
}
|
||||||
|
remoteNodeID, err := insertRes.LastInsertId()
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("get remote node id: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
body, err := json.Marshal(createPeerShareRequest{
|
||||||
|
Name: "remote-node-share",
|
||||||
|
NodeID: remoteNodeID,
|
||||||
|
MaxBandwidth: 0,
|
||||||
|
ExpiryTime: 0,
|
||||||
|
PortRangeStart: 20000,
|
||||||
|
PortRangeEnd: 20010,
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("marshal request: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
req := httptest.NewRequest(http.MethodPost, "/api/v1/federation/share/create", bytes.NewReader(body))
|
||||||
|
req.Header.Set("Content-Type", "application/json")
|
||||||
|
res := httptest.NewRecorder()
|
||||||
|
|
||||||
|
h.federationShareCreate(res, req)
|
||||||
|
|
||||||
|
if res.Code != http.StatusOK {
|
||||||
|
t.Fatalf("expected status %d, got %d", http.StatusOK, res.Code)
|
||||||
|
}
|
||||||
|
|
||||||
|
var payload response.R
|
||||||
|
if err := json.NewDecoder(res.Body).Decode(&payload); err != nil {
|
||||||
|
t.Fatalf("decode response: %v", err)
|
||||||
|
}
|
||||||
|
if payload.Code != -1 {
|
||||||
|
t.Fatalf("expected response code -1, got %d", payload.Code)
|
||||||
|
}
|
||||||
|
if payload.Msg != "Only local nodes can be shared" {
|
||||||
|
t.Fatalf("expected rejection message %q, got %q", "Only local nodes can be shared", payload.Msg)
|
||||||
|
}
|
||||||
|
|
||||||
|
var shareCount int
|
||||||
|
if err := repo.DB().QueryRow(`SELECT COUNT(1) FROM peer_share WHERE node_id = ?`, remoteNodeID).Scan(&shareCount); err != nil {
|
||||||
|
t.Fatalf("query peer_share count: %v", err)
|
||||||
|
}
|
||||||
|
if shareCount != 0 {
|
||||||
|
t.Fatalf("expected no share rows for remote node, got %d", shareCount)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestFederationShareCreateRejectsInvalidAllowedIPs(t *testing.T) {
|
||||||
|
repo, err := sqlite.Open(filepath.Join(t.TempDir(), "panel.db"))
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("open sqlite: %v", err)
|
||||||
|
}
|
||||||
|
t.Cleanup(func() { _ = repo.Close() })
|
||||||
|
|
||||||
|
h := New(repo, "test-jwt-secret")
|
||||||
|
now := time.Now().UnixMilli()
|
||||||
|
|
||||||
|
insertRes, err := repo.DB().Exec(`
|
||||||
|
INSERT INTO node(name, secret, server_ip, server_ip_v4, server_ip_v6, port, interface_name, version, http, tls, socks, created_time, updated_time, status, tcp_listen_addr, udp_listen_addr, inx, is_remote, remote_url, remote_token, remote_config)
|
||||||
|
VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
||||||
|
`, "local-share-node", "local-share-secret", "10.20.30.40", "10.20.30.40", "", "21000-21010", "", "v1", 1, 1, 1, now, now, 1, "[::]", "[::]", 0, 0, "", "", "")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("insert local node: %v", err)
|
||||||
|
}
|
||||||
|
localNodeID, err := insertRes.LastInsertId()
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("get local node id: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
body, err := json.Marshal(createPeerShareRequest{
|
||||||
|
Name: "local-node-share",
|
||||||
|
NodeID: localNodeID,
|
||||||
|
MaxBandwidth: 0,
|
||||||
|
ExpiryTime: 0,
|
||||||
|
PortRangeStart: 21000,
|
||||||
|
PortRangeEnd: 21010,
|
||||||
|
AllowedIPs: "bad-ip-entry",
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("marshal request: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
req := httptest.NewRequest(http.MethodPost, "/api/v1/federation/share/create", bytes.NewReader(body))
|
||||||
|
req.Header.Set("Content-Type", "application/json")
|
||||||
|
res := httptest.NewRecorder()
|
||||||
|
|
||||||
|
h.federationShareCreate(res, req)
|
||||||
|
|
||||||
|
if res.Code != http.StatusOK {
|
||||||
|
t.Fatalf("expected status %d, got %d", http.StatusOK, res.Code)
|
||||||
|
}
|
||||||
|
|
||||||
|
var payload response.R
|
||||||
|
if err := json.NewDecoder(res.Body).Decode(&payload); err != nil {
|
||||||
|
t.Fatalf("decode response: %v", err)
|
||||||
|
}
|
||||||
|
if payload.Code != -1 {
|
||||||
|
t.Fatalf("expected response code -1, got %d", payload.Code)
|
||||||
|
}
|
||||||
|
if !strings.Contains(payload.Msg, "Invalid allowed IP or CIDR") {
|
||||||
|
t.Fatalf("expected invalid IP message, got %q", payload.Msg)
|
||||||
|
}
|
||||||
|
|
||||||
|
var shareCount int
|
||||||
|
if err := repo.DB().QueryRow(`SELECT COUNT(1) FROM peer_share WHERE node_id = ?`, localNodeID).Scan(&shareCount); err != nil {
|
||||||
|
t.Fatalf("query peer_share count: %v", err)
|
||||||
|
}
|
||||||
|
if shareCount != 0 {
|
||||||
|
t.Fatalf("expected no share rows for node, got %d", shareCount)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestFederationShareListIncludesRemoteUsedPorts(t *testing.T) {
|
||||||
|
repo, err := sqlite.Open(filepath.Join(t.TempDir(), "panel.db"))
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("open sqlite: %v", err)
|
||||||
|
}
|
||||||
|
t.Cleanup(func() { _ = repo.Close() })
|
||||||
|
|
||||||
|
h := New(repo, "test-jwt-secret")
|
||||||
|
now := time.Now().UnixMilli()
|
||||||
|
|
||||||
|
if err := repo.CreatePeerShare(&sqlite.PeerShare{
|
||||||
|
Name: "provider-share",
|
||||||
|
NodeID: 9,
|
||||||
|
Token: "share-list-token",
|
||||||
|
MaxBandwidth: 1024,
|
||||||
|
CurrentFlow: 512,
|
||||||
|
PortRangeStart: 22000,
|
||||||
|
PortRangeEnd: 22010,
|
||||||
|
IsActive: 1,
|
||||||
|
CreatedTime: now,
|
||||||
|
UpdatedTime: now,
|
||||||
|
}); err != nil {
|
||||||
|
t.Fatalf("create peer share: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
share, err := repo.GetPeerShareByToken("share-list-token")
|
||||||
|
if err != nil || share == nil {
|
||||||
|
t.Fatalf("load peer share: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
if _, err := repo.DB().Exec(`
|
||||||
|
INSERT INTO peer_share_runtime(share_id, node_id, reservation_id, resource_key, binding_id, role, chain_name, service_name, protocol, strategy, port, target, applied, status, created_time, updated_time)
|
||||||
|
VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?),
|
||||||
|
(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?),
|
||||||
|
(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
||||||
|
`,
|
||||||
|
share.ID, share.NodeID, "r-1", "rk-1", "b-1", "middle", "fed_chain_1", "fed_svc_1", "tls", "round", 22001, "", 1, 1, now, now,
|
||||||
|
share.ID, share.NodeID, "r-2", "rk-2", "b-2", "exit", "", "fed_svc_2", "tls", "round", 22002, "", 1, 1, now, now,
|
||||||
|
share.ID, share.NodeID, "r-3", "rk-3", "", "", "", "", "tls", "round", 22003, "", 0, 0, now, now,
|
||||||
|
); err != nil {
|
||||||
|
t.Fatalf("insert peer_share_runtime rows: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
req := httptest.NewRequest(http.MethodPost, "/api/v1/federation/share/list", nil)
|
||||||
|
res := httptest.NewRecorder()
|
||||||
|
h.federationShareList(res, req)
|
||||||
|
|
||||||
|
if res.Code != http.StatusOK {
|
||||||
|
t.Fatalf("expected status %d, got %d", http.StatusOK, res.Code)
|
||||||
|
}
|
||||||
|
|
||||||
|
var payload response.R
|
||||||
|
if err := json.NewDecoder(res.Body).Decode(&payload); err != nil {
|
||||||
|
t.Fatalf("decode response: %v", err)
|
||||||
|
}
|
||||||
|
if payload.Code != 0 {
|
||||||
|
t.Fatalf("expected response code 0, got %d (%s)", payload.Code, payload.Msg)
|
||||||
|
}
|
||||||
|
|
||||||
|
rows, ok := payload.Data.([]interface{})
|
||||||
|
if !ok || len(rows) == 0 {
|
||||||
|
t.Fatalf("expected non-empty share list, got %T", payload.Data)
|
||||||
|
}
|
||||||
|
|
||||||
|
first, ok := rows[0].(map[string]interface{})
|
||||||
|
if !ok {
|
||||||
|
t.Fatalf("expected share row object, got %T", rows[0])
|
||||||
|
}
|
||||||
|
|
||||||
|
if int(first["activeRuntimeNum"].(float64)) != 2 {
|
||||||
|
t.Fatalf("expected activeRuntimeNum=2, got %v", first["activeRuntimeNum"])
|
||||||
|
}
|
||||||
|
|
||||||
|
usedPortsRaw, ok := first["usedPorts"].([]interface{})
|
||||||
|
if !ok {
|
||||||
|
t.Fatalf("expected usedPorts array, got %T", first["usedPorts"])
|
||||||
|
}
|
||||||
|
if len(usedPortsRaw) != 2 {
|
||||||
|
t.Fatalf("expected 2 used ports, got %d", len(usedPortsRaw))
|
||||||
|
}
|
||||||
|
if int(usedPortsRaw[0].(float64)) != 22001 || int(usedPortsRaw[1].(float64)) != 22002 {
|
||||||
|
t.Fatalf("unexpected used ports payload: %v", usedPortsRaw)
|
||||||
|
}
|
||||||
|
|
||||||
|
detailsRaw, ok := first["usedPortDetails"].([]interface{})
|
||||||
|
if !ok {
|
||||||
|
t.Fatalf("expected usedPortDetails array, got %T", first["usedPortDetails"])
|
||||||
|
}
|
||||||
|
if len(detailsRaw) != 2 {
|
||||||
|
t.Fatalf("expected 2 usedPortDetails rows, got %d", len(detailsRaw))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestFederationShareDeleteCleansUpRuntimes(t *testing.T) {
|
||||||
|
repo, err := sqlite.Open(filepath.Join(t.TempDir(), "panel.db"))
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("open sqlite: %v", err)
|
||||||
|
}
|
||||||
|
t.Cleanup(func() { _ = repo.Close() })
|
||||||
|
|
||||||
|
h := New(repo, "test-jwt-secret")
|
||||||
|
now := time.Now().UnixMilli()
|
||||||
|
|
||||||
|
if err := repo.CreatePeerShare(&sqlite.PeerShare{
|
||||||
|
Name: "delete-cleanup-share",
|
||||||
|
NodeID: 99,
|
||||||
|
Token: "delete-cleanup-token",
|
||||||
|
MaxBandwidth: 4096,
|
||||||
|
PortRangeStart: 40000,
|
||||||
|
PortRangeEnd: 40010,
|
||||||
|
IsActive: 1,
|
||||||
|
CreatedTime: now,
|
||||||
|
UpdatedTime: now,
|
||||||
|
}); err != nil {
|
||||||
|
t.Fatalf("create peer share: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
share, err := repo.GetPeerShareByToken("delete-cleanup-token")
|
||||||
|
if err != nil || share == nil {
|
||||||
|
t.Fatalf("load peer share: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
if _, err := repo.DB().Exec(`
|
||||||
|
INSERT INTO peer_share_runtime(share_id, node_id, reservation_id, resource_key, binding_id, role, chain_name, service_name, protocol, strategy, port, target, applied, status, created_time, updated_time)
|
||||||
|
VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?),
|
||||||
|
(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
||||||
|
`,
|
||||||
|
share.ID, 99, "dc-r1", "dc-rk1", "dc-b1", "exit", "", "fed_svc_dc1", "tls", "round", 40001, "", 1, 1, now, now,
|
||||||
|
share.ID, 99, "dc-r2", "dc-rk2", "dc-b2", "middle", "fed_chain_dc2", "fed_svc_dc2", "tls", "round", 40002, "", 1, 1, now, now,
|
||||||
|
); err != nil {
|
||||||
|
t.Fatalf("insert peer_share_runtime rows: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
var runtimeCount int
|
||||||
|
if err := repo.DB().QueryRow(`SELECT COUNT(1) FROM peer_share_runtime WHERE share_id = ? AND status = 1`, share.ID).Scan(&runtimeCount); err != nil {
|
||||||
|
t.Fatalf("count active runtimes before: %v", err)
|
||||||
|
}
|
||||||
|
if runtimeCount != 2 {
|
||||||
|
t.Fatalf("expected 2 active runtimes before delete, got %d", runtimeCount)
|
||||||
|
}
|
||||||
|
|
||||||
|
body, err := json.Marshal(deletePeerShareRequest{ID: share.ID})
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("marshal request: %v", err)
|
||||||
|
}
|
||||||
|
req := httptest.NewRequest(http.MethodPost, "/api/v1/federation/share/delete", bytes.NewReader(body))
|
||||||
|
req.Header.Set("Content-Type", "application/json")
|
||||||
|
res := httptest.NewRecorder()
|
||||||
|
|
||||||
|
h.federationShareDelete(res, req)
|
||||||
|
|
||||||
|
if res.Code != http.StatusOK {
|
||||||
|
t.Fatalf("expected status %d, got %d", http.StatusOK, res.Code)
|
||||||
|
}
|
||||||
|
var payload response.R
|
||||||
|
if err := json.NewDecoder(res.Body).Decode(&payload); err != nil {
|
||||||
|
t.Fatalf("decode response: %v", err)
|
||||||
|
}
|
||||||
|
if payload.Code != 0 {
|
||||||
|
t.Fatalf("expected response code 0, got %d (%s)", payload.Code, payload.Msg)
|
||||||
|
}
|
||||||
|
|
||||||
|
var shareCount int
|
||||||
|
if err := repo.DB().QueryRow(`SELECT COUNT(1) FROM peer_share WHERE id = ?`, share.ID).Scan(&shareCount); err != nil {
|
||||||
|
t.Fatalf("count peer_share after: %v", err)
|
||||||
|
}
|
||||||
|
if shareCount != 0 {
|
||||||
|
t.Fatalf("expected peer_share deleted, got %d rows", shareCount)
|
||||||
|
}
|
||||||
|
|
||||||
|
var runtimeCountAfter int
|
||||||
|
if err := repo.DB().QueryRow(`SELECT COUNT(1) FROM peer_share_runtime WHERE share_id = ?`, share.ID).Scan(&runtimeCountAfter); err != nil {
|
||||||
|
t.Fatalf("count peer_share_runtime after: %v", err)
|
||||||
|
}
|
||||||
|
if runtimeCountAfter != 0 {
|
||||||
|
t.Fatalf("expected all peer_share_runtime rows deleted, got %d", runtimeCountAfter)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestFederationRemoteUsageListSyncErrorFallback(t *testing.T) {
|
||||||
|
repo, err := sqlite.Open(filepath.Join(t.TempDir(), "panel.db"))
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("open sqlite: %v", err)
|
||||||
|
}
|
||||||
|
t.Cleanup(func() { _ = repo.Close() })
|
||||||
|
|
||||||
|
h := New(repo, "test-jwt-secret")
|
||||||
|
now := time.Now().UnixMilli()
|
||||||
|
|
||||||
|
if _, err := repo.DB().Exec(`
|
||||||
|
INSERT INTO node(name, secret, server_ip, server_ip_v4, server_ip_v6, port, interface_name, version, http, tls, socks, created_time, updated_time, status, tcp_listen_addr, udp_listen_addr, inx, is_remote, remote_url, remote_token, remote_config)
|
||||||
|
VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
||||||
|
`, "sync-error-node", "sync-error-secret", "10.50.60.70", "10.50.60.70", "", "32000-32010", "", "v1", 1, 1, 1, now, now, 1, "[::]", "[::]", 0, 1, "http://unreachable.invalid:9999", "bad-token", `{"shareId":42,"maxBandwidth":5368709120,"currentFlow":999999,"portRangeStart":32000,"portRangeEnd":32010}`); err != nil {
|
||||||
|
t.Fatalf("insert remote node: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
req := httptest.NewRequest(http.MethodPost, "/api/v1/federation/share/remote-usage/list", nil)
|
||||||
|
res := httptest.NewRecorder()
|
||||||
|
h.federationRemoteUsageList(res, req)
|
||||||
|
|
||||||
|
if res.Code != http.StatusOK {
|
||||||
|
t.Fatalf("expected status %d, got %d", http.StatusOK, res.Code)
|
||||||
|
}
|
||||||
|
|
||||||
|
var payload response.R
|
||||||
|
if err := json.NewDecoder(res.Body).Decode(&payload); err != nil {
|
||||||
|
t.Fatalf("decode response: %v", err)
|
||||||
|
}
|
||||||
|
if payload.Code != 0 {
|
||||||
|
t.Fatalf("expected response code 0, got %d (%s)", payload.Code, payload.Msg)
|
||||||
|
}
|
||||||
|
|
||||||
|
rows, ok := payload.Data.([]interface{})
|
||||||
|
if !ok || len(rows) == 0 {
|
||||||
|
t.Fatalf("expected non-empty usage list, got %T", payload.Data)
|
||||||
|
}
|
||||||
|
|
||||||
|
first, ok := rows[0].(map[string]interface{})
|
||||||
|
if !ok {
|
||||||
|
t.Fatalf("expected row map, got %T", rows[0])
|
||||||
|
}
|
||||||
|
|
||||||
|
if int64(first["shareId"].(float64)) != 42 {
|
||||||
|
t.Fatalf("expected stale shareId=42 on sync failure, got %v", first["shareId"])
|
||||||
|
}
|
||||||
|
if int64(first["currentFlow"].(float64)) != 999999 {
|
||||||
|
t.Fatalf("expected stale currentFlow=999999 on sync failure, got %v", first["currentFlow"])
|
||||||
|
}
|
||||||
|
|
||||||
|
syncErr, _ := first["syncError"].(string)
|
||||||
|
if syncErr == "" {
|
||||||
|
t.Fatalf("expected non-empty syncError field on unreachable provider")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestFederationShareResetFlow(t *testing.T) {
|
||||||
|
repo, err := sqlite.Open(filepath.Join(t.TempDir(), "panel.db"))
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("open sqlite: %v", err)
|
||||||
|
}
|
||||||
|
t.Cleanup(func() { _ = repo.Close() })
|
||||||
|
|
||||||
|
h := New(repo, "test-jwt-secret")
|
||||||
|
now := time.Now().UnixMilli()
|
||||||
|
if err := repo.CreatePeerShare(&sqlite.PeerShare{
|
||||||
|
Name: "reset-flow-share",
|
||||||
|
NodeID: 11,
|
||||||
|
Token: "reset-flow-token",
|
||||||
|
MaxBandwidth: 4096,
|
||||||
|
CurrentFlow: 2048,
|
||||||
|
PortRangeStart: 23000,
|
||||||
|
PortRangeEnd: 23010,
|
||||||
|
IsActive: 1,
|
||||||
|
CreatedTime: now,
|
||||||
|
UpdatedTime: now,
|
||||||
|
}); err != nil {
|
||||||
|
t.Fatalf("create peer share: %v", err)
|
||||||
|
}
|
||||||
|
share, err := repo.GetPeerShareByToken("reset-flow-token")
|
||||||
|
if err != nil || share == nil {
|
||||||
|
t.Fatalf("load peer share: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
body, err := json.Marshal(resetPeerShareFlowRequest{ID: share.ID})
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("marshal request: %v", err)
|
||||||
|
}
|
||||||
|
req := httptest.NewRequest(http.MethodPost, "/api/v1/federation/share/reset-flow", bytes.NewReader(body))
|
||||||
|
req.Header.Set("Content-Type", "application/json")
|
||||||
|
res := httptest.NewRecorder()
|
||||||
|
|
||||||
|
h.federationShareResetFlow(res, req)
|
||||||
|
|
||||||
|
if res.Code != http.StatusOK {
|
||||||
|
t.Fatalf("expected status %d, got %d", http.StatusOK, res.Code)
|
||||||
|
}
|
||||||
|
var payload response.R
|
||||||
|
if err := json.NewDecoder(res.Body).Decode(&payload); err != nil {
|
||||||
|
t.Fatalf("decode response: %v", err)
|
||||||
|
}
|
||||||
|
if payload.Code != 0 {
|
||||||
|
t.Fatalf("expected response code 0, got %d (%s)", payload.Code, payload.Msg)
|
||||||
|
}
|
||||||
|
|
||||||
|
updated, err := repo.GetPeerShare(share.ID)
|
||||||
|
if err != nil || updated == nil {
|
||||||
|
t.Fatalf("reload peer share: %v", err)
|
||||||
|
}
|
||||||
|
if updated.CurrentFlow != 0 {
|
||||||
|
t.Fatalf("expected current flow reset to 0, got %d", updated.CurrentFlow)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestFederationRemoteUsageList(t *testing.T) {
|
||||||
|
repo, err := sqlite.Open(filepath.Join(t.TempDir(), "panel.db"))
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("open sqlite: %v", err)
|
||||||
|
}
|
||||||
|
t.Cleanup(func() { _ = repo.Close() })
|
||||||
|
|
||||||
|
h := New(repo, "test-jwt-secret")
|
||||||
|
now := time.Now().UnixMilli()
|
||||||
|
|
||||||
|
resNode, err := repo.DB().Exec(`
|
||||||
|
INSERT INTO node(name, secret, server_ip, server_ip_v4, server_ip_v6, port, interface_name, version, http, tls, socks, created_time, updated_time, status, tcp_listen_addr, udp_listen_addr, inx, is_remote, remote_url, remote_token, remote_config)
|
||||||
|
VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
||||||
|
`, "remote-consumer-node", "remote-consumer-secret", "10.30.40.50", "10.30.40.50", "", "31000-31010", "", "v1", 1, 1, 1, now, now, 1, "[::]", "[::]", 0, 1, "http://peer.example", "peer-token", `{"shareId":88,"maxBandwidth":2147483648,"currentFlow":1073741824,"portRangeStart":31000,"portRangeEnd":31010}`)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("insert remote node: %v", err)
|
||||||
|
}
|
||||||
|
nodeID, err := resNode.LastInsertId()
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("remote node id: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
resTunnelA, err := repo.DB().Exec(`INSERT INTO tunnel(name, type, protocol, flow, created_time, updated_time, status, in_ip, inx) VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?)`, "consumer-tunnel-a", 2, "tls", 1, now, now, 1, "", 0)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("insert tunnel a: %v", err)
|
||||||
|
}
|
||||||
|
tunnelAID, _ := resTunnelA.LastInsertId()
|
||||||
|
|
||||||
|
resTunnelB, err := repo.DB().Exec(`INSERT INTO tunnel(name, type, protocol, flow, created_time, updated_time, status, in_ip, inx) VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?)`, "consumer-tunnel-b", 2, "tls", 1, now, now, 1, "", 0)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("insert tunnel b: %v", err)
|
||||||
|
}
|
||||||
|
tunnelBID, _ := resTunnelB.LastInsertId()
|
||||||
|
|
||||||
|
if _, err := repo.DB().Exec(`
|
||||||
|
INSERT INTO federation_tunnel_binding(tunnel_id, node_id, chain_type, hop_inx, remote_url, resource_key, remote_binding_id, allocated_port, status, created_time, updated_time)
|
||||||
|
VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?),
|
||||||
|
(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
||||||
|
`,
|
||||||
|
tunnelAID, nodeID, 2, 1, "http://peer.example", "rk-a", "rb-a", 31001, 1, now, now,
|
||||||
|
tunnelBID, nodeID, 3, 0, "http://peer.example", "rk-b", "rb-b", 31002, 1, now, now,
|
||||||
|
); err != nil {
|
||||||
|
t.Fatalf("insert federation bindings: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
req := httptest.NewRequest(http.MethodPost, "/api/v1/federation/share/remote-usage/list", nil)
|
||||||
|
res := httptest.NewRecorder()
|
||||||
|
h.federationRemoteUsageList(res, req)
|
||||||
|
|
||||||
|
if res.Code != http.StatusOK {
|
||||||
|
t.Fatalf("expected status %d, got %d", http.StatusOK, res.Code)
|
||||||
|
}
|
||||||
|
|
||||||
|
var payload response.R
|
||||||
|
if err := json.NewDecoder(res.Body).Decode(&payload); err != nil {
|
||||||
|
t.Fatalf("decode response: %v", err)
|
||||||
|
}
|
||||||
|
if payload.Code != 0 {
|
||||||
|
t.Fatalf("expected response code 0, got %d (%s)", payload.Code, payload.Msg)
|
||||||
|
}
|
||||||
|
|
||||||
|
rows, ok := payload.Data.([]interface{})
|
||||||
|
if !ok || len(rows) == 0 {
|
||||||
|
t.Fatalf("expected non-empty usage list, got %T", payload.Data)
|
||||||
|
}
|
||||||
|
|
||||||
|
first, ok := rows[0].(map[string]interface{})
|
||||||
|
if !ok {
|
||||||
|
t.Fatalf("expected first usage row map, got %T", rows[0])
|
||||||
|
}
|
||||||
|
if int64(first["shareId"].(float64)) != 88 {
|
||||||
|
t.Fatalf("expected shareId=88, got %v", first["shareId"])
|
||||||
|
}
|
||||||
|
|
||||||
|
usedPortsRaw, ok := first["usedPorts"].([]interface{})
|
||||||
|
if !ok {
|
||||||
|
t.Fatalf("expected usedPorts array, got %T", first["usedPorts"])
|
||||||
|
}
|
||||||
|
if len(usedPortsRaw) != 2 {
|
||||||
|
t.Fatalf("expected 2 used ports, got %d", len(usedPortsRaw))
|
||||||
|
}
|
||||||
|
if int(usedPortsRaw[0].(float64)) != 31001 || int(usedPortsRaw[1].(float64)) != 31002 {
|
||||||
|
t.Fatalf("unexpected used ports payload: %v", usedPortsRaw)
|
||||||
|
}
|
||||||
|
|
||||||
|
bindingsRaw, ok := first["bindings"].([]interface{})
|
||||||
|
if !ok {
|
||||||
|
t.Fatalf("expected bindings array, got %T", first["bindings"])
|
||||||
|
}
|
||||||
|
if len(bindingsRaw) != 2 {
|
||||||
|
t.Fatalf("expected 2 binding rows, got %d", len(bindingsRaw))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestAuthPeerAllowedIPs(t *testing.T) {
|
||||||
|
repo, err := sqlite.Open(filepath.Join(t.TempDir(), "panel.db"))
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("open sqlite: %v", err)
|
||||||
|
}
|
||||||
|
t.Cleanup(func() { _ = repo.Close() })
|
||||||
|
|
||||||
|
h := New(repo, "test-jwt-secret")
|
||||||
|
now := time.Now().UnixMilli()
|
||||||
|
|
||||||
|
tests := []struct {
|
||||||
|
name string
|
||||||
|
allowedIPs string
|
||||||
|
remoteAddr string
|
||||||
|
xff string
|
||||||
|
wantAllowed bool
|
||||||
|
}{
|
||||||
|
{
|
||||||
|
name: "exact ip allowed",
|
||||||
|
allowedIPs: "203.0.113.10",
|
||||||
|
remoteAddr: "203.0.113.10:23456",
|
||||||
|
wantAllowed: true,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "cidr allowed",
|
||||||
|
allowedIPs: "203.0.113.0/24",
|
||||||
|
remoteAddr: "203.0.113.11:23456",
|
||||||
|
wantAllowed: true,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "trusted proxy xff allowed",
|
||||||
|
allowedIPs: "198.51.100.20",
|
||||||
|
remoteAddr: "172.20.0.3:34567",
|
||||||
|
xff: "198.51.100.20, 172.20.0.3",
|
||||||
|
wantAllowed: true,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "non whitelisted ip denied",
|
||||||
|
allowedIPs: "203.0.113.10",
|
||||||
|
remoteAddr: "203.0.113.99:23456",
|
||||||
|
wantAllowed: false,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
for idx, tt := range tests {
|
||||||
|
t.Run(tt.name, func(t *testing.T) {
|
||||||
|
token := fmt.Sprintf("share-token-%d", idx)
|
||||||
|
if err := repo.CreatePeerShare(&sqlite.PeerShare{
|
||||||
|
Name: "share-" + tt.name,
|
||||||
|
NodeID: 1,
|
||||||
|
Token: token,
|
||||||
|
PortRangeStart: 10000,
|
||||||
|
PortRangeEnd: 10010,
|
||||||
|
IsActive: 1,
|
||||||
|
CreatedTime: now,
|
||||||
|
UpdatedTime: now,
|
||||||
|
AllowedIPs: tt.allowedIPs,
|
||||||
|
}); err != nil {
|
||||||
|
t.Fatalf("create peer share: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
nextCalled := false
|
||||||
|
wrapped := h.authPeer(func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
nextCalled = true
|
||||||
|
response.WriteJSON(w, response.OKEmpty())
|
||||||
|
})
|
||||||
|
|
||||||
|
req := httptest.NewRequest(http.MethodPost, "/api/v1/federation/connect", nil)
|
||||||
|
req.Header.Set("Authorization", "Bearer "+token)
|
||||||
|
if tt.xff != "" {
|
||||||
|
req.Header.Set("X-Forwarded-For", tt.xff)
|
||||||
|
}
|
||||||
|
req.RemoteAddr = tt.remoteAddr
|
||||||
|
|
||||||
|
res := httptest.NewRecorder()
|
||||||
|
wrapped(res, req)
|
||||||
|
|
||||||
|
var payload response.R
|
||||||
|
if err := json.NewDecoder(res.Body).Decode(&payload); err != nil {
|
||||||
|
t.Fatalf("decode response: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
if tt.wantAllowed {
|
||||||
|
if !nextCalled {
|
||||||
|
t.Fatalf("expected next handler to be called")
|
||||||
|
}
|
||||||
|
if payload.Code != 0 {
|
||||||
|
t.Fatalf("expected code 0, got %d (%s)", payload.Code, payload.Msg)
|
||||||
|
}
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
if nextCalled {
|
||||||
|
t.Fatalf("expected next handler not to be called")
|
||||||
|
}
|
||||||
|
if payload.Code != 403 {
|
||||||
|
t.Fatalf("expected code 403, got %d (%s)", payload.Code, payload.Msg)
|
||||||
|
}
|
||||||
|
if payload.Msg != "IP not allowed" {
|
||||||
|
t.Fatalf("expected IP rejection message, got %q", payload.Msg)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -38,16 +38,21 @@ func (h *Handler) processFlowItem(item flowItem) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
forwardID, userID, userTunnelID, ok := parseFlowServiceIDs(serviceName)
|
forwardID, userID, userTunnelID, ok := parseFlowServiceIDs(serviceName)
|
||||||
if !ok {
|
if ok {
|
||||||
|
inFlow, outFlow := h.scaleFlowByTunnel(forwardID, item.D, item.U)
|
||||||
|
_ = h.repo.AddFlow(forwardID, userID, userTunnelID, inFlow, outFlow)
|
||||||
|
|
||||||
|
if userTunnelID > 0 {
|
||||||
|
h.enforceFlowPolicies(userID, userTunnelID)
|
||||||
|
}
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
inFlow, outFlow := h.scaleFlowByTunnel(forwardID, item.D, item.U)
|
runtimeID, ok := parsePeerShareRuntimeServiceID(serviceName)
|
||||||
_ = h.repo.AddFlow(forwardID, userID, userTunnelID, inFlow, outFlow)
|
if !ok {
|
||||||
|
return
|
||||||
if userTunnelID > 0 {
|
|
||||||
h.enforceFlowPolicies(userID, userTunnelID)
|
|
||||||
}
|
}
|
||||||
|
h.processPeerShareFlow(runtimeID, item)
|
||||||
}
|
}
|
||||||
|
|
||||||
func parseFlowServiceIDs(serviceName string) (int64, int64, int64, bool) {
|
func parseFlowServiceIDs(serviceName string) (int64, int64, int64, bool) {
|
||||||
@@ -66,6 +71,72 @@ func parseFlowServiceIDs(serviceName string) (int64, int64, int64, bool) {
|
|||||||
return forwardID, userID, userTunnelID, true
|
return forwardID, userID, userTunnelID, true
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func parsePeerShareRuntimeServiceID(serviceName string) (int64, bool) {
|
||||||
|
const prefix = "fed_svc_"
|
||||||
|
if !strings.HasPrefix(serviceName, prefix) {
|
||||||
|
return 0, false
|
||||||
|
}
|
||||||
|
raw := strings.TrimPrefix(serviceName, prefix)
|
||||||
|
if raw == "" {
|
||||||
|
return 0, false
|
||||||
|
}
|
||||||
|
parts := strings.SplitN(raw, "_", 2)
|
||||||
|
runtimeID, err := strconv.ParseInt(parts[0], 10, 64)
|
||||||
|
if err != nil || runtimeID <= 0 {
|
||||||
|
return 0, false
|
||||||
|
}
|
||||||
|
return runtimeID, true
|
||||||
|
}
|
||||||
|
|
||||||
|
func (h *Handler) processPeerShareFlow(runtimeID int64, item flowItem) {
|
||||||
|
if h == nil || h.repo == nil || runtimeID <= 0 {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
runtime, err := h.repo.GetPeerShareRuntimeByID(runtimeID)
|
||||||
|
if err != nil || runtime == nil || runtime.ShareID <= 0 || runtime.Status != 1 {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
delta := item.D + item.U
|
||||||
|
if delta <= 0 {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
_ = h.repo.AddPeerShareCurrentFlow(runtime.ShareID, delta)
|
||||||
|
|
||||||
|
share, err := h.repo.GetPeerShare(runtime.ShareID)
|
||||||
|
if err != nil || share == nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if !isPeerShareFlowExceeded(share) {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
h.enforcePeerShareFlowLimit(share.ID)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (h *Handler) enforcePeerShareFlowLimit(shareID int64) {
|
||||||
|
if h == nil || h.repo == nil || shareID <= 0 {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
runtimes, err := h.repo.ListActivePeerShareRuntimesByShareID(shareID)
|
||||||
|
if err != nil || len(runtimes) == 0 {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
now := time.Now().UnixMilli()
|
||||||
|
for _, runtime := range runtimes {
|
||||||
|
if h.wsServer != nil && runtime.Applied == 1 {
|
||||||
|
if strings.TrimSpace(runtime.ServiceName) != "" {
|
||||||
|
_, _ = h.sendNodeCommand(runtime.NodeID, "DeleteService", map[string]interface{}{"services": []string{runtime.ServiceName}}, false, true)
|
||||||
|
}
|
||||||
|
if strings.TrimSpace(runtime.Role) == "middle" && strings.TrimSpace(runtime.ChainName) != "" {
|
||||||
|
_, _ = h.sendNodeCommand(runtime.NodeID, "DeleteChains", map[string]interface{}{"chain": runtime.ChainName}, false, true)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
_ = h.repo.MarkPeerShareRuntimeReleased(runtime.ID, now)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
func (h *Handler) scaleFlowByTunnel(forwardID int64, inFlow int64, outFlow int64) (int64, int64) {
|
func (h *Handler) scaleFlowByTunnel(forwardID int64, inFlow int64, outFlow int64) (int64, int64) {
|
||||||
forward, err := h.getForwardRecord(forwardID)
|
forward, err := h.getForwardRecord(forwardID)
|
||||||
if err != nil || forward == nil {
|
if err != nil || forward == nil {
|
||||||
|
|||||||
@@ -0,0 +1,63 @@
|
|||||||
|
package handler
|
||||||
|
|
||||||
|
import (
|
||||||
|
"path/filepath"
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"go-backend/internal/store/sqlite"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestProcessFlowItemTracksPeerShareFlowAndEnforcesLimit(t *testing.T) {
|
||||||
|
repo, err := sqlite.Open(filepath.Join(t.TempDir(), "panel.db"))
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("open repo: %v", err)
|
||||||
|
}
|
||||||
|
defer repo.Close()
|
||||||
|
|
||||||
|
now := time.Now().UnixMilli()
|
||||||
|
if err := repo.CreatePeerShare(&sqlite.PeerShare{
|
||||||
|
Name: "flow-share",
|
||||||
|
NodeID: 1,
|
||||||
|
Token: "flow-share-token",
|
||||||
|
MaxBandwidth: 3000,
|
||||||
|
CurrentFlow: 1000,
|
||||||
|
PortRangeStart: 32000,
|
||||||
|
PortRangeEnd: 32010,
|
||||||
|
IsActive: 1,
|
||||||
|
CreatedTime: now,
|
||||||
|
UpdatedTime: now,
|
||||||
|
}); err != nil {
|
||||||
|
t.Fatalf("create peer share: %v", err)
|
||||||
|
}
|
||||||
|
share, err := repo.GetPeerShareByToken("flow-share-token")
|
||||||
|
if err != nil || share == nil {
|
||||||
|
t.Fatalf("load peer share: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
if _, err := repo.DB().Exec(`
|
||||||
|
INSERT INTO peer_share_runtime(id, share_id, node_id, reservation_id, resource_key, binding_id, role, chain_name, service_name, protocol, strategy, port, target, applied, status, created_time, updated_time)
|
||||||
|
VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
||||||
|
`, 17, share.ID, share.NodeID, "res-17", "rk-17", "17", "exit", "", "fed_svc_17", "tls", "round", 32001, "", 1, 1, now, now); err != nil {
|
||||||
|
t.Fatalf("insert peer_share_runtime: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
h := &Handler{repo: repo}
|
||||||
|
h.processFlowItem(flowItem{N: "fed_svc_17", U: 1200, D: 900})
|
||||||
|
|
||||||
|
updatedShare, err := repo.GetPeerShare(share.ID)
|
||||||
|
if err != nil || updatedShare == nil {
|
||||||
|
t.Fatalf("reload share: %v", err)
|
||||||
|
}
|
||||||
|
if updatedShare.CurrentFlow != 3100 {
|
||||||
|
t.Fatalf("expected current_flow=3100, got %d", updatedShare.CurrentFlow)
|
||||||
|
}
|
||||||
|
|
||||||
|
runtime, err := repo.GetPeerShareRuntimeByID(17)
|
||||||
|
if err != nil || runtime == nil {
|
||||||
|
t.Fatalf("reload runtime: %v", err)
|
||||||
|
}
|
||||||
|
if runtime.Status != 0 {
|
||||||
|
t.Fatalf("expected runtime status=0 after limit enforcement, got %d", runtime.Status)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -7,6 +7,7 @@ import (
|
|||||||
"fmt"
|
"fmt"
|
||||||
"io"
|
"io"
|
||||||
"net/http"
|
"net/http"
|
||||||
|
"net/url"
|
||||||
"sort"
|
"sort"
|
||||||
"strconv"
|
"strconv"
|
||||||
"strings"
|
"strings"
|
||||||
@@ -41,6 +42,11 @@ type loginRequest struct {
|
|||||||
CaptchaID string `json:"captchaId"`
|
CaptchaID string `json:"captchaId"`
|
||||||
}
|
}
|
||||||
|
|
||||||
|
type captchaVerifyRequest struct {
|
||||||
|
ID string `json:"id"`
|
||||||
|
Data string `json:"data"`
|
||||||
|
}
|
||||||
|
|
||||||
type nameRequest struct {
|
type nameRequest struct {
|
||||||
Name string `json:"name"`
|
Name string `json:"name"`
|
||||||
}
|
}
|
||||||
@@ -88,7 +94,6 @@ func (h *Handler) Register(mux *http.ServeMux) {
|
|||||||
mux.HandleFunc("/api/v1/config/update", h.updateConfigs)
|
mux.HandleFunc("/api/v1/config/update", h.updateConfigs)
|
||||||
mux.HandleFunc("/api/v1/config/update-single", h.updateSingleConfig)
|
mux.HandleFunc("/api/v1/config/update-single", h.updateSingleConfig)
|
||||||
mux.HandleFunc("/api/v1/captcha/check", h.checkCaptcha)
|
mux.HandleFunc("/api/v1/captcha/check", h.checkCaptcha)
|
||||||
mux.HandleFunc("/api/v1/captcha/generate", h.captchaGenerate)
|
|
||||||
mux.HandleFunc("/api/v1/captcha/verify", h.captchaVerify)
|
mux.HandleFunc("/api/v1/captcha/verify", h.captchaVerify)
|
||||||
mux.HandleFunc("/api/v1/user/package", h.userPackage)
|
mux.HandleFunc("/api/v1/user/package", h.userPackage)
|
||||||
mux.HandleFunc("/api/v1/user/updatePassword", h.updatePassword)
|
mux.HandleFunc("/api/v1/user/updatePassword", h.updatePassword)
|
||||||
@@ -148,6 +153,18 @@ func (h *Handler) Register(mux *http.ServeMux) {
|
|||||||
mux.HandleFunc("/api/v1/group/permission/assign", h.groupPermissionAssign)
|
mux.HandleFunc("/api/v1/group/permission/assign", h.groupPermissionAssign)
|
||||||
mux.HandleFunc("/api/v1/group/permission/remove", h.groupPermissionRemove)
|
mux.HandleFunc("/api/v1/group/permission/remove", h.groupPermissionRemove)
|
||||||
mux.HandleFunc("/api/v1/open_api/sub_store", h.openAPISubStore)
|
mux.HandleFunc("/api/v1/open_api/sub_store", h.openAPISubStore)
|
||||||
|
mux.HandleFunc("/api/v1/federation/share/list", h.federationShareList)
|
||||||
|
mux.HandleFunc("/api/v1/federation/share/create", h.federationShareCreate)
|
||||||
|
mux.HandleFunc("/api/v1/federation/share/delete", h.federationShareDelete)
|
||||||
|
mux.HandleFunc("/api/v1/federation/share/reset-flow", h.federationShareResetFlow)
|
||||||
|
mux.HandleFunc("/api/v1/federation/share/remote-usage/list", h.federationRemoteUsageList)
|
||||||
|
mux.HandleFunc("/api/v1/federation/connect", h.authPeer(h.federationConnect))
|
||||||
|
mux.HandleFunc("/api/v1/federation/tunnel/create", h.authPeer(h.federationTunnelCreate))
|
||||||
|
mux.HandleFunc("/api/v1/federation/runtime/reserve-port", h.authPeer(h.federationRuntimeReservePort))
|
||||||
|
mux.HandleFunc("/api/v1/federation/runtime/apply-role", h.authPeer(h.federationRuntimeApplyRole))
|
||||||
|
mux.HandleFunc("/api/v1/federation/runtime/release-role", h.authPeer(h.federationRuntimeReleaseRole))
|
||||||
|
mux.HandleFunc("/api/v1/federation/runtime/diagnose", h.authPeer(h.federationRuntimeDiagnose))
|
||||||
|
mux.HandleFunc("/api/v1/federation/node/import", h.nodeImport)
|
||||||
|
|
||||||
mux.HandleFunc("/flow/test", h.flowTest)
|
mux.HandleFunc("/flow/test", h.flowTest)
|
||||||
mux.HandleFunc("/flow/config", h.flowConfig)
|
mux.HandleFunc("/flow/config", h.flowConfig)
|
||||||
@@ -181,13 +198,25 @@ func (h *Handler) login(w http.ResponseWriter, r *http.Request) {
|
|||||||
response.WriteJSON(w, response.Err(-2, err.Error()))
|
response.WriteJSON(w, response.Err(-2, err.Error()))
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
if captchaEnabled && strings.TrimSpace(req.CaptchaID) == "" {
|
if captchaEnabled {
|
||||||
response.WriteJSON(w, response.ErrDefault("验证码校验失败"))
|
captchaID := strings.TrimSpace(req.CaptchaID)
|
||||||
return
|
if captchaID == "" {
|
||||||
}
|
response.WriteJSON(w, response.ErrDefault("验证码校验失败"))
|
||||||
if captchaEnabled && !h.consumeCaptchaToken(req.CaptchaID) {
|
return
|
||||||
response.WriteJSON(w, response.ErrDefault("验证码校验失败"))
|
}
|
||||||
return
|
|
||||||
|
if !h.consumeCaptchaToken(captchaID) {
|
||||||
|
secretCfg, err := h.repo.GetConfigByName("cloudflare_secret_key")
|
||||||
|
if err != nil || secretCfg == nil || strings.TrimSpace(secretCfg.Value) == "" {
|
||||||
|
response.WriteJSON(w, response.ErrDefault("验证码校验失败"))
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
if !h.verifyCloudflareTurnstile(captchaID, strings.TrimSpace(secretCfg.Value)) {
|
||||||
|
response.WriteJSON(w, response.ErrDefault("验证码校验失败"))
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
user, err := h.repo.GetUserByUsername(req.Username)
|
user, err := h.repo.GetUserByUsername(req.Username)
|
||||||
@@ -575,6 +604,40 @@ func (h *Handler) checkCaptcha(w http.ResponseWriter, r *http.Request) {
|
|||||||
response.WriteJSON(w, response.OK(0))
|
response.WriteJSON(w, response.OK(0))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func (h *Handler) captchaVerify(w http.ResponseWriter, r *http.Request) {
|
||||||
|
if r.Method != http.MethodPost {
|
||||||
|
response.WriteJSON(w, response.ErrDefault("请求失败"))
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
var req captchaVerifyRequest
|
||||||
|
if err := decodeJSON(r.Body, &req); err != nil {
|
||||||
|
h.writeCaptchaVerifyResult(w, false, "")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
id := strings.TrimSpace(req.ID)
|
||||||
|
data := strings.TrimSpace(req.Data)
|
||||||
|
if id == "" || data == "" {
|
||||||
|
h.writeCaptchaVerifyResult(w, false, "")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
verified := false
|
||||||
|
secretCfg, err := h.repo.GetConfigByName("cloudflare_secret_key")
|
||||||
|
if err == nil && secretCfg != nil && strings.TrimSpace(secretCfg.Value) != "" {
|
||||||
|
verified = h.verifyCloudflareTurnstile(data, strings.TrimSpace(secretCfg.Value))
|
||||||
|
} else {
|
||||||
|
verified = data == "ok"
|
||||||
|
}
|
||||||
|
if !verified {
|
||||||
|
h.writeCaptchaVerifyResult(w, false, "")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
h.markCaptchaToken(id)
|
||||||
|
h.writeCaptchaVerifyResult(w, true, id)
|
||||||
|
}
|
||||||
|
|
||||||
func (h *Handler) flowTest(w http.ResponseWriter, _ *http.Request) {
|
func (h *Handler) flowTest(w http.ResponseWriter, _ *http.Request) {
|
||||||
w.Header().Set("Content-Type", "text/plain; charset=utf-8")
|
w.Header().Set("Content-Type", "text/plain; charset=utf-8")
|
||||||
_, _ = w.Write([]byte("test"))
|
_, _ = w.Write([]byte("test"))
|
||||||
@@ -889,6 +952,69 @@ func (h *Handler) captchaEnabled() (bool, error) {
|
|||||||
return strings.EqualFold(cfg.Value, "true"), nil
|
return strings.EqualFold(cfg.Value, "true"), nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func (h *Handler) markCaptchaToken(token string) {
|
||||||
|
if h == nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
token = strings.TrimSpace(token)
|
||||||
|
if token == "" {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
now := time.Now().UnixMilli()
|
||||||
|
exp := now + int64(5*time.Minute/time.Millisecond)
|
||||||
|
|
||||||
|
h.captchaMu.Lock()
|
||||||
|
defer h.captchaMu.Unlock()
|
||||||
|
if h.captchaTokens == nil {
|
||||||
|
h.captchaTokens = make(map[string]int64)
|
||||||
|
}
|
||||||
|
for k, v := range h.captchaTokens {
|
||||||
|
if v <= now {
|
||||||
|
delete(h.captchaTokens, k)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
h.captchaTokens[token] = exp
|
||||||
|
}
|
||||||
|
|
||||||
|
func (h *Handler) consumeCaptchaToken(token string) bool {
|
||||||
|
if h == nil {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
token = strings.TrimSpace(token)
|
||||||
|
if token == "" {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
now := time.Now().UnixMilli()
|
||||||
|
|
||||||
|
h.captchaMu.Lock()
|
||||||
|
defer h.captchaMu.Unlock()
|
||||||
|
if h.captchaTokens == nil {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
for k, v := range h.captchaTokens {
|
||||||
|
if v <= now {
|
||||||
|
delete(h.captchaTokens, k)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
exp, ok := h.captchaTokens[token]
|
||||||
|
if !ok {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
delete(h.captchaTokens, token)
|
||||||
|
return exp > now
|
||||||
|
}
|
||||||
|
|
||||||
|
func (h *Handler) writeCaptchaVerifyResult(w http.ResponseWriter, success bool, token string) {
|
||||||
|
w.Header().Set("Content-Type", "application/json; charset=utf-8")
|
||||||
|
payload := map[string]interface{}{
|
||||||
|
"success": success,
|
||||||
|
"data": map[string]interface{}{
|
||||||
|
"validToken": token,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
_ = json.NewEncoder(w).Encode(payload)
|
||||||
|
}
|
||||||
|
|
||||||
func decodeJSON(body io.ReadCloser, out interface{}) error {
|
func decodeJSON(body io.ReadCloser, out interface{}) error {
|
||||||
defer body.Close()
|
defer body.Close()
|
||||||
decoder := json.NewDecoder(body)
|
decoder := json.NewDecoder(body)
|
||||||
@@ -961,3 +1087,24 @@ func readAndDecryptFlowBody(body io.ReadCloser, secret string) (string, error) {
|
|||||||
}
|
}
|
||||||
return string(plain), nil
|
return string(plain), nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func (h *Handler) verifyCloudflareTurnstile(token, secretKey string) bool {
|
||||||
|
if token == "" || secretKey == "" {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
resp, err := http.PostForm("https://challenges.cloudflare.com/turnstile/v0/siteverify", url.Values{
|
||||||
|
"secret": {secretKey},
|
||||||
|
"response": {token},
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
defer resp.Body.Close()
|
||||||
|
var body struct {
|
||||||
|
Success bool `json:"success"`
|
||||||
|
}
|
||||||
|
if err := json.NewDecoder(resp.Body).Decode(&body); err != nil {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
return body.Success
|
||||||
|
}
|
||||||
|
|||||||
@@ -81,6 +81,18 @@ func shouldSkip(path string) bool {
|
|||||||
return true
|
return true
|
||||||
case path == "/api/v1/user/login":
|
case path == "/api/v1/user/login":
|
||||||
return true
|
return true
|
||||||
|
case path == "/api/v1/federation/connect":
|
||||||
|
return true
|
||||||
|
case path == "/api/v1/federation/tunnel/create":
|
||||||
|
return true
|
||||||
|
case path == "/api/v1/federation/runtime/reserve-port":
|
||||||
|
return true
|
||||||
|
case path == "/api/v1/federation/runtime/apply-role":
|
||||||
|
return true
|
||||||
|
case path == "/api/v1/federation/runtime/release-role":
|
||||||
|
return true
|
||||||
|
case path == "/api/v1/federation/runtime/diagnose":
|
||||||
|
return true
|
||||||
default:
|
default:
|
||||||
return false
|
return false
|
||||||
}
|
}
|
||||||
@@ -91,6 +103,10 @@ func requiresAdmin(path string) bool {
|
|||||||
return true
|
return true
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if strings.HasPrefix(path, "/api/v1/federation/share/") {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
if strings.HasPrefix(path, "/api/v1/node/") {
|
if strings.HasPrefix(path, "/api/v1/node/") {
|
||||||
return true
|
return true
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -95,13 +95,69 @@ type StatisticsFlow struct {
|
|||||||
}
|
}
|
||||||
|
|
||||||
type Node struct {
|
type Node struct {
|
||||||
ID int64
|
ID int64
|
||||||
Secret string
|
Secret string
|
||||||
Version sql.NullString
|
Version sql.NullString
|
||||||
HTTP int
|
HTTP int
|
||||||
TLS int
|
TLS int
|
||||||
Socks int
|
Socks int
|
||||||
Status int
|
Status int
|
||||||
|
IsRemote int
|
||||||
|
RemoteURL sql.NullString
|
||||||
|
RemoteToken sql.NullString
|
||||||
|
RemoteConfig sql.NullString
|
||||||
|
}
|
||||||
|
|
||||||
|
type PeerShare struct {
|
||||||
|
ID int64 `json:"id"`
|
||||||
|
Name string `json:"name"`
|
||||||
|
NodeID int64 `json:"nodeId"`
|
||||||
|
Token string `json:"token"`
|
||||||
|
MaxBandwidth int64 `json:"maxBandwidth"`
|
||||||
|
ExpiryTime int64 `json:"expiryTime"`
|
||||||
|
PortRangeStart int `json:"portRangeStart"`
|
||||||
|
PortRangeEnd int `json:"portRangeEnd"`
|
||||||
|
CurrentFlow int64 `json:"currentFlow"`
|
||||||
|
IsActive int `json:"isActive"`
|
||||||
|
CreatedTime int64 `json:"createdTime"`
|
||||||
|
UpdatedTime int64 `json:"updatedTime"`
|
||||||
|
AllowedDomains string `json:"allowedDomains"`
|
||||||
|
AllowedIPs string `json:"allowedIps"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type PeerShareRuntime struct {
|
||||||
|
ID int64
|
||||||
|
ShareID int64
|
||||||
|
NodeID int64
|
||||||
|
ReservationID string
|
||||||
|
ResourceKey string
|
||||||
|
BindingID string
|
||||||
|
Role string
|
||||||
|
ChainName string
|
||||||
|
ServiceName string
|
||||||
|
Protocol string
|
||||||
|
Strategy string
|
||||||
|
Port int
|
||||||
|
Target string
|
||||||
|
Applied int
|
||||||
|
Status int
|
||||||
|
CreatedTime int64
|
||||||
|
UpdatedTime int64
|
||||||
|
}
|
||||||
|
|
||||||
|
type FederationTunnelBinding struct {
|
||||||
|
ID int64
|
||||||
|
TunnelID int64
|
||||||
|
NodeID int64
|
||||||
|
ChainType int
|
||||||
|
HopInx int
|
||||||
|
RemoteURL string
|
||||||
|
ResourceKey string
|
||||||
|
RemoteBindingID string
|
||||||
|
AllocatedPort int
|
||||||
|
Status int
|
||||||
|
CreatedTime int64
|
||||||
|
UpdatedTime int64
|
||||||
}
|
}
|
||||||
|
|
||||||
func Open(path string) (*Repository, error) {
|
func Open(path string) (*Repository, error) {
|
||||||
@@ -124,6 +180,11 @@ func Open(path string) (*Repository, error) {
|
|||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if err := migrateSchema(db); err != nil {
|
||||||
|
_ = db.Close()
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
return &Repository{db: db}, nil
|
return &Repository{db: db}, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -389,9 +450,25 @@ func (r *Repository) GetNodeBySecret(secret string) (*Node, error) {
|
|||||||
return nil, errors.New("repository not initialized")
|
return nil, errors.New("repository not initialized")
|
||||||
}
|
}
|
||||||
|
|
||||||
row := r.db.QueryRow(`SELECT id, secret, version, http, tls, socks, status FROM node WHERE secret = ? LIMIT 1`, secret)
|
row := r.db.QueryRow(`SELECT id, secret, version, http, tls, socks, status, is_remote, remote_url, remote_token, remote_config FROM node WHERE secret = ? LIMIT 1`, secret)
|
||||||
var n Node
|
var n Node
|
||||||
if err := row.Scan(&n.ID, &n.Secret, &n.Version, &n.HTTP, &n.TLS, &n.Socks, &n.Status); err != nil {
|
if err := row.Scan(&n.ID, &n.Secret, &n.Version, &n.HTTP, &n.TLS, &n.Socks, &n.Status, &n.IsRemote, &n.RemoteURL, &n.RemoteToken, &n.RemoteConfig); err != nil {
|
||||||
|
if errors.Is(err, sql.ErrNoRows) {
|
||||||
|
return nil, nil
|
||||||
|
}
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return &n, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *Repository) GetNodeByID(id int64) (*Node, error) {
|
||||||
|
if r == nil || r.db == nil {
|
||||||
|
return nil, errors.New("repository not initialized")
|
||||||
|
}
|
||||||
|
|
||||||
|
row := r.db.QueryRow(`SELECT id, secret, version, http, tls, socks, status, is_remote, remote_url, remote_token, remote_config FROM node WHERE id = ? LIMIT 1`, id)
|
||||||
|
var n Node
|
||||||
|
if err := row.Scan(&n.ID, &n.Secret, &n.Version, &n.HTTP, &n.TLS, &n.Socks, &n.Status, &n.IsRemote, &n.RemoteURL, &n.RemoteToken, &n.RemoteConfig); err != nil {
|
||||||
if errors.Is(err, sql.ErrNoRows) {
|
if errors.Is(err, sql.ErrNoRows) {
|
||||||
return nil, nil
|
return nil, nil
|
||||||
}
|
}
|
||||||
@@ -454,7 +531,7 @@ func (r *Repository) ListNodes() ([]map[string]interface{}, error) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
rows, err := r.db.Query(`
|
rows, err := r.db.Query(`
|
||||||
SELECT id, inx, name, server_ip, server_ip_v4, server_ip_v6, port, tcp_listen_addr, udp_listen_addr, version, http, tls, socks, status
|
SELECT id, inx, name, server_ip, server_ip_v4, server_ip_v6, port, tcp_listen_addr, udp_listen_addr, version, http, tls, socks, status, is_remote, remote_url, remote_token, remote_config
|
||||||
FROM node
|
FROM node
|
||||||
ORDER BY inx ASC, id ASC
|
ORDER BY inx ASC, id ASC
|
||||||
`)
|
`)
|
||||||
@@ -467,10 +544,10 @@ func (r *Repository) ListNodes() ([]map[string]interface{}, error) {
|
|||||||
for rows.Next() {
|
for rows.Next() {
|
||||||
var id, inx int64
|
var id, inx int64
|
||||||
var name, serverIP, port string
|
var name, serverIP, port string
|
||||||
var serverIPV4, serverIPV6, tcpListen, udpListen, version sql.NullString
|
var serverIPV4, serverIPV6, tcpListen, udpListen, version, remoteURL, remoteToken, remoteConfig sql.NullString
|
||||||
var httpVal, tlsVal, socksVal, status int
|
var httpVal, tlsVal, socksVal, status, isRemote int
|
||||||
|
|
||||||
if err := rows.Scan(&id, &inx, &name, &serverIP, &serverIPV4, &serverIPV6, &port, &tcpListen, &udpListen, &version, &httpVal, &tlsVal, &socksVal, &status); err != nil {
|
if err := rows.Scan(&id, &inx, &name, &serverIP, &serverIPV4, &serverIPV6, &port, &tcpListen, &udpListen, &version, &httpVal, &tlsVal, &socksVal, &status, &isRemote, &remoteURL, &remoteToken, &remoteConfig); err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -490,6 +567,10 @@ func (r *Repository) ListNodes() ([]map[string]interface{}, error) {
|
|||||||
"tls": tlsVal,
|
"tls": tlsVal,
|
||||||
"socks": socksVal,
|
"socks": socksVal,
|
||||||
"status": status,
|
"status": status,
|
||||||
|
"isRemote": isRemote,
|
||||||
|
"remoteUrl": nullableString(remoteURL),
|
||||||
|
"remoteToken": nullableString(remoteToken),
|
||||||
|
"remoteConfig": nullableString(remoteConfig),
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1167,25 +1248,410 @@ func bootstrapSchema(db *sql.DB) error {
|
|||||||
return errors.New("nil db")
|
return errors.New("nil db")
|
||||||
}
|
}
|
||||||
|
|
||||||
var exists int
|
|
||||||
err := db.QueryRow(`SELECT COUNT(1) FROM sqlite_master WHERE type='table' AND name='user'`).Scan(&exists)
|
|
||||||
if err != nil {
|
|
||||||
return fmt.Errorf("check schema: %w", err)
|
|
||||||
}
|
|
||||||
if exists > 0 {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
log.Printf("sqlite schema not found, bootstrapping embedded schema")
|
|
||||||
if _, err := db.Exec(embeddedSchema); err != nil {
|
if _, err := db.Exec(embeddedSchema); err != nil {
|
||||||
return fmt.Errorf("apply schema.sql: %w", err)
|
return fmt.Errorf("apply schema.sql: %w", err)
|
||||||
}
|
}
|
||||||
|
|
||||||
if _, err := db.Exec(embeddedSeedData); err != nil {
|
if _, err := db.Exec(embeddedSeedData); err != nil {
|
||||||
return fmt.Errorf("apply data.sql: %w", err)
|
return fmt.Errorf("apply data.sql: %w", err)
|
||||||
}
|
}
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func migrateSchema(db *sql.DB) error {
|
||||||
|
if db == nil {
|
||||||
|
return errors.New("nil db")
|
||||||
|
}
|
||||||
|
|
||||||
|
ensureColumn := func(table, col, typ string) {
|
||||||
|
var dummy interface{}
|
||||||
|
err := db.QueryRow(fmt.Sprintf("SELECT %s FROM %s LIMIT 1", col, table)).Scan(&dummy)
|
||||||
|
if err == nil || errors.Is(err, sql.ErrNoRows) {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if strings.Contains(err.Error(), "no such column") {
|
||||||
|
if _, alterErr := db.Exec(fmt.Sprintf("ALTER TABLE %s ADD COLUMN %s %s", table, col, typ)); alterErr != nil {
|
||||||
|
log.Printf("failed to add column %s to %s: %v", col, table, alterErr)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
columnsByTable := map[string]map[string]string{
|
||||||
|
"peer_share": {
|
||||||
|
"allowed_domains": "TEXT DEFAULT ''",
|
||||||
|
"allowed_ips": "TEXT DEFAULT ''",
|
||||||
|
},
|
||||||
|
"node": {
|
||||||
|
"server_ip_v4": "VARCHAR(100)",
|
||||||
|
"server_ip_v6": "VARCHAR(100)",
|
||||||
|
"inx": "INTEGER NOT NULL DEFAULT 0",
|
||||||
|
"is_remote": "INTEGER DEFAULT 0",
|
||||||
|
"remote_url": "TEXT",
|
||||||
|
"remote_token": "TEXT",
|
||||||
|
"remote_config": "TEXT",
|
||||||
|
},
|
||||||
|
"tunnel": {
|
||||||
|
"inx": "INTEGER NOT NULL DEFAULT 0",
|
||||||
|
},
|
||||||
|
"forward": {
|
||||||
|
"inx": "INTEGER NOT NULL DEFAULT 0",
|
||||||
|
},
|
||||||
|
"chain_tunnel": {
|
||||||
|
"inx": "INTEGER",
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
for table, columns := range columnsByTable {
|
||||||
|
for col, typ := range columns {
|
||||||
|
ensureColumn(table, col, typ)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *Repository) CreatePeerShare(share *PeerShare) error {
|
||||||
|
if r == nil || r.db == nil {
|
||||||
|
return errors.New("repository not initialized")
|
||||||
|
}
|
||||||
|
_, err := r.db.Exec(`
|
||||||
|
INSERT INTO peer_share(name, node_id, token, max_bandwidth, expiry_time, port_range_start, port_range_end, current_flow, is_active, created_time, updated_time, allowed_domains, allowed_ips)
|
||||||
|
VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
||||||
|
`, share.Name, share.NodeID, share.Token, share.MaxBandwidth, share.ExpiryTime, share.PortRangeStart, share.PortRangeEnd, share.CurrentFlow, share.IsActive, share.CreatedTime, share.UpdatedTime, share.AllowedDomains, share.AllowedIPs)
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *Repository) UpdatePeerShare(share *PeerShare) error {
|
||||||
|
if r == nil || r.db == nil {
|
||||||
|
return errors.New("repository not initialized")
|
||||||
|
}
|
||||||
|
_, err := r.db.Exec(`
|
||||||
|
UPDATE peer_share SET name=?, max_bandwidth=?, expiry_time=?, port_range_start=?, port_range_end=?, is_active=?, updated_time=?, allowed_domains=?, allowed_ips=?
|
||||||
|
WHERE id=?
|
||||||
|
`, share.Name, share.MaxBandwidth, share.ExpiryTime, share.PortRangeStart, share.PortRangeEnd, share.IsActive, share.UpdatedTime, share.AllowedDomains, share.AllowedIPs, share.ID)
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *Repository) DeletePeerShare(id int64) error {
|
||||||
|
if r == nil || r.db == nil {
|
||||||
|
return errors.New("repository not initialized")
|
||||||
|
}
|
||||||
|
tx, err := r.db.Begin()
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
defer func() { _ = tx.Rollback() }()
|
||||||
|
_, _ = tx.Exec(`DELETE FROM peer_share_runtime WHERE share_id = ?`, id)
|
||||||
|
if _, err := tx.Exec(`DELETE FROM peer_share WHERE id=?`, id); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
return tx.Commit()
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *Repository) GetPeerShare(id int64) (*PeerShare, error) {
|
||||||
|
if r == nil || r.db == nil {
|
||||||
|
return nil, errors.New("repository not initialized")
|
||||||
|
}
|
||||||
|
row := r.db.QueryRow(`SELECT id, name, node_id, token, max_bandwidth, expiry_time, port_range_start, port_range_end, current_flow, is_active, created_time, updated_time, allowed_domains, allowed_ips FROM peer_share WHERE id = ?`, id)
|
||||||
|
var s PeerShare
|
||||||
|
if err := row.Scan(&s.ID, &s.Name, &s.NodeID, &s.Token, &s.MaxBandwidth, &s.ExpiryTime, &s.PortRangeStart, &s.PortRangeEnd, &s.CurrentFlow, &s.IsActive, &s.CreatedTime, &s.UpdatedTime, &s.AllowedDomains, &s.AllowedIPs); err != nil {
|
||||||
|
if errors.Is(err, sql.ErrNoRows) {
|
||||||
|
return nil, nil
|
||||||
|
}
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return &s, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *Repository) GetPeerShareByToken(token string) (*PeerShare, error) {
|
||||||
|
if r == nil || r.db == nil {
|
||||||
|
return nil, errors.New("repository not initialized")
|
||||||
|
}
|
||||||
|
row := r.db.QueryRow(`SELECT id, name, node_id, token, max_bandwidth, expiry_time, port_range_start, port_range_end, current_flow, is_active, created_time, updated_time, allowed_domains, allowed_ips FROM peer_share WHERE token = ?`, token)
|
||||||
|
var s PeerShare
|
||||||
|
if err := row.Scan(&s.ID, &s.Name, &s.NodeID, &s.Token, &s.MaxBandwidth, &s.ExpiryTime, &s.PortRangeStart, &s.PortRangeEnd, &s.CurrentFlow, &s.IsActive, &s.CreatedTime, &s.UpdatedTime, &s.AllowedDomains, &s.AllowedIPs); err != nil {
|
||||||
|
if errors.Is(err, sql.ErrNoRows) {
|
||||||
|
return nil, nil
|
||||||
|
}
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return &s, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *Repository) ListPeerShares() ([]PeerShare, error) {
|
||||||
|
if r == nil || r.db == nil {
|
||||||
|
return nil, errors.New("repository not initialized")
|
||||||
|
}
|
||||||
|
rows, err := r.db.Query(`SELECT id, name, node_id, token, max_bandwidth, expiry_time, port_range_start, port_range_end, current_flow, is_active, created_time, updated_time, allowed_domains, allowed_ips FROM peer_share ORDER BY id DESC`)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
defer rows.Close()
|
||||||
|
|
||||||
|
var shares []PeerShare
|
||||||
|
for rows.Next() {
|
||||||
|
var s PeerShare
|
||||||
|
if err := rows.Scan(&s.ID, &s.Name, &s.NodeID, &s.Token, &s.MaxBandwidth, &s.ExpiryTime, &s.PortRangeStart, &s.PortRangeEnd, &s.CurrentFlow, &s.IsActive, &s.CreatedTime, &s.UpdatedTime, &s.AllowedDomains, &s.AllowedIPs); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
shares = append(shares, s)
|
||||||
|
}
|
||||||
|
return shares, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *Repository) GetPeerShareRuntimeByResourceKey(shareID int64, resourceKey string) (*PeerShareRuntime, error) {
|
||||||
|
if r == nil || r.db == nil {
|
||||||
|
return nil, errors.New("repository not initialized")
|
||||||
|
}
|
||||||
|
row := r.db.QueryRow(`
|
||||||
|
SELECT id, share_id, node_id, reservation_id, resource_key, binding_id, role, chain_name, service_name, protocol, strategy, port, target, applied, status, created_time, updated_time
|
||||||
|
FROM peer_share_runtime
|
||||||
|
WHERE share_id = ? AND resource_key = ?
|
||||||
|
LIMIT 1
|
||||||
|
`, shareID, resourceKey)
|
||||||
|
var item PeerShareRuntime
|
||||||
|
if err := row.Scan(&item.ID, &item.ShareID, &item.NodeID, &item.ReservationID, &item.ResourceKey, &item.BindingID, &item.Role, &item.ChainName, &item.ServiceName, &item.Protocol, &item.Strategy, &item.Port, &item.Target, &item.Applied, &item.Status, &item.CreatedTime, &item.UpdatedTime); err != nil {
|
||||||
|
if errors.Is(err, sql.ErrNoRows) {
|
||||||
|
return nil, nil
|
||||||
|
}
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return &item, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *Repository) GetPeerShareRuntimeByReservationID(shareID int64, reservationID string) (*PeerShareRuntime, error) {
|
||||||
|
if r == nil || r.db == nil {
|
||||||
|
return nil, errors.New("repository not initialized")
|
||||||
|
}
|
||||||
|
row := r.db.QueryRow(`
|
||||||
|
SELECT id, share_id, node_id, reservation_id, resource_key, binding_id, role, chain_name, service_name, protocol, strategy, port, target, applied, status, created_time, updated_time
|
||||||
|
FROM peer_share_runtime
|
||||||
|
WHERE share_id = ? AND reservation_id = ?
|
||||||
|
LIMIT 1
|
||||||
|
`, shareID, reservationID)
|
||||||
|
var item PeerShareRuntime
|
||||||
|
if err := row.Scan(&item.ID, &item.ShareID, &item.NodeID, &item.ReservationID, &item.ResourceKey, &item.BindingID, &item.Role, &item.ChainName, &item.ServiceName, &item.Protocol, &item.Strategy, &item.Port, &item.Target, &item.Applied, &item.Status, &item.CreatedTime, &item.UpdatedTime); err != nil {
|
||||||
|
if errors.Is(err, sql.ErrNoRows) {
|
||||||
|
return nil, nil
|
||||||
|
}
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return &item, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *Repository) GetPeerShareRuntimeByBindingID(shareID int64, bindingID string) (*PeerShareRuntime, error) {
|
||||||
|
if r == nil || r.db == nil {
|
||||||
|
return nil, errors.New("repository not initialized")
|
||||||
|
}
|
||||||
|
row := r.db.QueryRow(`
|
||||||
|
SELECT id, share_id, node_id, reservation_id, resource_key, binding_id, role, chain_name, service_name, protocol, strategy, port, target, applied, status, created_time, updated_time
|
||||||
|
FROM peer_share_runtime
|
||||||
|
WHERE share_id = ? AND binding_id = ?
|
||||||
|
LIMIT 1
|
||||||
|
`, shareID, bindingID)
|
||||||
|
var item PeerShareRuntime
|
||||||
|
if err := row.Scan(&item.ID, &item.ShareID, &item.NodeID, &item.ReservationID, &item.ResourceKey, &item.BindingID, &item.Role, &item.ChainName, &item.ServiceName, &item.Protocol, &item.Strategy, &item.Port, &item.Target, &item.Applied, &item.Status, &item.CreatedTime, &item.UpdatedTime); err != nil {
|
||||||
|
if errors.Is(err, sql.ErrNoRows) {
|
||||||
|
return nil, nil
|
||||||
|
}
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return &item, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *Repository) GetPeerShareRuntimeByID(id int64) (*PeerShareRuntime, error) {
|
||||||
|
if r == nil || r.db == nil {
|
||||||
|
return nil, errors.New("repository not initialized")
|
||||||
|
}
|
||||||
|
row := r.db.QueryRow(`
|
||||||
|
SELECT id, share_id, node_id, reservation_id, resource_key, binding_id, role, chain_name, service_name, protocol, strategy, port, target, applied, status, created_time, updated_time
|
||||||
|
FROM peer_share_runtime
|
||||||
|
WHERE id = ?
|
||||||
|
LIMIT 1
|
||||||
|
`, id)
|
||||||
|
var item PeerShareRuntime
|
||||||
|
if err := row.Scan(&item.ID, &item.ShareID, &item.NodeID, &item.ReservationID, &item.ResourceKey, &item.BindingID, &item.Role, &item.ChainName, &item.ServiceName, &item.Protocol, &item.Strategy, &item.Port, &item.Target, &item.Applied, &item.Status, &item.CreatedTime, &item.UpdatedTime); err != nil {
|
||||||
|
if errors.Is(err, sql.ErrNoRows) {
|
||||||
|
return nil, nil
|
||||||
|
}
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return &item, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *Repository) ListActivePeerShareRuntimesByShareID(shareID int64) ([]PeerShareRuntime, error) {
|
||||||
|
if r == nil || r.db == nil {
|
||||||
|
return nil, errors.New("repository not initialized")
|
||||||
|
}
|
||||||
|
rows, err := r.db.Query(`
|
||||||
|
SELECT id, share_id, node_id, reservation_id, resource_key, binding_id, role, chain_name, service_name, protocol, strategy, port, target, applied, status, created_time, updated_time
|
||||||
|
FROM peer_share_runtime
|
||||||
|
WHERE share_id = ? AND status = 1
|
||||||
|
ORDER BY port ASC, id ASC
|
||||||
|
`, shareID)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
defer rows.Close()
|
||||||
|
|
||||||
|
out := make([]PeerShareRuntime, 0)
|
||||||
|
for rows.Next() {
|
||||||
|
var item PeerShareRuntime
|
||||||
|
if err := rows.Scan(&item.ID, &item.ShareID, &item.NodeID, &item.ReservationID, &item.ResourceKey, &item.BindingID, &item.Role, &item.ChainName, &item.ServiceName, &item.Protocol, &item.Strategy, &item.Port, &item.Target, &item.Applied, &item.Status, &item.CreatedTime, &item.UpdatedTime); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
out = append(out, item)
|
||||||
|
}
|
||||||
|
if err := rows.Err(); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return out, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *Repository) AddPeerShareCurrentFlow(shareID int64, delta int64) error {
|
||||||
|
if r == nil || r.db == nil {
|
||||||
|
return errors.New("repository not initialized")
|
||||||
|
}
|
||||||
|
if shareID <= 0 || delta <= 0 {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
_, err := r.db.Exec(`UPDATE peer_share SET current_flow = current_flow + ?, updated_time = ? WHERE id = ?`, delta, unixMilliNow(), shareID)
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *Repository) ResetPeerShareCurrentFlow(shareID int64, updatedTime int64) error {
|
||||||
|
if r == nil || r.db == nil {
|
||||||
|
return errors.New("repository not initialized")
|
||||||
|
}
|
||||||
|
if shareID <= 0 {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
if updatedTime <= 0 {
|
||||||
|
updatedTime = unixMilliNow()
|
||||||
|
}
|
||||||
|
_, err := r.db.Exec(`UPDATE peer_share SET current_flow = 0, updated_time = ? WHERE id = ?`, updatedTime, shareID)
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *Repository) CreatePeerShareRuntime(item *PeerShareRuntime) error {
|
||||||
|
if r == nil || r.db == nil {
|
||||||
|
return errors.New("repository not initialized")
|
||||||
|
}
|
||||||
|
if item == nil {
|
||||||
|
return errors.New("runtime item is nil")
|
||||||
|
}
|
||||||
|
_, err := r.db.Exec(`
|
||||||
|
INSERT INTO peer_share_runtime(share_id, node_id, reservation_id, resource_key, binding_id, role, chain_name, service_name, protocol, strategy, port, target, applied, status, created_time, updated_time)
|
||||||
|
VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
||||||
|
`, item.ShareID, item.NodeID, item.ReservationID, item.ResourceKey, item.BindingID, item.Role, item.ChainName, item.ServiceName, item.Protocol, item.Strategy, item.Port, item.Target, item.Applied, item.Status, item.CreatedTime, item.UpdatedTime)
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *Repository) UpdatePeerShareRuntime(item *PeerShareRuntime) error {
|
||||||
|
if r == nil || r.db == nil {
|
||||||
|
return errors.New("repository not initialized")
|
||||||
|
}
|
||||||
|
if item == nil {
|
||||||
|
return errors.New("runtime item is nil")
|
||||||
|
}
|
||||||
|
_, err := r.db.Exec(`
|
||||||
|
UPDATE peer_share_runtime
|
||||||
|
SET binding_id = ?, role = ?, chain_name = ?, service_name = ?, protocol = ?, strategy = ?, port = ?, target = ?, applied = ?, status = ?, updated_time = ?
|
||||||
|
WHERE id = ?
|
||||||
|
`, item.BindingID, item.Role, item.ChainName, item.ServiceName, item.Protocol, item.Strategy, item.Port, item.Target, item.Applied, item.Status, item.UpdatedTime, item.ID)
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *Repository) MarkPeerShareRuntimeReleased(id int64, updatedTime int64) error {
|
||||||
|
if r == nil || r.db == nil {
|
||||||
|
return errors.New("repository not initialized")
|
||||||
|
}
|
||||||
|
_, err := r.db.Exec(`UPDATE peer_share_runtime SET status = 0, updated_time = ? WHERE id = ?`, updatedTime, id)
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *Repository) ListActivePeerShareRuntimePorts(shareID int64, nodeID int64) ([]int, error) {
|
||||||
|
if r == nil || r.db == nil {
|
||||||
|
return nil, errors.New("repository not initialized")
|
||||||
|
}
|
||||||
|
rows, err := r.db.Query(`SELECT port FROM peer_share_runtime WHERE share_id = ? AND node_id = ? AND status = 1 AND port > 0`, shareID, nodeID)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
defer rows.Close()
|
||||||
|
out := make([]int, 0)
|
||||||
|
for rows.Next() {
|
||||||
|
var port int
|
||||||
|
if err := rows.Scan(&port); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
if port > 0 {
|
||||||
|
out = append(out, port)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if err := rows.Err(); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return out, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *Repository) UpsertFederationTunnelBinding(item *FederationTunnelBinding) error {
|
||||||
|
if r == nil || r.db == nil {
|
||||||
|
return errors.New("repository not initialized")
|
||||||
|
}
|
||||||
|
if item == nil {
|
||||||
|
return errors.New("binding item is nil")
|
||||||
|
}
|
||||||
|
_, err := r.db.Exec(`
|
||||||
|
INSERT INTO federation_tunnel_binding(tunnel_id, node_id, chain_type, hop_inx, remote_url, resource_key, remote_binding_id, allocated_port, status, created_time, updated_time)
|
||||||
|
VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
||||||
|
ON CONFLICT(tunnel_id, node_id, chain_type, hop_inx)
|
||||||
|
DO UPDATE SET
|
||||||
|
remote_url = excluded.remote_url,
|
||||||
|
resource_key = excluded.resource_key,
|
||||||
|
remote_binding_id = excluded.remote_binding_id,
|
||||||
|
allocated_port = excluded.allocated_port,
|
||||||
|
status = excluded.status,
|
||||||
|
updated_time = excluded.updated_time
|
||||||
|
`, item.TunnelID, item.NodeID, item.ChainType, item.HopInx, item.RemoteURL, item.ResourceKey, item.RemoteBindingID, item.AllocatedPort, item.Status, item.CreatedTime, item.UpdatedTime)
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *Repository) ListActiveFederationTunnelBindingsByTunnel(tunnelID int64) ([]FederationTunnelBinding, error) {
|
||||||
|
if r == nil || r.db == nil {
|
||||||
|
return nil, errors.New("repository not initialized")
|
||||||
|
}
|
||||||
|
rows, err := r.db.Query(`
|
||||||
|
SELECT id, tunnel_id, node_id, chain_type, hop_inx, remote_url, resource_key, remote_binding_id, allocated_port, status, created_time, updated_time
|
||||||
|
FROM federation_tunnel_binding
|
||||||
|
WHERE tunnel_id = ? AND status = 1
|
||||||
|
ORDER BY chain_type ASC, hop_inx ASC, id ASC
|
||||||
|
`, tunnelID)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
defer rows.Close()
|
||||||
|
out := make([]FederationTunnelBinding, 0)
|
||||||
|
for rows.Next() {
|
||||||
|
var item FederationTunnelBinding
|
||||||
|
if err := rows.Scan(&item.ID, &item.TunnelID, &item.NodeID, &item.ChainType, &item.HopInx, &item.RemoteURL, &item.ResourceKey, &item.RemoteBindingID, &item.AllocatedPort, &item.Status, &item.CreatedTime, &item.UpdatedTime); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
out = append(out, item)
|
||||||
|
}
|
||||||
|
if err := rows.Err(); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return out, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *Repository) DeleteFederationTunnelBindingsByTunnel(tunnelID int64) error {
|
||||||
|
if r == nil || r.db == nil {
|
||||||
|
return errors.New("repository not initialized")
|
||||||
|
}
|
||||||
|
_, err := r.db.Exec(`DELETE FROM federation_tunnel_binding WHERE tunnel_id = ?`, tunnelID)
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
var osMkdirAll = func(path string) error {
|
var osMkdirAll = func(path string) error {
|
||||||
return os.MkdirAll(path, 0o755)
|
return os.MkdirAll(path, 0o755)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -42,7 +42,11 @@ CREATE TABLE IF NOT EXISTS node (
|
|||||||
status INTEGER NOT NULL,
|
status INTEGER NOT NULL,
|
||||||
tcp_listen_addr VARCHAR(100) NOT NULL DEFAULT '[::]',
|
tcp_listen_addr VARCHAR(100) NOT NULL DEFAULT '[::]',
|
||||||
udp_listen_addr VARCHAR(100) NOT NULL DEFAULT '[::]',
|
udp_listen_addr VARCHAR(100) NOT NULL DEFAULT '[::]',
|
||||||
inx INTEGER NOT NULL DEFAULT 0
|
inx INTEGER NOT NULL DEFAULT 0,
|
||||||
|
is_remote INTEGER DEFAULT 0,
|
||||||
|
remote_url TEXT,
|
||||||
|
remote_token TEXT,
|
||||||
|
remote_config TEXT
|
||||||
);
|
);
|
||||||
|
|
||||||
CREATE TABLE IF NOT EXISTS speed_limit (
|
CREATE TABLE IF NOT EXISTS speed_limit (
|
||||||
@@ -173,6 +177,7 @@ CREATE UNIQUE INDEX IF NOT EXISTS idx_tunnel_group_tunnel_unique ON tunnel_group
|
|||||||
CREATE UNIQUE INDEX IF NOT EXISTS idx_user_group_user_unique ON user_group_user(user_group_id, user_id);
|
CREATE UNIQUE INDEX IF NOT EXISTS idx_user_group_user_unique ON user_group_user(user_group_id, user_id);
|
||||||
CREATE UNIQUE INDEX IF NOT EXISTS idx_group_permission_unique ON group_permission(user_group_id, tunnel_group_id);
|
CREATE UNIQUE INDEX IF NOT EXISTS idx_group_permission_unique ON group_permission(user_group_id, tunnel_group_id);
|
||||||
CREATE UNIQUE INDEX IF NOT EXISTS idx_group_permission_grant_unique ON group_permission_grant(user_group_id, tunnel_group_id, user_tunnel_id);
|
CREATE UNIQUE INDEX IF NOT EXISTS idx_group_permission_grant_unique ON group_permission_grant(user_group_id, tunnel_group_id, user_tunnel_id);
|
||||||
|
CREATE UNIQUE INDEX IF NOT EXISTS idx_user_tunnel_unique ON user_tunnel(user_id, tunnel_id);
|
||||||
|
|
||||||
CREATE TABLE IF NOT EXISTS vite_config (
|
CREATE TABLE IF NOT EXISTS vite_config (
|
||||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||||
@@ -180,3 +185,61 @@ CREATE TABLE IF NOT EXISTS vite_config (
|
|||||||
value VARCHAR(200) NOT NULL,
|
value VARCHAR(200) NOT NULL,
|
||||||
time INTEGER NOT NULL
|
time INTEGER NOT NULL
|
||||||
);
|
);
|
||||||
|
|
||||||
|
CREATE TABLE IF NOT EXISTS peer_share (
|
||||||
|
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||||
|
name TEXT NOT NULL,
|
||||||
|
node_id INTEGER NOT NULL,
|
||||||
|
token TEXT NOT NULL UNIQUE,
|
||||||
|
max_bandwidth INTEGER DEFAULT 0,
|
||||||
|
expiry_time INTEGER DEFAULT 0,
|
||||||
|
port_range_start INTEGER DEFAULT 0,
|
||||||
|
port_range_end INTEGER DEFAULT 0,
|
||||||
|
current_flow INTEGER DEFAULT 0,
|
||||||
|
is_active INTEGER DEFAULT 1,
|
||||||
|
created_time INTEGER NOT NULL,
|
||||||
|
updated_time INTEGER NOT NULL,
|
||||||
|
allowed_domains TEXT DEFAULT '',
|
||||||
|
allowed_ips TEXT DEFAULT ''
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE TABLE IF NOT EXISTS peer_share_runtime (
|
||||||
|
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||||
|
share_id INTEGER NOT NULL,
|
||||||
|
node_id INTEGER NOT NULL,
|
||||||
|
reservation_id TEXT NOT NULL UNIQUE,
|
||||||
|
resource_key TEXT NOT NULL UNIQUE,
|
||||||
|
binding_id TEXT NOT NULL DEFAULT '',
|
||||||
|
role TEXT NOT NULL DEFAULT '',
|
||||||
|
chain_name TEXT NOT NULL DEFAULT '',
|
||||||
|
service_name TEXT NOT NULL DEFAULT '',
|
||||||
|
protocol TEXT NOT NULL DEFAULT 'tls',
|
||||||
|
strategy TEXT NOT NULL DEFAULT 'round',
|
||||||
|
port INTEGER NOT NULL DEFAULT 0,
|
||||||
|
target TEXT NOT NULL DEFAULT '',
|
||||||
|
applied INTEGER NOT NULL DEFAULT 0,
|
||||||
|
status INTEGER NOT NULL DEFAULT 1,
|
||||||
|
created_time INTEGER NOT NULL,
|
||||||
|
updated_time INTEGER NOT NULL
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_peer_share_runtime_share_node_status ON peer_share_runtime(share_id, node_id, status);
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_peer_share_runtime_binding_id ON peer_share_runtime(binding_id);
|
||||||
|
|
||||||
|
CREATE TABLE IF NOT EXISTS federation_tunnel_binding (
|
||||||
|
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||||
|
tunnel_id INTEGER NOT NULL,
|
||||||
|
node_id INTEGER NOT NULL,
|
||||||
|
chain_type INTEGER NOT NULL,
|
||||||
|
hop_inx INTEGER NOT NULL DEFAULT 0,
|
||||||
|
remote_url TEXT NOT NULL,
|
||||||
|
resource_key TEXT NOT NULL UNIQUE,
|
||||||
|
remote_binding_id TEXT NOT NULL,
|
||||||
|
allocated_port INTEGER NOT NULL,
|
||||||
|
status INTEGER NOT NULL DEFAULT 1,
|
||||||
|
created_time INTEGER NOT NULL,
|
||||||
|
updated_time INTEGER NOT NULL
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE UNIQUE INDEX IF NOT EXISTS idx_federation_tunnel_binding_unique ON federation_tunnel_binding(tunnel_id, node_id, chain_type, hop_inx);
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_federation_tunnel_binding_tunnel ON federation_tunnel_binding(tunnel_id, status);
|
||||||
|
|||||||
@@ -8,6 +8,7 @@ import (
|
|||||||
"path/filepath"
|
"path/filepath"
|
||||||
"strconv"
|
"strconv"
|
||||||
"strings"
|
"strings"
|
||||||
|
"sync/atomic"
|
||||||
"testing"
|
"testing"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
@@ -205,6 +206,173 @@ func TestDiagnosisChainCoverageContracts(t *testing.T) {
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TestDiagnosisUsesFederationRuntimeForRemoteNodes(t *testing.T) {
|
||||||
|
secret := "contract-jwt-secret"
|
||||||
|
router, repo := setupDiagnosisContractRouter(t, secret)
|
||||||
|
now := time.Now().UnixMilli()
|
||||||
|
|
||||||
|
remoteToken := "remote-diagnose-token"
|
||||||
|
var remoteDiagnoseCalls int32
|
||||||
|
remoteServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
if r.URL.Path != "/api/v1/federation/runtime/diagnose" {
|
||||||
|
http.NotFound(w, r)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if got := strings.TrimSpace(r.Header.Get("Authorization")); got != "Bearer "+remoteToken {
|
||||||
|
w.WriteHeader(http.StatusUnauthorized)
|
||||||
|
_ = json.NewEncoder(w).Encode(map[string]interface{}{"code": -1, "msg": "unauthorized"})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
var req map[string]interface{}
|
||||||
|
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
|
||||||
|
w.WriteHeader(http.StatusBadRequest)
|
||||||
|
_ = json.NewEncoder(w).Encode(map[string]interface{}{"code": -1, "msg": "bad request"})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if strings.TrimSpace(valueAsString(req["ip"])) != "10.50.0.30" {
|
||||||
|
w.WriteHeader(http.StatusBadRequest)
|
||||||
|
_ = json.NewEncoder(w).Encode(map[string]interface{}{"code": -1, "msg": "unexpected target ip"})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if valueAsInt(req["port"]) != 30003 {
|
||||||
|
w.WriteHeader(http.StatusBadRequest)
|
||||||
|
_ = json.NewEncoder(w).Encode(map[string]interface{}{"code": -1, "msg": "unexpected target port"})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
atomic.AddInt32(&remoteDiagnoseCalls, 1)
|
||||||
|
_ = json.NewEncoder(w).Encode(map[string]interface{}{
|
||||||
|
"code": 0,
|
||||||
|
"msg": "success",
|
||||||
|
"data": map[string]interface{}{
|
||||||
|
"success": true,
|
||||||
|
"averageTime": 12.5,
|
||||||
|
"packetLoss": 0,
|
||||||
|
"message": "remote tcp ok",
|
||||||
|
},
|
||||||
|
})
|
||||||
|
}))
|
||||||
|
defer remoteServer.Close()
|
||||||
|
|
||||||
|
insertLocalNode := func(name, ip string) int64 {
|
||||||
|
res, err := repo.DB().Exec(`
|
||||||
|
INSERT INTO node(name, secret, server_ip, server_ip_v4, server_ip_v6, port, interface_name, version, http, tls, socks, created_time, updated_time, status, tcp_listen_addr, udp_listen_addr, inx)
|
||||||
|
VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
||||||
|
`, name, name+"-secret", ip, ip, "", "30000-30010", "", "v1", 1, 1, 1, now, now, 1, "[::]", "[::]", 0)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("insert local node %s: %v", name, err)
|
||||||
|
}
|
||||||
|
id, err := res.LastInsertId()
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("get local node id %s: %v", name, err)
|
||||||
|
}
|
||||||
|
return id
|
||||||
|
}
|
||||||
|
|
||||||
|
insertRemoteNode := func(name, ip string) int64 {
|
||||||
|
res, err := repo.DB().Exec(`
|
||||||
|
INSERT INTO node(name, secret, server_ip, server_ip_v4, server_ip_v6, port, interface_name, version, http, tls, socks, created_time, updated_time, status, tcp_listen_addr, udp_listen_addr, inx, is_remote, remote_url, remote_token, remote_config)
|
||||||
|
VALUES(?, ?, ?, ?, ?, ?, ?, ?, 0, 0, 0, ?, ?, 1, ?, ?, ?, 1, ?, ?, ?)
|
||||||
|
`, name, name+"-secret", ip, "", "", "31000-31010", "", "", now, now, "[::]", "[::]", 1, remoteServer.URL, remoteToken, `{"shareId": 123}`)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("insert remote node %s: %v", name, err)
|
||||||
|
}
|
||||||
|
id, err := res.LastInsertId()
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("get remote node id %s: %v", name, err)
|
||||||
|
}
|
||||||
|
return id
|
||||||
|
}
|
||||||
|
|
||||||
|
entryNodeID := insertLocalNode("entry-local", "10.50.0.10")
|
||||||
|
remoteChainNodeID := insertRemoteNode("middle-remote", "10.50.0.20")
|
||||||
|
exitNodeID := insertLocalNode("exit-local", "10.50.0.30")
|
||||||
|
|
||||||
|
tunnelRes, err := repo.DB().Exec(`
|
||||||
|
INSERT INTO tunnel(name, traffic_ratio, type, protocol, flow, created_time, updated_time, status, in_ip, inx)
|
||||||
|
VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
||||||
|
`, "diagnose-remote-tunnel", 1.0, 2, "tls", 99999, now, now, 1, nil, 0)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("insert tunnel: %v", err)
|
||||||
|
}
|
||||||
|
tunnelID, err := tunnelRes.LastInsertId()
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("get tunnel id: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
if _, err := repo.DB().Exec(`
|
||||||
|
INSERT INTO chain_tunnel(tunnel_id, chain_type, node_id, port, strategy, inx, protocol)
|
||||||
|
VALUES(?, 1, ?, 30001, 'round', 1, 'tls')
|
||||||
|
`, tunnelID, entryNodeID); err != nil {
|
||||||
|
t.Fatalf("insert entry chain: %v", err)
|
||||||
|
}
|
||||||
|
if _, err := repo.DB().Exec(`
|
||||||
|
INSERT INTO chain_tunnel(tunnel_id, chain_type, node_id, port, strategy, inx, protocol)
|
||||||
|
VALUES(?, 2, ?, 30002, 'round', 1, 'tls')
|
||||||
|
`, tunnelID, remoteChainNodeID); err != nil {
|
||||||
|
t.Fatalf("insert middle chain: %v", err)
|
||||||
|
}
|
||||||
|
if _, err := repo.DB().Exec(`
|
||||||
|
INSERT INTO chain_tunnel(tunnel_id, chain_type, node_id, port, strategy, inx, protocol)
|
||||||
|
VALUES(?, 3, ?, 30003, 'round', 1, 'tls')
|
||||||
|
`, tunnelID, exitNodeID); err != nil {
|
||||||
|
t.Fatalf("insert exit chain: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
adminToken, err := auth.GenerateToken(1, "admin_user", 0, secret)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("generate admin token: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
req := httptest.NewRequest(http.MethodPost, "/api/v1/tunnel/diagnose", bytes.NewBufferString(`{"tunnelId":`+strconv.FormatInt(tunnelID, 10)+`}`))
|
||||||
|
req.Header.Set("Authorization", adminToken)
|
||||||
|
res := httptest.NewRecorder()
|
||||||
|
|
||||||
|
router.ServeHTTP(res, req)
|
||||||
|
|
||||||
|
var out response.R
|
||||||
|
if err := json.NewDecoder(res.Body).Decode(&out); err != nil {
|
||||||
|
t.Fatalf("decode response: %v", err)
|
||||||
|
}
|
||||||
|
if out.Code != 0 {
|
||||||
|
t.Fatalf("expected code 0, got %d (%s)", out.Code, out.Msg)
|
||||||
|
}
|
||||||
|
|
||||||
|
payload, ok := out.Data.(map[string]interface{})
|
||||||
|
if !ok {
|
||||||
|
t.Fatalf("expected object payload, got %T", out.Data)
|
||||||
|
}
|
||||||
|
results, ok := payload["results"].([]interface{})
|
||||||
|
if !ok || len(results) == 0 {
|
||||||
|
t.Fatalf("expected non-empty results, got %v", payload["results"])
|
||||||
|
}
|
||||||
|
|
||||||
|
remoteStepFound := false
|
||||||
|
for _, raw := range results {
|
||||||
|
item, ok := raw.(map[string]interface{})
|
||||||
|
if !ok {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if valueAsInt(item["fromChainType"]) == 2 && valueAsInt(item["toChainType"]) == 3 {
|
||||||
|
remoteStepFound = true
|
||||||
|
if !valueAsBool(item["success"]) {
|
||||||
|
t.Fatalf("expected remote chain->exit diagnosis success, got item=%v", item)
|
||||||
|
}
|
||||||
|
if strings.TrimSpace(valueAsString(item["message"])) != "remote tcp ok" {
|
||||||
|
t.Fatalf("expected remote diagnosis message, got %q", valueAsString(item["message"]))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if !remoteStepFound {
|
||||||
|
t.Fatalf("expected chain->exit diagnosis item for remote node")
|
||||||
|
}
|
||||||
|
if atomic.LoadInt32(&remoteDiagnoseCalls) == 0 {
|
||||||
|
t.Fatalf("expected federation runtime diagnose endpoint to be called")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
func valueAsInt(v interface{}) int {
|
func valueAsInt(v interface{}) int {
|
||||||
switch n := v.(type) {
|
switch n := v.(type) {
|
||||||
case float64:
|
case float64:
|
||||||
@@ -223,6 +391,24 @@ func valueAsString(v interface{}) string {
|
|||||||
return s
|
return s
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func valueAsBool(v interface{}) bool {
|
||||||
|
switch b := v.(type) {
|
||||||
|
case bool:
|
||||||
|
return b
|
||||||
|
case float64:
|
||||||
|
return b != 0
|
||||||
|
case int:
|
||||||
|
return b != 0
|
||||||
|
case int64:
|
||||||
|
return b != 0
|
||||||
|
case string:
|
||||||
|
s := strings.TrimSpace(strings.ToLower(b))
|
||||||
|
return s == "1" || s == "t" || s == "true" || s == "yes" || s == "y"
|
||||||
|
default:
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
func setupDiagnosisContractRouter(t *testing.T, jwtSecret string) (http.Handler, *sqlite.Repository) {
|
func setupDiagnosisContractRouter(t *testing.T, jwtSecret string) (http.Handler, *sqlite.Repository) {
|
||||||
t.Helper()
|
t.Helper()
|
||||||
dbPath := filepath.Join(t.TempDir(), "diagnosis-contract.db")
|
dbPath := filepath.Join(t.TempDir(), "diagnosis-contract.db")
|
||||||
|
|||||||
@@ -0,0 +1,516 @@
|
|||||||
|
package contract_test
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bytes"
|
||||||
|
"encoding/json"
|
||||||
|
"fmt"
|
||||||
|
"net/http"
|
||||||
|
"net/http/httptest"
|
||||||
|
"net/url"
|
||||||
|
"strings"
|
||||||
|
"sync"
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/gorilla/websocket"
|
||||||
|
|
||||||
|
"go-backend/internal/auth"
|
||||||
|
"go-backend/internal/http/response"
|
||||||
|
"go-backend/internal/security"
|
||||||
|
"go-backend/internal/store/sqlite"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestFederationDualPanelMiddleExitAutoPortContract(t *testing.T) {
|
||||||
|
providerSecret := "provider-contract-jwt"
|
||||||
|
providerRouter, providerRepo := setupContractRouter(t, providerSecret)
|
||||||
|
providerServer := httptest.NewServer(providerRouter)
|
||||||
|
defer providerServer.Close()
|
||||||
|
|
||||||
|
consumerSecret := "consumer-contract-jwt"
|
||||||
|
consumerRouter, consumerRepo := setupContractRouter(t, consumerSecret)
|
||||||
|
|
||||||
|
consumerAdminToken, err := auth.GenerateToken(1, "consumer-admin", 0, consumerSecret)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("generate consumer admin token: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
now := time.Now().UnixMilli()
|
||||||
|
providerEntryNodeID := insertContractNode(t, providerRepo, "provider-entry", "198.51.100.11", "43000-43010", "provider-entry-secret", 1)
|
||||||
|
providerMiddleNodeID := insertContractNode(t, providerRepo, "provider-middle", "198.51.100.12", "44000-44010", "provider-middle-secret", 1)
|
||||||
|
providerExitNodeID := insertContractNode(t, providerRepo, "provider-exit", "198.51.100.13", "45000-45010", "provider-exit-secret", 1)
|
||||||
|
|
||||||
|
entryShareID := insertPeerShare(t, providerRepo, &sqlite.PeerShare{
|
||||||
|
Name: "entry-share",
|
||||||
|
NodeID: providerEntryNodeID,
|
||||||
|
Token: "share-entry-token",
|
||||||
|
PortRangeStart: 43000,
|
||||||
|
PortRangeEnd: 43010,
|
||||||
|
IsActive: 1,
|
||||||
|
CreatedTime: now,
|
||||||
|
UpdatedTime: now,
|
||||||
|
})
|
||||||
|
middleShareID := insertPeerShare(t, providerRepo, &sqlite.PeerShare{
|
||||||
|
Name: "middle-share",
|
||||||
|
NodeID: providerMiddleNodeID,
|
||||||
|
Token: "share-middle-token",
|
||||||
|
PortRangeStart: 44000,
|
||||||
|
PortRangeEnd: 44010,
|
||||||
|
IsActive: 1,
|
||||||
|
CreatedTime: now,
|
||||||
|
UpdatedTime: now,
|
||||||
|
})
|
||||||
|
exitShareID := insertPeerShare(t, providerRepo, &sqlite.PeerShare{
|
||||||
|
Name: "exit-share",
|
||||||
|
NodeID: providerExitNodeID,
|
||||||
|
Token: "share-exit-token",
|
||||||
|
PortRangeStart: 45000,
|
||||||
|
PortRangeEnd: 45010,
|
||||||
|
IsActive: 1,
|
||||||
|
CreatedTime: now,
|
||||||
|
UpdatedTime: now,
|
||||||
|
})
|
||||||
|
|
||||||
|
importRemoteNodeForContract(t, consumerRouter, consumerAdminToken, providerServer.URL, "share-entry-token")
|
||||||
|
importRemoteNodeForContract(t, consumerRouter, consumerAdminToken, providerServer.URL, "share-middle-token")
|
||||||
|
importRemoteNodeForContract(t, consumerRouter, consumerAdminToken, providerServer.URL, "share-exit-token")
|
||||||
|
|
||||||
|
entryRemoteNodeID := queryRemoteNodeIDByToken(t, consumerRepo, "share-entry-token")
|
||||||
|
middleRemoteNodeID := queryRemoteNodeIDByToken(t, consumerRepo, "share-middle-token")
|
||||||
|
exitRemoteNodeID := queryRemoteNodeIDByToken(t, consumerRepo, "share-exit-token")
|
||||||
|
|
||||||
|
stopMiddle := startMockNodeSession(t, providerServer.URL, "provider-middle-secret")
|
||||||
|
defer stopMiddle()
|
||||||
|
stopExit := startMockNodeSession(t, providerServer.URL, "provider-exit-secret")
|
||||||
|
defer stopExit()
|
||||||
|
|
||||||
|
createTunnel := func(name string) int64 {
|
||||||
|
payload := map[string]interface{}{
|
||||||
|
"name": name,
|
||||||
|
"type": 2,
|
||||||
|
"flow": 99999,
|
||||||
|
"status": 1,
|
||||||
|
"inNodeId": []map[string]interface{}{
|
||||||
|
{"nodeId": entryRemoteNodeID, "protocol": "tls", "strategy": "round"},
|
||||||
|
},
|
||||||
|
"chainNodes": [][]map[string]interface{}{
|
||||||
|
{{"nodeId": middleRemoteNodeID, "protocol": "tls", "strategy": "round"}},
|
||||||
|
},
|
||||||
|
"outNodeId": []map[string]interface{}{
|
||||||
|
{"nodeId": exitRemoteNodeID, "protocol": "tls", "strategy": "round"},
|
||||||
|
},
|
||||||
|
}
|
||||||
|
body, err := json.Marshal(payload)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("marshal create payload: %v", err)
|
||||||
|
}
|
||||||
|
req := httptest.NewRequest(http.MethodPost, "/api/v1/tunnel/create", bytes.NewReader(body))
|
||||||
|
req.Header.Set("Authorization", consumerAdminToken)
|
||||||
|
req.Header.Set("Content-Type", "application/json")
|
||||||
|
res := httptest.NewRecorder()
|
||||||
|
consumerRouter.ServeHTTP(res, req)
|
||||||
|
assertCode(t, res, 0)
|
||||||
|
|
||||||
|
var tunnelID int64
|
||||||
|
if err := consumerRepo.DB().QueryRow(`SELECT id FROM tunnel WHERE name = ? ORDER BY id DESC LIMIT 1`, name).Scan(&tunnelID); err != nil {
|
||||||
|
t.Fatalf("query tunnel id (%s): %v", name, err)
|
||||||
|
}
|
||||||
|
if tunnelID <= 0 {
|
||||||
|
t.Fatalf("invalid tunnel id for %s", name)
|
||||||
|
}
|
||||||
|
return tunnelID
|
||||||
|
}
|
||||||
|
|
||||||
|
firstTunnelID := createTunnel("dual-panel-middle-exit-1")
|
||||||
|
|
||||||
|
assertTunnelPortInRange(t, consumerRepo, firstTunnelID, 2, middleRemoteNodeID, 44000, 44010)
|
||||||
|
assertTunnelPortInRange(t, consumerRepo, firstTunnelID, 3, exitRemoteNodeID, 45000, 45010)
|
||||||
|
|
||||||
|
assertCount(t, consumerRepo, `SELECT COUNT(1) FROM federation_tunnel_binding WHERE tunnel_id = ? AND status = 1`, firstTunnelID, 2)
|
||||||
|
assertCount(t, providerRepo, `SELECT COUNT(1) FROM peer_share_runtime WHERE share_id = ? AND status = 1 AND applied = 1`, middleShareID, 1)
|
||||||
|
assertCount(t, providerRepo, `SELECT COUNT(1) FROM peer_share_runtime WHERE share_id = ? AND status = 1 AND applied = 1`, exitShareID, 1)
|
||||||
|
|
||||||
|
deleteBody, err := json.Marshal(map[string]interface{}{"id": firstTunnelID})
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("marshal delete payload: %v", err)
|
||||||
|
}
|
||||||
|
deleteReq := httptest.NewRequest(http.MethodPost, "/api/v1/tunnel/delete", bytes.NewReader(deleteBody))
|
||||||
|
deleteReq.Header.Set("Authorization", consumerAdminToken)
|
||||||
|
deleteReq.Header.Set("Content-Type", "application/json")
|
||||||
|
deleteRes := httptest.NewRecorder()
|
||||||
|
consumerRouter.ServeHTTP(deleteRes, deleteReq)
|
||||||
|
assertCode(t, deleteRes, 0)
|
||||||
|
|
||||||
|
assertCount(t, consumerRepo, `SELECT COUNT(1) FROM federation_tunnel_binding WHERE tunnel_id = ?`, firstTunnelID, 0)
|
||||||
|
assertCount(t, providerRepo, `SELECT COUNT(1) FROM peer_share_runtime WHERE share_id = ? AND status = 0`, middleShareID, 1)
|
||||||
|
assertCount(t, providerRepo, `SELECT COUNT(1) FROM peer_share_runtime WHERE share_id = ? AND status = 0`, exitShareID, 1)
|
||||||
|
|
||||||
|
secondTunnelID := createTunnel("dual-panel-middle-exit-2")
|
||||||
|
assertTunnelPortInRange(t, consumerRepo, secondTunnelID, 2, middleRemoteNodeID, 44000, 44010)
|
||||||
|
assertTunnelPortInRange(t, consumerRepo, secondTunnelID, 3, exitRemoteNodeID, 45000, 45010)
|
||||||
|
|
||||||
|
assertCount(t, providerRepo, `SELECT COUNT(1) FROM peer_share_runtime WHERE share_id = ? AND status = 1 AND applied = 1`, middleShareID, 1)
|
||||||
|
assertCount(t, providerRepo, `SELECT COUNT(1) FROM peer_share_runtime WHERE share_id = ? AND status = 1 AND applied = 1`, exitShareID, 1)
|
||||||
|
assertCount(t, providerRepo, `SELECT COUNT(1) FROM peer_share_runtime WHERE share_id = ?`, entryShareID, 0)
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestFederationDualPanelRemoteDiagnosisContract(t *testing.T) {
|
||||||
|
providerSecret := "provider-contract-jwt"
|
||||||
|
providerRouter, providerRepo := setupContractRouter(t, providerSecret)
|
||||||
|
providerServer := httptest.NewServer(providerRouter)
|
||||||
|
defer providerServer.Close()
|
||||||
|
|
||||||
|
consumerSecret := "consumer-contract-jwt"
|
||||||
|
consumerRouter, consumerRepo := setupContractRouter(t, consumerSecret)
|
||||||
|
|
||||||
|
consumerAdminToken, err := auth.GenerateToken(1, "consumer-admin", 0, consumerSecret)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("generate consumer admin token: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
now := time.Now().UnixMilli()
|
||||||
|
providerEntryNodeID := insertContractNode(t, providerRepo, "provider-entry-dx", "203.0.113.11", "53000-53010", "provider-entry-dx-secret", 1)
|
||||||
|
providerMiddleNodeID := insertContractNode(t, providerRepo, "provider-middle-dx", "203.0.113.12", "54000-54010", "provider-middle-dx-secret", 1)
|
||||||
|
providerExitNodeID := insertContractNode(t, providerRepo, "provider-exit-dx", "203.0.113.13", "55000-55010", "provider-exit-dx-secret", 1)
|
||||||
|
|
||||||
|
entryShareID := insertPeerShare(t, providerRepo, &sqlite.PeerShare{
|
||||||
|
Name: "entry-share-dx",
|
||||||
|
NodeID: providerEntryNodeID,
|
||||||
|
Token: "share-entry-dx-token",
|
||||||
|
PortRangeStart: 53000,
|
||||||
|
PortRangeEnd: 53010,
|
||||||
|
IsActive: 1,
|
||||||
|
CreatedTime: now,
|
||||||
|
UpdatedTime: now,
|
||||||
|
})
|
||||||
|
middleShareID := insertPeerShare(t, providerRepo, &sqlite.PeerShare{
|
||||||
|
Name: "middle-share-dx",
|
||||||
|
NodeID: providerMiddleNodeID,
|
||||||
|
Token: "share-middle-dx-token",
|
||||||
|
PortRangeStart: 54000,
|
||||||
|
PortRangeEnd: 54010,
|
||||||
|
IsActive: 1,
|
||||||
|
CreatedTime: now,
|
||||||
|
UpdatedTime: now,
|
||||||
|
})
|
||||||
|
exitShareID := insertPeerShare(t, providerRepo, &sqlite.PeerShare{
|
||||||
|
Name: "exit-share-dx",
|
||||||
|
NodeID: providerExitNodeID,
|
||||||
|
Token: "share-exit-dx-token",
|
||||||
|
PortRangeStart: 55000,
|
||||||
|
PortRangeEnd: 55010,
|
||||||
|
IsActive: 1,
|
||||||
|
CreatedTime: now,
|
||||||
|
UpdatedTime: now,
|
||||||
|
})
|
||||||
|
|
||||||
|
importRemoteNodeForContract(t, consumerRouter, consumerAdminToken, providerServer.URL, "share-entry-dx-token")
|
||||||
|
importRemoteNodeForContract(t, consumerRouter, consumerAdminToken, providerServer.URL, "share-middle-dx-token")
|
||||||
|
importRemoteNodeForContract(t, consumerRouter, consumerAdminToken, providerServer.URL, "share-exit-dx-token")
|
||||||
|
|
||||||
|
entryRemoteNodeID := queryRemoteNodeIDByToken(t, consumerRepo, "share-entry-dx-token")
|
||||||
|
middleRemoteNodeID := queryRemoteNodeIDByToken(t, consumerRepo, "share-middle-dx-token")
|
||||||
|
exitRemoteNodeID := queryRemoteNodeIDByToken(t, consumerRepo, "share-exit-dx-token")
|
||||||
|
|
||||||
|
stopMiddle := startMockNodeSession(t, providerServer.URL, "provider-middle-dx-secret")
|
||||||
|
defer stopMiddle()
|
||||||
|
stopExit := startMockNodeSession(t, providerServer.URL, "provider-exit-dx-secret")
|
||||||
|
defer stopExit()
|
||||||
|
|
||||||
|
createPayload := map[string]interface{}{
|
||||||
|
"name": "dual-panel-diagnose-remote",
|
||||||
|
"type": 2,
|
||||||
|
"flow": 99999,
|
||||||
|
"status": 1,
|
||||||
|
"inNodeId": []map[string]interface{}{
|
||||||
|
{"nodeId": entryRemoteNodeID, "protocol": "tls", "strategy": "round"},
|
||||||
|
},
|
||||||
|
"chainNodes": [][]map[string]interface{}{
|
||||||
|
{{"nodeId": middleRemoteNodeID, "protocol": "tls", "strategy": "round"}},
|
||||||
|
},
|
||||||
|
"outNodeId": []map[string]interface{}{
|
||||||
|
{"nodeId": exitRemoteNodeID, "protocol": "tls", "strategy": "round"},
|
||||||
|
},
|
||||||
|
}
|
||||||
|
body, err := json.Marshal(createPayload)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("marshal create payload: %v", err)
|
||||||
|
}
|
||||||
|
createReq := httptest.NewRequest(http.MethodPost, "/api/v1/tunnel/create", bytes.NewReader(body))
|
||||||
|
createReq.Header.Set("Authorization", consumerAdminToken)
|
||||||
|
createReq.Header.Set("Content-Type", "application/json")
|
||||||
|
createRes := httptest.NewRecorder()
|
||||||
|
consumerRouter.ServeHTTP(createRes, createReq)
|
||||||
|
assertCode(t, createRes, 0)
|
||||||
|
|
||||||
|
var tunnelID int64
|
||||||
|
if err := consumerRepo.DB().QueryRow(`SELECT id FROM tunnel WHERE name = ? ORDER BY id DESC LIMIT 1`, "dual-panel-diagnose-remote").Scan(&tunnelID); err != nil {
|
||||||
|
t.Fatalf("query tunnel id: %v", err)
|
||||||
|
}
|
||||||
|
if tunnelID <= 0 {
|
||||||
|
t.Fatalf("invalid tunnel id")
|
||||||
|
}
|
||||||
|
|
||||||
|
assertCount(t, providerRepo, `SELECT COUNT(1) FROM peer_share_runtime WHERE share_id = ? AND status = 1 AND applied = 1`, middleShareID, 1)
|
||||||
|
assertCount(t, providerRepo, `SELECT COUNT(1) FROM peer_share_runtime WHERE share_id = ? AND status = 1 AND applied = 1`, exitShareID, 1)
|
||||||
|
assertCount(t, providerRepo, `SELECT COUNT(1) FROM peer_share_runtime WHERE share_id = ?`, entryShareID, 0)
|
||||||
|
|
||||||
|
diagnoseReq := httptest.NewRequest(http.MethodPost, "/api/v1/tunnel/diagnose", bytes.NewBufferString(fmt.Sprintf(`{"tunnelId":%d}`, tunnelID)))
|
||||||
|
diagnoseReq.Header.Set("Authorization", consumerAdminToken)
|
||||||
|
diagnoseRes := httptest.NewRecorder()
|
||||||
|
consumerRouter.ServeHTTP(diagnoseRes, diagnoseReq)
|
||||||
|
|
||||||
|
var out response.R
|
||||||
|
if err := json.NewDecoder(diagnoseRes.Body).Decode(&out); err != nil {
|
||||||
|
t.Fatalf("decode diagnose response: %v", err)
|
||||||
|
}
|
||||||
|
if out.Code != 0 {
|
||||||
|
t.Fatalf("expected diagnose code 0, got %d (%s)", out.Code, out.Msg)
|
||||||
|
}
|
||||||
|
|
||||||
|
payload, ok := out.Data.(map[string]interface{})
|
||||||
|
if !ok {
|
||||||
|
t.Fatalf("expected map payload, got %T", out.Data)
|
||||||
|
}
|
||||||
|
results, ok := payload["results"].([]interface{})
|
||||||
|
if !ok || len(results) == 0 {
|
||||||
|
t.Fatalf("expected non-empty results, got %v", payload["results"])
|
||||||
|
}
|
||||||
|
|
||||||
|
chainToExitFound := false
|
||||||
|
for _, raw := range results {
|
||||||
|
item, ok := raw.(map[string]interface{})
|
||||||
|
if !ok {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if valueAsInt(item["fromChainType"]) == 2 && valueAsInt(item["toChainType"]) == 3 {
|
||||||
|
chainToExitFound = true
|
||||||
|
if !valueAsBool(item["success"]) {
|
||||||
|
t.Fatalf("expected chain->exit diagnosis success, got item=%v", item)
|
||||||
|
}
|
||||||
|
if msg := strings.TrimSpace(valueAsString(item["message"])); msg != "mock tcp ok" {
|
||||||
|
t.Fatalf("expected remote diagnosis message 'mock tcp ok', got %q", msg)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if !chainToExitFound {
|
||||||
|
t.Fatalf("expected chain->exit diagnosis item in results")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func insertContractNode(t *testing.T, repo *sqlite.Repository, name, ip, portRange, secret string, status int) int64 {
|
||||||
|
t.Helper()
|
||||||
|
now := time.Now().UnixMilli()
|
||||||
|
res, err := repo.DB().Exec(`
|
||||||
|
INSERT INTO node(name, secret, server_ip, server_ip_v4, server_ip_v6, port, interface_name, version, http, tls, socks, created_time, updated_time, status, tcp_listen_addr, udp_listen_addr, inx)
|
||||||
|
VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
||||||
|
`, name, secret, ip, ip, "", portRange, "", "v1", 1, 1, 1, now, now, status, "[::]", "[::]", 0)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("insert node %s: %v", name, err)
|
||||||
|
}
|
||||||
|
id, err := res.LastInsertId()
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("node id %s: %v", name, err)
|
||||||
|
}
|
||||||
|
return id
|
||||||
|
}
|
||||||
|
|
||||||
|
func insertPeerShare(t *testing.T, repo *sqlite.Repository, share *sqlite.PeerShare) int64 {
|
||||||
|
t.Helper()
|
||||||
|
if share == nil {
|
||||||
|
t.Fatalf("share is nil")
|
||||||
|
}
|
||||||
|
if err := repo.CreatePeerShare(share); err != nil {
|
||||||
|
t.Fatalf("create peer share %s: %v", share.Name, err)
|
||||||
|
}
|
||||||
|
saved, err := repo.GetPeerShareByToken(share.Token)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("query peer share %s: %v", share.Name, err)
|
||||||
|
}
|
||||||
|
if saved == nil {
|
||||||
|
t.Fatalf("peer share %s not found after create", share.Name)
|
||||||
|
}
|
||||||
|
return saved.ID
|
||||||
|
}
|
||||||
|
|
||||||
|
func importRemoteNodeForContract(t *testing.T, router http.Handler, adminToken, remoteURL, token string) {
|
||||||
|
t.Helper()
|
||||||
|
body, err := json.Marshal(map[string]string{
|
||||||
|
"remoteUrl": remoteURL,
|
||||||
|
"token": token,
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("marshal import payload: %v", err)
|
||||||
|
}
|
||||||
|
req := httptest.NewRequest(http.MethodPost, "/api/v1/federation/node/import", bytes.NewReader(body))
|
||||||
|
req.Header.Set("Authorization", adminToken)
|
||||||
|
req.Header.Set("Content-Type", "application/json")
|
||||||
|
res := httptest.NewRecorder()
|
||||||
|
router.ServeHTTP(res, req)
|
||||||
|
assertCode(t, res, 0)
|
||||||
|
}
|
||||||
|
|
||||||
|
func queryRemoteNodeIDByToken(t *testing.T, repo *sqlite.Repository, token string) int64 {
|
||||||
|
t.Helper()
|
||||||
|
var id int64
|
||||||
|
if err := repo.DB().QueryRow(`SELECT id FROM node WHERE is_remote = 1 AND remote_token = ? ORDER BY id DESC LIMIT 1`, token).Scan(&id); err != nil {
|
||||||
|
t.Fatalf("query remote node by token %s: %v", token, err)
|
||||||
|
}
|
||||||
|
if id <= 0 {
|
||||||
|
t.Fatalf("invalid remote node id for token %s", token)
|
||||||
|
}
|
||||||
|
return id
|
||||||
|
}
|
||||||
|
|
||||||
|
func assertTunnelPortInRange(t *testing.T, repo *sqlite.Repository, tunnelID int64, chainType int, nodeID int64, minPort int, maxPort int) {
|
||||||
|
t.Helper()
|
||||||
|
var port int
|
||||||
|
err := repo.DB().QueryRow(`
|
||||||
|
SELECT port
|
||||||
|
FROM chain_tunnel
|
||||||
|
WHERE tunnel_id = ? AND chain_type = ? AND node_id = ?
|
||||||
|
LIMIT 1
|
||||||
|
`, tunnelID, chainType, nodeID).Scan(&port)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("query tunnel=%d chainType=%d node=%d port: %v", tunnelID, chainType, nodeID, err)
|
||||||
|
}
|
||||||
|
if port < minPort || port > maxPort {
|
||||||
|
t.Fatalf("expected port in range [%d,%d], got %d", minPort, maxPort, port)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func assertCount(t *testing.T, repo *sqlite.Repository, query string, arg interface{}, expected int) {
|
||||||
|
t.Helper()
|
||||||
|
var got int
|
||||||
|
if err := repo.DB().QueryRow(query, arg).Scan(&got); err != nil {
|
||||||
|
t.Fatalf("count query failed: %v", err)
|
||||||
|
}
|
||||||
|
if got != expected {
|
||||||
|
t.Fatalf("expected count %d, got %d (query: %s, arg: %v)", expected, got, query, arg)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func startMockNodeSession(t *testing.T, baseURL string, nodeSecret string) func() {
|
||||||
|
t.Helper()
|
||||||
|
u, err := url.Parse(baseURL)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("parse provider url: %v", err)
|
||||||
|
}
|
||||||
|
if strings.EqualFold(u.Scheme, "https") {
|
||||||
|
u.Scheme = "wss"
|
||||||
|
} else {
|
||||||
|
u.Scheme = "ws"
|
||||||
|
}
|
||||||
|
u.Path = "/system-info"
|
||||||
|
q := u.Query()
|
||||||
|
q.Set("type", "1")
|
||||||
|
q.Set("secret", nodeSecret)
|
||||||
|
q.Set("version", "v1")
|
||||||
|
q.Set("http", "1")
|
||||||
|
q.Set("tls", "1")
|
||||||
|
q.Set("socks", "1")
|
||||||
|
u.RawQuery = q.Encode()
|
||||||
|
|
||||||
|
conn, _, err := websocket.DefaultDialer.Dial(u.String(), nil)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("dial mock node websocket: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
var wg sync.WaitGroup
|
||||||
|
wg.Add(1)
|
||||||
|
go func() {
|
||||||
|
defer wg.Done()
|
||||||
|
for {
|
||||||
|
_, raw, readErr := conn.ReadMessage()
|
||||||
|
if readErr != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
plain := raw
|
||||||
|
var wrap struct {
|
||||||
|
Encrypted bool `json:"encrypted"`
|
||||||
|
Data string `json:"data"`
|
||||||
|
}
|
||||||
|
if err := json.Unmarshal(raw, &wrap); err == nil && wrap.Encrypted && strings.TrimSpace(wrap.Data) != "" {
|
||||||
|
crypto, cryptoErr := security.NewAESCrypto(nodeSecret)
|
||||||
|
if cryptoErr == nil {
|
||||||
|
if dec, decErr := crypto.Decrypt(wrap.Data); decErr == nil {
|
||||||
|
plain = []byte(dec)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
var cmd struct {
|
||||||
|
Type string `json:"type"`
|
||||||
|
RequestID string `json:"requestId"`
|
||||||
|
}
|
||||||
|
if err := json.Unmarshal(plain, &cmd); err != nil {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if strings.TrimSpace(cmd.RequestID) == "" {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
|
respType := fmt.Sprintf("%sResponse", cmd.Type)
|
||||||
|
respPayload := map[string]interface{}{
|
||||||
|
"type": respType,
|
||||||
|
"success": true,
|
||||||
|
"message": "OK",
|
||||||
|
"requestId": cmd.RequestID,
|
||||||
|
}
|
||||||
|
if strings.EqualFold(strings.TrimSpace(cmd.Type), "TcpPing") {
|
||||||
|
respPayload["data"] = map[string]interface{}{
|
||||||
|
"success": true,
|
||||||
|
"averageTime": 8.5,
|
||||||
|
"packetLoss": 0,
|
||||||
|
"message": "mock tcp ok",
|
||||||
|
}
|
||||||
|
}
|
||||||
|
respBytes, err := json.Marshal(respPayload)
|
||||||
|
if err != nil {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
_ = conn.WriteMessage(websocket.TextMessage, respBytes)
|
||||||
|
}
|
||||||
|
}()
|
||||||
|
|
||||||
|
return func() {
|
||||||
|
_ = conn.Close()
|
||||||
|
wg.Wait()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func valueAsInt(v interface{}) int {
|
||||||
|
switch n := v.(type) {
|
||||||
|
case float64:
|
||||||
|
return int(n)
|
||||||
|
case int:
|
||||||
|
return n
|
||||||
|
case int64:
|
||||||
|
return int(n)
|
||||||
|
default:
|
||||||
|
return 0
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func valueAsString(v interface{}) string {
|
||||||
|
s, _ := v.(string)
|
||||||
|
return s
|
||||||
|
}
|
||||||
|
|
||||||
|
func valueAsBool(v interface{}) bool {
|
||||||
|
switch b := v.(type) {
|
||||||
|
case bool:
|
||||||
|
return b
|
||||||
|
case float64:
|
||||||
|
return b != 0
|
||||||
|
case int:
|
||||||
|
return b != 0
|
||||||
|
case int64:
|
||||||
|
return b != 0
|
||||||
|
case string:
|
||||||
|
s := strings.TrimSpace(strings.ToLower(b))
|
||||||
|
return s == "1" || s == "t" || s == "true" || s == "yes" || s == "y"
|
||||||
|
default:
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -197,6 +197,339 @@ func TestForwardOwnershipAndScopeContracts(t *testing.T) {
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TestForwardSwitchTunnelRollbackOnSyncFailure(t *testing.T) {
|
||||||
|
secret := "contract-jwt-secret"
|
||||||
|
router, repo := setupContractRouter(t, secret)
|
||||||
|
now := time.Now().UnixMilli()
|
||||||
|
|
||||||
|
adminToken, err := auth.GenerateToken(1, "admin_user", 0, secret)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("generate admin token: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
if _, err := repo.DB().Exec(`
|
||||||
|
INSERT INTO user(id, user, pwd, role_id, exp_time, flow, in_flow, out_flow, flow_reset_time, num, created_time, updated_time, status)
|
||||||
|
VALUES(2, 'switch_user', '3c85cdebade1c51cf64ca9f3c09d182d', 1, 2727251700000, 99999, 0, 0, 1, 99999, ?, ?, 1)
|
||||||
|
`, now, now); err != nil {
|
||||||
|
t.Fatalf("insert user: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
insertTunnel := func(name string, inx int) int64 {
|
||||||
|
res, err := repo.DB().Exec(`
|
||||||
|
INSERT INTO tunnel(name, traffic_ratio, type, protocol, flow, created_time, updated_time, status, in_ip, inx)
|
||||||
|
VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
||||||
|
`, name, 1.0, 1, "tls", 99999, now, now, 1, nil, inx)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("insert tunnel %s: %v", name, err)
|
||||||
|
}
|
||||||
|
id, err := res.LastInsertId()
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("get tunnel id %s: %v", name, err)
|
||||||
|
}
|
||||||
|
return id
|
||||||
|
}
|
||||||
|
|
||||||
|
insertNode := func(name, ip, portRange string, inx int) int64 {
|
||||||
|
res, err := repo.DB().Exec(`
|
||||||
|
INSERT INTO node(name, secret, server_ip, server_ip_v4, server_ip_v6, port, interface_name, version, http, tls, socks, created_time, updated_time, status, tcp_listen_addr, udp_listen_addr, inx)
|
||||||
|
VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
||||||
|
`, name, name+"-secret", ip, ip, "", portRange, "", "v1", 1, 1, 1, now, now, 1, "[::]", "[::]", inx)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("insert node %s: %v", name, err)
|
||||||
|
}
|
||||||
|
id, err := res.LastInsertId()
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("get node id %s: %v", name, err)
|
||||||
|
}
|
||||||
|
return id
|
||||||
|
}
|
||||||
|
|
||||||
|
tunnelA := insertTunnel("switch-tunnel-a", 0)
|
||||||
|
tunnelB := insertTunnel("switch-tunnel-b", 1)
|
||||||
|
nodeA := insertNode("switch-node-a", "10.10.0.1", "21000-21010", 0)
|
||||||
|
nodeB := insertNode("switch-node-b", "10.10.0.2", "22000-22010", 1)
|
||||||
|
|
||||||
|
if _, err := repo.DB().Exec(`
|
||||||
|
INSERT INTO chain_tunnel(tunnel_id, chain_type, node_id, port, strategy, inx, protocol)
|
||||||
|
VALUES(?, 1, ?, 21001, 'round', 1, 'tls')
|
||||||
|
`, tunnelA, nodeA); err != nil {
|
||||||
|
t.Fatalf("insert chain_tunnel tunnelA: %v", err)
|
||||||
|
}
|
||||||
|
if _, err := repo.DB().Exec(`
|
||||||
|
INSERT INTO chain_tunnel(tunnel_id, chain_type, node_id, port, strategy, inx, protocol)
|
||||||
|
VALUES(?, 1, ?, 22001, 'round', 1, 'tls')
|
||||||
|
`, tunnelB, nodeB); err != nil {
|
||||||
|
t.Fatalf("insert chain_tunnel tunnelB: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
if _, err := repo.DB().Exec(`
|
||||||
|
INSERT INTO user_tunnel(id, user_id, tunnel_id, speed_id, num, flow, in_flow, out_flow, flow_reset_time, exp_time, status)
|
||||||
|
VALUES(10, 2, ?, NULL, 999, 99999, 0, 0, 1, 2727251700000, 1)
|
||||||
|
`, tunnelA); err != nil {
|
||||||
|
t.Fatalf("insert user_tunnel A: %v", err)
|
||||||
|
}
|
||||||
|
if _, err := repo.DB().Exec(`
|
||||||
|
INSERT INTO user_tunnel(id, user_id, tunnel_id, speed_id, num, flow, in_flow, out_flow, flow_reset_time, exp_time, status)
|
||||||
|
VALUES(11, 2, ?, NULL, 999, 99999, 0, 0, 1, 2727251700000, 1)
|
||||||
|
`, tunnelB); err != nil {
|
||||||
|
t.Fatalf("insert user_tunnel B: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
forwardRes, err := repo.DB().Exec(`
|
||||||
|
INSERT INTO forward(user_id, user_name, name, tunnel_id, remote_addr, strategy, in_flow, out_flow, created_time, updated_time, status, inx)
|
||||||
|
VALUES(2, 'switch_user', 'switch-forward', ?, '8.8.8.8:53', 'fifo', 0, 0, ?, ?, 1, 0)
|
||||||
|
`, tunnelA, now, now)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("insert forward: %v", err)
|
||||||
|
}
|
||||||
|
forwardID, err := forwardRes.LastInsertId()
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("get forward id: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
if _, err := repo.DB().Exec(`INSERT INTO forward_port(forward_id, node_id, port) VALUES(?, ?, ?)`, forwardID, nodeA, 21001); err != nil {
|
||||||
|
t.Fatalf("insert forward_port: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
payload := `{"id":` + jsonNumber(forwardID) + `,"tunnelId":` + jsonNumber(tunnelB) + `}`
|
||||||
|
req := httptest.NewRequest(http.MethodPost, "/api/v1/forward/update", bytes.NewBufferString(payload))
|
||||||
|
req.Header.Set("Authorization", adminToken)
|
||||||
|
req.Header.Set("Content-Type", "application/json")
|
||||||
|
res := httptest.NewRecorder()
|
||||||
|
|
||||||
|
router.ServeHTTP(res, req)
|
||||||
|
|
||||||
|
var out response.R
|
||||||
|
if err := json.NewDecoder(res.Body).Decode(&out); err != nil {
|
||||||
|
t.Fatalf("decode response: %v", err)
|
||||||
|
}
|
||||||
|
if out.Code == 0 {
|
||||||
|
t.Fatalf("expected update failure when node is offline")
|
||||||
|
}
|
||||||
|
|
||||||
|
var tunnelAfter int64
|
||||||
|
if err := repo.DB().QueryRow(`SELECT tunnel_id FROM forward WHERE id = ?`, forwardID).Scan(&tunnelAfter); err != nil {
|
||||||
|
t.Fatalf("query forward tunnel_id: %v", err)
|
||||||
|
}
|
||||||
|
if tunnelAfter != tunnelA {
|
||||||
|
t.Fatalf("expected tunnel rollback to %d, got %d", tunnelA, tunnelAfter)
|
||||||
|
}
|
||||||
|
|
||||||
|
var nodeAfter int64
|
||||||
|
var portAfter int
|
||||||
|
if err := repo.DB().QueryRow(`SELECT node_id, port FROM forward_port WHERE forward_id = ? LIMIT 1`, forwardID).Scan(&nodeAfter, &portAfter); err != nil {
|
||||||
|
t.Fatalf("query forward_port: %v", err)
|
||||||
|
}
|
||||||
|
if nodeAfter != nodeA || portAfter != 21001 {
|
||||||
|
t.Fatalf("expected forward_port rollback to node=%d port=21001, got node=%d port=%d", nodeA, nodeAfter, portAfter)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestForwardBatchChangeTunnelRollbackOnSyncFailure(t *testing.T) {
|
||||||
|
secret := "contract-jwt-secret"
|
||||||
|
router, repo := setupContractRouter(t, secret)
|
||||||
|
now := time.Now().UnixMilli()
|
||||||
|
|
||||||
|
adminToken, err := auth.GenerateToken(1, "admin_user", 0, secret)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("generate admin token: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
if _, err := repo.DB().Exec(`
|
||||||
|
INSERT INTO user(id, user, pwd, role_id, exp_time, flow, in_flow, out_flow, flow_reset_time, num, created_time, updated_time, status)
|
||||||
|
VALUES(2, 'batch_switch_user', '3c85cdebade1c51cf64ca9f3c09d182d', 1, 2727251700000, 99999, 0, 0, 1, 99999, ?, ?, 1)
|
||||||
|
`, now, now); err != nil {
|
||||||
|
t.Fatalf("insert user: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
tunnelResA, err := repo.DB().Exec(`
|
||||||
|
INSERT INTO tunnel(name, traffic_ratio, type, protocol, flow, created_time, updated_time, status, in_ip, inx)
|
||||||
|
VALUES('batch-switch-tunnel-a', 1.0, 1, 'tls', 99999, ?, ?, 1, NULL, 0)
|
||||||
|
`, now, now)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("insert tunnel A: %v", err)
|
||||||
|
}
|
||||||
|
tunnelA, _ := tunnelResA.LastInsertId()
|
||||||
|
|
||||||
|
tunnelResB, err := repo.DB().Exec(`
|
||||||
|
INSERT INTO tunnel(name, traffic_ratio, type, protocol, flow, created_time, updated_time, status, in_ip, inx)
|
||||||
|
VALUES('batch-switch-tunnel-b', 1.0, 1, 'tls', 99999, ?, ?, 1, NULL, 1)
|
||||||
|
`, now, now)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("insert tunnel B: %v", err)
|
||||||
|
}
|
||||||
|
tunnelB, _ := tunnelResB.LastInsertId()
|
||||||
|
|
||||||
|
nodeResA, err := repo.DB().Exec(`
|
||||||
|
INSERT INTO node(name, secret, server_ip, server_ip_v4, server_ip_v6, port, interface_name, version, http, tls, socks, created_time, updated_time, status, tcp_listen_addr, udp_listen_addr, inx)
|
||||||
|
VALUES('batch-switch-node-a', 'batch-switch-node-a-secret', '10.11.0.1', '10.11.0.1', '', '23000-23010', '', 'v1', 1, 1, 1, ?, ?, 1, '[::]', '[::]', 0)
|
||||||
|
`, now, now)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("insert node A: %v", err)
|
||||||
|
}
|
||||||
|
nodeA, _ := nodeResA.LastInsertId()
|
||||||
|
|
||||||
|
nodeResB, err := repo.DB().Exec(`
|
||||||
|
INSERT INTO node(name, secret, server_ip, server_ip_v4, server_ip_v6, port, interface_name, version, http, tls, socks, created_time, updated_time, status, tcp_listen_addr, udp_listen_addr, inx)
|
||||||
|
VALUES('batch-switch-node-b', 'batch-switch-node-b-secret', '10.11.0.2', '10.11.0.2', '', '24000-24010', '', 'v1', 1, 1, 1, ?, ?, 1, '[::]', '[::]', 1)
|
||||||
|
`, now, now)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("insert node B: %v", err)
|
||||||
|
}
|
||||||
|
nodeB, _ := nodeResB.LastInsertId()
|
||||||
|
|
||||||
|
if _, err := repo.DB().Exec(`INSERT INTO chain_tunnel(tunnel_id, chain_type, node_id, port, strategy, inx, protocol) VALUES(?, 1, ?, 23001, 'round', 1, 'tls')`, tunnelA, nodeA); err != nil {
|
||||||
|
t.Fatalf("insert chain_tunnel A: %v", err)
|
||||||
|
}
|
||||||
|
if _, err := repo.DB().Exec(`INSERT INTO chain_tunnel(tunnel_id, chain_type, node_id, port, strategy, inx, protocol) VALUES(?, 1, ?, 24001, 'round', 1, 'tls')`, tunnelB, nodeB); err != nil {
|
||||||
|
t.Fatalf("insert chain_tunnel B: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
if _, err := repo.DB().Exec(`INSERT INTO user_tunnel(id, user_id, tunnel_id, speed_id, num, flow, in_flow, out_flow, flow_reset_time, exp_time, status) VALUES(20, 2, ?, NULL, 999, 99999, 0, 0, 1, 2727251700000, 1)`, tunnelA); err != nil {
|
||||||
|
t.Fatalf("insert user_tunnel A: %v", err)
|
||||||
|
}
|
||||||
|
if _, err := repo.DB().Exec(`INSERT INTO user_tunnel(id, user_id, tunnel_id, speed_id, num, flow, in_flow, out_flow, flow_reset_time, exp_time, status) VALUES(21, 2, ?, NULL, 999, 99999, 0, 0, 1, 2727251700000, 1)`, tunnelB); err != nil {
|
||||||
|
t.Fatalf("insert user_tunnel B: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
forwardRes, err := repo.DB().Exec(`
|
||||||
|
INSERT INTO forward(user_id, user_name, name, tunnel_id, remote_addr, strategy, in_flow, out_flow, created_time, updated_time, status, inx)
|
||||||
|
VALUES(2, 'batch_switch_user', 'batch-switch-forward', ?, '1.1.1.1:443', 'fifo', 0, 0, ?, ?, 1, 0)
|
||||||
|
`, tunnelA, now, now)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("insert forward: %v", err)
|
||||||
|
}
|
||||||
|
forwardID, _ := forwardRes.LastInsertId()
|
||||||
|
|
||||||
|
if _, err := repo.DB().Exec(`INSERT INTO forward_port(forward_id, node_id, port) VALUES(?, ?, ?)`, forwardID, nodeA, 23001); err != nil {
|
||||||
|
t.Fatalf("insert forward_port: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
payload := `{"forwardIds":[` + jsonNumber(forwardID) + `],"targetTunnelId":` + jsonNumber(tunnelB) + `}`
|
||||||
|
req := httptest.NewRequest(http.MethodPost, "/api/v1/forward/batch-change-tunnel", bytes.NewBufferString(payload))
|
||||||
|
req.Header.Set("Authorization", adminToken)
|
||||||
|
req.Header.Set("Content-Type", "application/json")
|
||||||
|
res := httptest.NewRecorder()
|
||||||
|
|
||||||
|
router.ServeHTTP(res, req)
|
||||||
|
|
||||||
|
var out response.R
|
||||||
|
if err := json.NewDecoder(res.Body).Decode(&out); err != nil {
|
||||||
|
t.Fatalf("decode response: %v", err)
|
||||||
|
}
|
||||||
|
if out.Code != 0 {
|
||||||
|
t.Fatalf("expected API success envelope, got code=%d msg=%q", out.Code, out.Msg)
|
||||||
|
}
|
||||||
|
|
||||||
|
result, ok := out.Data.(map[string]interface{})
|
||||||
|
if !ok {
|
||||||
|
t.Fatalf("expected map result, got %T", out.Data)
|
||||||
|
}
|
||||||
|
if int(result["failCount"].(float64)) != 1 {
|
||||||
|
t.Fatalf("expected failCount=1, got %v", result["failCount"])
|
||||||
|
}
|
||||||
|
|
||||||
|
var tunnelAfter int64
|
||||||
|
if err := repo.DB().QueryRow(`SELECT tunnel_id FROM forward WHERE id = ?`, forwardID).Scan(&tunnelAfter); err != nil {
|
||||||
|
t.Fatalf("query forward tunnel_id: %v", err)
|
||||||
|
}
|
||||||
|
if tunnelAfter != tunnelA {
|
||||||
|
t.Fatalf("expected tunnel rollback to %d, got %d", tunnelA, tunnelAfter)
|
||||||
|
}
|
||||||
|
|
||||||
|
var nodeAfter int64
|
||||||
|
var portAfter int
|
||||||
|
if err := repo.DB().QueryRow(`SELECT node_id, port FROM forward_port WHERE forward_id = ? LIMIT 1`, forwardID).Scan(&nodeAfter, &portAfter); err != nil {
|
||||||
|
t.Fatalf("query forward_port: %v", err)
|
||||||
|
}
|
||||||
|
if nodeAfter != nodeA || portAfter != 23001 {
|
||||||
|
t.Fatalf("expected forward_port rollback to node=%d port=23001, got node=%d port=%d", nodeA, nodeAfter, portAfter)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestUserTunnelReassignmentKeepsStableID(t *testing.T) {
|
||||||
|
secret := "contract-jwt-secret"
|
||||||
|
router, repo := setupContractRouter(t, secret)
|
||||||
|
now := time.Now().UnixMilli()
|
||||||
|
|
||||||
|
adminToken, err := auth.GenerateToken(1, "admin_user", 0, secret)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("generate admin token: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
if _, err := repo.DB().Exec(`
|
||||||
|
INSERT INTO user(id, user, pwd, role_id, exp_time, flow, in_flow, out_flow, flow_reset_time, num, created_time, updated_time, status)
|
||||||
|
VALUES(100, 'stable_user', 'pwd', 1, 2727251700000, 99999, 0, 0, 1, 99999, ?, ?, 1)
|
||||||
|
`, now, now); err != nil {
|
||||||
|
t.Fatalf("insert user: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
tunnelRes, err := repo.DB().Exec(`
|
||||||
|
INSERT INTO tunnel(name, traffic_ratio, type, protocol, flow, created_time, updated_time, status, in_ip, inx)
|
||||||
|
VALUES('stable-tunnel', 1.0, 1, 'tls', 99999, ?, ?, 1, NULL, 0)
|
||||||
|
`, now, now)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("insert tunnel: %v", err)
|
||||||
|
}
|
||||||
|
tunnelID, _ := tunnelRes.LastInsertId()
|
||||||
|
|
||||||
|
// 1. Assign permission (creates new user_tunnel)
|
||||||
|
// userTunnelBatchAssign expects structure: {userId: 123, tunnels: [{tunnelId: 456, ...}]}
|
||||||
|
assignPayload := `{"userId":100,"tunnels":[{"tunnelId":` + jsonNumber(tunnelID) + `}]}`
|
||||||
|
req := httptest.NewRequest(http.MethodPost, "/api/v1/tunnel/user/batch-assign", bytes.NewBufferString(assignPayload))
|
||||||
|
req.Header.Set("Authorization", adminToken)
|
||||||
|
req.Header.Set("Content-Type", "application/json")
|
||||||
|
res := httptest.NewRecorder()
|
||||||
|
router.ServeHTTP(res, req)
|
||||||
|
|
||||||
|
var out response.R
|
||||||
|
if err := json.NewDecoder(res.Body).Decode(&out); err != nil {
|
||||||
|
t.Fatalf("decode response: %v", err)
|
||||||
|
}
|
||||||
|
if out.Code != 0 {
|
||||||
|
t.Fatalf("expected code 0, got %d msg=%q", out.Code, out.Msg)
|
||||||
|
}
|
||||||
|
|
||||||
|
var initialID int64
|
||||||
|
if err := repo.DB().QueryRow(`SELECT id FROM user_tunnel WHERE user_id = 100 AND tunnel_id = ?`, tunnelID).Scan(&initialID); err != nil {
|
||||||
|
t.Fatalf("query initial user_tunnel id: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
// 2. Re-assign permission (should UPDATE, not INSERT)
|
||||||
|
reassignPayload := `{"userId":100,"tunnels":[{"tunnelId":` + jsonNumber(tunnelID) + `}]}`
|
||||||
|
req2 := httptest.NewRequest(http.MethodPost, "/api/v1/tunnel/user/batch-assign", bytes.NewBufferString(reassignPayload))
|
||||||
|
req2.Header.Set("Authorization", adminToken)
|
||||||
|
req2.Header.Set("Content-Type", "application/json")
|
||||||
|
res2 := httptest.NewRecorder()
|
||||||
|
router.ServeHTTP(res2, req2)
|
||||||
|
|
||||||
|
var out2 response.R
|
||||||
|
if err := json.NewDecoder(res2.Body).Decode(&out2); err != nil {
|
||||||
|
t.Fatalf("decode response 2: %v", err)
|
||||||
|
}
|
||||||
|
if out2.Code != 0 {
|
||||||
|
t.Fatalf("expected code 0, got %d msg=%q", out2.Code, out2.Msg)
|
||||||
|
}
|
||||||
|
|
||||||
|
// 3. Verify stable ID and no duplicates
|
||||||
|
var count int
|
||||||
|
if err := repo.DB().QueryRow(`SELECT COUNT(1) FROM user_tunnel WHERE user_id = 100 AND tunnel_id = ?`, tunnelID).Scan(&count); err != nil {
|
||||||
|
t.Fatalf("query count: %v", err)
|
||||||
|
}
|
||||||
|
if count != 1 {
|
||||||
|
t.Fatalf("expected exactly 1 user_tunnel record, got %d", count)
|
||||||
|
}
|
||||||
|
|
||||||
|
var currentID int64
|
||||||
|
if err := repo.DB().QueryRow(`SELECT id FROM user_tunnel WHERE user_id = 100 AND tunnel_id = ?`, tunnelID).Scan(¤tID); err != nil {
|
||||||
|
t.Fatalf("query current user_tunnel: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
if currentID != initialID {
|
||||||
|
t.Fatalf("user_tunnel ID changed from %d to %d (unstable ID!)", initialID, currentID)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
func jsonNumber(v int64) string {
|
func jsonNumber(v int64) string {
|
||||||
return strconv.FormatInt(v, 10)
|
return strconv.FormatInt(v, 10)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -2,6 +2,7 @@ package contract_test
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"bytes"
|
"bytes"
|
||||||
|
"database/sql"
|
||||||
"encoding/json"
|
"encoding/json"
|
||||||
"io"
|
"io"
|
||||||
"net/http"
|
"net/http"
|
||||||
@@ -17,6 +18,8 @@ import (
|
|||||||
"go-backend/internal/http/handler"
|
"go-backend/internal/http/handler"
|
||||||
"go-backend/internal/http/response"
|
"go-backend/internal/http/response"
|
||||||
"go-backend/internal/store/sqlite"
|
"go-backend/internal/store/sqlite"
|
||||||
|
|
||||||
|
_ "modernc.org/sqlite"
|
||||||
)
|
)
|
||||||
|
|
||||||
func TestCaptchaVerifyLoginContract(t *testing.T) {
|
func TestCaptchaVerifyLoginContract(t *testing.T) {
|
||||||
@@ -213,3 +216,117 @@ func setupContractRouter(t *testing.T, jwtSecret string) (http.Handler, *sqlite.
|
|||||||
h := handler.New(repo, jwtSecret)
|
h := handler.New(repo, jwtSecret)
|
||||||
return httpserver.NewRouter(h, jwtSecret), repo
|
return httpserver.NewRouter(h, jwtSecret), repo
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TestOpenMigratesLegacyNodeDualStackColumns(t *testing.T) {
|
||||||
|
dbPath := filepath.Join(t.TempDir(), "legacy-2.0.7-beta.db")
|
||||||
|
legacyDB, err := sql.Open("sqlite", dbPath)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("open legacy sqlite: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
t.Cleanup(func() {
|
||||||
|
_ = legacyDB.Close()
|
||||||
|
})
|
||||||
|
|
||||||
|
if _, err := legacyDB.Exec(`
|
||||||
|
CREATE TABLE IF NOT EXISTS node (
|
||||||
|
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||||
|
name VARCHAR(100) NOT NULL,
|
||||||
|
secret VARCHAR(100) NOT NULL,
|
||||||
|
server_ip VARCHAR(100) NOT NULL,
|
||||||
|
port TEXT NOT NULL,
|
||||||
|
interface_name VARCHAR(200),
|
||||||
|
version VARCHAR(100),
|
||||||
|
http INTEGER NOT NULL DEFAULT 0,
|
||||||
|
tls INTEGER NOT NULL DEFAULT 0,
|
||||||
|
socks INTEGER NOT NULL DEFAULT 0,
|
||||||
|
created_time INTEGER NOT NULL,
|
||||||
|
updated_time INTEGER,
|
||||||
|
status INTEGER NOT NULL,
|
||||||
|
tcp_listen_addr VARCHAR(100) NOT NULL DEFAULT '[::]',
|
||||||
|
udp_listen_addr VARCHAR(100) NOT NULL DEFAULT '[::]'
|
||||||
|
)
|
||||||
|
`); err != nil {
|
||||||
|
t.Fatalf("create legacy node table: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
if _, err := legacyDB.Exec(`
|
||||||
|
CREATE TABLE IF NOT EXISTS tunnel (
|
||||||
|
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||||
|
name VARCHAR(100) NOT NULL,
|
||||||
|
traffic_ratio REAL NOT NULL DEFAULT 1.0,
|
||||||
|
type INTEGER NOT NULL,
|
||||||
|
protocol VARCHAR(10) NOT NULL DEFAULT 'tls',
|
||||||
|
flow INTEGER NOT NULL,
|
||||||
|
created_time INTEGER NOT NULL,
|
||||||
|
updated_time INTEGER NOT NULL,
|
||||||
|
status INTEGER NOT NULL,
|
||||||
|
in_ip TEXT
|
||||||
|
)
|
||||||
|
`); err != nil {
|
||||||
|
t.Fatalf("create legacy tunnel table: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
now := time.Now().UnixMilli()
|
||||||
|
if _, err := legacyDB.Exec(`
|
||||||
|
INSERT INTO node(name, secret, server_ip, port, interface_name, version, http, tls, socks, created_time, updated_time, status, tcp_listen_addr, udp_listen_addr)
|
||||||
|
VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
||||||
|
`, "legacy-node", "legacy-secret", "10.10.0.1", "10000-10010", "eth0", "v-old", 1, 1, 1, now, now, 1, "[::]", "[::]"); err != nil {
|
||||||
|
t.Fatalf("seed legacy node row: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
repo, err := sqlite.Open(dbPath)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("open migrated sqlite: %v", err)
|
||||||
|
}
|
||||||
|
t.Cleanup(func() {
|
||||||
|
_ = repo.Close()
|
||||||
|
})
|
||||||
|
|
||||||
|
nodes, err := repo.ListNodes()
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("list nodes after migration: %v", err)
|
||||||
|
}
|
||||||
|
if len(nodes) != 1 {
|
||||||
|
t.Fatalf("expected 1 node after migration, got %d", len(nodes))
|
||||||
|
}
|
||||||
|
|
||||||
|
columns := readTableColumns(t, repo.DB(), "node")
|
||||||
|
|
||||||
|
for _, required := range []string{"server_ip_v4", "server_ip_v6", "inx"} {
|
||||||
|
if !columns[required] {
|
||||||
|
t.Fatalf("expected node column %q to exist after migration", required)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
tunnelColumns := readTableColumns(t, repo.DB(), "tunnel")
|
||||||
|
if !tunnelColumns["inx"] {
|
||||||
|
t.Fatalf("expected tunnel column %q to exist after migration", "inx")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func readTableColumns(t *testing.T, db *sql.DB, table string) map[string]bool {
|
||||||
|
t.Helper()
|
||||||
|
|
||||||
|
rows, err := db.Query("PRAGMA table_info(" + table + ")")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("inspect %s columns: %v", table, err)
|
||||||
|
}
|
||||||
|
defer rows.Close()
|
||||||
|
|
||||||
|
columns := map[string]bool{}
|
||||||
|
for rows.Next() {
|
||||||
|
var cid, notNull, pk int
|
||||||
|
var name, typ string
|
||||||
|
var defaultValue sql.NullString
|
||||||
|
if err := rows.Scan(&cid, &name, &typ, ¬Null, &defaultValue, &pk); err != nil {
|
||||||
|
t.Fatalf("scan %s pragma row: %v", table, err)
|
||||||
|
}
|
||||||
|
columns[name] = true
|
||||||
|
}
|
||||||
|
if err := rows.Err(); err != nil {
|
||||||
|
t.Fatalf("iterate %s pragma rows: %v", table, err)
|
||||||
|
}
|
||||||
|
|
||||||
|
return columns
|
||||||
|
}
|
||||||
|
|||||||
@@ -3,6 +3,7 @@ package service
|
|||||||
import (
|
import (
|
||||||
"fmt"
|
"fmt"
|
||||||
"runtime"
|
"runtime"
|
||||||
|
"strconv"
|
||||||
"strings"
|
"strings"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
@@ -30,6 +31,7 @@ import (
|
|||||||
logger_parser "github.com/go-gost/x/config/parsing/logger"
|
logger_parser "github.com/go-gost/x/config/parsing/logger"
|
||||||
selector_parser "github.com/go-gost/x/config/parsing/selector"
|
selector_parser "github.com/go-gost/x/config/parsing/selector"
|
||||||
tls_util "github.com/go-gost/x/internal/util/tls"
|
tls_util "github.com/go-gost/x/internal/util/tls"
|
||||||
|
xtraffic "github.com/go-gost/x/limiter/traffic"
|
||||||
cache_limiter "github.com/go-gost/x/limiter/traffic/cache"
|
cache_limiter "github.com/go-gost/x/limiter/traffic/cache"
|
||||||
"github.com/go-gost/x/metadata"
|
"github.com/go-gost/x/metadata"
|
||||||
mdutil "github.com/go-gost/x/metadata/util"
|
mdutil "github.com/go-gost/x/metadata/util"
|
||||||
@@ -181,6 +183,32 @@ func ParseService(cfg *config.ServiceConfig) (service.Service, error) {
|
|||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
var trafficLimiter listener.Option
|
||||||
|
if cfg.Limiter != "" {
|
||||||
|
lim := registry.TrafficLimiterRegistry().Get(cfg.Limiter)
|
||||||
|
if lim == nil {
|
||||||
|
// Try to parse as simple number (bandwidth in bytes/sec)
|
||||||
|
if val, err := strconv.Atoi(cfg.Limiter); err == nil && val > 0 {
|
||||||
|
lim = xtraffic.NewTrafficLimiter(
|
||||||
|
xtraffic.LimitsOption(fmt.Sprintf("%s %dB %dB", xtraffic.ServiceLimitKey, val, val)),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
if lim == nil {
|
||||||
|
lim = xtraffic.NewTrafficLimiter(
|
||||||
|
xtraffic.LimitsOption(fmt.Sprintf("%s %s %s", xtraffic.ServiceLimitKey, cfg.Limiter, cfg.Limiter)),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
trafficLimiter = listener.TrafficLimiterOption(
|
||||||
|
cache_limiter.NewCachedTrafficLimiter(
|
||||||
|
lim,
|
||||||
|
cache_limiter.RefreshIntervalOption(limiterRefreshInterval),
|
||||||
|
cache_limiter.CleanupIntervalOption(limiterCleanupInterval),
|
||||||
|
cache_limiter.ScopeOption(limiterScope),
|
||||||
|
),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
listenOpts := []listener.Option{
|
listenOpts := []listener.Option{
|
||||||
listener.AddrOption(cfg.Addr),
|
listener.AddrOption(cfg.Addr),
|
||||||
listener.RouterOption(xchain.NewRouter(routerOpts...)),
|
listener.RouterOption(xchain.NewRouter(routerOpts...)),
|
||||||
@@ -188,14 +216,6 @@ func ParseService(cfg *config.ServiceConfig) (service.Service, error) {
|
|||||||
listener.AuthOption(auth_parser.Info(cfg.Listener.Auth)),
|
listener.AuthOption(auth_parser.Info(cfg.Listener.Auth)),
|
||||||
listener.TLSConfigOption(tlsConfig),
|
listener.TLSConfigOption(tlsConfig),
|
||||||
listener.AdmissionOption(xadmission.AdmissionGroup(admissions...)),
|
listener.AdmissionOption(xadmission.AdmissionGroup(admissions...)),
|
||||||
listener.TrafficLimiterOption(
|
|
||||||
cache_limiter.NewCachedTrafficLimiter(
|
|
||||||
registry.TrafficLimiterRegistry().Get(cfg.Limiter),
|
|
||||||
cache_limiter.RefreshIntervalOption(limiterRefreshInterval),
|
|
||||||
cache_limiter.CleanupIntervalOption(limiterCleanupInterval),
|
|
||||||
cache_limiter.ScopeOption(limiterScope),
|
|
||||||
),
|
|
||||||
),
|
|
||||||
listener.ConnLimiterOption(registry.ConnLimiterRegistry().Get(cfg.CLimiter)),
|
listener.ConnLimiterOption(registry.ConnLimiterRegistry().Get(cfg.CLimiter)),
|
||||||
listener.ServiceOption(cfg.Name),
|
listener.ServiceOption(cfg.Name),
|
||||||
listener.ProxyProtocolOption(ppv),
|
listener.ProxyProtocolOption(ppv),
|
||||||
@@ -203,6 +223,9 @@ func ParseService(cfg *config.ServiceConfig) (service.Service, error) {
|
|||||||
listener.NetnsOption(netnsIn),
|
listener.NetnsOption(netnsIn),
|
||||||
listener.LoggerOption(listenerLogger),
|
listener.LoggerOption(listenerLogger),
|
||||||
}
|
}
|
||||||
|
if trafficLimiter != nil {
|
||||||
|
listenOpts = append(listenOpts, trafficLimiter)
|
||||||
|
}
|
||||||
|
|
||||||
if netnsIn != "" {
|
if netnsIn != "" {
|
||||||
runtime.LockOSThread()
|
runtime.LockOSThread()
|
||||||
|
|||||||
@@ -4,9 +4,7 @@ go 1.22.0
|
|||||||
|
|
||||||
toolchain go1.23.4
|
toolchain go1.23.4
|
||||||
|
|
||||||
require (
|
require github.com/shirou/gopsutil/v3 v3.24.5
|
||||||
github.com/shirou/gopsutil/v3 v3.24.5
|
|
||||||
)
|
|
||||||
|
|
||||||
require (
|
require (
|
||||||
github.com/alecthomas/units v0.0.0-20211218093645-b94a6e3cc137
|
github.com/alecthomas/units v0.0.0-20211218093645-b94a6e3cc137
|
||||||
@@ -76,6 +74,7 @@ require (
|
|||||||
github.com/fsnotify/fsnotify v1.7.0 // indirect
|
github.com/fsnotify/fsnotify v1.7.0 // indirect
|
||||||
github.com/gabriel-vasile/mimetype v1.4.3 // indirect
|
github.com/gabriel-vasile/mimetype v1.4.3 // indirect
|
||||||
github.com/gin-contrib/sse v0.1.0 // indirect
|
github.com/gin-contrib/sse v0.1.0 // indirect
|
||||||
|
github.com/go-ole/go-ole v1.2.6 // indirect
|
||||||
github.com/go-playground/locales v0.14.1 // indirect
|
github.com/go-playground/locales v0.14.1 // indirect
|
||||||
github.com/go-playground/universal-translator v0.18.1 // indirect
|
github.com/go-playground/universal-translator v0.18.1 // indirect
|
||||||
github.com/go-playground/validator/v10 v10.20.0 // indirect
|
github.com/go-playground/validator/v10 v10.20.0 // indirect
|
||||||
@@ -91,6 +90,7 @@ require (
|
|||||||
github.com/klauspost/cpuid/v2 v2.2.7 // indirect
|
github.com/klauspost/cpuid/v2 v2.2.7 // indirect
|
||||||
github.com/klauspost/reedsolomon v1.11.8 // indirect
|
github.com/klauspost/reedsolomon v1.11.8 // indirect
|
||||||
github.com/leodido/go-urn v1.4.0 // indirect
|
github.com/leodido/go-urn v1.4.0 // indirect
|
||||||
|
github.com/lufia/plan9stats v0.0.0-20211012122336-39d0f177ccd0 // indirect
|
||||||
github.com/magiconair/properties v1.8.7 // indirect
|
github.com/magiconair/properties v1.8.7 // indirect
|
||||||
github.com/mattn/go-isatty v0.0.20 // indirect
|
github.com/mattn/go-isatty v0.0.20 // indirect
|
||||||
github.com/mitchellh/mapstructure v1.5.0 // indirect
|
github.com/mitchellh/mapstructure v1.5.0 // indirect
|
||||||
@@ -103,6 +103,7 @@ require (
|
|||||||
github.com/pion/udp/v2 v2.0.1 // indirect
|
github.com/pion/udp/v2 v2.0.1 // indirect
|
||||||
github.com/pkg/errors v0.9.1 // indirect
|
github.com/pkg/errors v0.9.1 // indirect
|
||||||
github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 // indirect
|
github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 // indirect
|
||||||
|
github.com/power-devops/perfstat v0.0.0-20210106213030-5aafc221ea8c // indirect
|
||||||
github.com/prometheus/client_model v0.6.0 // indirect
|
github.com/prometheus/client_model v0.6.0 // indirect
|
||||||
github.com/prometheus/common v0.48.0 // indirect
|
github.com/prometheus/common v0.48.0 // indirect
|
||||||
github.com/prometheus/procfs v0.12.0 // indirect
|
github.com/prometheus/procfs v0.12.0 // indirect
|
||||||
@@ -110,6 +111,7 @@ require (
|
|||||||
github.com/riobard/go-bloom v0.0.0-20200614022211-cdc8013cb5b3 // indirect
|
github.com/riobard/go-bloom v0.0.0-20200614022211-cdc8013cb5b3 // indirect
|
||||||
github.com/sagikazarmark/locafero v0.4.0 // indirect
|
github.com/sagikazarmark/locafero v0.4.0 // indirect
|
||||||
github.com/sagikazarmark/slog-shim v0.1.0 // indirect
|
github.com/sagikazarmark/slog-shim v0.1.0 // indirect
|
||||||
|
github.com/shoenig/go-m1cpu v0.1.6 // indirect
|
||||||
github.com/sourcegraph/conc v0.3.0 // indirect
|
github.com/sourcegraph/conc v0.3.0 // indirect
|
||||||
github.com/spf13/afero v1.11.0 // indirect
|
github.com/spf13/afero v1.11.0 // indirect
|
||||||
github.com/spf13/cast v1.6.0 // indirect
|
github.com/spf13/cast v1.6.0 // indirect
|
||||||
@@ -118,8 +120,11 @@ require (
|
|||||||
github.com/templexxx/cpu v0.1.0 // indirect
|
github.com/templexxx/cpu v0.1.0 // indirect
|
||||||
github.com/templexxx/xorsimd v0.4.2 // indirect
|
github.com/templexxx/xorsimd v0.4.2 // indirect
|
||||||
github.com/tjfoc/gmsm v1.4.1 // indirect
|
github.com/tjfoc/gmsm v1.4.1 // indirect
|
||||||
|
github.com/tklauser/go-sysconf v0.3.12 // indirect
|
||||||
|
github.com/tklauser/numcpus v0.6.1 // indirect
|
||||||
github.com/twitchyliquid64/golang-asm v0.15.1 // indirect
|
github.com/twitchyliquid64/golang-asm v0.15.1 // indirect
|
||||||
github.com/ugorji/go/codec v1.2.12 // indirect
|
github.com/ugorji/go/codec v1.2.12 // indirect
|
||||||
|
github.com/yusufpapurcu/wmi v1.2.4 // indirect
|
||||||
go.uber.org/mock v0.5.0 // indirect
|
go.uber.org/mock v0.5.0 // indirect
|
||||||
go.uber.org/multierr v1.11.0 // indirect
|
go.uber.org/multierr v1.11.0 // indirect
|
||||||
golang.org/x/arch v0.8.0 // indirect
|
golang.org/x/arch v0.8.0 // indirect
|
||||||
|
|||||||
@@ -65,6 +65,8 @@ github.com/go-gost/tls-dissector v0.1.1 h1:2zUOTPzCQAUQ54Rpy0UEi3JPMQSYsIFSeFeKr
|
|||||||
github.com/go-gost/tls-dissector v0.1.1/go.mod h1:/9QfdewqmHdaE362Hv5nDaSWLx3pCmtD870d6GaquXs=
|
github.com/go-gost/tls-dissector v0.1.1/go.mod h1:/9QfdewqmHdaE362Hv5nDaSWLx3pCmtD870d6GaquXs=
|
||||||
github.com/go-logr/logr v1.4.2 h1:6pFjapn8bFcIbiKo3XT4j/BhANplGihG6tvd+8rYgrY=
|
github.com/go-logr/logr v1.4.2 h1:6pFjapn8bFcIbiKo3XT4j/BhANplGihG6tvd+8rYgrY=
|
||||||
github.com/go-logr/logr v1.4.2/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY=
|
github.com/go-logr/logr v1.4.2/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY=
|
||||||
|
github.com/go-ole/go-ole v1.2.6 h1:/Fpf6oFPoeFik9ty7siob0G6Ke8QvQEuVcuChpwXzpY=
|
||||||
|
github.com/go-ole/go-ole v1.2.6/go.mod h1:pprOEPIfldk/42T2oK7lQ4v4JSDwmV0As9GaiUsvbm0=
|
||||||
github.com/go-playground/assert/v2 v2.2.0 h1:JvknZsQTYeFEAhQwI4qEt9cyV5ONwRHC+lYKSsYSR8s=
|
github.com/go-playground/assert/v2 v2.2.0 h1:JvknZsQTYeFEAhQwI4qEt9cyV5ONwRHC+lYKSsYSR8s=
|
||||||
github.com/go-playground/assert/v2 v2.2.0/go.mod h1:VDjEfimB/XKnb+ZQfWdccd7VUvScMdVu0Titje2rxJ4=
|
github.com/go-playground/assert/v2 v2.2.0/go.mod h1:VDjEfimB/XKnb+ZQfWdccd7VUvScMdVu0Titje2rxJ4=
|
||||||
github.com/go-playground/locales v0.14.1 h1:EWaQ/wswjilfKLTECiXz7Rh+3BjFhfDFKv/oXslEjJA=
|
github.com/go-playground/locales v0.14.1 h1:EWaQ/wswjilfKLTECiXz7Rh+3BjFhfDFKv/oXslEjJA=
|
||||||
@@ -102,6 +104,7 @@ github.com/google/go-cmp v0.2.0/go.mod h1:oXzfMopK8JAjlY9xF4vHSVASa0yLyX7SntLO5a
|
|||||||
github.com/google/go-cmp v0.3.0/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU=
|
github.com/google/go-cmp v0.3.0/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU=
|
||||||
github.com/google/go-cmp v0.3.1/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU=
|
github.com/google/go-cmp v0.3.1/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU=
|
||||||
github.com/google/go-cmp v0.4.0/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=
|
github.com/google/go-cmp v0.4.0/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=
|
||||||
|
github.com/google/go-cmp v0.5.6/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=
|
||||||
github.com/google/go-cmp v0.6.0 h1:ofyhxvXcZhMsU5ulbFiLKl/XBFqE1GSq7atu8tAmTRI=
|
github.com/google/go-cmp v0.6.0 h1:ofyhxvXcZhMsU5ulbFiLKl/XBFqE1GSq7atu8tAmTRI=
|
||||||
github.com/google/go-cmp v0.6.0/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY=
|
github.com/google/go-cmp v0.6.0/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY=
|
||||||
github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg=
|
github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg=
|
||||||
@@ -133,6 +136,8 @@ github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=
|
|||||||
github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE=
|
github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE=
|
||||||
github.com/leodido/go-urn v1.4.0 h1:WT9HwE9SGECu3lg4d/dIA+jxlljEa1/ffXKmRjqdmIQ=
|
github.com/leodido/go-urn v1.4.0 h1:WT9HwE9SGECu3lg4d/dIA+jxlljEa1/ffXKmRjqdmIQ=
|
||||||
github.com/leodido/go-urn v1.4.0/go.mod h1:bvxc+MVxLKB4z00jd1z+Dvzr47oO32F/QSNjSBOlFxI=
|
github.com/leodido/go-urn v1.4.0/go.mod h1:bvxc+MVxLKB4z00jd1z+Dvzr47oO32F/QSNjSBOlFxI=
|
||||||
|
github.com/lufia/plan9stats v0.0.0-20211012122336-39d0f177ccd0 h1:6E+4a0GO5zZEnZ81pIr0yLvtUWk2if982qA3F3QD6H4=
|
||||||
|
github.com/lufia/plan9stats v0.0.0-20211012122336-39d0f177ccd0/go.mod h1:zJYVVT2jmtg6P3p1VtQj7WsuWi/y4VnjVBn7F8KPB3I=
|
||||||
github.com/magiconair/properties v1.8.7 h1:IeQXZAiQcpL9mgcAe1Nu6cX9LLw6ExEHKjN0VQdvPDY=
|
github.com/magiconair/properties v1.8.7 h1:IeQXZAiQcpL9mgcAe1Nu6cX9LLw6ExEHKjN0VQdvPDY=
|
||||||
github.com/magiconair/properties v1.8.7/go.mod h1:Dhd985XPs7jluiymwWYZ0G4Z61jb3vdS329zhj2hYo0=
|
github.com/magiconair/properties v1.8.7/go.mod h1:Dhd985XPs7jluiymwWYZ0G4Z61jb3vdS329zhj2hYo0=
|
||||||
github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY=
|
github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY=
|
||||||
@@ -175,6 +180,8 @@ github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINE
|
|||||||
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
|
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
|
||||||
github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 h1:Jamvg5psRIccs7FGNTlIRMkT8wgtp5eCXdBlqhYGL6U=
|
github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 h1:Jamvg5psRIccs7FGNTlIRMkT8wgtp5eCXdBlqhYGL6U=
|
||||||
github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
|
github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
|
||||||
|
github.com/power-devops/perfstat v0.0.0-20210106213030-5aafc221ea8c h1:ncq/mPwQF4JjgDlrVEn3C11VoGHZN7m8qihwgMEtzYw=
|
||||||
|
github.com/power-devops/perfstat v0.0.0-20210106213030-5aafc221ea8c/go.mod h1:OmDBASR4679mdNQnz2pUhc2G8CO2JrUAVFDRBDP/hJE=
|
||||||
github.com/prometheus/client_golang v1.19.1 h1:wZWJDwK+NameRJuPGDhlnFgx8e8HN3XHQeLaYJFJBOE=
|
github.com/prometheus/client_golang v1.19.1 h1:wZWJDwK+NameRJuPGDhlnFgx8e8HN3XHQeLaYJFJBOE=
|
||||||
github.com/prometheus/client_golang v1.19.1/go.mod h1:mP78NwGzrVks5S2H6ab8+ZZGJLZUq1hoULYBAYBw1Ho=
|
github.com/prometheus/client_golang v1.19.1/go.mod h1:mP78NwGzrVks5S2H6ab8+ZZGJLZUq1hoULYBAYBw1Ho=
|
||||||
github.com/prometheus/client_model v0.0.0-20190812154241-14fe0d1b01d4/go.mod h1:xMI15A0UPsDsEKsMN9yxemIoYk6Tm2C1GtYGdfGttqA=
|
github.com/prometheus/client_model v0.0.0-20190812154241-14fe0d1b01d4/go.mod h1:xMI15A0UPsDsEKsMN9yxemIoYk6Tm2C1GtYGdfGttqA=
|
||||||
@@ -204,7 +211,12 @@ github.com/shadowsocks/go-shadowsocks2 v0.1.5 h1:PDSQv9y2S85Fl7VBeOMF9StzeXZyK1H
|
|||||||
github.com/shadowsocks/go-shadowsocks2 v0.1.5/go.mod h1:AGGpIoek4HRno4xzyFiAtLHkOpcoznZEkAccaI/rplM=
|
github.com/shadowsocks/go-shadowsocks2 v0.1.5/go.mod h1:AGGpIoek4HRno4xzyFiAtLHkOpcoznZEkAccaI/rplM=
|
||||||
github.com/shadowsocks/shadowsocks-go v0.0.0-20200409064450-3e585ff90601 h1:XU9hik0exChEmY92ALW4l9WnDodxLVS9yOSNh2SizaQ=
|
github.com/shadowsocks/shadowsocks-go v0.0.0-20200409064450-3e585ff90601 h1:XU9hik0exChEmY92ALW4l9WnDodxLVS9yOSNh2SizaQ=
|
||||||
github.com/shadowsocks/shadowsocks-go v0.0.0-20200409064450-3e585ff90601/go.mod h1:mttDPaeLm87u74HMrP+n2tugXvIKWcwff/cqSX0lehY=
|
github.com/shadowsocks/shadowsocks-go v0.0.0-20200409064450-3e585ff90601/go.mod h1:mttDPaeLm87u74HMrP+n2tugXvIKWcwff/cqSX0lehY=
|
||||||
|
github.com/shirou/gopsutil/v3 v3.24.5 h1:i0t8kL+kQTvpAYToeuiVk3TgDeKOFioZO3Ztz/iZ9pI=
|
||||||
github.com/shirou/gopsutil/v3 v3.24.5/go.mod h1:bsoOS1aStSs9ErQ1WWfxllSeS1K5D+U30r2NfcubMVk=
|
github.com/shirou/gopsutil/v3 v3.24.5/go.mod h1:bsoOS1aStSs9ErQ1WWfxllSeS1K5D+U30r2NfcubMVk=
|
||||||
|
github.com/shoenig/go-m1cpu v0.1.6 h1:nxdKQNcEB6vzgA2E2bvzKIYRuNj7XNJ4S/aRSwKzFtM=
|
||||||
|
github.com/shoenig/go-m1cpu v0.1.6/go.mod h1:1JJMcUBvfNwpq05QDQVAnx3gUHr9IYF7GNg9SUEw2VQ=
|
||||||
|
github.com/shoenig/test v0.6.4 h1:kVTaSd7WLz5WZ2IaoM0RSzRsUD+m8wRR+5qvntpn4LU=
|
||||||
|
github.com/shoenig/test v0.6.4/go.mod h1:byHiCGXqrVaflBLAMq/srcZIHynQPQgeyvkvXnjqq0k=
|
||||||
github.com/sirupsen/logrus v1.7.0/go.mod h1:yWOB1SBYBC5VeMP7gHvWumXLIWorT60ONWic61uBYv0=
|
github.com/sirupsen/logrus v1.7.0/go.mod h1:yWOB1SBYBC5VeMP7gHvWumXLIWorT60ONWic61uBYv0=
|
||||||
github.com/sirupsen/logrus v1.8.1 h1:dJKuHgqk1NNQlqoA6BTlM1Wf9DOH3NBjQyu0h9+AZZE=
|
github.com/sirupsen/logrus v1.8.1 h1:dJKuHgqk1NNQlqoA6BTlM1Wf9DOH3NBjQyu0h9+AZZE=
|
||||||
github.com/sirupsen/logrus v1.8.1/go.mod h1:yWOB1SBYBC5VeMP7gHvWumXLIWorT60ONWic61uBYv0=
|
github.com/sirupsen/logrus v1.8.1/go.mod h1:yWOB1SBYBC5VeMP7gHvWumXLIWorT60ONWic61uBYv0=
|
||||||
@@ -244,6 +256,10 @@ github.com/templexxx/xorsimd v0.4.2 h1:ocZZ+Nvu65LGHmCLZ7OoCtg8Fx8jnHKK37SjvngUo
|
|||||||
github.com/templexxx/xorsimd v0.4.2/go.mod h1:HgwaPoDREdi6OnULpSfxhzaiiSUY4Fi3JPn1wpt28NI=
|
github.com/templexxx/xorsimd v0.4.2/go.mod h1:HgwaPoDREdi6OnULpSfxhzaiiSUY4Fi3JPn1wpt28NI=
|
||||||
github.com/tjfoc/gmsm v1.4.1 h1:aMe1GlZb+0bLjn+cKTPEvvn9oUEBlJitaZiiBwsbgho=
|
github.com/tjfoc/gmsm v1.4.1 h1:aMe1GlZb+0bLjn+cKTPEvvn9oUEBlJitaZiiBwsbgho=
|
||||||
github.com/tjfoc/gmsm v1.4.1/go.mod h1:j4INPkHWMrhJb38G+J6W4Tw0AbuN8Thu3PbdVYhVcTE=
|
github.com/tjfoc/gmsm v1.4.1/go.mod h1:j4INPkHWMrhJb38G+J6W4Tw0AbuN8Thu3PbdVYhVcTE=
|
||||||
|
github.com/tklauser/go-sysconf v0.3.12 h1:0QaGUFOdQaIVdPgfITYzaTegZvdCjmYO52cSFAEVmqU=
|
||||||
|
github.com/tklauser/go-sysconf v0.3.12/go.mod h1:Ho14jnntGE1fpdOqQEEaiKRpvIavV0hSfmBq8nJbHYI=
|
||||||
|
github.com/tklauser/numcpus v0.6.1 h1:ng9scYS7az0Bk4OZLvrNXNSAO2Pxr1XXRAPyjhIx+Fk=
|
||||||
|
github.com/tklauser/numcpus v0.6.1/go.mod h1:1XfjsgE2zo8GVw7POkMbHENHzVg3GzmoZ9fESEdAacY=
|
||||||
github.com/twitchyliquid64/golang-asm v0.15.1 h1:SU5vSMR7hnwNxj24w34ZyCi/FmDZTkS4MhqMhdFk5YI=
|
github.com/twitchyliquid64/golang-asm v0.15.1 h1:SU5vSMR7hnwNxj24w34ZyCi/FmDZTkS4MhqMhdFk5YI=
|
||||||
github.com/twitchyliquid64/golang-asm v0.15.1/go.mod h1:a1lVb/DtPvCB8fslRZhAngC2+aY1QWCk3Cedj/Gdt08=
|
github.com/twitchyliquid64/golang-asm v0.15.1/go.mod h1:a1lVb/DtPvCB8fslRZhAngC2+aY1QWCk3Cedj/Gdt08=
|
||||||
github.com/ugorji/go/codec v1.2.12 h1:9LC83zGrHhuUA9l16C9AHXAqEV/2wBQ4nkvumAE65EE=
|
github.com/ugorji/go/codec v1.2.12 h1:9LC83zGrHhuUA9l16C9AHXAqEV/2wBQ4nkvumAE65EE=
|
||||||
@@ -266,6 +282,8 @@ github.com/xtaci/tcpraw v1.2.25/go.mod h1:dKyZ2V75s0cZ7cbgJYdxPvms7af0joIeOyx1Gg
|
|||||||
github.com/yl2chen/cidranger v1.0.2 h1:lbOWZVCG1tCRX4u24kuM1Tb4nHqWkDxwLdoS+SevawU=
|
github.com/yl2chen/cidranger v1.0.2 h1:lbOWZVCG1tCRX4u24kuM1Tb4nHqWkDxwLdoS+SevawU=
|
||||||
github.com/yl2chen/cidranger v1.0.2/go.mod h1:9U1yz7WPYDwf0vpNWFaeRh0bjwz5RVgRy/9UEQfHl0g=
|
github.com/yl2chen/cidranger v1.0.2/go.mod h1:9U1yz7WPYDwf0vpNWFaeRh0bjwz5RVgRy/9UEQfHl0g=
|
||||||
github.com/yuin/goldmark v1.4.13/go.mod h1:6yULJ656Px+3vBD8DxQVa3kxgyrAnzto9xy5taEt/CY=
|
github.com/yuin/goldmark v1.4.13/go.mod h1:6yULJ656Px+3vBD8DxQVa3kxgyrAnzto9xy5taEt/CY=
|
||||||
|
github.com/yusufpapurcu/wmi v1.2.4 h1:zFUKzehAFReQwLys1b/iSMl+JQGSCSjtVqQn9bBrPo0=
|
||||||
|
github.com/yusufpapurcu/wmi v1.2.4/go.mod h1:SBZ9tNy3G9/m5Oi98Zks0QjeHVDvuK0qfxQmPyzfmi0=
|
||||||
github.com/zalando/go-keyring v0.2.4 h1:wi2xxTqdiwMKbM6TWwi+uJCG/Tum2UV0jqaQhCa9/68=
|
github.com/zalando/go-keyring v0.2.4 h1:wi2xxTqdiwMKbM6TWwi+uJCG/Tum2UV0jqaQhCa9/68=
|
||||||
github.com/zalando/go-keyring v0.2.4/go.mod h1:HL4k+OXQfJUWaMnqyuSOc0drfGPX2b51Du6K+MRgZMk=
|
github.com/zalando/go-keyring v0.2.4/go.mod h1:HL4k+OXQfJUWaMnqyuSOc0drfGPX2b51Du6K+MRgZMk=
|
||||||
go.uber.org/mock v0.5.0 h1:KAMbZvZPyBPWgD14IrIQ38QCyjwpvVVV6K/bHl1IwQU=
|
go.uber.org/mock v0.5.0 h1:KAMbZvZPyBPWgD14IrIQ38QCyjwpvVVV6K/bHl1IwQU=
|
||||||
@@ -321,15 +339,19 @@ golang.org/x/sys v0.0.0-20180830151530-49385e6e1522/go.mod h1:STP8DvDyc/dI5b8T5h
|
|||||||
golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
|
golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
|
||||||
golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||||
golang.org/x/sys v0.0.0-20190606203320-7fc4e5ec1444/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
golang.org/x/sys v0.0.0-20190606203320-7fc4e5ec1444/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||||
|
golang.org/x/sys v0.0.0-20190916202348-b4ddaad3f8a3/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||||
golang.org/x/sys v0.0.0-20191026070338-33540a1f6037/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
golang.org/x/sys v0.0.0-20191026070338-33540a1f6037/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||||
golang.org/x/sys v0.0.0-20200930185726-fdedc70b468f/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
golang.org/x/sys v0.0.0-20200930185726-fdedc70b468f/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||||
golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||||
|
golang.org/x/sys v0.0.0-20201204225414-ed752295db88/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||||
golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||||
golang.org/x/sys v0.0.0-20220520151302-bc2c85ada10a/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
golang.org/x/sys v0.0.0-20220520151302-bc2c85ada10a/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||||
golang.org/x/sys v0.0.0-20220722155257-8c9f86f7a55f/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
golang.org/x/sys v0.0.0-20220722155257-8c9f86f7a55f/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||||
golang.org/x/sys v0.4.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
golang.org/x/sys v0.4.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||||
golang.org/x/sys v0.5.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
golang.org/x/sys v0.5.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||||
golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||||
|
golang.org/x/sys v0.8.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||||
|
golang.org/x/sys v0.11.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||||
golang.org/x/sys v0.28.0 h1:Fksou7UEQUWlKvIdsqzJmUmCX3cZuD2+P3XyyzwMhlA=
|
golang.org/x/sys v0.28.0 h1:Fksou7UEQUWlKvIdsqzJmUmCX3cZuD2+P3XyyzwMhlA=
|
||||||
golang.org/x/sys v0.28.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
|
golang.org/x/sys v0.28.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
|
||||||
golang.org/x/term v0.0.0-20201117132131-f5c789dd3221/go.mod h1:Nr5EML6q2oocZ2LXRh80K7BxOlk5/8JxuGnuhpl+muw=
|
golang.org/x/term v0.0.0-20201117132131-f5c789dd3221/go.mod h1:Nr5EML6q2oocZ2LXRh80K7BxOlk5/8JxuGnuhpl+muw=
|
||||||
|
|||||||
@@ -136,6 +136,9 @@ func (l *trafficLimiter) In(ctx context.Context, key string, opts ...limiter.Opt
|
|||||||
return nil
|
return nil
|
||||||
|
|
||||||
case limiter.ScopeClient:
|
case limiter.ScopeClient:
|
||||||
|
if lim, ok := l.inLimits.Get(key); ok && lim != nil {
|
||||||
|
return lim.(traffic.Limiter)
|
||||||
|
}
|
||||||
return nil
|
return nil
|
||||||
|
|
||||||
case limiter.ScopeConn:
|
case limiter.ScopeConn:
|
||||||
@@ -215,6 +218,9 @@ func (l *trafficLimiter) Out(ctx context.Context, key string, opts ...limiter.Op
|
|||||||
return nil
|
return nil
|
||||||
|
|
||||||
case limiter.ScopeClient:
|
case limiter.ScopeClient:
|
||||||
|
if lim, ok := l.outLimits.Get(key); ok && lim != nil {
|
||||||
|
return lim.(traffic.Limiter)
|
||||||
|
}
|
||||||
return nil
|
return nil
|
||||||
|
|
||||||
case limiter.ScopeConn:
|
case limiter.ScopeConn:
|
||||||
|
|||||||
@@ -43,8 +43,8 @@ func updateChain(req updateChainRequest) error {
|
|||||||
|
|
||||||
name := strings.TrimSpace(req.Chain)
|
name := strings.TrimSpace(req.Chain)
|
||||||
|
|
||||||
if !registry.ChainRegistry().IsRegistered(name) {
|
if registry.ChainRegistry().IsRegistered(name) {
|
||||||
return errors.New("chain " + name + " not found")
|
registry.ChainRegistry().Unregister(name)
|
||||||
}
|
}
|
||||||
|
|
||||||
req.Data.Name = name
|
req.Data.Name = name
|
||||||
@@ -54,19 +54,22 @@ func updateChain(req updateChainRequest) error {
|
|||||||
return errors.New("create chain " + name + " failed: " + err.Error())
|
return errors.New("create chain " + name + " failed: " + err.Error())
|
||||||
}
|
}
|
||||||
|
|
||||||
registry.ChainRegistry().Unregister(name)
|
|
||||||
|
|
||||||
if err := registry.ChainRegistry().Register(name, v); err != nil {
|
if err := registry.ChainRegistry().Register(name, v); err != nil {
|
||||||
return errors.New("chain " + name + " already exists")
|
return errors.New("chain " + name + " already exists")
|
||||||
}
|
}
|
||||||
|
|
||||||
config.OnUpdate(func(c *config.Config) error {
|
config.OnUpdate(func(c *config.Config) error {
|
||||||
|
found := false
|
||||||
for i := range c.Chains {
|
for i := range c.Chains {
|
||||||
if c.Chains[i].Name == name {
|
if c.Chains[i].Name == name {
|
||||||
c.Chains[i] = &req.Data
|
c.Chains[i] = &req.Data
|
||||||
|
found = true
|
||||||
break
|
break
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
if !found {
|
||||||
|
c.Chains = append(c.Chains, &req.Data)
|
||||||
|
}
|
||||||
return nil
|
return nil
|
||||||
})
|
})
|
||||||
|
|
||||||
@@ -77,10 +80,9 @@ func deleteChain(req deleteChainRequest) error {
|
|||||||
|
|
||||||
name := strings.TrimSpace(req.Chain)
|
name := strings.TrimSpace(req.Chain)
|
||||||
|
|
||||||
if !registry.ChainRegistry().IsRegistered(name) {
|
if registry.ChainRegistry().IsRegistered(name) {
|
||||||
return errors.New("chain " + name + " not found")
|
registry.ChainRegistry().Unregister(name)
|
||||||
}
|
}
|
||||||
registry.ChainRegistry().Unregister(name)
|
|
||||||
|
|
||||||
config.OnUpdate(func(c *config.Config) error {
|
config.OnUpdate(func(c *config.Config) error {
|
||||||
chains := c.Chains
|
chains := c.Chains
|
||||||
|
|||||||
@@ -10,7 +10,7 @@ import (
|
|||||||
// configMutex 保护配置文件的并发写入
|
// configMutex 保护配置文件的并发写入
|
||||||
var configMutex sync.Mutex
|
var configMutex sync.Mutex
|
||||||
|
|
||||||
func saveConfig() {
|
func saveConfig() error {
|
||||||
configMutex.Lock()
|
configMutex.Lock()
|
||||||
defer configMutex.Unlock()
|
defer configMutex.Unlock()
|
||||||
|
|
||||||
@@ -18,14 +18,13 @@ func saveConfig() {
|
|||||||
|
|
||||||
f, err := os.Create(file)
|
f, err := os.Create(file)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return
|
return err
|
||||||
}
|
}
|
||||||
defer f.Close()
|
defer f.Close()
|
||||||
|
|
||||||
if err := config.Global().Write(f, "json"); err != nil {
|
if err := config.Global().Write(f, "json"); err != nil {
|
||||||
|
return err
|
||||||
return
|
|
||||||
}
|
}
|
||||||
|
|
||||||
return
|
return nil
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -37,27 +37,30 @@ func updateLimiter(req updateLimiterRequest) error {
|
|||||||
|
|
||||||
name := strings.TrimSpace(req.Limiter)
|
name := strings.TrimSpace(req.Limiter)
|
||||||
|
|
||||||
if !registry.TrafficLimiterRegistry().IsRegistered(name) {
|
if registry.TrafficLimiterRegistry().IsRegistered(name) {
|
||||||
return errors.New("limiter " + name + " not found")
|
registry.TrafficLimiterRegistry().Unregister(name)
|
||||||
}
|
}
|
||||||
|
|
||||||
req.Data.Name = name
|
req.Data.Name = name
|
||||||
|
|
||||||
v := parser.ParseTrafficLimiter(&req.Data)
|
v := parser.ParseTrafficLimiter(&req.Data)
|
||||||
|
|
||||||
registry.TrafficLimiterRegistry().Unregister(name)
|
|
||||||
|
|
||||||
if err := registry.TrafficLimiterRegistry().Register(name, v); err != nil {
|
if err := registry.TrafficLimiterRegistry().Register(name, v); err != nil {
|
||||||
return errors.New("limiter " + name + " already exists")
|
return errors.New("limiter " + name + " already exists")
|
||||||
}
|
}
|
||||||
|
|
||||||
config.OnUpdate(func(c *config.Config) error {
|
config.OnUpdate(func(c *config.Config) error {
|
||||||
|
found := false
|
||||||
for i := range c.Limiters {
|
for i := range c.Limiters {
|
||||||
if c.Limiters[i].Name == name {
|
if c.Limiters[i].Name == name {
|
||||||
c.Limiters[i] = &req.Data
|
c.Limiters[i] = &req.Data
|
||||||
|
found = true
|
||||||
break
|
break
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
if !found {
|
||||||
|
c.Limiters = append(c.Limiters, &req.Data)
|
||||||
|
}
|
||||||
return nil
|
return nil
|
||||||
})
|
})
|
||||||
|
|
||||||
@@ -68,10 +71,9 @@ func deleteLimiter(req deleteLimiterRequest) error {
|
|||||||
|
|
||||||
name := strings.TrimSpace(req.Limiter)
|
name := strings.TrimSpace(req.Limiter)
|
||||||
|
|
||||||
if !registry.TrafficLimiterRegistry().IsRegistered(name) {
|
if registry.TrafficLimiterRegistry().IsRegistered(name) {
|
||||||
return errors.New("limiter " + name + " not found")
|
registry.TrafficLimiterRegistry().Unregister(name)
|
||||||
}
|
}
|
||||||
registry.TrafficLimiterRegistry().Unregister(name)
|
|
||||||
|
|
||||||
config.OnUpdate(func(c *config.Config) error {
|
config.OnUpdate(func(c *config.Config) error {
|
||||||
limiteres := c.Limiters
|
limiteres := c.Limiters
|
||||||
|
|||||||
@@ -87,36 +87,32 @@ func updateServices(req updateServicesRequest) error {
|
|||||||
return errors.New("services list cannot be empty")
|
return errors.New("services list cannot be empty")
|
||||||
}
|
}
|
||||||
|
|
||||||
// 第一阶段:验证所有服务存在
|
// 第一阶段:验证所有服务名称有效性
|
||||||
for _, serviceConfig := range req.Data {
|
for i := range req.Data {
|
||||||
name := strings.TrimSpace(serviceConfig.Name)
|
name := strings.TrimSpace(req.Data[i].Name)
|
||||||
if name == "" {
|
if name == "" {
|
||||||
return errors.New("service name is required")
|
return errors.New("service name is required")
|
||||||
}
|
}
|
||||||
serviceConfig.Name = name
|
req.Data[i].Name = name
|
||||||
|
|
||||||
old := registry.ServiceRegistry().Get(name)
|
|
||||||
if old == nil {
|
|
||||||
return errors.New("service " + name + " not found")
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// 第二阶段:按照原来的updateService逻辑,逐个更新服务
|
// 第二阶段:逐个更新服务(Upsert模式:存在则更新,不存在则创建)
|
||||||
for _, serviceConfig := range req.Data {
|
for i := range req.Data {
|
||||||
name := strings.TrimSpace(serviceConfig.Name)
|
serviceConfig := &req.Data[i]
|
||||||
serviceConfig.Name = name
|
name := serviceConfig.Name
|
||||||
|
|
||||||
// 1. 获取旧服务
|
// 1. 获取旧服务
|
||||||
old := registry.ServiceRegistry().Get(name)
|
old := registry.ServiceRegistry().Get(name)
|
||||||
|
|
||||||
// 2. 关闭旧服务
|
// 2. 关闭旧服务 (如果存在)
|
||||||
old.Close()
|
if old != nil {
|
||||||
|
old.Close()
|
||||||
// 3. 从注册表移除旧服务
|
// 3. 从注册表移除旧服务
|
||||||
registry.ServiceRegistry().Unregister(name)
|
registry.ServiceRegistry().Unregister(name)
|
||||||
|
}
|
||||||
|
|
||||||
// 4. 解析新服务配置
|
// 4. 解析新服务配置
|
||||||
svc, err := parser.ParseService(&serviceConfig)
|
svc, err := parser.ParseService(serviceConfig)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return errors.New("create service " + name + " failed: " + err.Error())
|
return errors.New("create service " + name + " failed: " + err.Error())
|
||||||
}
|
}
|
||||||
@@ -133,13 +129,20 @@ func updateServices(req updateServicesRequest) error {
|
|||||||
|
|
||||||
// 第三阶段:更新配置
|
// 第三阶段:更新配置
|
||||||
config.OnUpdate(func(c *config.Config) error {
|
config.OnUpdate(func(c *config.Config) error {
|
||||||
for _, serviceConfig := range req.Data {
|
for i := range req.Data {
|
||||||
for i := range c.Services {
|
// 创建副本以确保指针安全
|
||||||
if c.Services[i].Name == serviceConfig.Name {
|
cfgCopy := req.Data[i]
|
||||||
c.Services[i] = &serviceConfig
|
found := false
|
||||||
|
for j := range c.Services {
|
||||||
|
if c.Services[j].Name == cfgCopy.Name {
|
||||||
|
c.Services[j] = &cfgCopy
|
||||||
|
found = true
|
||||||
break
|
break
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
if !found {
|
||||||
|
c.Services = append(c.Services, &cfgCopy)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
return nil
|
return nil
|
||||||
})
|
})
|
||||||
@@ -158,22 +161,22 @@ func deleteServices(req deleteServicesRequest) error {
|
|||||||
name string
|
name string
|
||||||
service service.Service
|
service service.Service
|
||||||
}
|
}
|
||||||
|
var namesToRemove []string
|
||||||
|
|
||||||
for _, serviceName := range req.Services {
|
for _, serviceName := range req.Services {
|
||||||
name := strings.TrimSpace(serviceName)
|
name := strings.TrimSpace(serviceName)
|
||||||
if name == "" {
|
if name == "" {
|
||||||
return errors.New("service name is required")
|
return errors.New("service name is required")
|
||||||
}
|
}
|
||||||
|
namesToRemove = append(namesToRemove, name)
|
||||||
|
|
||||||
svc := registry.ServiceRegistry().Get(name)
|
svc := registry.ServiceRegistry().Get(name)
|
||||||
if svc == nil {
|
if svc != nil {
|
||||||
return errors.New("service " + name + " not found")
|
servicesToDelete = append(servicesToDelete, struct {
|
||||||
|
name string
|
||||||
|
service service.Service
|
||||||
|
}{name, svc})
|
||||||
}
|
}
|
||||||
|
|
||||||
servicesToDelete = append(servicesToDelete, struct {
|
|
||||||
name string
|
|
||||||
service service.Service
|
|
||||||
}{name, svc})
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// 第二阶段:删除所有服务
|
// 第二阶段:删除所有服务
|
||||||
@@ -181,6 +184,12 @@ func deleteServices(req deleteServicesRequest) error {
|
|||||||
registry.ServiceRegistry().Unregister(std.name)
|
registry.ServiceRegistry().Unregister(std.name)
|
||||||
std.service.Close()
|
std.service.Close()
|
||||||
}
|
}
|
||||||
|
// 确保所有请求删除的服务都从注册表中移除(即使之前未找到实例)
|
||||||
|
for _, name := range namesToRemove {
|
||||||
|
if registry.ServiceRegistry().IsRegistered(name) {
|
||||||
|
registry.ServiceRegistry().Unregister(name)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// 第三阶段:更新配置
|
// 第三阶段:更新配置
|
||||||
config.OnUpdate(func(c *config.Config) error {
|
config.OnUpdate(func(c *config.Config) error {
|
||||||
@@ -188,8 +197,8 @@ func deleteServices(req deleteServicesRequest) error {
|
|||||||
c.Services = nil
|
c.Services = nil
|
||||||
for _, s := range services {
|
for _, s := range services {
|
||||||
shouldDelete := false
|
shouldDelete := false
|
||||||
for _, std := range servicesToDelete {
|
for _, name := range namesToRemove {
|
||||||
if s.Name == std.name {
|
if s.Name == name {
|
||||||
shouldDelete = true
|
shouldDelete = true
|
||||||
break
|
break
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -586,7 +586,16 @@ func (w *WebSocketReporter) routeCommand(cmd CommandMessage) {
|
|||||||
|
|
||||||
// 只有状态变更命令才保存配置
|
// 只有状态变更命令才保存配置
|
||||||
if needSaveConfig {
|
if needSaveConfig {
|
||||||
saveConfig()
|
if saveErr := saveConfig(); saveErr != nil {
|
||||||
|
fmt.Printf("❌ 保存配置失败: %v\n", saveErr)
|
||||||
|
if err == nil {
|
||||||
|
err = fmt.Errorf("保存配置失败: %v", saveErr)
|
||||||
|
} else {
|
||||||
|
err = fmt.Errorf("%v; 保存配置失败: %v", err, saveErr)
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
fmt.Println("✅ 配置已保存到 gost.json")
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// 发送响应
|
// 发送响应
|
||||||
|
|||||||
@@ -1,89 +0,0 @@
|
|||||||
package middleware
|
|
||||||
|
|
||||||
import (
|
|
||||||
"errors"
|
|
||||||
"strconv"
|
|
||||||
"time"
|
|
||||||
|
|
||||||
"github.com/flipped-aurora/gin-vue-admin/server/global"
|
|
||||||
"github.com/flipped-aurora/gin-vue-admin/server/utils"
|
|
||||||
"github.com/golang-jwt/jwt/v5"
|
|
||||||
|
|
||||||
"github.com/flipped-aurora/gin-vue-admin/server/model/common/response"
|
|
||||||
"github.com/gin-gonic/gin"
|
|
||||||
)
|
|
||||||
|
|
||||||
func JWTAuth() gin.HandlerFunc {
|
|
||||||
return func(c *gin.Context) {
|
|
||||||
// 我们这里jwt鉴权取头部信息 x-token 登录时回返回token信息 这里前端需要把token存储到cookie或者本地localStorage中 不过需要跟后端协商过期时间 可以约定刷新令牌或者重新登录
|
|
||||||
token := utils.GetToken(c)
|
|
||||||
if token == "" {
|
|
||||||
response.NoAuth("未登录或非法访问,请登录", c)
|
|
||||||
c.Abort()
|
|
||||||
return
|
|
||||||
}
|
|
||||||
if isBlacklist(token) {
|
|
||||||
response.NoAuth("您的帐户异地登陆或令牌失效", c)
|
|
||||||
utils.ClearToken(c)
|
|
||||||
c.Abort()
|
|
||||||
return
|
|
||||||
}
|
|
||||||
j := utils.NewJWT()
|
|
||||||
// parseToken 解析token包含的信息
|
|
||||||
claims, err := j.ParseToken(token)
|
|
||||||
if err != nil {
|
|
||||||
if errors.Is(err, utils.TokenExpired) {
|
|
||||||
response.NoAuth("登录已过期,请重新登录", c)
|
|
||||||
utils.ClearToken(c)
|
|
||||||
c.Abort()
|
|
||||||
return
|
|
||||||
}
|
|
||||||
response.NoAuth(err.Error(), c)
|
|
||||||
utils.ClearToken(c)
|
|
||||||
c.Abort()
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
// 已登录用户被管理员禁用 需要使该用户的jwt失效 此处比较消耗性能 如果需要 请自行打开
|
|
||||||
// 用户被删除的逻辑 需要优化 此处比较消耗性能 如果需要 请自行打开
|
|
||||||
|
|
||||||
//if user, err := userService.FindUserByUuid(claims.UUID.String()); err != nil || user.Enable == 2 {
|
|
||||||
// _ = jwtService.JsonInBlacklist(system.JwtBlacklist{Jwt: token})
|
|
||||||
// response.FailWithDetailed(gin.H{"reload": true}, err.Error(), c)
|
|
||||||
// c.Abort()
|
|
||||||
//}
|
|
||||||
c.Set("claims", claims)
|
|
||||||
if claims.ExpiresAt.Unix()-time.Now().Unix() < claims.BufferTime {
|
|
||||||
dr, _ := utils.ParseDuration(global.GVA_CONFIG.JWT.ExpiresTime)
|
|
||||||
claims.ExpiresAt = jwt.NewNumericDate(time.Now().Add(dr))
|
|
||||||
newToken, _ := j.CreateTokenByOldToken(token, *claims)
|
|
||||||
newClaims, _ := j.ParseToken(newToken)
|
|
||||||
c.Header("new-token", newToken)
|
|
||||||
c.Header("new-expires-at", strconv.FormatInt(newClaims.ExpiresAt.Unix(), 10))
|
|
||||||
utils.SetToken(c, newToken, int(dr.Seconds()/60))
|
|
||||||
if global.GVA_CONFIG.System.UseMultipoint {
|
|
||||||
// 记录新的活跃jwt
|
|
||||||
_ = utils.SetRedisJWT(newToken, newClaims.Username)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
c.Next()
|
|
||||||
|
|
||||||
if newToken, exists := c.Get("new-token"); exists {
|
|
||||||
c.Header("new-token", newToken.(string))
|
|
||||||
}
|
|
||||||
if newExpiresAt, exists := c.Get("new-expires-at"); exists {
|
|
||||||
c.Header("new-expires-at", newExpiresAt.(string))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
//@author: [piexlmax](https://github.com/piexlmax)
|
|
||||||
//@function: IsBlacklist
|
|
||||||
//@description: 判断JWT是否在黑名单内部
|
|
||||||
//@param: jwt string
|
|
||||||
//@return: bool
|
|
||||||
|
|
||||||
func isBlacklist(jwt string) bool {
|
|
||||||
_, ok := global.BlackCache.Get(jwt)
|
|
||||||
return ok
|
|
||||||
}
|
|
||||||
@@ -1,62 +0,0 @@
|
|||||||
package response
|
|
||||||
|
|
||||||
import (
|
|
||||||
"net/http"
|
|
||||||
|
|
||||||
"github.com/gin-gonic/gin"
|
|
||||||
)
|
|
||||||
|
|
||||||
type Response struct {
|
|
||||||
Code int `json:"code"`
|
|
||||||
Data interface{} `json:"data"`
|
|
||||||
Msg string `json:"msg"`
|
|
||||||
}
|
|
||||||
|
|
||||||
const (
|
|
||||||
ERROR = 7
|
|
||||||
SUCCESS = 0
|
|
||||||
)
|
|
||||||
|
|
||||||
func Result(code int, data interface{}, msg string, c *gin.Context) {
|
|
||||||
c.JSON(http.StatusOK, Response{
|
|
||||||
code,
|
|
||||||
data,
|
|
||||||
msg,
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
func Ok(c *gin.Context) {
|
|
||||||
Result(SUCCESS, map[string]interface{}{}, "操作成功", c)
|
|
||||||
}
|
|
||||||
|
|
||||||
func OkWithMessage(message string, c *gin.Context) {
|
|
||||||
Result(SUCCESS, map[string]interface{}{}, message, c)
|
|
||||||
}
|
|
||||||
|
|
||||||
func OkWithData(data interface{}, c *gin.Context) {
|
|
||||||
Result(SUCCESS, data, "成功", c)
|
|
||||||
}
|
|
||||||
|
|
||||||
func OkWithDetailed(data interface{}, message string, c *gin.Context) {
|
|
||||||
Result(SUCCESS, data, message, c)
|
|
||||||
}
|
|
||||||
|
|
||||||
func Fail(c *gin.Context) {
|
|
||||||
Result(ERROR, map[string]interface{}{}, "操作失败", c)
|
|
||||||
}
|
|
||||||
|
|
||||||
func FailWithMessage(message string, c *gin.Context) {
|
|
||||||
Result(ERROR, map[string]interface{}{}, message, c)
|
|
||||||
}
|
|
||||||
|
|
||||||
func NoAuth(message string, c *gin.Context) {
|
|
||||||
c.JSON(http.StatusUnauthorized, Response{
|
|
||||||
7,
|
|
||||||
nil,
|
|
||||||
message,
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
func FailWithDetailed(data interface{}, message string, c *gin.Context) {
|
|
||||||
Result(ERROR, data, message, c)
|
|
||||||
}
|
|
||||||
@@ -1,28 +0,0 @@
|
|||||||
package system
|
|
||||||
|
|
||||||
import (
|
|
||||||
"github.com/flipped-aurora/gin-vue-admin/server/middleware"
|
|
||||||
"github.com/gin-gonic/gin"
|
|
||||||
)
|
|
||||||
|
|
||||||
type UserRouter struct{}
|
|
||||||
|
|
||||||
func (s *UserRouter) InitUserRouter(Router *gin.RouterGroup) {
|
|
||||||
userRouter := Router.Group("user").Use(middleware.OperationRecord())
|
|
||||||
userRouterWithoutRecord := Router.Group("user")
|
|
||||||
{
|
|
||||||
userRouter.POST("admin_register", baseApi.Register) // 管理员注册账号
|
|
||||||
userRouter.POST("changePassword", baseApi.ChangePassword) // 用户修改密码
|
|
||||||
userRouter.POST("setUserAuthority", baseApi.SetUserAuthority) // 设置用户权限
|
|
||||||
userRouter.DELETE("deleteUser", baseApi.DeleteUser) // 删除用户
|
|
||||||
userRouter.PUT("setUserInfo", baseApi.SetUserInfo) // 设置用户信息
|
|
||||||
userRouter.PUT("setSelfInfo", baseApi.SetSelfInfo) // 设置自身信息
|
|
||||||
userRouter.POST("setUserAuthorities", baseApi.SetUserAuthorities) // 设置用户权限组
|
|
||||||
userRouter.POST("resetPassword", baseApi.ResetPassword) // 重置用户密码
|
|
||||||
userRouter.PUT("setSelfSetting", baseApi.SetSelfSetting) // 用户界面配置
|
|
||||||
}
|
|
||||||
{
|
|
||||||
userRouterWithoutRecord.POST("getUserList", baseApi.GetUserList) // 分页获取用户列表
|
|
||||||
userRouterWithoutRecord.GET("getUserInfo", baseApi.GetUserInfo) // 获取自身信息
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -3,6 +3,9 @@
|
|||||||
# GitHub repo used for release downloads
|
# GitHub repo used for release downloads
|
||||||
REPO="Sagit-chu/flux-panel"
|
REPO="Sagit-chu/flux-panel"
|
||||||
|
|
||||||
|
# 固定版本号(Release 构建时自动填充,留空则获取最新版)
|
||||||
|
PINNED_VERSION=""
|
||||||
|
|
||||||
# 获取系统架构
|
# 获取系统架构
|
||||||
get_architecture() {
|
get_architecture() {
|
||||||
ARCH=$(uname -m)
|
ARCH=$(uname -m)
|
||||||
@@ -22,16 +25,10 @@ get_architecture() {
|
|||||||
# 安装目录
|
# 安装目录
|
||||||
INSTALL_DIR="/etc/flux_agent"
|
INSTALL_DIR="/etc/flux_agent"
|
||||||
|
|
||||||
# 识别国家(用于镜像加速)
|
# 镜像加速(所有下载均经过镜像源,以支持 IPv6)
|
||||||
COUNTRY=$(curl -s https://ipinfo.io/country)
|
|
||||||
|
|
||||||
maybe_proxy_url() {
|
maybe_proxy_url() {
|
||||||
local url="$1"
|
local url="$1"
|
||||||
if [ "$COUNTRY" = "CN" ]; then
|
echo "https://gcode.hostcentral.cc/${url}"
|
||||||
echo "https://ghfast.top/${url}"
|
|
||||||
else
|
|
||||||
echo "$url"
|
|
||||||
fi
|
|
||||||
}
|
}
|
||||||
|
|
||||||
resolve_latest_release_tag() {
|
resolve_latest_release_tag() {
|
||||||
@@ -40,39 +37,19 @@ resolve_latest_release_tag() {
|
|||||||
latest_url="https://github.com/${REPO}/releases/latest"
|
latest_url="https://github.com/${REPO}/releases/latest"
|
||||||
api_url="https://api.github.com/repos/${REPO}/releases/latest"
|
api_url="https://api.github.com/repos/${REPO}/releases/latest"
|
||||||
|
|
||||||
# 方式1:跟随重定向,取最终 URL 的最后一段作为 tag
|
effective_url=$(curl -fsSL -o /dev/null -w '%{url_effective}' -L "$(maybe_proxy_url "$latest_url")" 2>/dev/null || true)
|
||||||
effective_url=$(curl -fsSL -o /dev/null -w '%{url_effective}' -L "$latest_url" 2>/dev/null || true)
|
|
||||||
tag="${effective_url##*/}"
|
tag="${effective_url##*/}"
|
||||||
if [[ -n "$tag" && "$tag" != "latest" ]]; then
|
if [[ -n "$tag" && "$tag" != "latest" ]]; then
|
||||||
echo "$tag"
|
echo "$tag"
|
||||||
return 0
|
return 0
|
||||||
fi
|
fi
|
||||||
|
|
||||||
# CN 环境下可尝试通过镜像访问(不影响非 CN)
|
api_tag=$(curl -fsSL "$(maybe_proxy_url "$api_url")" 2>/dev/null | grep -m1 '"tag_name"' | sed -E 's/.*"tag_name"[[:space:]]*:[[:space:]]*"([^"]+)".*/\1/' || true)
|
||||||
if [ "$COUNTRY" = "CN" ]; then
|
|
||||||
effective_url=$(curl -fsSL -o /dev/null -w '%{url_effective}' -L "$(maybe_proxy_url "$latest_url")" 2>/dev/null || true)
|
|
||||||
tag="${effective_url##*/}"
|
|
||||||
if [[ -n "$tag" && "$tag" != "latest" ]]; then
|
|
||||||
echo "$tag"
|
|
||||||
return 0
|
|
||||||
fi
|
|
||||||
fi
|
|
||||||
|
|
||||||
# 方式2:GitHub API(无需 jq)
|
|
||||||
api_tag=$(curl -fsSL "$api_url" 2>/dev/null | grep -m1 '"tag_name"' | sed -E 's/.*"tag_name"[[:space:]]*:[[:space:]]*"([^"]+)".*/\1/' || true)
|
|
||||||
if [[ -n "$api_tag" ]]; then
|
if [[ -n "$api_tag" ]]; then
|
||||||
echo "$api_tag"
|
echo "$api_tag"
|
||||||
return 0
|
return 0
|
||||||
fi
|
fi
|
||||||
|
|
||||||
if [ "$COUNTRY" = "CN" ]; then
|
|
||||||
api_tag=$(curl -fsSL "$(maybe_proxy_url "$api_url")" 2>/dev/null | grep -m1 '"tag_name"' | sed -E 's/.*"tag_name"[[:space:]]*:[[:space:]]*"([^"]+)".*/\1/' || true)
|
|
||||||
if [[ -n "$api_tag" ]]; then
|
|
||||||
echo "$api_tag"
|
|
||||||
return 0
|
|
||||||
fi
|
|
||||||
fi
|
|
||||||
|
|
||||||
return 1
|
return 1
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -85,6 +62,10 @@ resolve_version() {
|
|||||||
echo "$FLUX_VERSION"
|
echo "$FLUX_VERSION"
|
||||||
return 0
|
return 0
|
||||||
fi
|
fi
|
||||||
|
if [[ -n "${PINNED_VERSION:-}" ]]; then
|
||||||
|
echo "$PINNED_VERSION"
|
||||||
|
return 0
|
||||||
|
fi
|
||||||
|
|
||||||
if resolve_latest_release_tag; then
|
if resolve_latest_release_tag; then
|
||||||
return 0
|
return 0
|
||||||
|
|||||||
@@ -1,563 +0,0 @@
|
|||||||
// !$*UTF8*$!
|
|
||||||
{
|
|
||||||
archiveVersion = 1;
|
|
||||||
classes = {
|
|
||||||
};
|
|
||||||
objectVersion = 77;
|
|
||||||
objects = {
|
|
||||||
|
|
||||||
/* Begin PBXContainerItemProxy section */
|
|
||||||
296FEB8A2E56AAF900DC77A3 /* PBXContainerItemProxy */ = {
|
|
||||||
isa = PBXContainerItemProxy;
|
|
||||||
containerPortal = 296FEB742E56AAF700DC77A3 /* Project object */;
|
|
||||||
proxyType = 1;
|
|
||||||
remoteGlobalIDString = 296FEB7B2E56AAF700DC77A3;
|
|
||||||
remoteInfo = flux;
|
|
||||||
};
|
|
||||||
296FEB942E56AAF900DC77A3 /* PBXContainerItemProxy */ = {
|
|
||||||
isa = PBXContainerItemProxy;
|
|
||||||
containerPortal = 296FEB742E56AAF700DC77A3 /* Project object */;
|
|
||||||
proxyType = 1;
|
|
||||||
remoteGlobalIDString = 296FEB7B2E56AAF700DC77A3;
|
|
||||||
remoteInfo = flux;
|
|
||||||
};
|
|
||||||
/* End PBXContainerItemProxy section */
|
|
||||||
|
|
||||||
/* Begin PBXFileReference section */
|
|
||||||
296FEB7C2E56AAF700DC77A3 /* flux.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = flux.app; sourceTree = BUILT_PRODUCTS_DIR; };
|
|
||||||
296FEB892E56AAF900DC77A3 /* fluxTests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = fluxTests.xctest; sourceTree = BUILT_PRODUCTS_DIR; };
|
|
||||||
296FEB932E56AAF900DC77A3 /* fluxUITests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = fluxUITests.xctest; sourceTree = BUILT_PRODUCTS_DIR; };
|
|
||||||
/* End PBXFileReference section */
|
|
||||||
|
|
||||||
/* Begin PBXFileSystemSynchronizedRootGroup section */
|
|
||||||
296FEB7E2E56AAF700DC77A3 /* flux */ = {
|
|
||||||
isa = PBXFileSystemSynchronizedRootGroup;
|
|
||||||
path = flux;
|
|
||||||
sourceTree = "<group>";
|
|
||||||
};
|
|
||||||
296FEB8C2E56AAF900DC77A3 /* fluxTests */ = {
|
|
||||||
isa = PBXFileSystemSynchronizedRootGroup;
|
|
||||||
path = fluxTests;
|
|
||||||
sourceTree = "<group>";
|
|
||||||
};
|
|
||||||
296FEB962E56AAF900DC77A3 /* fluxUITests */ = {
|
|
||||||
isa = PBXFileSystemSynchronizedRootGroup;
|
|
||||||
path = fluxUITests;
|
|
||||||
sourceTree = "<group>";
|
|
||||||
};
|
|
||||||
/* End PBXFileSystemSynchronizedRootGroup section */
|
|
||||||
|
|
||||||
/* Begin PBXFrameworksBuildPhase section */
|
|
||||||
296FEB792E56AAF700DC77A3 /* Frameworks */ = {
|
|
||||||
isa = PBXFrameworksBuildPhase;
|
|
||||||
buildActionMask = 2147483647;
|
|
||||||
files = (
|
|
||||||
);
|
|
||||||
runOnlyForDeploymentPostprocessing = 0;
|
|
||||||
};
|
|
||||||
296FEB862E56AAF900DC77A3 /* Frameworks */ = {
|
|
||||||
isa = PBXFrameworksBuildPhase;
|
|
||||||
buildActionMask = 2147483647;
|
|
||||||
files = (
|
|
||||||
);
|
|
||||||
runOnlyForDeploymentPostprocessing = 0;
|
|
||||||
};
|
|
||||||
296FEB902E56AAF900DC77A3 /* Frameworks */ = {
|
|
||||||
isa = PBXFrameworksBuildPhase;
|
|
||||||
buildActionMask = 2147483647;
|
|
||||||
files = (
|
|
||||||
);
|
|
||||||
runOnlyForDeploymentPostprocessing = 0;
|
|
||||||
};
|
|
||||||
/* End PBXFrameworksBuildPhase section */
|
|
||||||
|
|
||||||
/* Begin PBXGroup section */
|
|
||||||
296FEB732E56AAF700DC77A3 = {
|
|
||||||
isa = PBXGroup;
|
|
||||||
children = (
|
|
||||||
296FEB7E2E56AAF700DC77A3 /* flux */,
|
|
||||||
296FEB8C2E56AAF900DC77A3 /* fluxTests */,
|
|
||||||
296FEB962E56AAF900DC77A3 /* fluxUITests */,
|
|
||||||
296FEB7D2E56AAF700DC77A3 /* Products */,
|
|
||||||
);
|
|
||||||
sourceTree = "<group>";
|
|
||||||
};
|
|
||||||
296FEB7D2E56AAF700DC77A3 /* Products */ = {
|
|
||||||
isa = PBXGroup;
|
|
||||||
children = (
|
|
||||||
296FEB7C2E56AAF700DC77A3 /* flux.app */,
|
|
||||||
296FEB892E56AAF900DC77A3 /* fluxTests.xctest */,
|
|
||||||
296FEB932E56AAF900DC77A3 /* fluxUITests.xctest */,
|
|
||||||
);
|
|
||||||
name = Products;
|
|
||||||
sourceTree = "<group>";
|
|
||||||
};
|
|
||||||
/* End PBXGroup section */
|
|
||||||
|
|
||||||
/* Begin PBXNativeTarget section */
|
|
||||||
296FEB7B2E56AAF700DC77A3 /* flux */ = {
|
|
||||||
isa = PBXNativeTarget;
|
|
||||||
buildConfigurationList = 296FEB9D2E56AAF900DC77A3 /* Build configuration list for PBXNativeTarget "flux" */;
|
|
||||||
buildPhases = (
|
|
||||||
296FEB782E56AAF700DC77A3 /* Sources */,
|
|
||||||
296FEB792E56AAF700DC77A3 /* Frameworks */,
|
|
||||||
296FEB7A2E56AAF700DC77A3 /* Resources */,
|
|
||||||
);
|
|
||||||
buildRules = (
|
|
||||||
);
|
|
||||||
dependencies = (
|
|
||||||
);
|
|
||||||
fileSystemSynchronizedGroups = (
|
|
||||||
296FEB7E2E56AAF700DC77A3 /* flux */,
|
|
||||||
);
|
|
||||||
name = flux;
|
|
||||||
packageProductDependencies = (
|
|
||||||
);
|
|
||||||
productName = flux;
|
|
||||||
productReference = 296FEB7C2E56AAF700DC77A3 /* flux.app */;
|
|
||||||
productType = "com.apple.product-type.application";
|
|
||||||
};
|
|
||||||
296FEB882E56AAF900DC77A3 /* fluxTests */ = {
|
|
||||||
isa = PBXNativeTarget;
|
|
||||||
buildConfigurationList = 296FEBA02E56AAF900DC77A3 /* Build configuration list for PBXNativeTarget "fluxTests" */;
|
|
||||||
buildPhases = (
|
|
||||||
296FEB852E56AAF900DC77A3 /* Sources */,
|
|
||||||
296FEB862E56AAF900DC77A3 /* Frameworks */,
|
|
||||||
296FEB872E56AAF900DC77A3 /* Resources */,
|
|
||||||
);
|
|
||||||
buildRules = (
|
|
||||||
);
|
|
||||||
dependencies = (
|
|
||||||
296FEB8B2E56AAF900DC77A3 /* PBXTargetDependency */,
|
|
||||||
);
|
|
||||||
fileSystemSynchronizedGroups = (
|
|
||||||
296FEB8C2E56AAF900DC77A3 /* fluxTests */,
|
|
||||||
);
|
|
||||||
name = fluxTests;
|
|
||||||
packageProductDependencies = (
|
|
||||||
);
|
|
||||||
productName = fluxTests;
|
|
||||||
productReference = 296FEB892E56AAF900DC77A3 /* fluxTests.xctest */;
|
|
||||||
productType = "com.apple.product-type.bundle.unit-test";
|
|
||||||
};
|
|
||||||
296FEB922E56AAF900DC77A3 /* fluxUITests */ = {
|
|
||||||
isa = PBXNativeTarget;
|
|
||||||
buildConfigurationList = 296FEBA32E56AAF900DC77A3 /* Build configuration list for PBXNativeTarget "fluxUITests" */;
|
|
||||||
buildPhases = (
|
|
||||||
296FEB8F2E56AAF900DC77A3 /* Sources */,
|
|
||||||
296FEB902E56AAF900DC77A3 /* Frameworks */,
|
|
||||||
296FEB912E56AAF900DC77A3 /* Resources */,
|
|
||||||
);
|
|
||||||
buildRules = (
|
|
||||||
);
|
|
||||||
dependencies = (
|
|
||||||
296FEB952E56AAF900DC77A3 /* PBXTargetDependency */,
|
|
||||||
);
|
|
||||||
fileSystemSynchronizedGroups = (
|
|
||||||
296FEB962E56AAF900DC77A3 /* fluxUITests */,
|
|
||||||
);
|
|
||||||
name = fluxUITests;
|
|
||||||
packageProductDependencies = (
|
|
||||||
);
|
|
||||||
productName = fluxUITests;
|
|
||||||
productReference = 296FEB932E56AAF900DC77A3 /* fluxUITests.xctest */;
|
|
||||||
productType = "com.apple.product-type.bundle.ui-testing";
|
|
||||||
};
|
|
||||||
/* End PBXNativeTarget section */
|
|
||||||
|
|
||||||
/* Begin PBXProject section */
|
|
||||||
296FEB742E56AAF700DC77A3 /* Project object */ = {
|
|
||||||
isa = PBXProject;
|
|
||||||
attributes = {
|
|
||||||
BuildIndependentTargetsInParallel = 1;
|
|
||||||
LastSwiftUpdateCheck = 1640;
|
|
||||||
LastUpgradeCheck = 1640;
|
|
||||||
TargetAttributes = {
|
|
||||||
296FEB7B2E56AAF700DC77A3 = {
|
|
||||||
CreatedOnToolsVersion = 16.4;
|
|
||||||
};
|
|
||||||
296FEB882E56AAF900DC77A3 = {
|
|
||||||
CreatedOnToolsVersion = 16.4;
|
|
||||||
TestTargetID = 296FEB7B2E56AAF700DC77A3;
|
|
||||||
};
|
|
||||||
296FEB922E56AAF900DC77A3 = {
|
|
||||||
CreatedOnToolsVersion = 16.4;
|
|
||||||
TestTargetID = 296FEB7B2E56AAF700DC77A3;
|
|
||||||
};
|
|
||||||
};
|
|
||||||
};
|
|
||||||
buildConfigurationList = 296FEB772E56AAF700DC77A3 /* Build configuration list for PBXProject "flux" */;
|
|
||||||
developmentRegion = en;
|
|
||||||
hasScannedForEncodings = 0;
|
|
||||||
knownRegions = (
|
|
||||||
en,
|
|
||||||
Base,
|
|
||||||
);
|
|
||||||
mainGroup = 296FEB732E56AAF700DC77A3;
|
|
||||||
minimizedProjectReferenceProxies = 1;
|
|
||||||
preferredProjectObjectVersion = 77;
|
|
||||||
productRefGroup = 296FEB7D2E56AAF700DC77A3 /* Products */;
|
|
||||||
projectDirPath = "";
|
|
||||||
projectRoot = "";
|
|
||||||
targets = (
|
|
||||||
296FEB7B2E56AAF700DC77A3 /* flux */,
|
|
||||||
296FEB882E56AAF900DC77A3 /* fluxTests */,
|
|
||||||
296FEB922E56AAF900DC77A3 /* fluxUITests */,
|
|
||||||
);
|
|
||||||
};
|
|
||||||
/* End PBXProject section */
|
|
||||||
|
|
||||||
/* Begin PBXResourcesBuildPhase section */
|
|
||||||
296FEB7A2E56AAF700DC77A3 /* Resources */ = {
|
|
||||||
isa = PBXResourcesBuildPhase;
|
|
||||||
buildActionMask = 2147483647;
|
|
||||||
files = (
|
|
||||||
);
|
|
||||||
runOnlyForDeploymentPostprocessing = 0;
|
|
||||||
};
|
|
||||||
296FEB872E56AAF900DC77A3 /* Resources */ = {
|
|
||||||
isa = PBXResourcesBuildPhase;
|
|
||||||
buildActionMask = 2147483647;
|
|
||||||
files = (
|
|
||||||
);
|
|
||||||
runOnlyForDeploymentPostprocessing = 0;
|
|
||||||
};
|
|
||||||
296FEB912E56AAF900DC77A3 /* Resources */ = {
|
|
||||||
isa = PBXResourcesBuildPhase;
|
|
||||||
buildActionMask = 2147483647;
|
|
||||||
files = (
|
|
||||||
);
|
|
||||||
runOnlyForDeploymentPostprocessing = 0;
|
|
||||||
};
|
|
||||||
/* End PBXResourcesBuildPhase section */
|
|
||||||
|
|
||||||
/* Begin PBXSourcesBuildPhase section */
|
|
||||||
296FEB782E56AAF700DC77A3 /* Sources */ = {
|
|
||||||
isa = PBXSourcesBuildPhase;
|
|
||||||
buildActionMask = 2147483647;
|
|
||||||
files = (
|
|
||||||
);
|
|
||||||
runOnlyForDeploymentPostprocessing = 0;
|
|
||||||
};
|
|
||||||
296FEB852E56AAF900DC77A3 /* Sources */ = {
|
|
||||||
isa = PBXSourcesBuildPhase;
|
|
||||||
buildActionMask = 2147483647;
|
|
||||||
files = (
|
|
||||||
);
|
|
||||||
runOnlyForDeploymentPostprocessing = 0;
|
|
||||||
};
|
|
||||||
296FEB8F2E56AAF900DC77A3 /* Sources */ = {
|
|
||||||
isa = PBXSourcesBuildPhase;
|
|
||||||
buildActionMask = 2147483647;
|
|
||||||
files = (
|
|
||||||
);
|
|
||||||
runOnlyForDeploymentPostprocessing = 0;
|
|
||||||
};
|
|
||||||
/* End PBXSourcesBuildPhase section */
|
|
||||||
|
|
||||||
/* Begin PBXTargetDependency section */
|
|
||||||
296FEB8B2E56AAF900DC77A3 /* PBXTargetDependency */ = {
|
|
||||||
isa = PBXTargetDependency;
|
|
||||||
target = 296FEB7B2E56AAF700DC77A3 /* flux */;
|
|
||||||
targetProxy = 296FEB8A2E56AAF900DC77A3 /* PBXContainerItemProxy */;
|
|
||||||
};
|
|
||||||
296FEB952E56AAF900DC77A3 /* PBXTargetDependency */ = {
|
|
||||||
isa = PBXTargetDependency;
|
|
||||||
target = 296FEB7B2E56AAF700DC77A3 /* flux */;
|
|
||||||
targetProxy = 296FEB942E56AAF900DC77A3 /* PBXContainerItemProxy */;
|
|
||||||
};
|
|
||||||
/* End PBXTargetDependency section */
|
|
||||||
|
|
||||||
/* Begin XCBuildConfiguration section */
|
|
||||||
296FEB9B2E56AAF900DC77A3 /* Debug */ = {
|
|
||||||
isa = XCBuildConfiguration;
|
|
||||||
buildSettings = {
|
|
||||||
ALWAYS_SEARCH_USER_PATHS = NO;
|
|
||||||
ASSETCATALOG_COMPILER_GENERATE_SWIFT_ASSET_SYMBOL_EXTENSIONS = YES;
|
|
||||||
CLANG_ANALYZER_NONNULL = YES;
|
|
||||||
CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE;
|
|
||||||
CLANG_CXX_LANGUAGE_STANDARD = "gnu++20";
|
|
||||||
CLANG_ENABLE_MODULES = YES;
|
|
||||||
CLANG_ENABLE_OBJC_ARC = YES;
|
|
||||||
CLANG_ENABLE_OBJC_WEAK = YES;
|
|
||||||
CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES;
|
|
||||||
CLANG_WARN_BOOL_CONVERSION = YES;
|
|
||||||
CLANG_WARN_COMMA = YES;
|
|
||||||
CLANG_WARN_CONSTANT_CONVERSION = YES;
|
|
||||||
CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES;
|
|
||||||
CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR;
|
|
||||||
CLANG_WARN_DOCUMENTATION_COMMENTS = YES;
|
|
||||||
CLANG_WARN_EMPTY_BODY = YES;
|
|
||||||
CLANG_WARN_ENUM_CONVERSION = YES;
|
|
||||||
CLANG_WARN_INFINITE_RECURSION = YES;
|
|
||||||
CLANG_WARN_INT_CONVERSION = YES;
|
|
||||||
CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES;
|
|
||||||
CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES;
|
|
||||||
CLANG_WARN_OBJC_LITERAL_CONVERSION = YES;
|
|
||||||
CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR;
|
|
||||||
CLANG_WARN_QUOTED_INCLUDE_IN_FRAMEWORK_HEADER = YES;
|
|
||||||
CLANG_WARN_RANGE_LOOP_ANALYSIS = YES;
|
|
||||||
CLANG_WARN_STRICT_PROTOTYPES = YES;
|
|
||||||
CLANG_WARN_SUSPICIOUS_MOVE = YES;
|
|
||||||
CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE;
|
|
||||||
CLANG_WARN_UNREACHABLE_CODE = YES;
|
|
||||||
CLANG_WARN__DUPLICATE_METHOD_MATCH = YES;
|
|
||||||
COPY_PHASE_STRIP = NO;
|
|
||||||
DEBUG_INFORMATION_FORMAT = dwarf;
|
|
||||||
ENABLE_STRICT_OBJC_MSGSEND = YES;
|
|
||||||
ENABLE_TESTABILITY = YES;
|
|
||||||
ENABLE_USER_SCRIPT_SANDBOXING = YES;
|
|
||||||
GCC_C_LANGUAGE_STANDARD = gnu17;
|
|
||||||
GCC_DYNAMIC_NO_PIC = NO;
|
|
||||||
GCC_NO_COMMON_BLOCKS = YES;
|
|
||||||
GCC_OPTIMIZATION_LEVEL = 0;
|
|
||||||
GCC_PREPROCESSOR_DEFINITIONS = (
|
|
||||||
"DEBUG=1",
|
|
||||||
"$(inherited)",
|
|
||||||
);
|
|
||||||
GCC_WARN_64_TO_32_BIT_CONVERSION = YES;
|
|
||||||
GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR;
|
|
||||||
GCC_WARN_UNDECLARED_SELECTOR = YES;
|
|
||||||
GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE;
|
|
||||||
GCC_WARN_UNUSED_FUNCTION = YES;
|
|
||||||
GCC_WARN_UNUSED_VARIABLE = YES;
|
|
||||||
IPHONEOS_DEPLOYMENT_TARGET = 18.5;
|
|
||||||
LOCALIZATION_PREFERS_STRING_CATALOGS = YES;
|
|
||||||
MTL_ENABLE_DEBUG_INFO = INCLUDE_SOURCE;
|
|
||||||
MTL_FAST_MATH = YES;
|
|
||||||
ONLY_ACTIVE_ARCH = YES;
|
|
||||||
SDKROOT = iphoneos;
|
|
||||||
SWIFT_ACTIVE_COMPILATION_CONDITIONS = "DEBUG $(inherited)";
|
|
||||||
SWIFT_OPTIMIZATION_LEVEL = "-Onone";
|
|
||||||
};
|
|
||||||
name = Debug;
|
|
||||||
};
|
|
||||||
296FEB9C2E56AAF900DC77A3 /* Release */ = {
|
|
||||||
isa = XCBuildConfiguration;
|
|
||||||
buildSettings = {
|
|
||||||
ALWAYS_SEARCH_USER_PATHS = NO;
|
|
||||||
ASSETCATALOG_COMPILER_GENERATE_SWIFT_ASSET_SYMBOL_EXTENSIONS = YES;
|
|
||||||
CLANG_ANALYZER_NONNULL = YES;
|
|
||||||
CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE;
|
|
||||||
CLANG_CXX_LANGUAGE_STANDARD = "gnu++20";
|
|
||||||
CLANG_ENABLE_MODULES = YES;
|
|
||||||
CLANG_ENABLE_OBJC_ARC = YES;
|
|
||||||
CLANG_ENABLE_OBJC_WEAK = YES;
|
|
||||||
CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES;
|
|
||||||
CLANG_WARN_BOOL_CONVERSION = YES;
|
|
||||||
CLANG_WARN_COMMA = YES;
|
|
||||||
CLANG_WARN_CONSTANT_CONVERSION = YES;
|
|
||||||
CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES;
|
|
||||||
CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR;
|
|
||||||
CLANG_WARN_DOCUMENTATION_COMMENTS = YES;
|
|
||||||
CLANG_WARN_EMPTY_BODY = YES;
|
|
||||||
CLANG_WARN_ENUM_CONVERSION = YES;
|
|
||||||
CLANG_WARN_INFINITE_RECURSION = YES;
|
|
||||||
CLANG_WARN_INT_CONVERSION = YES;
|
|
||||||
CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES;
|
|
||||||
CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES;
|
|
||||||
CLANG_WARN_OBJC_LITERAL_CONVERSION = YES;
|
|
||||||
CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR;
|
|
||||||
CLANG_WARN_QUOTED_INCLUDE_IN_FRAMEWORK_HEADER = YES;
|
|
||||||
CLANG_WARN_RANGE_LOOP_ANALYSIS = YES;
|
|
||||||
CLANG_WARN_STRICT_PROTOTYPES = YES;
|
|
||||||
CLANG_WARN_SUSPICIOUS_MOVE = YES;
|
|
||||||
CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE;
|
|
||||||
CLANG_WARN_UNREACHABLE_CODE = YES;
|
|
||||||
CLANG_WARN__DUPLICATE_METHOD_MATCH = YES;
|
|
||||||
COPY_PHASE_STRIP = NO;
|
|
||||||
DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym";
|
|
||||||
ENABLE_NS_ASSERTIONS = NO;
|
|
||||||
ENABLE_STRICT_OBJC_MSGSEND = YES;
|
|
||||||
ENABLE_USER_SCRIPT_SANDBOXING = YES;
|
|
||||||
GCC_C_LANGUAGE_STANDARD = gnu17;
|
|
||||||
GCC_NO_COMMON_BLOCKS = YES;
|
|
||||||
GCC_WARN_64_TO_32_BIT_CONVERSION = YES;
|
|
||||||
GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR;
|
|
||||||
GCC_WARN_UNDECLARED_SELECTOR = YES;
|
|
||||||
GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE;
|
|
||||||
GCC_WARN_UNUSED_FUNCTION = YES;
|
|
||||||
GCC_WARN_UNUSED_VARIABLE = YES;
|
|
||||||
IPHONEOS_DEPLOYMENT_TARGET = 18.5;
|
|
||||||
LOCALIZATION_PREFERS_STRING_CATALOGS = YES;
|
|
||||||
MTL_ENABLE_DEBUG_INFO = NO;
|
|
||||||
MTL_FAST_MATH = YES;
|
|
||||||
SDKROOT = iphoneos;
|
|
||||||
SWIFT_COMPILATION_MODE = wholemodule;
|
|
||||||
VALIDATE_PRODUCT = YES;
|
|
||||||
};
|
|
||||||
name = Release;
|
|
||||||
};
|
|
||||||
296FEB9E2E56AAF900DC77A3 /* Debug */ = {
|
|
||||||
isa = XCBuildConfiguration;
|
|
||||||
buildSettings = {
|
|
||||||
ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;
|
|
||||||
ASSETCATALOG_COMPILER_GLOBAL_ACCENT_COLOR_NAME = AccentColor;
|
|
||||||
CODE_SIGN_IDENTITY = "Apple Development";
|
|
||||||
CODE_SIGN_STYLE = Automatic;
|
|
||||||
CURRENT_PROJECT_VERSION = 1;
|
|
||||||
DEVELOPMENT_TEAM = XRXD4YN2Y6;
|
|
||||||
ENABLE_PREVIEWS = YES;
|
|
||||||
GENERATE_INFOPLIST_FILE = YES;
|
|
||||||
INFOPLIST_KEY_UIApplicationSceneManifest_Generation = YES;
|
|
||||||
INFOPLIST_KEY_UIApplicationSupportsIndirectInputEvents = YES;
|
|
||||||
INFOPLIST_KEY_UILaunchScreen_Generation = YES;
|
|
||||||
INFOPLIST_KEY_UISupportedInterfaceOrientations_iPad = "UIInterfaceOrientationPortrait UIInterfaceOrientationPortraitUpsideDown UIInterfaceOrientationLandscapeLeft UIInterfaceOrientationLandscapeRight";
|
|
||||||
INFOPLIST_KEY_UISupportedInterfaceOrientations_iPhone = "UIInterfaceOrientationPortrait UIInterfaceOrientationLandscapeLeft UIInterfaceOrientationLandscapeRight";
|
|
||||||
IPHONEOS_DEPLOYMENT_TARGET = 15.6;
|
|
||||||
LD_RUNPATH_SEARCH_PATHS = (
|
|
||||||
"$(inherited)",
|
|
||||||
"@executable_path/Frameworks",
|
|
||||||
);
|
|
||||||
MARKETING_VERSION = 1.0;
|
|
||||||
PRODUCT_BUNDLE_IDENTIFIER = bqlpfy.flux;
|
|
||||||
PRODUCT_NAME = "$(TARGET_NAME)";
|
|
||||||
PROVISIONING_PROFILE_SPECIFIER = "";
|
|
||||||
SWIFT_EMIT_LOC_STRINGS = YES;
|
|
||||||
SWIFT_VERSION = 5.0;
|
|
||||||
TARGETED_DEVICE_FAMILY = "1,2";
|
|
||||||
};
|
|
||||||
name = Debug;
|
|
||||||
};
|
|
||||||
296FEB9F2E56AAF900DC77A3 /* Release */ = {
|
|
||||||
isa = XCBuildConfiguration;
|
|
||||||
buildSettings = {
|
|
||||||
ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;
|
|
||||||
ASSETCATALOG_COMPILER_GLOBAL_ACCENT_COLOR_NAME = AccentColor;
|
|
||||||
CODE_SIGN_IDENTITY = "Apple Development";
|
|
||||||
CODE_SIGN_STYLE = Automatic;
|
|
||||||
CURRENT_PROJECT_VERSION = 1;
|
|
||||||
DEVELOPMENT_TEAM = XRXD4YN2Y6;
|
|
||||||
ENABLE_PREVIEWS = YES;
|
|
||||||
GENERATE_INFOPLIST_FILE = YES;
|
|
||||||
INFOPLIST_KEY_UIApplicationSceneManifest_Generation = YES;
|
|
||||||
INFOPLIST_KEY_UIApplicationSupportsIndirectInputEvents = YES;
|
|
||||||
INFOPLIST_KEY_UILaunchScreen_Generation = YES;
|
|
||||||
INFOPLIST_KEY_UISupportedInterfaceOrientations_iPad = "UIInterfaceOrientationPortrait UIInterfaceOrientationPortraitUpsideDown UIInterfaceOrientationLandscapeLeft UIInterfaceOrientationLandscapeRight";
|
|
||||||
INFOPLIST_KEY_UISupportedInterfaceOrientations_iPhone = "UIInterfaceOrientationPortrait UIInterfaceOrientationLandscapeLeft UIInterfaceOrientationLandscapeRight";
|
|
||||||
IPHONEOS_DEPLOYMENT_TARGET = 15.6;
|
|
||||||
LD_RUNPATH_SEARCH_PATHS = (
|
|
||||||
"$(inherited)",
|
|
||||||
"@executable_path/Frameworks",
|
|
||||||
);
|
|
||||||
MARKETING_VERSION = 1.0;
|
|
||||||
PRODUCT_BUNDLE_IDENTIFIER = bqlpfy.flux;
|
|
||||||
PRODUCT_NAME = "$(TARGET_NAME)";
|
|
||||||
PROVISIONING_PROFILE_SPECIFIER = "";
|
|
||||||
SWIFT_EMIT_LOC_STRINGS = YES;
|
|
||||||
SWIFT_VERSION = 5.0;
|
|
||||||
TARGETED_DEVICE_FAMILY = "1,2";
|
|
||||||
};
|
|
||||||
name = Release;
|
|
||||||
};
|
|
||||||
296FEBA12E56AAF900DC77A3 /* Debug */ = {
|
|
||||||
isa = XCBuildConfiguration;
|
|
||||||
buildSettings = {
|
|
||||||
BUNDLE_LOADER = "$(TEST_HOST)";
|
|
||||||
CODE_SIGN_STYLE = Automatic;
|
|
||||||
CURRENT_PROJECT_VERSION = 1;
|
|
||||||
GENERATE_INFOPLIST_FILE = YES;
|
|
||||||
IPHONEOS_DEPLOYMENT_TARGET = 18.5;
|
|
||||||
MARKETING_VERSION = 1.0;
|
|
||||||
PRODUCT_BUNDLE_IDENTIFIER = bqlpfy.fluxTests;
|
|
||||||
PRODUCT_NAME = "$(TARGET_NAME)";
|
|
||||||
SWIFT_EMIT_LOC_STRINGS = NO;
|
|
||||||
SWIFT_VERSION = 5.0;
|
|
||||||
TARGETED_DEVICE_FAMILY = "1,2";
|
|
||||||
TEST_HOST = "$(BUILT_PRODUCTS_DIR)/flux.app/$(BUNDLE_EXECUTABLE_FOLDER_PATH)/flux";
|
|
||||||
};
|
|
||||||
name = Debug;
|
|
||||||
};
|
|
||||||
296FEBA22E56AAF900DC77A3 /* Release */ = {
|
|
||||||
isa = XCBuildConfiguration;
|
|
||||||
buildSettings = {
|
|
||||||
BUNDLE_LOADER = "$(TEST_HOST)";
|
|
||||||
CODE_SIGN_STYLE = Automatic;
|
|
||||||
CURRENT_PROJECT_VERSION = 1;
|
|
||||||
GENERATE_INFOPLIST_FILE = YES;
|
|
||||||
IPHONEOS_DEPLOYMENT_TARGET = 18.5;
|
|
||||||
MARKETING_VERSION = 1.0;
|
|
||||||
PRODUCT_BUNDLE_IDENTIFIER = bqlpfy.fluxTests;
|
|
||||||
PRODUCT_NAME = "$(TARGET_NAME)";
|
|
||||||
SWIFT_EMIT_LOC_STRINGS = NO;
|
|
||||||
SWIFT_VERSION = 5.0;
|
|
||||||
TARGETED_DEVICE_FAMILY = "1,2";
|
|
||||||
TEST_HOST = "$(BUILT_PRODUCTS_DIR)/flux.app/$(BUNDLE_EXECUTABLE_FOLDER_PATH)/flux";
|
|
||||||
};
|
|
||||||
name = Release;
|
|
||||||
};
|
|
||||||
296FEBA42E56AAF900DC77A3 /* Debug */ = {
|
|
||||||
isa = XCBuildConfiguration;
|
|
||||||
buildSettings = {
|
|
||||||
CODE_SIGN_STYLE = Automatic;
|
|
||||||
CURRENT_PROJECT_VERSION = 1;
|
|
||||||
GENERATE_INFOPLIST_FILE = YES;
|
|
||||||
MARKETING_VERSION = 1.0;
|
|
||||||
PRODUCT_BUNDLE_IDENTIFIER = bqlpfy.fluxUITests;
|
|
||||||
PRODUCT_NAME = "$(TARGET_NAME)";
|
|
||||||
SWIFT_EMIT_LOC_STRINGS = NO;
|
|
||||||
SWIFT_VERSION = 5.0;
|
|
||||||
TARGETED_DEVICE_FAMILY = "1,2";
|
|
||||||
TEST_TARGET_NAME = flux;
|
|
||||||
};
|
|
||||||
name = Debug;
|
|
||||||
};
|
|
||||||
296FEBA52E56AAF900DC77A3 /* Release */ = {
|
|
||||||
isa = XCBuildConfiguration;
|
|
||||||
buildSettings = {
|
|
||||||
CODE_SIGN_STYLE = Automatic;
|
|
||||||
CURRENT_PROJECT_VERSION = 1;
|
|
||||||
GENERATE_INFOPLIST_FILE = YES;
|
|
||||||
MARKETING_VERSION = 1.0;
|
|
||||||
PRODUCT_BUNDLE_IDENTIFIER = bqlpfy.fluxUITests;
|
|
||||||
PRODUCT_NAME = "$(TARGET_NAME)";
|
|
||||||
SWIFT_EMIT_LOC_STRINGS = NO;
|
|
||||||
SWIFT_VERSION = 5.0;
|
|
||||||
TARGETED_DEVICE_FAMILY = "1,2";
|
|
||||||
TEST_TARGET_NAME = flux;
|
|
||||||
};
|
|
||||||
name = Release;
|
|
||||||
};
|
|
||||||
/* End XCBuildConfiguration section */
|
|
||||||
|
|
||||||
/* Begin XCConfigurationList section */
|
|
||||||
296FEB772E56AAF700DC77A3 /* Build configuration list for PBXProject "flux" */ = {
|
|
||||||
isa = XCConfigurationList;
|
|
||||||
buildConfigurations = (
|
|
||||||
296FEB9B2E56AAF900DC77A3 /* Debug */,
|
|
||||||
296FEB9C2E56AAF900DC77A3 /* Release */,
|
|
||||||
);
|
|
||||||
defaultConfigurationIsVisible = 0;
|
|
||||||
defaultConfigurationName = Release;
|
|
||||||
};
|
|
||||||
296FEB9D2E56AAF900DC77A3 /* Build configuration list for PBXNativeTarget "flux" */ = {
|
|
||||||
isa = XCConfigurationList;
|
|
||||||
buildConfigurations = (
|
|
||||||
296FEB9E2E56AAF900DC77A3 /* Debug */,
|
|
||||||
296FEB9F2E56AAF900DC77A3 /* Release */,
|
|
||||||
);
|
|
||||||
defaultConfigurationIsVisible = 0;
|
|
||||||
defaultConfigurationName = Release;
|
|
||||||
};
|
|
||||||
296FEBA02E56AAF900DC77A3 /* Build configuration list for PBXNativeTarget "fluxTests" */ = {
|
|
||||||
isa = XCConfigurationList;
|
|
||||||
buildConfigurations = (
|
|
||||||
296FEBA12E56AAF900DC77A3 /* Debug */,
|
|
||||||
296FEBA22E56AAF900DC77A3 /* Release */,
|
|
||||||
);
|
|
||||||
defaultConfigurationIsVisible = 0;
|
|
||||||
defaultConfigurationName = Release;
|
|
||||||
};
|
|
||||||
296FEBA32E56AAF900DC77A3 /* Build configuration list for PBXNativeTarget "fluxUITests" */ = {
|
|
||||||
isa = XCConfigurationList;
|
|
||||||
buildConfigurations = (
|
|
||||||
296FEBA42E56AAF900DC77A3 /* Debug */,
|
|
||||||
296FEBA52E56AAF900DC77A3 /* Release */,
|
|
||||||
);
|
|
||||||
defaultConfigurationIsVisible = 0;
|
|
||||||
defaultConfigurationName = Release;
|
|
||||||
};
|
|
||||||
/* End XCConfigurationList section */
|
|
||||||
};
|
|
||||||
rootObject = 296FEB742E56AAF700DC77A3 /* Project object */;
|
|
||||||
}
|
|
||||||
@@ -1,7 +0,0 @@
|
|||||||
<?xml version="1.0" encoding="UTF-8"?>
|
|
||||||
<Workspace
|
|
||||||
version = "1.0">
|
|
||||||
<FileRef
|
|
||||||
location = "self:">
|
|
||||||
</FileRef>
|
|
||||||
</Workspace>
|
|
||||||
@@ -1,217 +0,0 @@
|
|||||||
<?xml version="1.0" encoding="UTF-8"?>
|
|
||||||
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
|
||||||
<plist version="1.0">
|
|
||||||
<dict>
|
|
||||||
<key>top-level-items</key>
|
|
||||||
<array>
|
|
||||||
<dict>
|
|
||||||
<key>children</key>
|
|
||||||
<array>
|
|
||||||
<dict>
|
|
||||||
<key>children</key>
|
|
||||||
<array>
|
|
||||||
<dict>
|
|
||||||
<key>destination</key>
|
|
||||||
<dict>
|
|
||||||
<key>rebasable-url</key>
|
|
||||||
<dict>
|
|
||||||
<key>base</key>
|
|
||||||
<string>workspace</string>
|
|
||||||
<key>payload</key>
|
|
||||||
<dict>
|
|
||||||
<key>relative-path</key>
|
|
||||||
<string>flux/dist/assets/bg-Ck8MrDZ5.jpg</string>
|
|
||||||
</dict>
|
|
||||||
</dict>
|
|
||||||
<key>type</key>
|
|
||||||
<string>DVTDocumentLocation</string>
|
|
||||||
</dict>
|
|
||||||
<key>type</key>
|
|
||||||
<string>bookmark</string>
|
|
||||||
</dict>
|
|
||||||
<dict>
|
|
||||||
<key>destination</key>
|
|
||||||
<dict>
|
|
||||||
<key>rebasable-url</key>
|
|
||||||
<dict>
|
|
||||||
<key>base</key>
|
|
||||||
<string>workspace</string>
|
|
||||||
<key>payload</key>
|
|
||||||
<dict>
|
|
||||||
<key>relative-path</key>
|
|
||||||
<string>flux/dist/assets/favicon-DI5FVxIz.ico</string>
|
|
||||||
</dict>
|
|
||||||
</dict>
|
|
||||||
<key>type</key>
|
|
||||||
<string>DVTDocumentLocation</string>
|
|
||||||
</dict>
|
|
||||||
<key>type</key>
|
|
||||||
<string>bookmark</string>
|
|
||||||
</dict>
|
|
||||||
<dict>
|
|
||||||
<key>destination</key>
|
|
||||||
<dict>
|
|
||||||
<key>rebasable-url</key>
|
|
||||||
<dict>
|
|
||||||
<key>base</key>
|
|
||||||
<string>workspace</string>
|
|
||||||
<key>payload</key>
|
|
||||||
<dict>
|
|
||||||
<key>relative-path</key>
|
|
||||||
<string>flux/dist/assets/index-Bf4rZ0gS.css</string>
|
|
||||||
</dict>
|
|
||||||
</dict>
|
|
||||||
<key>type</key>
|
|
||||||
<string>DVTDocumentLocation</string>
|
|
||||||
</dict>
|
|
||||||
<key>type</key>
|
|
||||||
<string>bookmark</string>
|
|
||||||
</dict>
|
|
||||||
<dict>
|
|
||||||
<key>destination</key>
|
|
||||||
<dict>
|
|
||||||
<key>rebasable-url</key>
|
|
||||||
<dict>
|
|
||||||
<key>base</key>
|
|
||||||
<string>workspace</string>
|
|
||||||
<key>payload</key>
|
|
||||||
<dict>
|
|
||||||
<key>relative-path</key>
|
|
||||||
<string>flux/dist/assets/index-ByTRlFFk.js</string>
|
|
||||||
</dict>
|
|
||||||
</dict>
|
|
||||||
<key>type</key>
|
|
||||||
<string>DVTDocumentLocation</string>
|
|
||||||
</dict>
|
|
||||||
<key>type</key>
|
|
||||||
<string>bookmark</string>
|
|
||||||
</dict>
|
|
||||||
<dict>
|
|
||||||
<key>destination</key>
|
|
||||||
<dict>
|
|
||||||
<key>rebasable-url</key>
|
|
||||||
<dict>
|
|
||||||
<key>base</key>
|
|
||||||
<string>workspace</string>
|
|
||||||
<key>payload</key>
|
|
||||||
<dict>
|
|
||||||
<key>relative-path</key>
|
|
||||||
<string>flux/dist/assets/index-Drx943H4.js</string>
|
|
||||||
</dict>
|
|
||||||
</dict>
|
|
||||||
<key>type</key>
|
|
||||||
<string>DVTDocumentLocation</string>
|
|
||||||
</dict>
|
|
||||||
<key>type</key>
|
|
||||||
<string>bookmark</string>
|
|
||||||
</dict>
|
|
||||||
<dict>
|
|
||||||
<key>destination</key>
|
|
||||||
<dict>
|
|
||||||
<key>rebasable-url</key>
|
|
||||||
<dict>
|
|
||||||
<key>base</key>
|
|
||||||
<string>workspace</string>
|
|
||||||
<key>payload</key>
|
|
||||||
<dict>
|
|
||||||
<key>relative-path</key>
|
|
||||||
<string>flux/dist/assets/index-legacy-BYgRAl5I.js</string>
|
|
||||||
</dict>
|
|
||||||
</dict>
|
|
||||||
<key>type</key>
|
|
||||||
<string>DVTDocumentLocation</string>
|
|
||||||
</dict>
|
|
||||||
<key>type</key>
|
|
||||||
<string>bookmark</string>
|
|
||||||
</dict>
|
|
||||||
<dict>
|
|
||||||
<key>destination</key>
|
|
||||||
<dict>
|
|
||||||
<key>rebasable-url</key>
|
|
||||||
<dict>
|
|
||||||
<key>base</key>
|
|
||||||
<string>workspace</string>
|
|
||||||
<key>payload</key>
|
|
||||||
<dict>
|
|
||||||
<key>relative-path</key>
|
|
||||||
<string>flux/dist/assets/index-legacy-DUPUAMxs.js</string>
|
|
||||||
</dict>
|
|
||||||
</dict>
|
|
||||||
<key>type</key>
|
|
||||||
<string>DVTDocumentLocation</string>
|
|
||||||
</dict>
|
|
||||||
<key>type</key>
|
|
||||||
<string>bookmark</string>
|
|
||||||
</dict>
|
|
||||||
<dict>
|
|
||||||
<key>destination</key>
|
|
||||||
<dict>
|
|
||||||
<key>rebasable-url</key>
|
|
||||||
<dict>
|
|
||||||
<key>base</key>
|
|
||||||
<string>workspace</string>
|
|
||||||
<key>payload</key>
|
|
||||||
<dict>
|
|
||||||
<key>relative-path</key>
|
|
||||||
<string>flux/dist/assets/polyfills-legacy-DIE4kOxF.js</string>
|
|
||||||
</dict>
|
|
||||||
</dict>
|
|
||||||
<key>type</key>
|
|
||||||
<string>DVTDocumentLocation</string>
|
|
||||||
</dict>
|
|
||||||
<key>type</key>
|
|
||||||
<string>bookmark</string>
|
|
||||||
</dict>
|
|
||||||
</array>
|
|
||||||
<key>title</key>
|
|
||||||
<string>assets</string>
|
|
||||||
<key>type</key>
|
|
||||||
<string>group</string>
|
|
||||||
</dict>
|
|
||||||
<dict>
|
|
||||||
<key>destination</key>
|
|
||||||
<dict>
|
|
||||||
<key>rebasable-url</key>
|
|
||||||
<dict>
|
|
||||||
<key>base</key>
|
|
||||||
<string>workspace</string>
|
|
||||||
<key>payload</key>
|
|
||||||
<dict>
|
|
||||||
<key>relative-path</key>
|
|
||||||
<string>flux/dist/index.html</string>
|
|
||||||
</dict>
|
|
||||||
</dict>
|
|
||||||
<key>type</key>
|
|
||||||
<string>DVTDocumentLocation</string>
|
|
||||||
</dict>
|
|
||||||
<key>type</key>
|
|
||||||
<string>bookmark</string>
|
|
||||||
</dict>
|
|
||||||
<dict>
|
|
||||||
<key>destination</key>
|
|
||||||
<dict>
|
|
||||||
<key>rebasable-url</key>
|
|
||||||
<dict>
|
|
||||||
<key>base</key>
|
|
||||||
<string>workspace</string>
|
|
||||||
<key>payload</key>
|
|
||||||
<dict>
|
|
||||||
<key>relative-path</key>
|
|
||||||
<string>flux/dist/vite.svg</string>
|
|
||||||
</dict>
|
|
||||||
</dict>
|
|
||||||
<key>type</key>
|
|
||||||
<string>DVTDocumentLocation</string>
|
|
||||||
</dict>
|
|
||||||
<key>type</key>
|
|
||||||
<string>bookmark</string>
|
|
||||||
</dict>
|
|
||||||
</array>
|
|
||||||
<key>title</key>
|
|
||||||
<string>dist</string>
|
|
||||||
<key>type</key>
|
|
||||||
<string>group</string>
|
|
||||||
</dict>
|
|
||||||
</array>
|
|
||||||
</dict>
|
|
||||||
</plist>
|
|
||||||