This repository has been archived by the owner on Sep 1, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 8
/
cns.go
195 lines (176 loc) · 5 KB
/
cns.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
// cns.go
package main
import (
"bytes"
"flag"
"fmt"
"log"
"net"
"os"
"os/exec"
"regexp"
"runtime"
"strconv"
"time"
)
var (
udpFlag string
enable_dns_tcpOverUdp, enable_httpDNS, enable_TFO bool
listenAddrs []string
udp_timeout time.Duration
hostRegex *regexp.Regexp
)
var METHODS [][]byte = [][]byte{
[]byte("CONNECT"), []byte("GET"), []byte("POST"), []byte("HEAD"), []byte("PUT"), []byte("COPY"), []byte("DELETE"), []byte("MOVE"), []byte("OPTOINS"), []byte("LINK"), []byte("UNLINK"), []byte("TRACE"),
[]byte("PATCH"), []byte("WRAPPED"),
}
func isHttpHeader(header []byte) bool {
for _, method := range METHODS {
if bytes.HasPrefix(header, method) {
return true
}
}
return false
}
func rspHeader(header []byte) []byte {
if bytes.Contains(header, []byte("WebSocket")) {
return []byte("HTTP/1.1 101 Switching Protocols\r\nUpgrade: websocket\r\nConnection: Upgrade\r\nSec-WebSocket-Accept: CuteBi Network Tunnel, (%>w<%)\r\n\r\n")
} else if bytes.HasPrefix(header, []byte("CON")) {
return []byte("HTTP/1.1 200 Connection established\r\nServer: CuteBi Network Tunnel, (%>w<%)\r\nConnection: keep-alive\r\n\r\n")
} else {
return []byte("HTTP/1.1 200 OK\r\nTransfer-Encoding: chunked\r\nServer: CuteBi Network Tunnel, (%>w<%)\r\nConnection: keep-alive\r\n\r\n")
}
}
func handleConn(cConn *net.TCPConn) {
var payload = make([]byte, 65536)
var rlen, err = cConn.Read(payload)
if err == nil {
payload = payload[:rlen]
if isHttpHeader(payload) {
/* handle http requests */
// process httpDNS request first
if enable_httpDNS {
var domain, err = GetHttpdnsDomain(payload)
if err == nil {
RespondHttpdns(cConn, domain)
}
} else {
// process TCP request next
var WLen, err = cConn.Write(rspHeader(payload))
if err == nil && WLen > 0 {
if bytes.Contains(payload, []byte(udpFlag)) {
// 丢弃含有udpFlag标识的请求
handleConn(cConn)
} else {
handleTcpSession(cConn, payload)
}
}
}
} else {
// handle udp requests
handleUdpSession(cConn, payload)
}
}
cConn.Close()
}
func pidSaveToFile(pidPath string) {
fp, err := os.Create(pidPath)
if err == nil {
_, err = fp.WriteString(fmt.Sprintf("%d", os.Getpid()))
if err != nil {
fmt.Println(err)
}
fp.Close()
} else {
fmt.Println(err)
}
}
func initConfig() {
var CuteBi_XorCrypt_passwordStr, pidPath string
var isHelp, enable_daemon bool
var configFile string
flag.BoolVar(&enable_daemon, "daemon", true, "daemon mode switch(开启后台运行)")
flag.StringVar(&configFile, "config-file", "config.cfg", "set configuration file, default `config.cfg`(指定配置文件,不指定时默认为`config.cfg`)")
flag.BoolVar(&isHelp, "help", false, "display this message(显示此帮助信息)")
flag.Parse()
var configMap = InitConfig(configFile)
if proxyKey := configMap["proxyKey"]; proxyKey != "" {
hostRegex = regexp.MustCompile(proxyKey + ":\\s*(.*)\r")
} else {
fmt.Fprintf(os.Stderr, "proxyKey为必填项,请先在配置文件中设置它")
return
}
udpFlag = configMap["udpFlag"]
listenAddrs = toAddrs(configMap["listenAddr"])
CuteBi_XorCrypt_passwordStr = configMap["password"]
/* udp timeout */
udpTimeout, err := strconv.ParseInt(configMap["udpTimeout"], 10, 64)
if err != nil {
fmt.Printf("udpTimeout参数错误:%v,将使用默认值30", configMap["udpTimeout"])
udp_timeout = 30
} else {
udp_timeout = time.Duration(udpTimeout)
}
udp_timeout *= time.Second
pidPath = configMap["pidPath"]
if configMap["enableDnsTcpOverUdp"] == "#t" {
enable_dns_tcpOverUdp = true
} else {
enable_dns_tcpOverUdp = false
}
enable_httpDNS = configMap["enableHttpDNS"] == "#t"
enable_TFO = configMap["enableTFO"] == "#t"
if isHelp {
fmt.Println("CuteBi Network Server v0.2.4")
flag.Usage()
os.Exit(0)
}
if enable_daemon {
exec.Command(os.Args[0], []string(append(os.Args[1:], "-daemon=false"))...).Start()
os.Exit(0)
}
if CuteBi_XorCrypt_passwordStr == "" {
CuteBi_XorCrypt_password = nil
} else {
CuteBi_XorCrypt_password = []byte(CuteBi_XorCrypt_passwordStr)
}
if pidPath != "" {
pidSaveToFile(pidPath)
}
setsid()
setMaxNofile()
}
func handling(listener *net.TCPListener) {
for {
conn, err := listener.AcceptTCP()
if err == nil {
go handleConn(conn)
} else {
log.Println(err)
time.Sleep(3 * time.Second)
}
}
// listener.Close()
}
func initListener(listenAddr string) *net.TCPListener {
addr, _ := net.ResolveTCPAddr("tcp", listenAddr)
listener, err := net.ListenTCP("tcp", addr)
if err != nil {
log.Fatal(err)
}
if enable_TFO {
enableTcpFastOpen(listener)
}
return listener
}
func main() {
runtime.GOMAXPROCS(runtime.NumCPU())
initConfig()
var addrsLen = len(listenAddrs)
for i := 0; i < addrsLen-1; i++ {
listener := initListener(listenAddrs[i])
go handling(listener)
}
var listener = initListener(listenAddrs[addrsLen-1])
handling(listener)
}