-
Notifications
You must be signed in to change notification settings - Fork 21
/
main.go
273 lines (212 loc) · 5.14 KB
/
main.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
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
package main
import (
"encoding/json"
"flag"
"fmt"
"io"
"log"
"net"
"net/http"
"os"
"os/signal"
"runtime"
"sync"
"syscall"
"time"
)
var restApiServer = flag.String("restApi", "", "listen addr for restapi")
var auth = flag.String("auth", "taven123", "restApi Password")
var gLocalConn net.Listener
var clientSMap map[string]net.Conn
var forwardInfo string
func main() {
clientSMap = make(map[string]net.Conn)
//解析传入的参数
flag.Parse()
if *restApiServer == "" {
*restApiServer = "0.0.0.0:8000"
}
go StartHttpServer(*restApiServer)
log.Println("restApiServer:", *restApiServer)
fmt.Println("------------启动成功------------")
//开启线程同步锁
var w sync.WaitGroup
w.Add(2)
//开一个并发线程,接收退出信号
go func() {
c := make(chan os.Signal, 1)
signal.Notify(c, os.Interrupt, syscall.SIGTERM)
n := 0
f := func() {
<-c
n++
if n > 2 {
log.Println("force shutdown")
os.Exit(-1)
}
log.Println("received signal,shutdown")
closeAllConn()
}
f()
go func() {
for {
f()
}
}()
//执行完成一次,Done() 等同于 Add(-1),计数不为0,则阻塞
w.Done()
}()
loop := func() {
w.Done()
}
loop()
w.Wait()
fmt.Println("------------程序执行完成------------")
}
func StartHttpServer(addr string) {
http.HandleFunc("/ServerSummary", ServerSummary)
http.HandleFunc("/ForwardWork", ForwardWork)
//
err := http.ListenAndServe(addr, http.DefaultServeMux)
if err != nil {
fmt.Println("ListenAndServe error: ", err.Error())
}
}
func ServerSummary(rw http.ResponseWriter, req *http.Request) {
log.Println("ServerSummary")
obj := make(map[string]interface{})
obj["runtime_NumGoroutine"] = runtime.NumGoroutine()
obj["runtime_GOOS"] = runtime.GOOS
obj["runtime_GOARCH"] = runtime.GOARCH
obj["restApi_Addr"] = *restApiServer
obj["server_Time"] = time.Now()
obj["clients_Count"] = len(clientSMap)
var clist []string
for cId, _ := range clientSMap {
clist = append(clist, cId)
}
obj["clients_List"] = clist
obj["forwardInfo"] = forwardInfo
res, err := json.Marshal(obj)
if err != nil {
log.Println("json marshal:", err)
return
}
rw.Header().Add("Content-Type", "application/json;charset=utf-8")
_, err = rw.Write(res)
if err != nil {
log.Println("write err:", err)
}
return
}
func ForwardWork(rw http.ResponseWriter, req *http.Request) {
req.ParseForm()
obj := make(map[string]interface{})
obj["code"] = 0
obj["msg"] = ""
paramAuth, hasAuth := req.Form["auth"]
if !hasAuth {
log.Println("request no auth")
obj["code"] = 1
obj["msg"] = "request no auth"
responseResult(obj, rw)
return
}
if paramAuth[0] != *auth {
log.Println("request auth failed")
obj["code"] = 1
obj["msg"] = "request auth failed"
responseResult(obj, rw)
return
}
paramStatus, hasStatus := req.Form["status"]
if !hasStatus {
return
}
log.Println("param_status:", paramStatus)
if paramStatus[0] == "1" {
//启动服务
paramFromAddr, hasFromAddr := req.Form["fromAddr"]
paramToAddr, hasToAddr := req.Form["toAddr"]
if gLocalConn != nil {
gLocalConn.Close()
}
if hasFromAddr && hasToAddr {
go forwardPort(paramFromAddr[0], paramToAddr[0])
}
}
if paramStatus[0] == "0" {
//关闭服务
closeAllConn()
forwardInfo = ""
}
responseResult(obj, rw)
return
}
func responseResult(data map[string]interface{}, rw http.ResponseWriter) {
res, err := json.Marshal(data)
if err != nil {
log.Println("json marshal:", err)
return
}
rw.Header().Add("Content-Type", "application/json;charset=utf-8")
_, err = rw.Write(res)
if err != nil {
log.Println("write err:", err)
}
}
func closeAllConn() {
for cId, conn := range clientSMap {
log.Println("clientMap id:", cId)
conn.Close()
delete(clientSMap, cId)
}
if gLocalConn != nil {
gLocalConn.Close()
log.Println("Listener Close")
} else {
gLocalConn = nil
log.Println("Listener set to nil", gLocalConn)
}
}
func forwardPort(sourcePort string, targetPort string) {
fmt.Println("sourcePort:", sourcePort, "targetPort:", targetPort)
localConn, err := net.Listen("tcp", sourcePort)
if err != nil {
fmt.Println(err.Error())
return
}
gLocalConn = localConn
fmt.Println("服务启动成功,服务地址:", sourcePort)
forwardInfo = fmt.Sprintf("%s - %s", sourcePort, targetPort)
for {
fmt.Println("Ready to Accept ...")
sourceConn, err := gLocalConn.Accept()
if err != nil {
log.Println("server err:", err.Error())
break
}
//log.Println("client", sc.id, "create session", sessionId)
id := sourceConn.RemoteAddr().String()
clientSMap[id] = sourceConn
fmt.Println("conn.RemoteAddr().String() :", id)
//targetPort := "172.16.128.83:22"
targetConn, err := net.DialTimeout("tcp", targetPort, 30*time.Second)
go func() {
_, err = io.Copy(targetConn, sourceConn)
if err != nil {
//log.Fatalf("io.Copy 1 failed: %v", err)
fmt.Println("io.Copy 1 failed:", err.Error())
}
}()
go func() {
_, err = io.Copy(sourceConn, targetConn)
if err != nil {
//log.Fatalf("io.Copy 2 failed: %v", err)
fmt.Println("io.Copy 2 failed:", err.Error())
}
}()
}
//
log.Println("forwardPort end.")
}