forked from SpectoLabs/hoverfly
-
Notifications
You must be signed in to change notification settings - Fork 0
/
hoverfly.go
213 lines (174 loc) · 5.32 KB
/
hoverfly.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
package main
import (
log "github.com/Sirupsen/logrus"
"github.com/elazarl/goproxy"
"bufio"
"flag"
"fmt"
"net"
"net/http"
"os"
"regexp"
)
const DefaultPort = ":8500"
// modes
const VirtualizeMode = "virtualize"
const SynthesizeMode = "synthesize"
const ModifyMode = "modify"
const CaptureMode = "capture"
// orPanic - wrapper for logging errors
func orPanic(err error) {
if err != nil {
log.WithFields(log.Fields{
"error": err.Error(),
}).Panic("Got error.")
}
}
func main() {
// Output to stderr instead of stdout, could also be a file.
log.SetOutput(os.Stderr)
log.SetFormatter(&log.TextFormatter{})
// getting proxy configuration
verbose := flag.Bool("v", false, "should every proxy request be logged to stdout")
// modes
capture := flag.Bool("capture", false, "should proxy capture requests")
synthesize := flag.Bool("synthesize", false, "should proxy capture requests")
modify := flag.Bool("modify", false, "should proxy only modify requests")
destination := flag.String("destination", ".", "destination URI to catch")
middleware := flag.String("middleware", "", "should proxy use middleware")
flag.Parse()
if *verbose {
// Only log the warning severity or above.
log.SetLevel(log.DebugLevel)
}
// getting settings
initSettings()
// overriding default middleware setting
AppConfig.middleware = *middleware
// setting default mode
mode := VirtualizeMode
if *capture {
mode = CaptureMode
// checking whether user supplied other modes
if *synthesize == true || *modify == true {
log.Fatal("Two or more modes supplied, check your flags")
}
} else if *synthesize {
mode = SynthesizeMode
if AppConfig.middleware == "" {
log.Fatal("Synthesize mode chosen although middleware not supplied")
}
if *capture == true || *modify == true {
log.Fatal("Two or more modes supplied, check your flags")
}
} else if *modify {
mode = ModifyMode
if AppConfig.middleware == "" {
log.Fatal("Modify mode chosen although middleware not supplied")
}
if *capture == true || *synthesize == true {
log.Fatal("Two or more modes supplied, check your flags")
}
}
// overriding default settings
AppConfig.mode = mode
// overriding destination
AppConfig.destination = *destination
// getting default database
port := os.Getenv("ProxyPort")
if port == "" {
port = DefaultPort
} else {
port = fmt.Sprintf(":%s", port)
}
// getting boltDB
db := getDB(AppConfig.databaseName)
defer db.Close()
cache := Cache{
db: db,
requestsBucket: []byte(requestsBucketName),
}
// getting connections
d := DBClient{
cache: cache,
http: &http.Client{},
}
// creating proxy
proxy := goproxy.NewProxyHttpServer()
proxy.OnRequest(goproxy.ReqHostMatches(regexp.MustCompile("^.*$"))).
HandleConnect(goproxy.AlwaysMitm)
// enable curl -p for all hosts on port 80
proxy.OnRequest(goproxy.ReqHostMatches(regexp.MustCompile(*destination))).
HijackConnect(func(req *http.Request, client net.Conn, ctx *goproxy.ProxyCtx) {
defer func() {
if e := recover(); e != nil {
ctx.Logf("error connecting to remote: %v", e)
client.Write([]byte("HTTP/1.1 500 Cannot reach destination\r\n\r\n"))
}
client.Close()
}()
clientBuf := bufio.NewReadWriter(bufio.NewReader(client), bufio.NewWriter(client))
remote, err := net.Dial("tcp", req.URL.Host)
orPanic(err)
remoteBuf := bufio.NewReadWriter(bufio.NewReader(remote), bufio.NewWriter(remote))
for {
req, err := http.ReadRequest(clientBuf.Reader)
orPanic(err)
orPanic(req.Write(remoteBuf))
orPanic(remoteBuf.Flush())
resp, err := http.ReadResponse(remoteBuf.Reader, req)
orPanic(err)
orPanic(resp.Write(clientBuf.Writer))
orPanic(clientBuf.Flush())
}
})
// processing connections
proxy.OnRequest(goproxy.ReqHostMatches(regexp.MustCompile(*destination))).DoFunc(
func(r *http.Request, ctx *goproxy.ProxyCtx) (*http.Request, *http.Response) {
return d.processRequest(r)
})
go d.startAdminInterface()
proxy.Verbose = *verbose
// proxy starting message
log.WithFields(log.Fields{
"Destination": *destination,
"ProxyPort": port,
"Mode": AppConfig.mode,
}).Info("Proxy is starting...")
log.Warn(http.ListenAndServe(port, proxy))
}
// processRequest - processes incoming requests and based on proxy state (record/playback)
// returns HTTP response.
func (d *DBClient) processRequest(req *http.Request) (*http.Request, *http.Response) {
if AppConfig.mode == CaptureMode {
log.Info("*** Capture ***")
newResponse, err := d.captureRequest(req)
if err != nil {
// something bad happened, passing through
return req, nil
} else {
// discarding original requests and returns supplied response
return req, newResponse
}
} else if AppConfig.mode == SynthesizeMode {
log.Info("*** Sinthesize ***")
response := synthesizeResponse(req, AppConfig.middleware)
return req, response
} else if AppConfig.mode == ModifyMode {
log.Info("*** Modify ***")
response, err := d.modifyRequestResponse(req, AppConfig.middleware)
if err != nil {
log.WithFields(log.Fields{
"error": err.Error(),
"middleware": AppConfig.middleware,
}).Error("Got error when performing request modification")
return req, nil
}
// returning modified response
return req, response
} else {
log.Info("*** Virtualize ***")
newResponse := d.getResponse(req)
return req, newResponse
}
}