Compare commits

..
38 changed files with 399 additions and 779 deletions
-76
View File
@@ -1,76 +0,0 @@
# This workflow will build a golang project
# For more information see: https://docs.github.com/en/actions/automating-builds-and-tests/building-and-testing-go
name: Go
on:
workflow_dispatch:
release:
types: [published]
branches: [ master ]
jobs:
build_assets:
runs-on: ubuntu-latest
steps:
- name: Set up Go 1.x
uses: actions/setup-go@v2
with:
go-version: 1.15
id: go
- name: Check out code into the Go module directory
uses: actions/checkout@v2
- name: Get dependencies
run: |
go get -v -t -d ./...
if [ -f Gopkg.toml ]; then
curl https://raw.githubusercontent.com/golang/dep/master/install.sh | sh
dep ensure
fi
- name: Build
run: |
chmod +x build.assets.sh
./build.assets.sh
- name: Upload
uses: softprops/action-gh-release@v1
if: startsWith(github.ref, 'refs/tags/')
with:
files: |
freebsd_386_client.tar.gz
freebsd_386_server.tar.gz
freebsd_amd64_client.tar.gz
freebsd_amd64_server.tar.gz
freebsd_arm_client.tar.gz
freebsd_arm_server.tar.gz
linux_386_client.tar.gz
linux_386_server.tar.gz
linux_amd64_client.tar.gz
linux_amd64_server.tar.gz
linux_arm64_client.tar.gz
linux_arm64_server.tar.gz
linux_arm_v5_client.tar.gz
linux_arm_v6_client.tar.gz
linux_arm_v7_client.tar.gz
linux_arm_v5_server.tar.gz
linux_arm_v6_server.tar.gz
linux_arm_v7_server.tar.gz
linux_mips64le_client.tar.gz
linux_mips64le_server.tar.gz
linux_mips64_client.tar.gz
linux_mips64_server.tar.gz
linux_mipsle_client.tar.gz
linux_mipsle_server.tar.gz
linux_mips_client.tar.gz
linux_mips_server.tar.gz
darwin_amd64_client.tar.gz
darwin_amd64_server.tar.gz
windows_386_client.tar.gz
windows_386_server.tar.gz
windows_amd64_client.tar.gz
windows_amd64_server.tar.gz
npc_sdk.tar.gz
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
+46
View File
@@ -115,3 +115,49 @@ jobs:
npc_syno.spk
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
build_docker:
runs-on: ubuntu-latest
steps:
- name: Check out code into the Go module directory
uses: actions/checkout@v2
- name: Set env
run: echo "RELEASE_VERSION=${GITHUB_REF#refs/*/}" >> $GITHUB_ENV
- name: Set up QEMU
uses: docker/setup-qemu-action@v1
- name: Set up Docker Buildx
uses: docker/setup-buildx-action@v1
- name: Cache Docker layers
uses: actions/cache@v2
with:
path: /tmp/.buildx-cache
key: ${{ runner.os }}-buildx-${{ github.sha }}
restore-keys: |
${{ runner.os }}-buildx-
- name: Login to DockerHub
uses: docker/login-action@v1
with:
username: ${{ secrets.DOCKERHUB_USERNAME }}
password: ${{ secrets.DOCKERHUB_TOKEN }}
- name: Build and push nps
uses: docker/build-push-action@v2
with:
context: .
file: ./Dockerfile.nps
platforms: linux/amd64,linux/arm,linux/arm64
push: true
tags: |
${{ secrets.DOCKERHUB_USERNAME }}/nps:latest
${{ secrets.DOCKERHUB_USERNAME }}/nps:${{ env.RELEASE_VERSION }}
- name: Build and push npc
uses: docker/build-push-action@v2
with:
context: .
file: ./Dockerfile.npc
platforms: linux/amd64,linux/arm,linux/arm64
push: true
tags: |
${{ secrets.DOCKERHUB_USERNAME }}/npc:latest
${{ secrets.DOCKERHUB_USERNAME }}/npc:${{ env.RELEASE_VERSION }}
+1 -1
View File
@@ -9,4 +9,4 @@ FROM scratch
COPY --from=builder /go/src/ehang.io/nps/nps /
COPY --from=builder /go/src/ehang.io/nps/web /web
VOLUME /conf
CMD ["/nps"]
CMD ["/nps", "service"]
+74 -29
View File
@@ -1,41 +1,86 @@
# NPS
![](https://img.shields.io/github/stars/ehang-io/nps.svg) ![](https://img.shields.io/github/forks/ehang-io/nps.svg)
[![Gitter](https://badges.gitter.im/cnlh-nps/community.svg)](https://gitter.im/cnlh-nps/community?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge)
![Release](https://github.com/ehang-io/nps/workflows/Release/badge.svg)
![GitHub All Releases](https://img.shields.io/github/downloads/ehang-io/nps/total)
[README](https://github.com/ehang-io/nps/blob/master/README.md)|[中文文档](https://github.com/ehang-io/nps/blob/master/README_zh.md)
# 说明
由于nps已经有一年多的时间没有更新了,存留了不少bug和未完善的功能。
此版本基于 nps 0.26.10的基础上二次开发而来。
NPS is a lightweight, high-performance, powerful **intranet penetration** proxy server, with a powerful web management terminal.
## 更新日志
![image](https://github.com/ehang-io/nps/blob/master/image/web.png?raw=true)
- 2022-10-30
***新增***:在管理面板中新增客户端时,可以配置多个黑名单IP,用于防止被肉鸡扫描端口或被恶意攻击。
***优化***:0.26.12 版本还原了注册系统功能,使用方式和以前一样。无论是否注册了系统服务,直接执行 nps 时只会读取当前目录下的配置文件。
## Feature
- Comprehensive protocol support, compatible with almost all commonly used protocols, such as tcp, udp, http(s), socks5, p2p, http proxy ...
- Full platform compatibility (linux, windows, macos, Synology, etc.), support installation as a system service simply.
- Comprehensive control, both client and server control are allowed.
- Https integration, support to convert backend proxy and web services to https, and support multiple certificates.
- Just simple configuration on web ui can complete most requirements.
- Complete information display, such as traffic, system information, real-time bandwidth, client version, etc.
- Powerful extension functions, everything is available (cache, compression, encryption, traffic limit, bandwidth limit, port reuse, etc.)
- Domain name resolution has functions such as custom headers, 404 page configuration, host modification, site protection, URL routing, and pan-resolution.
- Multi-user and user registration support on server.
**Didn't find the feature you want? It doesn't matter, click [Enter the document](https://ehang-io.github.io/nps/) to find it!**
## Quick start
### Installation
> [releases](https://github.com/ehang-io/nps/releases)
Download the corresponding system version, the server and client are separate.
### Server start
After downloading the server compressed package, unzip it, and then enter the unzipped folder.
- execute installation command
For linux、darwin ```sudo ./nps install```
For windows, run cmd as administrator and enter the installation directory ```nps.exe install```
- default ports
The default configuration file of nps use 80,443,8080,8024 ports
80 and 443 ports for host mode default ports
8080 for web management access port
8024 for net bridge port, to communicate between server and client
- start up
For linux、darwin ```sudo nps start```
For windows, run cmd as administrator and enter the program directory ```nps.exe start```
```After installation, the windows configuration file is located at C:\Program Files\nps, linux or darwin is located at /etc/nps```
**If you don't find it started successfully, you can check the log (Windows log files are located in the current running directory, linux and darwin are located in /var/log/nps.log).**
- Access server IP:web service port (default is 8080).
- Login with username and password (default is admin/123, must be modified when officially used).
- Create a client.
### Client connection
- Click the + sign in front of the client in web management and copy the startup command.
- Execute the startup command, Linux can be executed directly, Windows will replace ./npc with npc.exe and execute it with cmd.
- 2022-10-27
***新增***:在管理面板登录时开启验证码校验,开启方式:nps.conf `open_captcha=true`,感谢 [@dongFangTuring](https://github.com/dongFangTuring) 提供的PR
If you need to register to the system service, you can check [Register to the system service](https://ehang-io.github.io/nps/#/use?id=注册到系统服务)
- 2022-10-24:
***修复***:HTTP协议支持WebSocket(稳定性待测试)
- 2022-10-21:
***修复***:HTTP协议下实时统计流量,能够精准的限制住流量(上下行对等)
***优化***:删除HTTP隧道时,客户端已用流量不再清空
- 2022-10-19:
***BUG***:在TCP协议下,流量统计有问题,只有当连接断开时才会统计流量。例如,限制客户端流量20m,当传输100m的文件时,也能传输成功。
***修复***:TCP协议下实时统计流量,能够精准的限制住流量(上下行对等)
***优化***:删除TCP隧道时,客户端已用流量不再清空
![image](image/new/tcp_limit.png)
- 2022-09-14:
修改NPS工作目录为当前可执行文件目录(即配置文件和nps可执行文件放在同一目录下,直接执行nps文件即可),去除注册系统服务,启动、停止、升级等命令
### Configuration
- After the client connects, configure the corresponding penetration service in the web.
- For more advanced usage, see [Complete Documentation](https://ehang-io.github.io/nps/)
## Contribution
- If you encounter a bug, you can submit it to the dev branch directly.
- If you encounter a problem, you can feedback through the issue.
- The project is under development, and there is still a lot of room for improvement. If you can contribute code, please submit PR to the dev branch.
- If there is feedback on new features, you can feedback via issues or qq group.
+143
View File
@@ -0,0 +1,143 @@
SET VERSION=100.26.10
SET GOPROXY=direct
SET CGO_ENABLED=0
SET GOOS=linux
SET GOARCH=amd64
go build -ldflags "-s -w -extldflags -static -extldflags -static" ./cmd/npc/npc.go
tar -czvf linux_amd64_client.tar.gz npc conf/npc.conf conf/multi_account.conf
go build -ldflags "-s -w -extldflags -static -extldflags -static" ./cmd/nps/nps.go
tar -czvf linux_amd64_server.tar.gz conf/nps.conf conf/tasks.json conf/clients.json conf/hosts.json conf/server.key conf/server.pem web/views web/static nps
SET GOARCH=386
go build -ldflags "-s -w -extldflags -static -extldflags -static" ./cmd/npc/npc.go
tar -czvf linux_386_client.tar.gz npc conf/npc.conf conf/multi_account.conf
go build -ldflags "-s -w -extldflags -static -extldflags -static" ./cmd/nps/nps.go
tar -czvf linux_386_server.tar.gz conf/nps.conf conf/tasks.json conf/clients.json conf/hosts.json conf/server.key conf/server.pem web/views web/static nps
SET GOARCH=arm
SET GOARM=7
go build -ldflags "-s -w -extldflags -static -extldflags -static" ./cmd/npc/npc.go
tar -czvf linux_arm_v7_client.tar.gz npc conf/npc.conf conf/multi_account.conf
go build -ldflags "-s -w -extldflags -static -extldflags -static" ./cmd/nps/nps.go
tar -czvf linux_arm_v7_server.tar.gz conf/nps.conf conf/tasks.json conf/clients.json conf/hosts.json conf/server.key conf/server.pem web/views web/static nps
SET GOARM=6
go build -ldflags "-s -w -extldflags -static -extldflags -static" ./cmd/npc/npc.go
tar -czvf linux_arm_v6_client.tar.gz npc conf/npc.conf conf/multi_account.conf
go build -ldflags "-s -w -extldflags -static -extldflags -static" ./cmd/nps/nps.go
tar -czvf linux_arm_v6_server.tar.gz conf/nps.conf conf/tasks.json conf/clients.json conf/hosts.json conf/server.key conf/server.pem web/views web/static nps
SET GOARM=5
go build -ldflags "-s -w -extldflags -static -extldflags -static" ./cmd/npc/npc.go
tar -czvf linux_arm_v5_client.tar.gz npc conf/npc.conf conf/multi_account.conf
go build -ldflags "-s -w -extldflags -static -extldflags -static" ./cmd/nps/nps.go
tar -czvf linux_arm_v5_server.tar.gz conf/nps.conf conf/tasks.json conf/clients.json conf/hosts.json conf/server.key conf/server.pem web/views web/static nps
SET GOARCH=arm64
go build -ldflags "-s -w -extldflags -static -extldflags -static" ./cmd/npc/npc.go
tar -czvf linux_arm64_client.tar.gz npc conf/npc.conf conf/multi_account.conf
go build -ldflags "-s -w -extldflags -static -extldflags -static" ./cmd/nps/nps.go
tar -czvf linux_arm64_server.tar.gz conf/nps.conf conf/tasks.json conf/clients.json conf/hosts.json conf/server.key conf/server.pem web/views web/static nps
SET GOARCH=mips64
go build -ldflags "-s -w -extldflags -static -extldflags -static" ./cmd/npc/npc.go
tar -czvf linux_mips64_client.tar.gz npc conf/npc.conf conf/multi_account.conf
go build -ldflags "-s -w -extldflags -static -extldflags -static" ./cmd/nps/nps.go
tar -czvf linux_mips64_server.tar.gz conf/nps.conf conf/tasks.json conf/clients.json conf/hosts.json conf/server.key conf/server.pem web/views web/static nps
SET GOARCH=mips64le
go build -ldflags "-s -w -extldflags -static -extldflags -static" ./cmd/npc/npc.go
tar -czvf linux_mips64le_client.tar.gz npc conf/npc.conf conf/multi_account.conf
go build -ldflags "-s -w -extldflags -static -extldflags -static" ./cmd/nps/nps.go
tar -czvf linux_mips64le_server.tar.gz conf/nps.conf conf/tasks.json conf/clients.json conf/hosts.json conf/server.key conf/server.pem web/views web/static nps
SET GOARCH=mipsle
go build -ldflags "-s -w -extldflags -static -extldflags -static" ./cmd/npc/npc.go
tar -czvf linux_mipsle_client.tar.gz npc conf/npc.conf conf/multi_account.conf
go build -ldflags "-s -w -extldflags -static -extldflags -static" ./cmd/nps/nps.go
tar -czvf linux_mipsle_server.tar.gz conf/nps.conf conf/tasks.json conf/clients.json conf/hosts.json conf/server.key conf/server.pem web/views web/static nps
SET GOARCH=mips
go build -ldflags "-s -w -extldflags -static -extldflags -static" ./cmd/npc/npc.go
tar -czvf linux_mips_client.tar.gz npc conf/npc.conf conf/multi_account.conf
go build -ldflags "-s -w -extldflags -static -extldflags -static" ./cmd/nps/nps.go
tar -czvf linux_mips_server.tar.gz conf/nps.conf conf/tasks.json conf/clients.json conf/hosts.json conf/server.key conf/server.pem web/views web/static nps
SET GOOS=freebsd
SET GOARCH=386
go build -ldflags "-s -w -extldflags -static -extldflags -static" ./cmd/npc/npc.go
tar -czvf freebsd_386_client.tar.gz npc conf/npc.conf conf/multi_account.conf
go build -ldflags "-s -w -extldflags -static -extldflags -static" ./cmd/nps/nps.go
tar -czvf freebsd_386_server.tar.gz conf/nps.conf conf/tasks.json conf/clients.json conf/hosts.json conf/server.key conf/server.pem web/views web/static nps
SET GOARCH=amd64
go build -ldflags "-s -w -extldflags -static -extldflags -static" ./cmd/npc/npc.go
tar -czvf freebsd_amd64_client.tar.gz npc conf/npc.conf conf/multi_account.conf
go build -ldflags "-s -w -extldflags -static -extldflags -static" ./cmd/nps/nps.go
tar -czvf freebsd_amd64_server.tar.gz conf/nps.conf conf/tasks.json conf/clients.json conf/hosts.json conf/server.key conf/server.pem web/views web/static nps
SET GOARCH=arm
go build -ldflags "-s -w -extldflags -static -extldflags -static" ./cmd/npc/npc.go
tar -czvf freebsd_arm_client.tar.gz npc conf/npc.conf conf/multi_account.conf
go build -ldflags "-s -w -extldflags -static -extldflags -static" ./cmd/nps/nps.go
tar -czvf freebsd_arm_server.tar.gz conf/nps.conf conf/tasks.json conf/clients.json conf/hosts.json conf/server.key conf/server.pem web/views web/static nps
SET GOOS=windows
SET GOARCH=386
go build -ldflags "-s -w -extldflags -static -extldflags -static" ./cmd/npc/npc.go
tar -czvf windows_386_client.tar.gz npc.exe conf/npc.conf conf/multi_account.conf
go build -ldflags "-s -w -extldflags -static -extldflags -static" ./cmd/nps/nps.go
tar -czvf windows_386_server.tar.gz conf/nps.conf conf/tasks.json conf/clients.json conf/hosts.json conf/server.key conf/server.pem web/views web/static nps.exe
SET GOARCH=amd64
go build -ldflags "-s -w -extldflags -static -extldflags -static" ./cmd/npc/npc.go
tar -czvf windows_amd64_client.tar.gz npc.exe conf/npc.conf conf/multi_account.conf
go build -ldflags "-s -w -extldflags -static -extldflags -static" ./cmd/nps/nps.go
tar -czvf windows_amd64_server.tar.gz conf/nps.conf conf/tasks.json conf/clients.json conf/hosts.json conf/server.key conf/server.pem web/views web/static nps.exe
SET GOOS=darwin
SET GOARCH=amd64
go build -ldflags "-s -w -extldflags -static -extldflags -static" ./cmd/npc/npc.go
tar -czvf darwin_amd64_client.tar.gz npc conf/npc.conf conf/multi_account.conf
go build -ldflags "-s -w -extldflags -static -extldflags -static" ./cmd/nps/nps.go
tar -czvf darwin_amd64_server.tar.gz conf/nps.conf conf/tasks.json conf/clients.json conf/hosts.json conf/server.key conf/server.pem web/views web/static nps
SET GOARCH=arm64
go build -ldflags "-s -w -extldflags -static -extldflags -static" ./cmd/npc/npc.go
tar -czvf darwin_arm64_client.tar.gz npc conf/npc.conf conf/multi_account.conf
go build -ldflags "-s -w -extldflags -static -extldflags -static" ./cmd/nps/nps.go
tar -czvf darwin_arm64_server.tar.gz conf/nps.conf conf/tasks.json conf/clients.json conf/hosts.json conf/server.key conf/server.pem web/views web/static nps
+1 -1
View File
@@ -1,5 +1,5 @@
#/bash/sh
export VERSION=0.26.12
export VERSION=100.26.10
export GOPROXY=direct
sudo apt-get update
+1 -1
View File
@@ -214,7 +214,7 @@ func (s *TRPClient) handleChan(src net.Conn) {
src.Close()
} else {
logs.Trace("new %s connection with the goal of %s, remote address:%s", lk.ConnType, lk.Host, lk.RemoteAddr)
conn.CopyWaitGroup(src, targetConn, lk.Crypt, lk.Compress, nil, nil, false, nil, nil)
conn.CopyWaitGroup(src, targetConn, lk.Crypt, lk.Compress, nil, nil, false, nil)
}
}
+2 -2
View File
@@ -161,7 +161,7 @@ func handleSecret(localTcpConn net.Conn, config *config.CommonConfig, l *config.
logs.Error("Local connection server failed ", err.Error())
return
}
conn.CopyWaitGroup(remoteConn.Conn, localTcpConn, false, false, nil, nil, false, nil, nil)
conn.CopyWaitGroup(remoteConn.Conn, localTcpConn, false, false, nil, nil, false, nil)
}
func handleP2PVisitor(localTcpConn net.Conn, config *config.CommonConfig, l *config.LocalServer) {
@@ -178,7 +178,7 @@ func handleP2PVisitor(localTcpConn net.Conn, config *config.CommonConfig, l *con
udpConnStatus = false
return
} else {
conn.CopyWaitGroup(target, localTcpConn, false, config.Client.Cnf.Compress, nil, nil, false, nil, nil)
conn.CopyWaitGroup(target, localTcpConn, false, config.Client.Cnf.Compress, nil, nil, false, nil)
}
}
+1 -5
View File
@@ -1,7 +1,6 @@
package main
import (
"ehang.io/nps/lib/daemon"
"flag"
"log"
"os"
@@ -21,6 +20,7 @@ import (
"ehang.io/nps/lib/common"
"ehang.io/nps/lib/crypt"
"ehang.io/nps/lib/daemon"
"github.com/astaxie/beego"
"github.com/astaxie/beego/logs"
@@ -33,7 +33,6 @@ var (
)
func main() {
flag.Parse()
// init log
if *ver {
@@ -43,7 +42,6 @@ func main() {
if err := beego.LoadAppConfig("ini", filepath.Join(common.GetRunPath(), "conf", "nps.conf")); err != nil {
log.Fatalln("load config file error", err.Error())
}
common.InitPProfFromFile()
if level = beego.AppConfig.String("log_level"); level == "" {
level = "7"
@@ -91,7 +89,6 @@ func main() {
wg.Wait()
return
}
if len(os.Args) > 1 && os.Args[1] != "service" {
switch os.Args[1] {
case "reload":
@@ -154,7 +151,6 @@ func main() {
return
}
}
_ = s.Run()
}
+12 -22
View File
@@ -22,11 +22,11 @@ public_vkey=123
#Traffic data persistence interval(minute)
#Ignorance means no persistence
flow_store_interval=1
#flow_store_interval=1
# log level LevelEmergency->0 LevelAlert->1 LevelCritical->2 LevelError->3 LevelWarning->4 LevelNotice->5 LevelInformational->6 LevelDebug->7
log_level=6
log_path=nps.log
log_level=7
#log_path=nps.log
#Whether to restrict IP access, true or false or ignore
#ip_limit=true
@@ -39,7 +39,7 @@ log_path=nps.log
web_host=a.o.com
web_username=admin
web_password=123
web_port = 8081
web_port = 8080
web_ip=0.0.0.0
web_base_url=
web_open_ssl=false
@@ -60,22 +60,15 @@ allow_user_login=false
allow_user_register=false
allow_user_change_username=false
#extension
#流量限制
allow_flow_limit=true
#带宽限制
allow_rate_limit=true
#客户端最大隧道数限制
allow_tunnel_num_limit=true
allow_local_proxy=false
#客户端最大连接数
allow_connection_num_limit=true
#每个隧道监听不同的服务端端口
allow_multi_ip=true
system_info_display=true
#获取用户真实ip
http_add_origin_header=true
#extension
allow_flow_limit=false
allow_rate_limit=false
allow_tunnel_num_limit=false
allow_local_proxy=false
allow_connection_num_limit=false
allow_multi_ip=false
system_info_display=false
#cache
http_cache=false
@@ -90,6 +83,3 @@ http_add_origin_header=false
#client disconnect timeout
disconnect_timeout=60
#管理面板开启验证码校验
open_captcha=true
+1 -1
View File
@@ -1,6 +1,6 @@
![logo](logo.svg)
# NPS <small>0.26.10</small>
# NPS <small>100.26.10</small>
> 一款轻量级、高性能、功能强大的内网穿透代理服务器
+1 -1
View File
@@ -2,7 +2,7 @@
```
命令行模式启动客户端
从v0.26.10开始,此函数会阻塞,直到客户端退出返回,请自行管理是否重连
从v100.26.10开始,此函数会阻塞,直到客户端退出返回,请自行管理是否重连
p0->连接地址
p1->vkey
p2->连接类型(tcp or udp)
+5 -5
View File
@@ -53,8 +53,8 @@ npc-update.exe update
server_addr=1.1.1.1:8024
conn_type=tcp
vkey=123
username=111
password=222
basic_username=111
basic_password=222
compress=true
crypt=true
rate_limit=10000
@@ -68,8 +68,8 @@ max_conn=10
server_addr | 服务端ip/域名:port
conn_type | 与服务端通信模式(tcp或kcp)
vkey|服务端配置文件中的密钥(非web)
username|socks5或http(s)密码保护用户名(可忽略)
password|socks5或http(s)密码保护密码(可忽略)
basic_username|socks5或http(s)密码保护用户名(可忽略)
basic_password|socks5或http(s)密码保护密码(可忽略)
compress|是否压缩传输(true或false或忽略)
crypt|是否加密传输(true或false或忽略)
rate_limit|速度限制,可忽略
@@ -159,7 +159,7 @@ multi_account=multi_account.conf
---|---
mode | socks5
server_port | 在服务端的代理端口
multi_account | socks5多账号配置文件(可选),配置后使用basic_username和basic_password无法通过认证
multi_account | socks5多账号配置文件(可选),配置后使用basic_username和basic_password无法通过认证 <br> multi_account.conf要与可执行文件npc同一目录,或者npc.conf里面写相对路径,conf/multi_account.conf
#### 私密代理模式
```ini
+1 -1
View File
@@ -3,7 +3,7 @@
xmlns:android="http://schemas.android.com/apk/res/android"
package="org.nps.client"
android:versionCode="1"
android:versionName="0.26.10">
android:versionName="100.26.10">
<application android:label="Npc" android:debuggable="true">
<activity android:name="org.golang.app.GoNativeActivity"
Binary file not shown.

Before

Width:  |  Height:  |  Size: 61 KiB

+2 -7
View File
@@ -11,12 +11,8 @@ import (
//windows system, select the C:\Program Files\nps as config directory if exist, or select ./
func GetRunPath() string {
var path string
if len(os.Args) <= 1 {
return "./"
} else {
if path = GetInstallPath(); !FileExists(path) {
return GetAppPath()
}
if path = GetInstallPath(); !FileExists(path) {
return GetAppPath()
}
return path
}
@@ -29,7 +25,6 @@ func GetInstallPath() string {
} else {
path = "/etc/nps"
}
return path
}
-22
View File
@@ -7,7 +7,6 @@ import (
"encoding/binary"
"errors"
"fmt"
"github.com/astaxie/beego/logs"
"html/template"
"io"
"io/ioutil"
@@ -15,7 +14,6 @@ import (
"net/http"
"os"
"regexp"
"sort"
"strconv"
"strings"
"sync"
@@ -277,26 +275,6 @@ func GetPortByAddr(addr string) int {
return p
}
func in(target string, str_array []string) bool {
sort.Strings(str_array)
index := sort.SearchStrings(str_array, target)
if index < len(str_array) && str_array[index] == target {
return true
}
return false
}
// 判断访问地址是否在黑名单内
func IsBlackIp(ipPort, vkey string, blackIpList []string) bool {
ip := GetIpByAddr(ipPort)
if in(ip, blackIpList) {
logs.Error("IP地址[" + ip + "]在隧道[" + vkey + "]黑名单列表内")
return true
}
return false
}
func CopyBuffer(dst io.Writer, src io.Reader, label ...string) (written int64, err error) {
buf := CopyBuff.Get()
defer CopyBuff.Put(buf)
+2 -3
View File
@@ -373,8 +373,7 @@ func SetUdpSession(sess *kcp.UDPSession) {
}
//conn1 mux conn
func CopyWaitGroup(conn1, conn2 net.Conn, crypt bool, snappy bool, rate *rate.Rate,
flow *file.Flow, isServer bool, rb []byte, task *file.Tunnel) {
func CopyWaitGroup(conn1, conn2 net.Conn, crypt bool, snappy bool, rate *rate.Rate, flow *file.Flow, isServer bool, rb []byte) {
//var in, out int64
//var wg sync.WaitGroup
connHandle := GetConn(conn1, crypt, snappy, rate, isServer)
@@ -397,7 +396,7 @@ func CopyWaitGroup(conn1, conn2 net.Conn, crypt bool, snappy bool, rate *rate.Ra
//}
wg := new(sync.WaitGroup)
wg.Add(1)
err := goroutine.CopyConnsPool.Invoke(goroutine.NewConns(connHandle, conn2, flow, wg, task))
err := goroutine.CopyConnsPool.Invoke(goroutine.NewConns(connHandle, conn2, flow, wg))
wg.Wait()
if err != nil {
logs.Error(err)
-2
View File
@@ -51,7 +51,6 @@ type Client struct {
ConfigConnAllow bool //is allow connected by config file
MaxTunnelNum int
Version string
BlackIpList []string
sync.RWMutex
}
@@ -139,7 +138,6 @@ type Tunnel struct {
Remark string
TargetAddr string
NoStore bool
IsHttp bool
LocalPath string
StripPre string
Target *Target
+16 -105
View File
@@ -3,125 +3,40 @@ package goroutine
import (
"ehang.io/nps/lib/common"
"ehang.io/nps/lib/file"
"github.com/astaxie/beego/logs"
"github.com/panjf2000/ants/v2"
"io"
"net"
"strings"
"sync"
)
type connGroup struct {
src io.ReadWriteCloser
dst io.ReadWriteCloser
wg *sync.WaitGroup
n *int64
flow *file.Flow
task *file.Tunnel
remote string
src io.ReadWriteCloser
dst io.ReadWriteCloser
wg *sync.WaitGroup
n *int64
}
//func newConnGroup(dst, src io.ReadWriteCloser, wg *sync.WaitGroup, n *int64) connGroup {
// return connGroup{
// src: src,
// dst: dst,
// wg: wg,
// n: n,
// }
//}
func newConnGroup(dst, src io.ReadWriteCloser, wg *sync.WaitGroup, n *int64, flow *file.Flow, task *file.Tunnel, remote string) connGroup {
func newConnGroup(dst, src io.ReadWriteCloser, wg *sync.WaitGroup, n *int64) connGroup {
return connGroup{
src: src,
dst: dst,
wg: wg,
n: n,
flow: flow,
task: task,
remote: remote,
src: src,
dst: dst,
wg: wg,
n: n,
}
}
func CopyBuffer(dst io.Writer, src io.Reader, flow *file.Flow, task *file.Tunnel, remote string) (err error) {
buf := common.CopyBuff.Get()
defer common.CopyBuff.Put(buf)
for {
if len(buf) <= 0 {
break
}
nr, er := src.Read(buf)
//if len(pr)>0 && pr[0] && nr > 50 {
// logs.Warn(string(buf[:50]))
//}
if task != nil {
task.IsHttp = false
firstLine := string(buf[0:nr])
if len(firstLine) > 3 {
method := firstLine[0:3]
if method != "" && (method == "HTT" || method == "GET" || method == "POS" || method == "HEA" || method == "PUT" || method == "DEL") {
if method != "HTT" {
heads := strings.Split(firstLine, "\r\n")
if len(heads) >= 2 {
logs.Info("HTTP Request method %s, %s, remote address %s, target %s", heads[0], heads[1], remote, task.Target.TargetStr)
}
}
task.IsHttp = true
}
}
}
if nr > 0 {
nw, ew := dst.Write(buf[0:nr])
if nw > 0 {
//written += int64(nw)
if flow != nil {
flow.Add(int64(nw), int64(nw))
// <<20 = 1024 * 1024
if flow.FlowLimit > 0 && (flow.FlowLimit<<20) < (flow.ExportFlow+flow.InletFlow) {
logs.Info("流量已经超出.........")
break
}
}
}
if ew != nil {
err = ew
break
}
if nr != nw {
err = io.ErrShortWrite
break
}
}
if er != nil {
err = er
break
}
}
//return written, err
return err
}
func copyConnGroup(group interface{}) {
//logs.Info("copyConnGroup.........")
cg, ok := group.(connGroup)
if !ok {
return
}
var err error
err = CopyBuffer(cg.dst, cg.src, cg.flow, cg.task, cg.remote)
*cg.n, err = common.CopyBuffer(cg.dst, cg.src)
if err != nil {
cg.src.Close()
cg.dst.Close()
//logs.Warn("close npc by copy from nps", err, c.connId)
}
//if conns.flow != nil {
// conns.flow.Add(in, out)
//}
cg.wg.Done()
}
@@ -130,34 +45,30 @@ type Conns struct {
conn2 net.Conn // outside connection
flow *file.Flow
wg *sync.WaitGroup
task *file.Tunnel
}
func NewConns(c1 io.ReadWriteCloser, c2 net.Conn, flow *file.Flow, wg *sync.WaitGroup, task *file.Tunnel) Conns {
func NewConns(c1 io.ReadWriteCloser, c2 net.Conn, flow *file.Flow, wg *sync.WaitGroup) Conns {
return Conns{
conn1: c1,
conn2: c2,
flow: flow,
wg: wg,
task: task,
}
}
func copyConns(group interface{}) {
//logs.Info("copyConns.........")
conns := group.(Conns)
wg := new(sync.WaitGroup)
wg.Add(2)
var in, out int64
remoteAddr := conns.conn2.RemoteAddr().String()
_ = connCopyPool.Invoke(newConnGroup(conns.conn1, conns.conn2, wg, &in, conns.flow, conns.task, remoteAddr))
_ = connCopyPool.Invoke(newConnGroup(conns.conn1, conns.conn2, wg, &in))
// outside to mux : incoming
_ = connCopyPool.Invoke(newConnGroup(conns.conn2, conns.conn1, wg, &out, conns.flow, conns.task, remoteAddr))
_ = connCopyPool.Invoke(newConnGroup(conns.conn2, conns.conn1, wg, &out))
// mux to outside : outgoing
wg.Wait()
//if conns.flow != nil {
// conns.flow.Add(in, out)
//}
if conns.flow != nil {
conns.flow.Add(in, out)
}
conns.wg.Done()
}
-1
View File
@@ -239,7 +239,6 @@ func InstallNpc() {
func InstallNps() string {
path := common.GetInstallPath()
log.Println("install path:" + path)
if common.FileExists(path) {
MkidrDirAll(path, "web/static", "web/views")
} else {
+2 -2
View File
@@ -1,8 +1,8 @@
package version
const VERSION = "0.26.12"
const VERSION = "100.26.10"
// Compulsory minimum version, Minimum downward compatibility to this version
func GetVersion() string {
return "0.26.0"
return "100.26.0"
}
+2 -20
View File
@@ -4,7 +4,6 @@ import (
"errors"
"net"
"net/http"
"sort"
"sync"
"ehang.io/nps/bridge"
@@ -84,25 +83,8 @@ func (s *BaseServer) CheckFlowAndConnNum(client *file.Client) error {
return nil
}
func in(target string, str_array []string) bool {
sort.Strings(str_array)
index := sort.SearchStrings(str_array, target)
if index < len(str_array) && str_array[index] == target {
return true
}
return false
}
//create a new connection and start bytes copying
func (s *BaseServer) DealClient(c *conn.Conn, client *file.Client, addr string,
rb []byte, tp string, f func(), flow *file.Flow, localProxy bool, task *file.Tunnel) error {
// 判断访问地址是否在黑名单内
if common.IsBlackIp(c.RemoteAddr().String(), client.VerifyKey, client.BlackIpList) {
c.Close()
return nil
}
func (s *BaseServer) DealClient(c *conn.Conn, client *file.Client, addr string, rb []byte, tp string, f func(), flow *file.Flow, localProxy bool) error {
link := conn.NewLink(tp, addr, client.Cnf.Crypt, client.Cnf.Compress, c.Conn.RemoteAddr().String(), localProxy)
if target, err := s.bridge.SendLinkInfo(client.Id, link, s.task); err != nil {
logs.Warn("get connection from client id %d error %s", client.Id, err.Error())
@@ -112,7 +94,7 @@ func (s *BaseServer) DealClient(c *conn.Conn, client *file.Client, addr string,
if f != nil {
f()
}
conn.CopyWaitGroup(target, c.Conn, link.Crypt, link.Compress, client.Rate, flow, true, rb, task)
conn.CopyWaitGroup(target, c.Conn, link.Crypt, link.Compress, client.Rate, flow, true, rb)
}
return nil
}
+42 -53
View File
@@ -3,22 +3,23 @@ package proxy
import (
"bufio"
"crypto/tls"
"ehang.io/nps/bridge"
"ehang.io/nps/lib/cache"
"ehang.io/nps/lib/common"
"ehang.io/nps/lib/conn"
"ehang.io/nps/lib/file"
"ehang.io/nps/lib/goroutine"
"ehang.io/nps/server/connection"
"github.com/astaxie/beego/logs"
"io"
"net"
"net/http"
"net/http/httputil"
"os"
"path/filepath"
"strconv"
"strings"
"sync"
"ehang.io/nps/bridge"
"ehang.io/nps/lib/cache"
"ehang.io/nps/lib/common"
"ehang.io/nps/lib/conn"
"ehang.io/nps/lib/file"
"ehang.io/nps/server/connection"
"github.com/astaxie/beego/logs"
)
type httpServer struct {
@@ -101,24 +102,16 @@ func (s *httpServer) Close() error {
}
func (s *httpServer) handleTunneling(w http.ResponseWriter, r *http.Request) {
if r.Header.Get("Upgrade") != "" {
rProxy := NewHttpReverseProxy(s)
rProxy.ServeHTTP(w, r)
} else {
hijacker, ok := w.(http.Hijacker)
if !ok {
http.Error(w, "Hijacking not supported", http.StatusInternalServerError)
return
}
c, _, err := hijacker.Hijack()
if err != nil {
http.Error(w, err.Error(), http.StatusServiceUnavailable)
}
s.handleHttp(conn.NewConn(c), r)
hijacker, ok := w.(http.Hijacker)
if !ok {
http.Error(w, "Hijacking not supported", http.StatusInternalServerError)
return
}
c, _, err := hijacker.Hijack()
if err != nil {
http.Error(w, err.Error(), http.StatusServiceUnavailable)
}
s.handleHttp(conn.NewConn(c), r)
}
func (s *httpServer) handleHttp(c *conn.Conn, r *http.Request) {
@@ -165,13 +158,6 @@ reset:
logs.Warn(err.Error())
return
}
// 判断访问地址是否在黑名单内
if common.IsBlackIp(c.RemoteAddr().String(), host.Client.VerifyKey, host.Client.BlackIpList) {
c.Close()
return
}
lk = conn.NewLink("http", targetAddr, host.Client.Cnf.Crypt, host.Client.Cnf.Compress, r.RemoteAddr, host.Target.LocalProxy)
if target, err = s.bridge.SendLinkInfo(host.Client.Id, lk, nil); err != nil {
logs.Notice("connect to target %s error %s", lk.Host, err)
@@ -190,23 +176,28 @@ reset:
c.Close()
}
}()
err1 := goroutine.CopyBuffer(c, connClient, host.Client.Flow, nil, "")
if err1 != nil {
return
}
resp, err := http.ReadResponse(bufio.NewReader(connClient), r)
if err != nil || resp == nil || r == nil {
// if there got broken pipe, http.ReadResponse will get a nil
//break
return
} else {
lenConn := conn.NewLenConn(c)
if err := resp.Write(lenConn); err != nil {
logs.Error(err)
//break
for {
if resp, err := http.ReadResponse(bufio.NewReader(connClient), r); err != nil || resp == nil || r == nil {
// if there got broken pipe, http.ReadResponse will get a nil
return
} else {
//if the cache is start and the response is in the extension,store the response to the cache list
if s.useCache && r.URL != nil && strings.Contains(r.URL.Path, ".") {
b, err := httputil.DumpResponse(resp, true)
if err != nil {
return
}
c.Write(b)
host.Flow.Add(0, int64(len(b)))
s.cache.Add(filepath.Join(host.Host, r.URL.Path), b)
} else {
lenConn := conn.NewLenConn(c)
if err := resp.Write(lenConn); err != nil {
logs.Error(err)
return
}
host.Flow.Add(0, int64(lenConn.Len))
}
}
}
}()
@@ -220,7 +211,7 @@ reset:
break
}
logs.Trace("%s request, method %s, host %s, url %s, remote address %s, return cache", r.URL.Scheme, r.Method, r.Host, r.URL.Path, c.RemoteAddr().String())
host.Client.Flow.Add(int64(n), int64(n))
host.Flow.Add(0, int64(n))
//if return cache and does not create a new conn with client and Connection is not set or close, close the connection.
if strings.ToLower(r.Header.Get("Connection")) == "close" || strings.ToLower(r.Header.Get("Connection")) == "" {
break
@@ -234,17 +225,15 @@ reset:
logs.Trace("%s request, method %s, host %s, url %s, remote address %s, target %s", r.URL.Scheme, r.Method, r.Host, r.URL.Path, c.RemoteAddr().String(), lk.Host)
//write
lenConn = conn.NewLenConn(connClient)
//lenConn = conn.LenConn
if err := r.Write(lenConn); err != nil {
logs.Error(err)
break
}
host.Client.Flow.Add(int64(lenConn.Len), int64(lenConn.Len))
host.Flow.Add(int64(lenConn.Len), 0)
readReq:
//read req from connection
r, err = http.ReadRequest(bufio.NewReader(c))
if err != nil {
if r, err = http.ReadRequest(bufio.NewReader(c)); err != nil {
break
}
r.URL.Scheme = scheme
+1 -1
View File
@@ -125,7 +125,7 @@ func (https *HttpsServer) handleHttps(c net.Conn) {
logs.Warn(err.Error())
}
logs.Trace("new https connection,clientId %d,host %s,remote address %s", host.Client.Id, r.Host, c.RemoteAddr().String())
https.DealClient(conn.NewConn(c), host.Client, targetAddr, rb, common.CONN_TCP, nil, host.Flow, host.Target.LocalProxy, nil)
https.DealClient(conn.NewConn(c), host.Client, targetAddr, rb, common.CONN_TCP, nil, host.Flow, host.Target.LocalProxy)
}
type HttpsListener struct {
+1 -1
View File
@@ -142,7 +142,7 @@ func (s *Sock5ModeServer) doConnect(c net.Conn, command uint8) {
}
s.DealClient(conn.NewConn(c), s.task.Client, addr, nil, ltype, func() {
s.sendReply(c, succeeded)
}, s.task.Flow, s.task.Target.LocalProxy, nil)
}, s.task.Flow, s.task.Target.LocalProxy)
return
}
+2 -5
View File
@@ -103,13 +103,11 @@ func ProcessTunnel(c *conn.Conn, s *TunnelModeServer) error {
logs.Warn("tcp port %d ,client id %d,task id %d connect error %s", s.task.Port, s.task.Client.Id, s.task.Id, err.Error())
return err
}
return s.DealClient(c, s.task.Client, targetAddr, nil, common.CONN_TCP, nil, s.task.Client.Flow, s.task.Target.LocalProxy, s.task)
return s.DealClient(c, s.task.Client, targetAddr, nil, common.CONN_TCP, nil, s.task.Flow, s.task.Target.LocalProxy)
}
//http proxy
func ProcessHttp(c *conn.Conn, s *TunnelModeServer) error {
_, addr, rb, err, r := c.GetHost()
if err != nil {
c.Close()
@@ -123,6 +121,5 @@ func ProcessHttp(c *conn.Conn, s *TunnelModeServer) error {
if err := s.auth(r, c, s.task.Client.Cnf.U, s.task.Client.Cnf.P); err != nil {
return err
}
return s.DealClient(c, s.task.Client, addr, rb, common.CONN_TCP, nil, s.task.Client.Flow, s.task.Target.LocalProxy, nil)
return s.DealClient(c, s.task.Client, addr, rb, common.CONN_TCP, nil, s.task.Flow, s.task.Target.LocalProxy)
}
+1 -2
View File
@@ -1,4 +1,3 @@
//go:build !windows
// +build !windows
package proxy
@@ -16,7 +15,7 @@ func HandleTrans(c *conn.Conn, s *TunnelModeServer) error {
if addr, err := getAddress(c.Conn); err != nil {
return err
} else {
return s.DealClient(c, s.task.Client, addr, nil, common.CONN_TCP, nil, s.task.Flow, s.task.Target.LocalProxy, nil)
return s.DealClient(c, s.task.Client, addr, nil, common.CONN_TCP, nil, s.task.Flow, s.task.Target.LocalProxy)
}
}
+6 -28
View File
@@ -46,12 +46,6 @@ func (s *UdpModeServer) Start() error {
}
continue
}
// 判断访问地址是否在黑名单内
if common.IsBlackIp(addr.String(), s.task.Client.VerifyKey, s.task.Client.BlackIpList) {
break
}
logs.Trace("New udp connection,client %d,remote address %s", s.task.Client.Id, addr)
go s.process(addr, buf[:n])
}
@@ -62,12 +56,8 @@ func (s *UdpModeServer) process(addr *net.UDPAddr, data []byte) {
if v, ok := s.addrMap.Load(addr.String()); ok {
clientConn, ok := v.(io.ReadWriteCloser)
if ok {
_, err := clientConn.Write(data)
if err != nil {
logs.Warn(err)
return
}
s.task.Client.Flow.Add(int64(len(data)), int64(len(data)))
clientConn.Write(data)
s.task.Flow.Add(int64(len(data)), 0)
}
} else {
if err := s.CheckFlowAndConnNum(s.task.Client); err != nil {
@@ -83,16 +73,12 @@ func (s *UdpModeServer) process(addr *net.UDPAddr, data []byte) {
s.addrMap.Store(addr.String(), target)
defer target.Close()
_, err := target.Write(data)
if err != nil {
logs.Warn(err)
return
}
target.Write(data)
buf := common.BufPoolUdp.Get().([]byte)
defer common.BufPoolUdp.Put(buf)
s.task.Client.Flow.Add(int64(len(data)), int64(len(data)))
s.task.Flow.Add(int64(len(data)), 0)
for {
clientConn.SetReadDeadline(time.Now().Add(time.Minute * 10))
if n, err := target.Read(buf); err != nil {
@@ -100,16 +86,8 @@ func (s *UdpModeServer) process(addr *net.UDPAddr, data []byte) {
logs.Warn(err)
return
} else {
_, err := s.listener.WriteTo(buf[:n], addr)
if err != nil {
logs.Warn(err)
return
}
s.task.Client.Flow.Add(int64(n), int64(n))
}
if err := s.CheckFlowAndConnNum(s.task.Client); err != nil {
logs.Warn("client id %d, task id %d,error %s, when udp connection", s.task.Client.Id, s.task.Id, err.Error())
return
s.listener.WriteTo(buf[:n], addr)
s.task.Flow.Add(0, int64(n))
}
}
}
-270
View File
@@ -1,270 +0,0 @@
package proxy
import (
"context"
"ehang.io/nps/lib/common"
"ehang.io/nps/lib/conn"
"ehang.io/nps/lib/file"
"ehang.io/nps/lib/goroutine"
"errors"
"github.com/astaxie/beego/logs"
"io"
"net"
"net/http"
"net/http/httputil"
"strings"
"sync"
"time"
)
type HTTPError struct {
error
HTTPCode int
}
type HttpReverseProxy struct {
proxy *ReverseProxy
responseHeaderTimeout time.Duration
}
type flowConn struct {
io.ReadWriteCloser
fakeAddr net.Addr
host *file.Host
flowIn int64
flowOut int64
once sync.Once
}
func (rp *HttpReverseProxy) ServeHTTP(rw http.ResponseWriter, req *http.Request) {
var (
host *file.Host
targetAddr string
err error
)
if host, err = file.GetDb().GetInfoByHost(req.Host, req); err != nil {
rw.WriteHeader(http.StatusNotFound)
rw.Write([]byte(req.Host + " not found"))
return
}
if host.Client.Cnf.U != "" && host.Client.Cnf.P != "" && !common.CheckAuth(req, host.Client.Cnf.U, host.Client.Cnf.P) {
rw.WriteHeader(http.StatusUnauthorized)
rw.Write([]byte("Unauthorized"))
return
}
if targetAddr, err = host.Target.GetRandomTarget(); err != nil {
rw.WriteHeader(http.StatusBadGateway)
rw.Write([]byte("502 Bad Gateway"))
return
}
host.Client.CutConn()
req = req.WithContext(context.WithValue(req.Context(), "host", host))
req = req.WithContext(context.WithValue(req.Context(), "target", targetAddr))
req = req.WithContext(context.WithValue(req.Context(), "req", req))
rp.proxy.ServeHTTP(rw, req, host)
defer host.Client.AddConn()
}
func (c *flowConn) Read(p []byte) (n int, err error) {
n, err = c.ReadWriteCloser.Read(p)
return n, err
}
func (c *flowConn) Write(p []byte) (n int, err error) {
n, err = c.ReadWriteCloser.Write(p)
return n, err
}
func (c *flowConn) Close() error {
//c.once.Do(func() { c.host.Flow.Add(c.flowIn, c.flowOut) })
return c.ReadWriteCloser.Close()
}
func (c *flowConn) LocalAddr() net.Addr { return c.fakeAddr }
func (c *flowConn) RemoteAddr() net.Addr { return c.fakeAddr }
func (*flowConn) SetDeadline(t time.Time) error { return nil }
func (*flowConn) SetReadDeadline(t time.Time) error { return nil }
func (*flowConn) SetWriteDeadline(t time.Time) error { return nil }
func NewHttpReverseProxy(s *httpServer) *HttpReverseProxy {
rp := &HttpReverseProxy{
responseHeaderTimeout: 30 * time.Second,
}
local, _ := net.ResolveTCPAddr("tcp", "127.0.0.1")
proxy := NewReverseProxy(&httputil.ReverseProxy{
Director: func(r *http.Request) {
host := r.Context().Value("host").(*file.Host)
common.ChangeHostAndHeader(r, host.HostChange, host.HeaderChange, "", false)
},
Transport: &http.Transport{
ResponseHeaderTimeout: rp.responseHeaderTimeout,
DisableKeepAlives: true,
DialContext: func(ctx context.Context, network, addr string) (net.Conn, error) {
var (
host *file.Host
target net.Conn
err error
connClient io.ReadWriteCloser
targetAddr string
lk *conn.Link
)
r := ctx.Value("req").(*http.Request)
host = ctx.Value("host").(*file.Host)
targetAddr = ctx.Value("target").(string)
lk = conn.NewLink("http", targetAddr, host.Client.Cnf.Crypt, host.Client.Cnf.Compress, r.RemoteAddr, host.Target.LocalProxy)
if target, err = s.bridge.SendLinkInfo(host.Client.Id, lk, nil); err != nil {
logs.Notice("connect to target %s error %s", lk.Host, err)
return nil, NewHTTPError(http.StatusBadGateway, "Cannot connect to the server")
}
connClient = conn.GetConn(target, lk.Crypt, lk.Compress, host.Client.Rate, true)
return &flowConn{
ReadWriteCloser: connClient,
fakeAddr: local,
host: host,
}, nil
},
},
ErrorHandler: func(rw http.ResponseWriter, req *http.Request, err error) {
logs.Warn("do http proxy request error: %v", err)
rw.WriteHeader(http.StatusNotFound)
},
})
proxy.WebSocketDialContext = func(ctx context.Context, network, addr string) (net.Conn, error) {
var (
host *file.Host
target net.Conn
err error
connClient io.ReadWriteCloser
targetAddr string
lk *conn.Link
)
r := ctx.Value("req").(*http.Request)
host = ctx.Value("host").(*file.Host)
targetAddr = ctx.Value("target").(string)
lk = conn.NewLink("tcp", targetAddr, host.Client.Cnf.Crypt, host.Client.Cnf.Compress, r.RemoteAddr, host.Target.LocalProxy)
if target, err = s.bridge.SendLinkInfo(host.Client.Id, lk, nil); err != nil {
logs.Notice("connect to target %s error %s", lk.Host, err)
return nil, NewHTTPError(http.StatusBadGateway, "Cannot connect to the target")
}
connClient = conn.GetConn(target, lk.Crypt, lk.Compress, host.Client.Rate, true)
return &flowConn{
ReadWriteCloser: connClient,
fakeAddr: local,
host: host,
}, nil
}
rp.proxy = proxy
return rp
}
func NewHTTPError(code int, errmsg string) error {
return &HTTPError{
error: errors.New(errmsg),
HTTPCode: code,
}
}
type ReverseProxy struct {
*httputil.ReverseProxy
WebSocketDialContext func(ctx context.Context, network, addr string) (net.Conn, error)
}
func IsWebsocketRequest(req *http.Request) bool {
containsHeader := func(name, value string) bool {
items := strings.Split(req.Header.Get(name), ",")
for _, item := range items {
if value == strings.ToLower(strings.TrimSpace(item)) {
return true
}
}
return false
}
return containsHeader("Connection", "upgrade") && containsHeader("Upgrade", "websocket")
}
func NewReverseProxy(orp *httputil.ReverseProxy) *ReverseProxy {
rp := &ReverseProxy{
ReverseProxy: orp,
WebSocketDialContext: nil,
}
rp.ErrorHandler = rp.errHandler
return rp
}
func (p *ReverseProxy) errHandler(rw http.ResponseWriter, r *http.Request, e error) {
if e == io.EOF {
rw.WriteHeader(521)
//rw.Write(getWaitingPageContent())
} else {
if httperr, ok := e.(*HTTPError); ok {
rw.WriteHeader(httperr.HTTPCode)
} else {
rw.WriteHeader(http.StatusNotFound)
}
rw.Write([]byte("error: " + e.Error()))
}
}
func (p *ReverseProxy) ServeHTTP(rw http.ResponseWriter, req *http.Request, host *file.Host) {
if IsWebsocketRequest(req) {
p.serveWebSocket(rw, req, host)
}
}
func (p *ReverseProxy) serveWebSocket(rw http.ResponseWriter, req *http.Request, host *file.Host) {
if p.WebSocketDialContext == nil {
rw.WriteHeader(500)
return
}
targetConn, err := p.WebSocketDialContext(req.Context(), "tcp", "")
if err != nil {
rw.WriteHeader(501)
return
}
defer targetConn.Close()
p.Director(req)
hijacker, ok := rw.(http.Hijacker)
if !ok {
rw.WriteHeader(500)
return
}
conn, _, errHijack := hijacker.Hijack()
if errHijack != nil {
rw.WriteHeader(500)
return
}
defer conn.Close()
req.Write(targetConn)
Join(conn, targetConn, host)
}
func Join(c1 io.ReadWriteCloser, c2 io.ReadWriteCloser, host *file.Host) (inCount int64, outCount int64) {
var wait sync.WaitGroup
pipe := func(to io.ReadWriteCloser, from io.ReadWriteCloser, count *int64) {
defer to.Close()
defer from.Close()
defer wait.Done()
goroutine.CopyBuffer(to, from, host.Client.Flow, nil, "")
//*count, _ = io.Copy(to, from)
}
wait.Add(2)
go pipe(c1, c2, &inCount)
go pipe(c2, c1, &outCount)
wait.Wait()
return
}
+19 -32
View File
@@ -71,7 +71,7 @@ func DealBridgeTask() {
logs.Trace("New secret connection, addr", s.Conn.Conn.RemoteAddr())
if t := file.GetDb().GetTaskByMd5Password(s.Password); t != nil {
if t.Status {
go proxy.NewBaseServer(Bridge, t).DealClient(s.Conn, t.Client, t.Target.TargetStr, nil, common.CONN_TCP, nil, t.Flow, t.Target.LocalProxy, nil)
go proxy.NewBaseServer(Bridge, t).DealClient(s.Conn, t.Client, t.Target.TargetStr, nil, common.CONN_TCP, nil, t.Flow, t.Target.LocalProxy)
} else {
s.Conn.Close()
logs.Trace("This key %s cannot be processed,status is close", s.Password)
@@ -282,8 +282,6 @@ func GetClientList(start, length int, search, sort, order string, clientId int)
}
func dealClientData() {
//logs.Info("dealClientData.........")
file.GetDb().JsonDb.Clients.Range(func(key, value interface{}) bool {
v := value.(*file.Client)
if vv, ok := Bridge.Client.Load(v.Id); ok {
@@ -292,34 +290,24 @@ func dealClientData() {
} else {
v.IsConnect = false
}
//v.Flow.InletFlow = 0
//v.Flow.ExportFlow = 0
//if len(file.GetDb().JsonDb.Hosts) == 0 {
//
//}
//var inflow int64 = 0
//var outflow int64 = 0
//file.GetDb().JsonDb.Hosts.Range(func(key, value interface{}) bool {
// h := value.(*file.Host)
// if h.Client.Id == v.Id {
// inflow += h.Flow.InletFlow
// outflow += h.Flow.ExportFlow
// }
// return true
//})
//file.GetDb().JsonDb.Tasks.Range(func(key, value interface{}) bool {
// t := value.(*file.Tunnel)
// if t.Client.Id == v.Id {
// inflow += t.Flow.InletFlow
// outflow += t.Flow.ExportFlow
// }
// return true
//})
//
//if inflow >0 || outflow >0{
// v.Flow.InletFlow = inflow
// v.Flow.ExportFlow = outflow
//}
v.Flow.InletFlow = 0
v.Flow.ExportFlow = 0
file.GetDb().JsonDb.Hosts.Range(func(key, value interface{}) bool {
h := value.(*file.Host)
if h.Client.Id == v.Id {
v.Flow.InletFlow += h.Flow.InletFlow
v.Flow.ExportFlow += h.Flow.ExportFlow
}
return true
})
file.GetDb().JsonDb.Tasks.Range(func(key, value interface{}) bool {
t := value.(*file.Tunnel)
if t.Client.Id == v.Id {
v.Flow.InletFlow += t.Flow.InletFlow
v.Flow.ExportFlow += t.Flow.ExportFlow
}
return true
})
return true
})
return
@@ -459,7 +447,6 @@ func GetDashboardData() map[string]interface{} {
return data
}
// 实例化流量数据到文件
func flowSession(m time.Duration) {
ticker := time.NewTicker(m)
defer ticker.Stop()
+14 -11
View File
@@ -20,7 +20,7 @@ type BaseController struct {
actionName string
}
//初始化参数
// 初始化参数
func (s *BaseController) Prepare() {
s.Data["web_base_url"] = beego.AppConfig.String("web_base_url")
controllerName, actionName := s.GetControllerAndAction()
@@ -33,6 +33,9 @@ func (s *BaseController) Prepare() {
timestamp := s.GetIntNoErr("timestamp")
configKey := beego.AppConfig.String("auth_key")
timeNowUnix := time.Now().Unix()
if configKey == "" {
configKey = crypt.GetRandomString(128)
}
if !(md5Key != "" && (math.Abs(float64(timeNowUnix-int64(timestamp))) <= 20) && (crypt.Md5(configKey+strconv.Itoa(timestamp)) == md5Key)) {
if s.GetSession("auth") != true {
s.Redirect(beego.AppConfig.String("web_base_url")+"/login/index", 302)
@@ -62,7 +65,7 @@ func (s *BaseController) Prepare() {
s.Data["allow_user_change_username"], _ = beego.AppConfig.Bool("allow_user_change_username")
}
//加载模板
// 加载模板
func (s *BaseController) display(tpl ...string) {
s.Data["web_base_url"] = beego.AppConfig.String("web_base_url")
var tplname string
@@ -86,19 +89,19 @@ func (s *BaseController) display(tpl ...string) {
s.TplName = tplname
}
//错误
// 错误
func (s *BaseController) error() {
s.Data["web_base_url"] = beego.AppConfig.String("web_base_url")
s.Layout = "public/layout.html"
s.TplName = "public/error.html"
}
//getEscapeString
// getEscapeString
func (s *BaseController) getEscapeString(key string) string {
return html.EscapeString(s.GetString(key))
}
//去掉没有err返回值的int
// 去掉没有err返回值的int
func (s *BaseController) GetIntNoErr(key string, def ...int) int {
strv := s.Ctx.Input.Query(key)
if len(strv) == 0 && len(def) > 0 {
@@ -108,7 +111,7 @@ func (s *BaseController) GetIntNoErr(key string, def ...int) int {
return val
}
//获取去掉错误的bool值
// 获取去掉错误的bool值
func (s *BaseController) GetBoolNoErr(key string, def ...bool) bool {
strv := s.Ctx.Input.Query(key)
if len(strv) == 0 && len(def) > 0 {
@@ -118,21 +121,21 @@ func (s *BaseController) GetBoolNoErr(key string, def ...bool) bool {
return val
}
//ajax正确返回
// ajax正确返回
func (s *BaseController) AjaxOk(str string) {
s.Data["json"] = ajax(str, 1)
s.ServeJSON()
s.StopRun()
}
//ajax错误返回
// ajax错误返回
func (s *BaseController) AjaxErr(str string) {
s.Data["json"] = ajax(str, 0)
s.ServeJSON()
s.StopRun()
}
//组装ajax
// 组装ajax
func ajax(str string, status int) map[string]interface{} {
json := make(map[string]interface{})
json["status"] = status
@@ -140,7 +143,7 @@ func ajax(str string, status int) map[string]interface{} {
return json
}
//ajax table返回
// ajax table返回
func (s *BaseController) AjaxTable(list interface{}, cnt int, recordsTotal int, kwargs map[string]interface{}) {
json := make(map[string]interface{})
json["rows"] = list
@@ -157,7 +160,7 @@ func (s *BaseController) AjaxTable(list interface{}, cnt int, recordsTotal int,
s.StopRun()
}
//ajax table参数
// ajax table参数
func (s *BaseController) GetAjaxParams() (start, limit int) {
return s.GetIntNoErr("offset"), s.GetIntNoErr("limit")
}
-22
View File
@@ -6,7 +6,6 @@ import (
"ehang.io/nps/lib/rate"
"ehang.io/nps/server"
"github.com/astaxie/beego"
"strings"
)
type ClientController struct {
@@ -66,7 +65,6 @@ func (s *ClientController) Add() {
InletFlow: 0,
FlowLimit: int64(s.GetIntNoErr("flow_limit")),
},
BlackIpList: RemoveRepeatedElement(strings.Split(s.getEscapeString("blackiplist"), "\r\n")),
}
if err := file.GetDb().NewClient(t); err != nil {
s.AjaxErr(err.Error())
@@ -98,7 +96,6 @@ func (s *ClientController) Edit() {
s.error()
} else {
s.Data["c"] = c
s.Data["BlackIpList"] = strings.Join(c.BlackIpList, "\r\n")
}
s.SetInfo("edit client")
s.display()
@@ -146,31 +143,12 @@ func (s *ClientController) Edit() {
c.Rate = rate.NewRate(int64(2 << 23))
c.Rate.Start()
}
c.BlackIpList = RemoveRepeatedElement(strings.Split(s.getEscapeString("blackiplist"), "\r\n"))
file.GetDb().JsonDb.StoreClientsToJsonFile()
}
s.AjaxOk("save success")
}
}
func RemoveRepeatedElement(arr []string) (newArr []string) {
newArr = make([]string, 0)
for i := 0; i < len(arr); i++ {
repeat := false
for j := i + 1; j < len(arr); j++ {
if arr[i] == arr[j] {
repeat = true
break
}
}
if !repeat {
newArr = append(newArr, arr[i])
}
}
return
}
//更改状态
func (s *ClientController) ChangeStatus() {
id := s.GetIntNoErr("id")
-27
View File
@@ -149,10 +149,6 @@
<zh-CN>Basic 认证用户名</zh-CN>
<en-US>Basic authentication username</en-US>
</lang>
<lang id="word-ishttp">
<zh-CN>是否为HTTP</zh-CN>
<en-US>Is HTTP</en-US>
</lang>
<lang id="word-bridgingmode">
<zh-CN>桥接模式</zh-CN>
<en-US>Bridging mode</en-US>
@@ -695,29 +691,6 @@
<en-US>Empty means to be unrestricted</en-US>
</lang>
<lang id="word-blackiplist">
<zh-CN>IP黑名单(防暴力破解)</zh-CN>
<en-US>IP Black List</en-US>
</lang>
<lang id="info-suchasblackiplist">
<zh-CN>例如&#10;10.1.50.203&#10;10.1.50.202</zh-CN>
<en-US>such as&#10;10.1.50.203&#10;10.1.50.202</en-US>
</lang>
<lang id="info-descblackiplist">
<zh-CN>一行一个,IPV4,不支持范围匹配</zh-CN>
<en-US>IPV4</en-US>
</lang>
<lang id="word-blackip">
<zh-CN>IP黑名单</zh-CN>
<en-US>IP Black List</en-US>
</lang>
<confirm>
<lang id="delete">
<zh-CN>你确定你要删除它吗?</zh-CN>
-9
View File
@@ -106,15 +106,6 @@
</select>
</div>
</div>
<div class="form-group" id="black_ip_list">
<label class="control-label font-bold" langtag="word-blackiplist"></label>
<div class="col-sm-10">
<textarea class="form-control" rows="4" type="text" name="blackiplist" placeholder="" langtag="info-suchasblackiplist">{{.BlackIpList}}</textarea>
<span class="help-block m-b-none" langtag="info-descblackiplist"></span>
</div>
</div>
<div class="hr-line-dashed"></div>
<div class="form-group">
<div class="col-sm-4 col-sm-offset-2">
-9
View File
@@ -115,15 +115,6 @@
</select>
</div>
</div>
<div class="form-group" id="black_ip_list">
<label class="control-label font-bold" langtag="word-blackiplist"></label>
<div class="col-sm-10">
<textarea class="form-control" rows="4" type="text" name="blackiplist" placeholder="" langtag="info-suchasblackiplist">{{.BlackIpList}}</textarea>
<span class="help-block m-b-none" langtag="info-descblackiplist"></span>
</div>
</div>
<div class="hr-line-dashed"></div>
<div class="form-group">
<div class="col-sm-4 col-sm-offset-2">
-1
View File
@@ -70,7 +70,6 @@
+ '<b langtag="word-crypt"></b>: <span langtag="word-' + row.Cnf.Crypt + '"></span>&emsp;'
+ '<b langtag="word-compress"></b>: <span langtag="word-' + row.Cnf.Compress + '"></span>&emsp;'
+ '<b langtag="word-connectbyconfig"></b>: <span langtag="word-' + row.ConfigConnAllow + '"></span>&emsp;<br/><br/>'
+ '<b langtag="word-blackip"></b>: ' + row.BlackIpList + '&emsp;<br/><br/>'
+ '<b langtag="word-commandclient"></b>: ' + "<code>./npc{{.win}} -server={{.ip}}:{{.p}} -vkey=" + row.VerifyKey + " -type=" +{{.bridgeType}} +"</code>"
},
//表格的列
-1
View File
@@ -74,7 +74,6 @@
+ '<b langtag="word-compress"></b>: ' + row.Client.Cnf.Compress + '&emsp;'
+ '<b langtag="word-basicusername"></b>: ' + row.Client.Cnf.U + '&emsp;'
+ '<b langtag="word-basicpassword"></b>: ' + row.Client.Cnf.P + '&emsp;'
+ '<b langtag="word-ishttp"></b>: ' + row.IsHttp + '&emsp;'
if (row.Mode == "p2p") {
return tmp + "<br/><br>"
+ '<b langtag="word-commandaccessp2p"></b>: ' + "<code>./npc{{.win}} -server={{.ip}}:{{.p}} -vkey=" + row.Client.VerifyKey