-
Notifications
You must be signed in to change notification settings - Fork 285
/
http_modify.go
321 lines (305 loc) · 7.66 KB
/
http_modify.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
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
package shuttle
import (
"bytes"
"fmt"
"github.com/sipt/shuttle/config"
"github.com/sipt/shuttle/log"
"github.com/sipt/shuttle/pool"
"github.com/sipt/shuttle/proxy"
"github.com/sipt/shuttle/rule"
"github.com/sipt/shuttle/util"
"net"
"net/http"
"net/url"
"os"
"regexp"
"strconv"
"strings"
"time"
)
const (
ModifyTypeURL = "URL"
ModifyTypeHeader = "HEADER"
ModifyTypeStatus = "STATUS"
ModifyTypeBody = "BODY"
ModifyMock = "MOCK"
ModifyUpdate = "UPDATE"
BodyFileDir = "RespFiles"
)
var reqPolicies []*ModifyPolicy
var respPolicies []*ModifyPolicy
type IHttpModifyConfig interface {
GetHTTPMap() *config.HttpMap
}
func ApplyHTTPModifyConfig(config IHttpModifyConfig) (err error) {
httpMap := config.GetHTTPMap()
if httpMap != nil {
if len(httpMap.ReqMap) > 0 {
reqps := make([]*ModifyPolicy, len(httpMap.ReqMap))
for i, v := range httpMap.ReqMap {
switch v.Type {
case ModifyMock, ModifyUpdate:
default:
return fmt.Errorf("resolve config file [Http-Map] [Req-Map] not support [%s]", v.Type)
}
reqps[i] = &ModifyPolicy{
Type: v.Type,
UrlRex: v.UrlRex,
}
reqps[i].rex, err = regexp.Compile(v.UrlRex)
if err != nil {
return fmt.Errorf("resolve config file [Http-Map] [%s] failed: %v", v.UrlRex, err)
}
if len(v.Items) > 0 {
reqps[i].MVs = make([]*ModifyValue, len(v.Items))
for j, e := range v.Items {
if len(e) != 3 {
return fmt.Errorf("resolve config file [Http-Map] failed: %v, item's count must be 3", e)
}
switch e[0] {
case ModifyTypeURL, ModifyTypeHeader, ModifyTypeStatus, ModifyTypeBody:
default:
return fmt.Errorf("resolve config file [Http-Map] [Req-Map] not support [%s]", v.Type)
}
reqps[i].MVs[j] = &ModifyValue{
Type: e[0],
Key: e[1],
Value: e[2],
}
}
}
}
reqPolicies = reqps
}
if len(httpMap.ReqMap) > 0 {
respps := make([]*ModifyPolicy, len(httpMap.RespMap))
for i, v := range httpMap.RespMap {
switch v.Type {
case ModifyMock, ModifyUpdate:
default:
return fmt.Errorf("resolve config file [Http-Map] [Resp-Map] not support [%s]", v.Type)
}
respps[i] = &ModifyPolicy{
Type: v.Type,
UrlRex: v.UrlRex,
}
respps[i].rex, err = regexp.Compile(v.UrlRex)
if err != nil {
return fmt.Errorf("resolve config file [Http-Map] [%s] failed: %v", err)
}
if len(v.Items) > 0 {
respps[i].MVs = make([]*ModifyValue, len(v.Items))
for j, e := range v.Items {
if len(e) != 3 {
return fmt.Errorf("resolve config file [Http-Map] failed: %v, item's count must be 3", e)
}
switch e[0] {
case ModifyTypeHeader, ModifyTypeStatus, ModifyTypeBody:
default:
return fmt.Errorf("resolve config file [Http-Map] [Req-Map] not support [%s]", v.Type)
}
respps[i].MVs[j] = &ModifyValue{
Type: e[0],
Key: e[1],
Value: e[2],
}
}
}
}
respPolicies = respps
}
}
return
}
func RequestModifyOrMock(req *HttpRequest, hreq *http.Request, isHttps bool) (respBuf []byte, err error) {
//request update
resp := RequestModify(hreq, isHttps)
req.domain = hreq.URL.Hostname()
if net.ParseIP(req.domain) != nil {
req.ip = req.domain
req.domain = ""
}
req.port = hreq.URL.Port()
req.target = hreq.URL.String()
if strings.HasPrefix(req.target, "//") {
req.target = req.target[2:]
}
if resp != nil { // response mock ?
buffer := &bytes.Buffer{}
err = resp.Write(buffer)
if err != nil {
return
}
respBuf = buffer.Bytes()
//mock record to storage
id := util.NextID()
boxChan <- &Box{
Op: RecordAppend,
Value: &Record{
ID: id,
Protocol: req.protocol,
Created: time.Now(),
Proxy: proxy.MockServer,
Status: RecordStatusCompleted,
Dumped: allowDump,
URL: req.target,
Rule: &rule.Rule{},
},
}
if allowDump {
go func(id int64, respBuf []byte) {
dump.InitDump(id)
writer := bytes.NewBuffer(pool.GetBuf()[:0])
hreq.Write(writer)
dump.WriteRequest(id, writer.Bytes())
dump.WriteResponse(id, respBuf)
dump.Complete(id)
}(id, respBuf)
}
}
return
}
func RequestModify(req *http.Request, isHttps bool) *http.Response {
if len(reqPolicies) == 0 {
return nil
}
l := req.URL.String()
if req.URL.Host == "" {
if isHttps {
l = "https://" + req.Host + l
} else {
l = "http://" + req.Host + l
}
}
for _, v := range reqPolicies {
if v.rex.MatchString(l) {
switch v.Type {
case ModifyMock:
return modifyMock(v, req, isHttps)
case ModifyUpdate:
modifyUpdate(v, req, isHttps)
return nil
}
}
}
return nil
}
func modifyMock(v *ModifyPolicy, req *http.Request, _ bool) *http.Response {
resp := &http.Response{
StatusCode: 200,
Proto: req.Proto,
ContentLength: 0,
Header: make(http.Header),
}
for _, e := range v.MVs {
var err error
switch e.Type {
case ModifyTypeHeader:
log.Logger.Debugf("[Http Modify] [Mock] response set Header [%s:%s]", e.Key, e.Value)
resp.Header.Set(e.Key, e.Value)
case ModifyTypeBody:
file, err := os.Open(e.Value)
if err != nil {
log.Logger.Errorf("[HTTP MODIFY] open mock file failed: %v", err)
return nil
}
status, err := file.Stat()
if err != nil {
log.Logger.Errorf("[HTTP MODIFY] read mock file [FileInfo] failed: %v", err)
return nil
}
log.Logger.Debugf("[Http Modify] [Mock] response set body [ContentLength:%d]", status.Size())
resp.ContentLength = status.Size()
resp.Body = file
case ModifyTypeStatus:
log.Logger.Debugf("[Http Modify] [Mock] response set body [Status:%s]", e.Value)
resp.StatusCode, err = strconv.Atoi(e.Value)
if err != nil {
resp.StatusCode = 200
}
}
}
return resp
}
func modifyUpdate(v *ModifyPolicy, req *http.Request, isHttps bool) {
for _, e := range v.MVs {
switch e.Type {
case ModifyTypeURL:
l := req.URL.String()
if req.URL.Host == "" {
if isHttps {
l = "https://" + req.Host + l
} else {
l = "http://" + req.Host + l
}
}
l = v.rex.ReplaceAllString(l, e.Value)
u, err := url.Parse(l)
if err != nil {
log.Logger.Errorf("[HTTP MODIFY] parse [%s] to url failed: %v", e.Value, err)
return
}
req.Host = u.Host
if req.URL.Scheme == "" {
u.Scheme = ""
}
if req.Host == "" {
u.Host = ""
}
if req.URL.Scheme != u.Scheme {
log.Logger.Errorf("[HTTP MODIFY] not support [%s] to [%s]", req.URL.Scheme, u.Scheme)
return
}
log.Logger.Debugf("[Http Modify] [Update] response set URL [%s]", e.Value)
req.URL = u
case ModifyTypeHeader:
log.Logger.Debugf("[Http Modify] [Update] response set Header [%s:%s]", e.Key, e.Value)
req.Header.Set(e.Key, e.Value)
}
}
}
func ResponseModify(req *http.Request, resp *http.Response, isHttps bool) {
if len(respPolicies) == 0 {
return
}
if req.URL == nil {
return
}
l := req.URL.String()
if req.URL.Host == "" {
if isHttps {
l = "https://" + req.Host + l
} else {
l = "http://" + req.Host + l
}
}
for _, v := range respPolicies {
if v.rex.MatchString(l) {
for _, e := range v.MVs {
switch e.Type {
case ModifyTypeHeader:
log.Logger.Debugf("[Http Modify] [Update] response set Header [%s, %s]", e.Key, e.Value)
resp.Header.Set(e.Key, e.Value)
case ModifyTypeStatus:
log.Logger.Debugf("[Http Modify] [Update] response [Status:%s]", e.Value)
code, err := strconv.Atoi(e.Value)
if err == nil {
resp.StatusCode = code
resp.Status = ""
}
}
}
}
}
}
type ModifyPolicy struct {
Type string
UrlRex string
rex *regexp.Regexp
MVs []*ModifyValue
}
type ModifyValue struct {
Type string
Key string
Value string
}