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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
package main
|
| 2 |
+
|
| 3 |
+
import (
|
| 4 |
+
"encoding/base64"
|
| 5 |
+
"encoding/binary"
|
| 6 |
+
"encoding/json"
|
| 7 |
+
"fmt"
|
| 8 |
+
"io"
|
| 9 |
+
"log"
|
| 10 |
+
"net"
|
| 11 |
+
"net/http"
|
| 12 |
+
"os"
|
| 13 |
+
"os/exec"
|
| 14 |
+
"runtime"
|
| 15 |
+
"strconv"
|
| 16 |
+
"strings"
|
| 17 |
+
"sync"
|
| 18 |
+
"time"
|
| 19 |
+
)
|
| 20 |
+
|
| 21 |
+
type Config struct {
|
| 22 |
+
UUID string
|
| 23 |
+
XPath string
|
| 24 |
+
SubPath string
|
| 25 |
+
Domain string
|
| 26 |
+
Name string
|
| 27 |
+
Port string
|
| 28 |
+
LogLevel string
|
| 29 |
+
ChunkSize int
|
| 30 |
+
NezhaServer string
|
| 31 |
+
NezhaPort string
|
| 32 |
+
NezhaKey string
|
| 33 |
+
AutoAccess bool
|
| 34 |
+
}
|
| 35 |
+
|
| 36 |
+
type VlessSession struct {
|
| 37 |
+
UUID string
|
| 38 |
+
Remote net.Conn
|
| 39 |
+
ResponseHeader []byte
|
| 40 |
+
mu sync.Mutex
|
| 41 |
+
}
|
| 42 |
+
|
| 43 |
+
type CloudflareSpeedMeta struct {
|
| 44 |
+
Country string `json:"country"`
|
| 45 |
+
AsOrganization string `json:"asOrganization"`
|
| 46 |
+
}
|
| 47 |
+
|
| 48 |
+
var (
|
| 49 |
+
config *Config
|
| 50 |
+
sessions = make(map[string]*VlessSession)
|
| 51 |
+
sessionsMu sync.RWMutex
|
| 52 |
+
logger *log.Logger
|
| 53 |
+
)
|
| 54 |
+
|
| 55 |
+
func init() {
|
| 56 |
+
logger = log.New(os.Stdout, "[Server] ", log.LstdFlags)
|
| 57 |
+
}
|
| 58 |
+
|
| 59 |
+
// load config
|
| 60 |
+
func loadConfig() *Config {
|
| 61 |
+
uuid := getEnv("UUID", "a2056d0d-c98e-4aeb-9aab-37f64edd5710") // UUID,哪吒v1依赖UUID
|
| 62 |
+
nezhaServer := getEnv("NEZHA_SERVER", "") // 哪吒v1形式:nezha.xxx.com:8008 哪吒v0形式:nezha.xxx.com
|
| 63 |
+
nezhaPort := getEnv("NEZHA_PORT", "") // 哪吒v1请留空,哪吒v0的agent端口
|
| 64 |
+
nezhaKey := getEnv("NEZHA_KEY", "") // 哪吒v1的NZ_CLIENT_SECRET或哪吒v0的agent密钥
|
| 65 |
+
subPath := getEnv("SUB_PATH", "sub") // 节点订阅token
|
| 66 |
+
name := getEnv("NAME", "Xhttp") // 节点名称
|
| 67 |
+
port := getEnv("PORT", "3000") // 监听端口
|
| 68 |
+
domain := getEnv("DOMAIN", "sap-ryanrsacks-jp.2.2.a.a.f.f.0.7.0.0.6.2.ip6.arpa") // 服务域名
|
| 69 |
+
|
| 70 |
+
xpath := getEnv("XPATH", uuid[:8])
|
| 71 |
+
autoAccess := false
|
| 72 |
+
if getEnv("AUTO_ACCESS", "false") == "true" { // 是否开启自动保活,true开启,false关闭,默认关闭
|
| 73 |
+
autoAccess = true
|
| 74 |
+
}
|
| 75 |
+
|
| 76 |
+
return &Config{
|
| 77 |
+
UUID: uuid,
|
| 78 |
+
XPath: xpath,
|
| 79 |
+
NezhaServer: nezhaServer,
|
| 80 |
+
NezhaPort: nezhaPort,
|
| 81 |
+
NezhaKey: nezhaKey,
|
| 82 |
+
SubPath: subPath,
|
| 83 |
+
Domain: domain,
|
| 84 |
+
Name: name,
|
| 85 |
+
Port: port,
|
| 86 |
+
ChunkSize: 32768,
|
| 87 |
+
AutoAccess: autoAccess,
|
| 88 |
+
LogLevel: getEnv("LOG_LEVEL", "none"), // 日志等级 none, info, debug, warn, error
|
| 89 |
+
}
|
| 90 |
+
}
|
| 91 |
+
|
| 92 |
+
func getEnv(key, defaultValue string) string {
|
| 93 |
+
if value := os.Getenv(key); value != "" {
|
| 94 |
+
return value
|
| 95 |
+
}
|
| 96 |
+
return defaultValue
|
| 97 |
+
}
|
| 98 |
+
|
| 99 |
+
// Log function
|
| 100 |
+
func logf(level, format string, args ...interface{}) {
|
| 101 |
+
levels := map[string]int{"none": -1, "debug": 0, "info": 1, "warn": 2, "error": 3}
|
| 102 |
+
|
| 103 |
+
configLevel := levels[config.LogLevel]
|
| 104 |
+
messageLevel := levels[level]
|
| 105 |
+
|
| 106 |
+
// if logevl is none,disable log
|
| 107 |
+
if configLevel == -1 {
|
| 108 |
+
return
|
| 109 |
+
}
|
| 110 |
+
|
| 111 |
+
if messageLevel >= configLevel {
|
| 112 |
+
msg := fmt.Sprintf(format, args...)
|
| 113 |
+
|
| 114 |
+
if strings.Contains(msg, "Failed to connect") {
|
| 115 |
+
if level == "error" {
|
| 116 |
+
level = "warn"
|
| 117 |
+
}
|
| 118 |
+
}
|
| 119 |
+
|
| 120 |
+
if strings.Contains(msg, "Processing POST data") ||
|
| 121 |
+
strings.Contains(msg, "Client read error: read tcp") ||
|
| 122 |
+
strings.Contains(msg, "Client write error: write tcp") ||
|
| 123 |
+
strings.Contains(msg, "Remote read error") ||
|
| 124 |
+
strings.Contains(msg, "Remote write error") ||
|
| 125 |
+
strings.Contains(msg, "connection reset by peer") ||
|
| 126 |
+
strings.Contains(msg, "use of closed network connection") {
|
| 127 |
+
return
|
| 128 |
+
}
|
| 129 |
+
|
| 130 |
+
logger.Printf("[%s] %s", strings.ToUpper(level), msg)
|
| 131 |
+
}
|
| 132 |
+
}
|
| 133 |
+
|
| 134 |
+
// Analy UUID
|
| 135 |
+
func parseUUID(uuidStr string) ([16]byte, error) {
|
| 136 |
+
var uuid [16]byte
|
| 137 |
+
uuidStr = strings.ReplaceAll(uuidStr, "-", "")
|
| 138 |
+
if len(uuidStr) != 32 {
|
| 139 |
+
return uuid, fmt.Errorf("invalid UUID length")
|
| 140 |
+
}
|
| 141 |
+
|
| 142 |
+
for i := 0; i < 16; i++ {
|
| 143 |
+
b, err := strconv.ParseUint(uuidStr[i*2:i*2+2], 16, 8)
|
| 144 |
+
if err != nil {
|
| 145 |
+
return uuid, err
|
| 146 |
+
}
|
| 147 |
+
uuid[i] = byte(b)
|
| 148 |
+
}
|
| 149 |
+
return uuid, nil
|
| 150 |
+
}
|
| 151 |
+
|
| 152 |
+
// Analy VLS Header
|
| 153 |
+
func parseSimpleVlessHeader(data []byte) (string, uint16, []byte, error) {
|
| 154 |
+
if len(data) < 18 {
|
| 155 |
+
return "", 0, nil, fmt.Errorf("data too short")
|
| 156 |
+
}
|
| 157 |
+
|
| 158 |
+
// Verify UUID
|
| 159 |
+
configUUID, _ := parseUUID(config.UUID)
|
| 160 |
+
receivedUUID := data[1:17]
|
| 161 |
+
|
| 162 |
+
for i := 0; i < 16; i++ {
|
| 163 |
+
if receivedUUID[i] != configUUID[i] {
|
| 164 |
+
return "", 0, nil, fmt.Errorf("UUID mismatch")
|
| 165 |
+
}
|
| 166 |
+
}
|
| 167 |
+
|
| 168 |
+
pbLen := data[17]
|
| 169 |
+
offset := 18 + int(pbLen)
|
| 170 |
+
|
| 171 |
+
if len(data) < offset+4 {
|
| 172 |
+
return "", 0, nil, fmt.Errorf("insufficient data for command/port/atype")
|
| 173 |
+
}
|
| 174 |
+
|
| 175 |
+
cmd := data[offset]
|
| 176 |
+
if cmd != 1 {
|
| 177 |
+
return "", 0, nil, fmt.Errorf("unsupported command: %d", cmd)
|
| 178 |
+
}
|
| 179 |
+
|
| 180 |
+
port := binary.BigEndian.Uint16(data[offset+1 : offset+3])
|
| 181 |
+
atype := data[offset+3]
|
| 182 |
+
offset += 4
|
| 183 |
+
|
| 184 |
+
var hostname string
|
| 185 |
+
switch atype {
|
| 186 |
+
case 1: // IPv4
|
| 187 |
+
if len(data) < offset+4 {
|
| 188 |
+
return "", 0, nil, fmt.Errorf("insufficient data for IPv4")
|
| 189 |
+
}
|
| 190 |
+
hostname = fmt.Sprintf("%d.%d.%d.%d", data[offset], data[offset+1], data[offset+2], data[offset+3])
|
| 191 |
+
offset += 4
|
| 192 |
+
case 2: // domain
|
| 193 |
+
if len(data) < offset+1 {
|
| 194 |
+
return "", 0, nil, fmt.Errorf("insufficient data for domain length")
|
| 195 |
+
}
|
| 196 |
+
domainLen := int(data[offset])
|
| 197 |
+
offset++
|
| 198 |
+
if len(data) < offset+domainLen {
|
| 199 |
+
return "", 0, nil, fmt.Errorf("insufficient data for domain")
|
| 200 |
+
}
|
| 201 |
+
hostname = string(data[offset : offset+domainLen])
|
| 202 |
+
offset += domainLen
|
| 203 |
+
case 3: // IPv6
|
| 204 |
+
if len(data) < offset+16 {
|
| 205 |
+
return "", 0, nil, fmt.Errorf("insufficient data for IPv6")
|
| 206 |
+
}
|
| 207 |
+
|
| 208 |
+
hostname = "::1"
|
| 209 |
+
offset += 16
|
| 210 |
+
default:
|
| 211 |
+
return "", 0, nil, fmt.Errorf("unsupported address type: %d", atype)
|
| 212 |
+
}
|
| 213 |
+
|
| 214 |
+
remaining := data[offset:]
|
| 215 |
+
return hostname, port, remaining, nil
|
| 216 |
+
}
|
| 217 |
+
|
| 218 |
+
// Handling VLS Connections - Using Hijack
|
| 219 |
+
func handleVlessConnection(w http.ResponseWriter, r *http.Request, uuid string) {
|
| 220 |
+
|
| 221 |
+
hijacker, ok := w.(http.Hijacker)
|
| 222 |
+
if !ok {
|
| 223 |
+
http.Error(w, "Hijacking not supported", http.StatusInternalServerError)
|
| 224 |
+
return
|
| 225 |
+
}
|
| 226 |
+
|
| 227 |
+
conn, _, err := hijacker.Hijack()
|
| 228 |
+
if err != nil {
|
| 229 |
+
logf("error", "Failed to hijack connection: %v", err)
|
| 230 |
+
return
|
| 231 |
+
}
|
| 232 |
+
defer conn.Close()
|
| 233 |
+
|
| 234 |
+
logf("info", "Hijacked connection for session: %s", uuid)
|
| 235 |
+
|
| 236 |
+
// send HTTP
|
| 237 |
+
httpResp := "HTTP/1.1 200 OK\r\n"
|
| 238 |
+
httpResp += "Content-Type: application/octet-stream\r\n"
|
| 239 |
+
httpResp += "Connection: close\r\n"
|
| 240 |
+
httpResp += "\r\n"
|
| 241 |
+
|
| 242 |
+
if _, err := conn.Write([]byte(httpResp)); err != nil {
|
| 243 |
+
logf("error", "Failed to write HTTP response: %v", err)
|
| 244 |
+
return
|
| 245 |
+
}
|
| 246 |
+
|
| 247 |
+
sessionsMu.Lock()
|
| 248 |
+
session, exists := sessions[uuid]
|
| 249 |
+
if !exists {
|
| 250 |
+
session = &VlessSession{UUID: uuid}
|
| 251 |
+
sessions[uuid] = session
|
| 252 |
+
logf("debug", "Created session placeholder for: %s", uuid)
|
| 253 |
+
}
|
| 254 |
+
sessionsMu.Unlock()
|
| 255 |
+
|
| 256 |
+
const maxWaitTime = 30 * time.Second
|
| 257 |
+
const checkInterval = 50 * time.Millisecond
|
| 258 |
+
maxChecks := int(maxWaitTime / checkInterval)
|
| 259 |
+
|
| 260 |
+
for i := 0; i < maxChecks; i++ {
|
| 261 |
+
session.mu.Lock()
|
| 262 |
+
if session.Remote != nil && session.ResponseHeader != nil {
|
| 263 |
+
session.mu.Unlock()
|
| 264 |
+
logf("debug", "Session initialized after %v for: %s", time.Duration(i)*checkInterval, uuid)
|
| 265 |
+
break
|
| 266 |
+
}
|
| 267 |
+
session.mu.Unlock()
|
| 268 |
+
|
| 269 |
+
if i > 0 && i%(int(5*time.Second/checkInterval)) == 0 {
|
| 270 |
+
logf("debug", "Still waiting for session initialization: %s (%.1fs)", uuid, float64(i)*checkInterval.Seconds())
|
| 271 |
+
}
|
| 272 |
+
|
| 273 |
+
time.Sleep(checkInterval)
|
| 274 |
+
}
|
| 275 |
+
|
| 276 |
+
session.mu.Lock()
|
| 277 |
+
if session.Remote == nil {
|
| 278 |
+
session.mu.Unlock()
|
| 279 |
+
logf("error", "Session not initialized within timeout: %s", uuid)
|
| 280 |
+
return
|
| 281 |
+
}
|
| 282 |
+
|
| 283 |
+
if _, err := conn.Write(session.ResponseHeader); err != nil {
|
| 284 |
+
session.mu.Unlock()
|
| 285 |
+
logf("error", "Failed to write VLS response: %v", err)
|
| 286 |
+
return
|
| 287 |
+
}
|
| 288 |
+
|
| 289 |
+
remote := session.Remote
|
| 290 |
+
session.mu.Unlock()
|
| 291 |
+
|
| 292 |
+
logf("info", "Starting data relay for session: %s", uuid)
|
| 293 |
+
|
| 294 |
+
// Enable bidirectional data forwarding
|
| 295 |
+
done := make(chan bool, 2)
|
| 296 |
+
|
| 297 |
+
// From remote to client
|
| 298 |
+
go func() {
|
| 299 |
+
defer func() { done <- true }()
|
| 300 |
+
buffer := make([]byte, config.ChunkSize)
|
| 301 |
+
for {
|
| 302 |
+
n, err := remote.Read(buffer)
|
| 303 |
+
if err != nil {
|
| 304 |
+
if err != io.EOF && !strings.Contains(err.Error(), "connection reset") {
|
| 305 |
+
logf("warn", "Remote connection error for %s", uuid)
|
| 306 |
+
}
|
| 307 |
+
break
|
| 308 |
+
}
|
| 309 |
+
if n > 0 {
|
| 310 |
+
if _, err := conn.Write(buffer[:n]); err != nil {
|
| 311 |
+
if !strings.Contains(err.Error(), "connection reset") && !strings.Contains(err.Error(), "closed network connection") {
|
| 312 |
+
logf("warn", "Client write error for %s", uuid)
|
| 313 |
+
}
|
| 314 |
+
break
|
| 315 |
+
}
|
| 316 |
+
}
|
| 317 |
+
}
|
| 318 |
+
}()
|
| 319 |
+
|
| 320 |
+
// From the client to the remote
|
| 321 |
+
go func() {
|
| 322 |
+
defer func() { done <- true }()
|
| 323 |
+
buffer := make([]byte, config.ChunkSize)
|
| 324 |
+
for {
|
| 325 |
+
n, err := conn.Read(buffer)
|
| 326 |
+
if err != nil {
|
| 327 |
+
if err != io.EOF && !strings.Contains(err.Error(), "connection reset") {
|
| 328 |
+
logf("warn", "Client connection error for %s", uuid)
|
| 329 |
+
}
|
| 330 |
+
break
|
| 331 |
+
}
|
| 332 |
+
if n > 0 {
|
| 333 |
+
if _, err := remote.Write(buffer[:n]); err != nil {
|
| 334 |
+
if !strings.Contains(err.Error(), "connection reset") && !strings.Contains(err.Error(), "closed network connection") {
|
| 335 |
+
logf("warn", "Remote write error for %s", uuid)
|
| 336 |
+
}
|
| 337 |
+
break
|
| 338 |
+
}
|
| 339 |
+
}
|
| 340 |
+
}
|
| 341 |
+
}()
|
| 342 |
+
|
| 343 |
+
<-done
|
| 344 |
+
logf("debug", "Session completed: %s", uuid)
|
| 345 |
+
|
| 346 |
+
sessionsMu.Lock()
|
| 347 |
+
delete(sessions, uuid)
|
| 348 |
+
sessionsMu.Unlock()
|
| 349 |
+
}
|
| 350 |
+
|
| 351 |
+
// slove post data
|
| 352 |
+
func handleVlessPost(w http.ResponseWriter, r *http.Request, uuid string, seq int) {
|
| 353 |
+
body, err := io.ReadAll(r.Body)
|
| 354 |
+
if err != nil {
|
| 355 |
+
logf("error", "Failed to read POST body: %v", err)
|
| 356 |
+
http.Error(w, "Bad Request", http.StatusBadRequest)
|
| 357 |
+
return
|
| 358 |
+
}
|
| 359 |
+
|
| 360 |
+
if seq == 0 {
|
| 361 |
+
logf("debug", "Initializing session: %s", uuid)
|
| 362 |
+
}
|
| 363 |
+
|
| 364 |
+
sessionsMu.Lock()
|
| 365 |
+
session, exists := sessions[uuid]
|
| 366 |
+
if !exists {
|
| 367 |
+
session = &VlessSession{UUID: uuid}
|
| 368 |
+
sessions[uuid] = session
|
| 369 |
+
}
|
| 370 |
+
sessionsMu.Unlock()
|
| 371 |
+
|
| 372 |
+
if seq == 0 {
|
| 373 |
+
hostname, port, remaining, err := parseSimpleVlessHeader(body)
|
| 374 |
+
if err != nil {
|
| 375 |
+
logf("error", "Failed to parse VLS header: %v", err)
|
| 376 |
+
http.Error(w, "Bad Request", http.StatusBadRequest)
|
| 377 |
+
return
|
| 378 |
+
}
|
| 379 |
+
|
| 380 |
+
logf("info", "VLS connection to %s:%d", hostname, port)
|
| 381 |
+
|
| 382 |
+
if config.LogLevel == "debug" {
|
| 383 |
+
go diagnoseConnection(hostname, port)
|
| 384 |
+
}
|
| 385 |
+
|
| 386 |
+
address := fmt.Sprintf("%s:%d", hostname, port)
|
| 387 |
+
var remote net.Conn
|
| 388 |
+
var connErr error
|
| 389 |
+
|
| 390 |
+
for i := 0; i < 3; i++ {
|
| 391 |
+
remote, connErr = net.DialTimeout("tcp", address, 15*time.Second)
|
| 392 |
+
if connErr == nil {
|
| 393 |
+
break
|
| 394 |
+
}
|
| 395 |
+
if i < 2 {
|
| 396 |
+
logf("warn", "Connection attempt %d failed for %s: %v, retrying...", i+1, address, connErr)
|
| 397 |
+
time.Sleep(1 * time.Second)
|
| 398 |
+
}
|
| 399 |
+
}
|
| 400 |
+
|
| 401 |
+
if connErr != nil {
|
| 402 |
+
logf("error", "Failed to connect to %s after 3 attempts: %v", address, connErr)
|
| 403 |
+
http.Error(w, "Connection Failed", http.StatusBadGateway)
|
| 404 |
+
return
|
| 405 |
+
}
|
| 406 |
+
|
| 407 |
+
logf("info", "Successfully connected to %s", address)
|
| 408 |
+
|
| 409 |
+
if tcpConn, ok := remote.(*net.TCPConn); ok {
|
| 410 |
+
tcpConn.SetNoDelay(true)
|
| 411 |
+
tcpConn.SetKeepAlive(true)
|
| 412 |
+
}
|
| 413 |
+
|
| 414 |
+
session.mu.Lock()
|
| 415 |
+
session.Remote = remote
|
| 416 |
+
session.ResponseHeader = []byte{0x00, 0x00}
|
| 417 |
+
session.mu.Unlock()
|
| 418 |
+
|
| 419 |
+
if len(remaining) > 0 {
|
| 420 |
+
if _, err := remote.Write(remaining); err != nil {
|
| 421 |
+
logf("error", "Failed to write initial data: %v", err)
|
| 422 |
+
}
|
| 423 |
+
}
|
| 424 |
+
|
| 425 |
+
logf("info", "VLS session initialized: %s", uuid)
|
| 426 |
+
} else {
|
| 427 |
+
session.mu.Lock()
|
| 428 |
+
if session.Remote != nil {
|
| 429 |
+
_, err := session.Remote.Write(body)
|
| 430 |
+
session.mu.Unlock()
|
| 431 |
+
if err != nil {
|
| 432 |
+
logf("error", "Failed to write data to remote: %v", err)
|
| 433 |
+
http.Error(w, "Write Failed", http.StatusBadGateway)
|
| 434 |
+
return
|
| 435 |
+
}
|
| 436 |
+
} else {
|
| 437 |
+
session.mu.Unlock()
|
| 438 |
+
logf("warn", "Received data for uninitialized session: %s", uuid)
|
| 439 |
+
}
|
| 440 |
+
}
|
| 441 |
+
|
| 442 |
+
w.WriteHeader(http.StatusOK)
|
| 443 |
+
}
|
| 444 |
+
|
| 445 |
+
// get ISP info from Cloudflare
|
| 446 |
+
func getISPInfo() string {
|
| 447 |
+
client := &http.Client{
|
| 448 |
+
Timeout: 10 * time.Second,
|
| 449 |
+
}
|
| 450 |
+
|
| 451 |
+
resp, err := client.Get("https://speed.cloudflare.com/meta")
|
| 452 |
+
if err != nil {
|
| 453 |
+
logf("warn", "Failed to get ISP info from Cloudflare: %v", err)
|
| 454 |
+
return "Unknown_ISP"
|
| 455 |
+
}
|
| 456 |
+
defer resp.Body.Close()
|
| 457 |
+
|
| 458 |
+
body, err := io.ReadAll(resp.Body)
|
| 459 |
+
if err != nil {
|
| 460 |
+
logf("warn", "Failed to read ISP response: %v", err)
|
| 461 |
+
return "Unknown_ISP"
|
| 462 |
+
}
|
| 463 |
+
|
| 464 |
+
var meta CloudflareSpeedMeta
|
| 465 |
+
if err := json.Unmarshal(body, &meta); err != nil {
|
| 466 |
+
logf("warn", "Failed to parse ISP response: %v", err)
|
| 467 |
+
return "Unknown_ISP"
|
| 468 |
+
}
|
| 469 |
+
|
| 470 |
+
country := strings.ReplaceAll(meta.Country, " ", "")
|
| 471 |
+
asOrg := strings.ReplaceAll(meta.AsOrganization, " ", "_")
|
| 472 |
+
asOrg = strings.ReplaceAll(asOrg, "(", "")
|
| 473 |
+
asOrg = strings.ReplaceAll(asOrg, ")", "")
|
| 474 |
+
|
| 475 |
+
isp := fmt.Sprintf("%s_%s", country, asOrg)
|
| 476 |
+
logf("debug", "Got ISP info: %s (Country: %s, ASOrganization: %s)", isp, meta.Country, meta.AsOrganization)
|
| 477 |
+
|
| 478 |
+
return isp
|
| 479 |
+
}
|
| 480 |
+
|
| 481 |
+
// http server
|
| 482 |
+
func handleRequest(w http.ResponseWriter, r *http.Request) {
|
| 483 |
+
// root path
|
| 484 |
+
if r.URL.Path == "/" {
|
| 485 |
+
w.Header().Set("Content-Type", "text/plain")
|
| 486 |
+
fmt.Fprint(w, "Hello, World\n")
|
| 487 |
+
return
|
| 488 |
+
}
|
| 489 |
+
|
| 490 |
+
// sub route
|
| 491 |
+
if r.URL.Path == "/"+config.SubPath {
|
| 492 |
+
ip := config.Domain
|
| 493 |
+
if ip == "" {
|
| 494 |
+
ip = getServerIP()
|
| 495 |
+
}
|
| 496 |
+
|
| 497 |
+
if net.ParseIP(ip) == nil && !strings.Contains(ip, ".") {
|
| 498 |
+
ip = "localhost"
|
| 499 |
+
logf("warn", "Invalid IP format detected, using localhost")
|
| 500 |
+
}
|
| 501 |
+
|
| 502 |
+
if strings.Contains(ip, "<") || strings.Contains(ip, ">") {
|
| 503 |
+
ip = "localhost"
|
| 504 |
+
logf("warn", "HTML content detected in IP, using localhost")
|
| 505 |
+
}
|
| 506 |
+
|
| 507 |
+
isp := getISPInfo()
|
| 508 |
+
nodeName := fmt.Sprintf("%s_%s", config.Name, isp)
|
| 509 |
+
|
| 510 |
+
vlessURL := fmt.Sprintf("vless://%s@%s:443?encryption=none&security=tls&type=xhttp&host=%s&sni=%s&fp=chrome&path=%%2F%s&mode=packet-up#%s",
|
| 511 |
+
config.UUID, ip, ip, ip, config.XPath, nodeName)
|
| 512 |
+
|
| 513 |
+
logf("debug", "Generated subscription URL: %s", vlessURL)
|
| 514 |
+
|
| 515 |
+
base64Content := base64.StdEncoding.EncodeToString([]byte(vlessURL))
|
| 516 |
+
w.Header().Set("Content-Type", "text/plain; charset=utf-8")
|
| 517 |
+
w.Header().Set("Access-Control-Allow-Origin", "*")
|
| 518 |
+
fmt.Fprintf(w, "%s\n", base64Content)
|
| 519 |
+
return
|
| 520 |
+
}
|
| 521 |
+
|
| 522 |
+
if !strings.Contains(r.URL.Path, config.XPath) {
|
| 523 |
+
http.NotFound(w, r)
|
| 524 |
+
return
|
| 525 |
+
}
|
| 526 |
+
|
| 527 |
+
// path prefix
|
| 528 |
+
pathPrefix := fmt.Sprintf("/%s/", config.XPath)
|
| 529 |
+
if !strings.HasPrefix(r.URL.Path, pathPrefix) {
|
| 530 |
+
http.NotFound(w, r)
|
| 531 |
+
return
|
| 532 |
+
}
|
| 533 |
+
|
| 534 |
+
remaining := strings.TrimPrefix(r.URL.Path, pathPrefix)
|
| 535 |
+
parts := strings.Split(remaining, "/")
|
| 536 |
+
|
| 537 |
+
if len(parts) < 1 || parts[0] == "" {
|
| 538 |
+
http.NotFound(w, r)
|
| 539 |
+
return
|
| 540 |
+
}
|
| 541 |
+
|
| 542 |
+
uuid := parts[0]
|
| 543 |
+
|
| 544 |
+
if r.Method == "GET" && len(parts) == 1 {
|
| 545 |
+
handleVlessConnection(w, r, uuid)
|
| 546 |
+
return
|
| 547 |
+
}
|
| 548 |
+
|
| 549 |
+
if r.Method == "POST" && len(parts) == 2 {
|
| 550 |
+
seq, err := strconv.Atoi(parts[1])
|
| 551 |
+
if err != nil {
|
| 552 |
+
http.NotFound(w, r)
|
| 553 |
+
return
|
| 554 |
+
}
|
| 555 |
+
handleVlessPost(w, r, uuid, seq)
|
| 556 |
+
return
|
| 557 |
+
}
|
| 558 |
+
|
| 559 |
+
http.NotFound(w, r)
|
| 560 |
+
}
|
| 561 |
+
|
| 562 |
+
// network diagnose
|
| 563 |
+
func diagnoseConnection(hostname string, port uint16) {
|
| 564 |
+
address := fmt.Sprintf("%s:%d", hostname, port)
|
| 565 |
+
|
| 566 |
+
ips, err := net.LookupIP(hostname)
|
| 567 |
+
if err != nil {
|
| 568 |
+
logf("warn", "DNS resolution failed for %s: %v", hostname, err)
|
| 569 |
+
return
|
| 570 |
+
}
|
| 571 |
+
|
| 572 |
+
logf("debug", "DNS resolved %s to %v", hostname, ips)
|
| 573 |
+
|
| 574 |
+
conn, err := net.DialTimeout("tcp", address, 5*time.Second)
|
| 575 |
+
if err != nil {
|
| 576 |
+
logf("warn", "Quick connection test failed for %s: %v", address, err)
|
| 577 |
+
return
|
| 578 |
+
}
|
| 579 |
+
conn.Close()
|
| 580 |
+
logf("debug", "Quick connection test successful for %s", address)
|
| 581 |
+
}
|
| 582 |
+
|
| 583 |
+
// get server IP
|
| 584 |
+
func getServerIP() string {
|
| 585 |
+
services := []string{
|
| 586 |
+
"https://ip.sb",
|
| 587 |
+
"https://ipinfo.io/ip",
|
| 588 |
+
"https://api.ipify.org",
|
| 589 |
+
"https://ifconfig.me",
|
| 590 |
+
|
| 591 |
+
}
|
| 592 |
+
|
| 593 |
+
client := &http.Client{
|
| 594 |
+
Timeout: 10 * time.Second,
|
| 595 |
+
}
|
| 596 |
+
|
| 597 |
+
for _, service := range services {
|
| 598 |
+
resp, err := client.Get(service)
|
| 599 |
+
if err != nil {
|
| 600 |
+
continue
|
| 601 |
+
}
|
| 602 |
+
|
| 603 |
+
body, err := io.ReadAll(resp.Body)
|
| 604 |
+
resp.Body.Close()
|
| 605 |
+
|
| 606 |
+
if err != nil {
|
| 607 |
+
continue
|
| 608 |
+
}
|
| 609 |
+
|
| 610 |
+
ip := strings.TrimSpace(string(body))
|
| 611 |
+
|
| 612 |
+
if net.ParseIP(ip) != nil {
|
| 613 |
+
logf("debug", "Got IP from %s: %s", service, ip)
|
| 614 |
+
return ip
|
| 615 |
+
}
|
| 616 |
+
}
|
| 617 |
+
|
| 618 |
+
// if all services fail, try to get local IP
|
| 619 |
+
conn, err := net.Dial("udp", "8.8.8.8:80")
|
| 620 |
+
if err == nil {
|
| 621 |
+
defer conn.Close()
|
| 622 |
+
localAddr := conn.LocalAddr().(*net.UDPAddr)
|
| 623 |
+
logf("debug", "Using local IP: %s", localAddr.IP)
|
| 624 |
+
return localAddr.IP.String()
|
| 625 |
+
}
|
| 626 |
+
|
| 627 |
+
logf("warn", "Failed to get server IP, using localhost")
|
| 628 |
+
return "localhost"
|
| 629 |
+
}
|
| 630 |
+
|
| 631 |
+
// get nz download url
|
| 632 |
+
func getNezhaDownloadURL() (string, string) {
|
| 633 |
+
if config.NezhaServer == "" || config.NezhaKey == "" {
|
| 634 |
+
return "", ""
|
| 635 |
+
}
|
| 636 |
+
|
| 637 |
+
arch := runtime.GOARCH
|
| 638 |
+
var version string
|
| 639 |
+
|
| 640 |
+
if config.NezhaServer != "" && config.NezhaPort != "" && config.NezhaKey != "" {
|
| 641 |
+
version = "agent"
|
| 642 |
+
} else if config.NezhaServer != "" && config.NezhaKey != "" && strings.Contains(config.NezhaServer, ":") {
|
| 643 |
+
version = "v1"
|
| 644 |
+
} else {
|
| 645 |
+
return "", ""
|
| 646 |
+
}
|
| 647 |
+
|
| 648 |
+
var url string
|
| 649 |
+
if arch == "arm" || arch == "arm64" {
|
| 650 |
+
url = fmt.Sprintf("https://arm64.ssss.nyc.mn/%s", version)
|
| 651 |
+
} else {
|
| 652 |
+
url = fmt.Sprintf("https://amd64.ssss.nyc.mn/%s", version)
|
| 653 |
+
}
|
| 654 |
+
|
| 655 |
+
return url, version
|
| 656 |
+
}
|
| 657 |
+
|
| 658 |
+
// download nz
|
| 659 |
+
func downloadNezhaAgent() (string, error) {
|
| 660 |
+
url, version := getNezhaDownloadURL()
|
| 661 |
+
if url == "" {
|
| 662 |
+
return "", nil
|
| 663 |
+
}
|
| 664 |
+
|
| 665 |
+
logf("info", "Downloading Nezha agent from %s", url)
|
| 666 |
+
|
| 667 |
+
client := &http.Client{
|
| 668 |
+
Timeout: 60 * time.Second,
|
| 669 |
+
}
|
| 670 |
+
|
| 671 |
+
resp, err := client.Get(url)
|
| 672 |
+
if err != nil {
|
| 673 |
+
return "", fmt.Errorf("failed to download: %v", err)
|
| 674 |
+
}
|
| 675 |
+
defer resp.Body.Close()
|
| 676 |
+
|
| 677 |
+
file, err := os.Create("npm")
|
| 678 |
+
if err != nil {
|
| 679 |
+
return "", fmt.Errorf("failed to create file: %v", err)
|
| 680 |
+
}
|
| 681 |
+
defer file.Close()
|
| 682 |
+
|
| 683 |
+
_, err = io.Copy(file, resp.Body)
|
| 684 |
+
if err != nil {
|
| 685 |
+
return "", fmt.Errorf("failed to save file: %v", err)
|
| 686 |
+
}
|
| 687 |
+
|
| 688 |
+
err = os.Chmod("npm", 0755)
|
| 689 |
+
if err != nil {
|
| 690 |
+
return "", fmt.Errorf("failed to set permissions: %v", err)
|
| 691 |
+
}
|
| 692 |
+
|
| 693 |
+
fmt.Println("nezha downloaded successfully")
|
| 694 |
+
return version, nil
|
| 695 |
+
}
|
| 696 |
+
|
| 697 |
+
// create nz config
|
| 698 |
+
func createNezhaConfig(version string) error {
|
| 699 |
+
if version == "agent" {
|
| 700 |
+
return nil
|
| 701 |
+
}
|
| 702 |
+
|
| 703 |
+
if version == "v1" {
|
| 704 |
+
server := config.NezhaServer
|
| 705 |
+
var port string
|
| 706 |
+
|
| 707 |
+
if strings.Contains(server, ":") {
|
| 708 |
+
parts := strings.Split(server, ":")
|
| 709 |
+
if len(parts) == 2 {
|
| 710 |
+
server = parts[0]
|
| 711 |
+
port = parts[1]
|
| 712 |
+
} else {
|
| 713 |
+
return fmt.Errorf("invalid NEZHA_SERVER format: %s", config.NezhaServer)
|
| 714 |
+
}
|
| 715 |
+
} else {
|
| 716 |
+
return fmt.Errorf("No port found in NEZHA_SERVER")
|
| 717 |
+
}
|
| 718 |
+
|
| 719 |
+
tlsPorts := []string{"443", "8443", "2096", "2087", "2083", "2053"}
|
| 720 |
+
tls := "false"
|
| 721 |
+
for _, tlsPort := range tlsPorts {
|
| 722 |
+
if port == tlsPort {
|
| 723 |
+
tls = "true"
|
| 724 |
+
break
|
| 725 |
+
}
|
| 726 |
+
}
|
| 727 |
+
|
| 728 |
+
serverAddr := fmt.Sprintf("%s:%s", server, port)
|
| 729 |
+
|
| 730 |
+
configContent := fmt.Sprintf(`client_secret: %s
|
| 731 |
+
debug: false
|
| 732 |
+
disable_auto_update: true
|
| 733 |
+
disable_command_execute: false
|
| 734 |
+
disable_force_update: true
|
| 735 |
+
disable_nat: false
|
| 736 |
+
disable_send_query: false
|
| 737 |
+
gpu: false
|
| 738 |
+
insecure_tls: false
|
| 739 |
+
ip_report_period: 1800
|
| 740 |
+
report_delay: 4
|
| 741 |
+
server: %s
|
| 742 |
+
skip_connection_count: false
|
| 743 |
+
skip_procs_count: false
|
| 744 |
+
temperature: false
|
| 745 |
+
tls: %s
|
| 746 |
+
use_gitee_to_upgrade: false
|
| 747 |
+
use_ipv6_country_code: false
|
| 748 |
+
uuid: %s`,
|
| 749 |
+
config.NezhaKey, serverAddr, tls, config.UUID)
|
| 750 |
+
|
| 751 |
+
err := os.WriteFile("config.yaml", []byte(configContent), 0644)
|
| 752 |
+
if err != nil {
|
| 753 |
+
return fmt.Errorf("failed to create config file: %v", err)
|
| 754 |
+
}
|
| 755 |
+
|
| 756 |
+
logf("info", "Nezha v1 config file created for %s with TLS: %s", serverAddr, tls)
|
| 757 |
+
}
|
| 758 |
+
|
| 759 |
+
return nil
|
| 760 |
+
}
|
| 761 |
+
|
| 762 |
+
// run nz
|
| 763 |
+
func runNezhaAgent(version string) error {
|
| 764 |
+
var cmd *exec.Cmd
|
| 765 |
+
|
| 766 |
+
if version == "agent" {
|
| 767 |
+
tlsPorts := []string{"443", "8443", "2096", "2087", "2083", "2053"}
|
| 768 |
+
tlsFlag := ""
|
| 769 |
+
for _, port := range tlsPorts {
|
| 770 |
+
if config.NezhaPort == port {
|
| 771 |
+
tlsFlag = "--tls"
|
| 772 |
+
break
|
| 773 |
+
}
|
| 774 |
+
}
|
| 775 |
+
|
| 776 |
+
server := fmt.Sprintf("%s:%s", config.NezhaServer, config.NezhaPort)
|
| 777 |
+
args := []string{"-s", server, "-p", config.NezhaKey}
|
| 778 |
+
if tlsFlag != "" {
|
| 779 |
+
args = append(args, tlsFlag)
|
| 780 |
+
}
|
| 781 |
+
|
| 782 |
+
cmd = exec.Command("./npm", args...)
|
| 783 |
+
} else if version == "v1" {
|
| 784 |
+
cmd = exec.Command("./npm", "-c", "config.yaml")
|
| 785 |
+
} else {
|
| 786 |
+
return fmt.Errorf("unknown version: %s", version)
|
| 787 |
+
}
|
| 788 |
+
|
| 789 |
+
cmd.Stdout = nil
|
| 790 |
+
cmd.Stderr = nil
|
| 791 |
+
|
| 792 |
+
err := cmd.Start()
|
| 793 |
+
if err != nil {
|
| 794 |
+
return fmt.Errorf("failed to start nezha agent: %v", err)
|
| 795 |
+
}
|
| 796 |
+
|
| 797 |
+
fmt.Println("nezha is running")
|
| 798 |
+
return nil
|
| 799 |
+
}
|
| 800 |
+
|
| 801 |
+
// download nz
|
| 802 |
+
func startNezhaAgent() {
|
| 803 |
+
if config.NezhaServer == "" || config.NezhaKey == "" {
|
| 804 |
+
logf("info", "Nezha agent doesn't enable")
|
| 805 |
+
return
|
| 806 |
+
}
|
| 807 |
+
|
| 808 |
+
go func() {
|
| 809 |
+
version, err := downloadNezhaAgent()
|
| 810 |
+
if err != nil {
|
| 811 |
+
logf("error", "Failed to download Nezha agent: %v", err)
|
| 812 |
+
return
|
| 813 |
+
}
|
| 814 |
+
|
| 815 |
+
if version == "" {
|
| 816 |
+
logf("info", "Nezha agent doesn't need to download")
|
| 817 |
+
return
|
| 818 |
+
}
|
| 819 |
+
|
| 820 |
+
err = createNezhaConfig(version)
|
| 821 |
+
if err != nil {
|
| 822 |
+
logf("error", "Failed to create Nezha config: %v", err)
|
| 823 |
+
return
|
| 824 |
+
}
|
| 825 |
+
|
| 826 |
+
time.Sleep(3 * time.Second)
|
| 827 |
+
|
| 828 |
+
err = runNezhaAgent(version)
|
| 829 |
+
if err != nil {
|
| 830 |
+
logf("error", "Failed to run Nezha agent: %v", err)
|
| 831 |
+
return
|
| 832 |
+
}
|
| 833 |
+
}()
|
| 834 |
+
}
|
| 835 |
+
|
| 836 |
+
// add auto access task
|
| 837 |
+
func addAccessTask() {
|
| 838 |
+
if !config.AutoAccess {
|
| 839 |
+
return
|
| 840 |
+
}
|
| 841 |
+
|
| 842 |
+
if config.Domain == "" {
|
| 843 |
+
logf("warn", "AUTO_ACCESS enabled but DOMAIN is empty")
|
| 844 |
+
return
|
| 845 |
+
}
|
| 846 |
+
|
| 847 |
+
fullURL := fmt.Sprintf("https://%s", config.Domain)
|
| 848 |
+
command := fmt.Sprintf(`curl -X POST "https://oooo.serv00.net/add-url" -H "Content-Type: application/json" -d '{"url": "%s"}'`, fullURL)
|
| 849 |
+
|
| 850 |
+
cmd := exec.Command("sh", "-c", command)
|
| 851 |
+
err := cmd.Run()
|
| 852 |
+
if err != nil {
|
| 853 |
+
logf("error", "Error sending access task request: %v", err)
|
| 854 |
+
return
|
| 855 |
+
}
|
| 856 |
+
|
| 857 |
+
fmt.Printf("Access task add successfully")
|
| 858 |
+
}
|
| 859 |
+
|
| 860 |
+
func main() {
|
| 861 |
+
config = loadConfig()
|
| 862 |
+
|
| 863 |
+
startNezhaAgent()
|
| 864 |
+
|
| 865 |
+
addAccessTask()
|
| 866 |
+
|
| 867 |
+
server := &http.Server{
|
| 868 |
+
Addr: ":" + config.Port,
|
| 869 |
+
Handler: http.HandlerFunc(handleRequest),
|
| 870 |
+
ReadTimeout: 30 * time.Second,
|
| 871 |
+
WriteTimeout: 30 * time.Second,
|
| 872 |
+
IdleTimeout: 60 * time.Second,
|
| 873 |
+
}
|
| 874 |
+
|
| 875 |
+
fmt.Printf("Server is running on port %s\n", config.Port)
|
| 876 |
+
if err := server.ListenAndServe(); err != nil {
|
| 877 |
+
fmt.Printf("Server error: %v\n", err)
|
| 878 |
+
logf("error", "Server error: %v", err)
|
| 879 |
+
}
|
| 880 |
+
}
|