-
Notifications
You must be signed in to change notification settings - Fork 27
/
httpProxy.go
214 lines (195 loc) · 5.8 KB
/
httpProxy.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
package session
import (
"context"
"errors"
"fmt"
"github.com/OpenIoTHub/grpc-api/pb-go"
"github.com/OpenIoTHub/utils/io"
"github.com/OpenIoTHub/utils/net/httpUtil"
"github.com/libp2p/go-yamux"
"golang.org/x/net/websocket"
"net"
"net/http"
"net/http/httputil"
"net/url"
"strings"
"time"
)
func init() {
fmt.Printf("初始化Http代理管理器\n")
}
//服务结构
type HttpProxy struct {
Domain string
RunId string
RemoteIP string
RemotePort int
UserName string
Password string
IfHttps bool
Description string
RemotePortStatus bool
}
func (hp *HttpProxy) UpdateRemotePortStatus() {
var online bool
if hp.IfHttps {
online, _ = SessionsCtl.CheckRemoteStatus("tls", hp.RunId, hp.RemoteIP, hp.RemotePort)
} else {
online, _ = SessionsCtl.CheckRemoteStatus("tcp", hp.RunId, hp.RemoteIP, hp.RemotePort)
}
hp.RemotePortStatus = online
}
//grpc
func (sm *SessionsManager) CreateOneHTTP(ctx context.Context, in *pb.HTTPConfig) (*pb.HTTPConfig, error) {
return in, sm.AddHttpProxy(&HttpProxy{
Domain: in.Domain,
RunId: in.RunId,
RemoteIP: in.RemoteIP,
RemotePort: int(in.RemotePort),
UserName: in.UserName,
Password: in.Password,
IfHttps: in.IfHttps,
Description: in.Description,
})
}
func (sm *SessionsManager) DeleteOneHTTP(ctx context.Context, in *pb.HTTPConfig) (*pb.Empty, error) {
sm.DelHttpProxy(in.Domain)
return &pb.Empty{}, nil
}
func (sm *SessionsManager) GetOneHTTP(ctx context.Context, in *pb.HTTPConfig) (*pb.HTTPConfig, error) {
config, err := sm.GetOneHttpProxy(in.Domain)
if err != nil {
return &pb.HTTPConfig{}, err
}
return &pb.HTTPConfig{
Domain: config.Domain,
RunId: config.RunId,
RemoteIP: config.RemoteIP,
RemotePort: int32(config.RemotePort),
UserName: config.UserName,
Password: config.Password,
IfHttps: config.IfHttps,
Description: config.Description,
RemotePortStatus: config.RemotePortStatus,
}, err
}
func (sm *SessionsManager) GetAllHTTP(ctx context.Context, in *pb.Empty) (*pb.HTTPList, error) {
var cfgs []*pb.HTTPConfig
for _, config := range sm.GetAllHttpProxy() {
cfgs = append(cfgs, &pb.HTTPConfig{
Domain: config.Domain,
RunId: config.RunId,
RemoteIP: config.RemoteIP,
RemotePort: int32(config.RemotePort),
UserName: config.UserName,
Password: config.Password,
IfHttps: config.IfHttps,
Description: config.Description,
RemotePortStatus: config.RemotePortStatus,
})
}
return &pb.HTTPList{HTTPConfigs: cfgs}, nil
}
//grpc end
func (sm *SessionsManager) GetOneHttpProxy(id string) (*HttpProxy, error) {
if _, ok := sm.HttpProxyMap[id]; ok {
go sm.HttpProxyMap[id].UpdateRemotePortStatus()
return sm.HttpProxyMap[id], nil //存在
}
fmt.Printf("httpProxy id未注册")
return nil, errors.New("httpProxy id未注册")
}
func (sm *SessionsManager) GetAllHttpProxy() map[string]*HttpProxy {
for _, hp := range sm.HttpProxyMap {
go hp.UpdateRemotePortStatus()
}
return sm.HttpProxyMap
}
func (sm *SessionsManager) AddHttpProxy(httpProxy *HttpProxy) error {
if _, ok := sm.HttpProxyMap[httpProxy.Domain]; ok {
return fmt.Errorf("域名%s已经被占用!", httpProxy.Domain) //存在
}
go httpProxy.UpdateRemotePortStatus()
sm.HttpProxyMap[httpProxy.Domain] = httpProxy
return nil
}
func (sm *SessionsManager) DelHttpProxy(id string) {
delete(sm.HttpProxyMap, id)
}
//监听服务
//type Handle struct{}
func (sm *SessionsManager) ServeHTTP(w http.ResponseWriter, r *http.Request) {
//:TODO 当前不支持websocket的代理(websocket支持basic Auth),或者从beego分发?
//:TODO 非80端口r.Host的支持情况
//fmt.Printf("host:" + r.Host) //"http://127.0.0.1:8080/"
hostInfo, err := sm.GetOneHttpProxy(strings.Split(r.Host, ":")[0])
if err != nil {
_, _ = w.Write([]byte(err.Error()))
return
}
if hostInfo.UserName != "" || hostInfo.Password != "" {
ok := httpUtil.Auth(w, r, hostInfo.UserName, hostInfo.Password)
if !ok {
return
}
}
remote, err := url.Parse(fmt.Sprintf("http://%s/", r.Host))
if err != nil {
fmt.Printf(err.Error())
w.Write([]byte(err.Error()))
return
}
//是websocket
if v, ok := r.Header["Upgrade"]; ok {
if v[0] == "websocket" {
fn := func(ws *websocket.Conn) {
var pro = "ws"
var orgpro = "http"
if hostInfo.IfHttps {
pro = "wss"
orgpro = "https"
}
conn, err := sm.ConnectToWs(hostInfo.RunId, fmt.Sprintf("%s://%s:%d%s", pro, hostInfo.RemoteIP, hostInfo.RemotePort, r.URL.String()),
"", fmt.Sprintf("%s://%s:%d%s", orgpro, hostInfo.RemoteIP, hostInfo.RemotePort, r.URL.String()))
if err != nil {
fmt.Printf(err.Error())
ws.Write([]byte(err.Error()))
return
}
io.Join(ws, conn)
w.Write([]byte("over"))
return
}
websocket.Handler(fn).ServeHTTP(w, r)
}
}
//是普通http的情况
proxy := httputil.NewSingleHostReverseProxy(remote)
var pTransport http.RoundTripper = &http.Transport{
Proxy: http.ProxyFromEnvironment,
Dial: sm.dial,
TLSHandshakeTimeout: 10 * time.Second,
ExpectContinueTimeout: 1 * time.Second,
}
proxy.Transport = pTransport
proxy.ServeHTTP(w, r)
}
func (sm *SessionsManager) dial(network, address string) (net.Conn, error) {
//fmt.Printf("请求的地址addr:%s", address)
end := strings.Index(address, ":")
host := address[0:end]
hostInfo, err := sm.GetOneHttpProxy(host) //id
if err != nil {
return nil, err
}
var stream *yamux.Stream
if hostInfo.IfHttps {
stream, err = sm.ConnectToTls(hostInfo.RunId, hostInfo.RemoteIP, hostInfo.RemotePort)
} else {
stream, err = sm.ConnectToTcp(hostInfo.RunId, hostInfo.RemoteIP, hostInfo.RemotePort)
}
if err != nil {
return nil, err
}
return stream, nil
}