forked from 30x/libgozerian
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
349 lines (299 loc) · 7.55 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
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
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
package main
import (
"bytes"
"errors"
"flag"
"fmt"
"net"
"net/http"
"os"
"os/signal"
"strconv"
"syscall"
"unsafe"
)
/*
#include <stdlib.h>
*/
import "C"
const (
defaultHandlerID = "default"
)
var defaultHandlerName = C.CString(defaultHandlerID)
/*
* The weaver project is designed to build a shared library, not a "main."
* However, for testing purposes we can start it up as an executable which
* listens on an HTTP port.
* In this mode, it can either act in echo mode by returning what is sent,
* or it can act in proxy mode.
*/
type gozerianServer struct {
listener *net.TCPListener
target string
debug bool
}
/*
* Start the server listening on the specified HTTP port. If "proxyTarget"
* is empty, then echo back all requests. Otherwise, proxy to that URL.
* If "testHandler" is true, install a test handler for unit test purposes.
* If "port" is 0, then listen on an ephemeral port.
*/
func startGozerianServer(port int, proxyTarget, handlerURL string) (*gozerianServer, error) {
cURL := C.CString(handlerURL)
defer C.free(unsafe.Pointer(cURL))
errStr := GoCreateHandler(defaultHandlerName, cURL)
if errStr != nil {
defer C.free(errStr)
return nil, errors.New(C.GoString(errStr))
}
addr := net.TCPAddr{
Port: port,
}
listener, err := net.ListenTCP("tcp", &addr)
if err != nil {
return nil, err
}
svr := gozerianServer{
listener: listener,
target: proxyTarget,
}
return &svr, nil
}
func (s *gozerianServer) run() {
handler := weaverHandler{
target: s.target,
debug: s.debug,
}
http.Serve(s.listener, &handler)
}
func (s *gozerianServer) stop() {
s.listener.Close()
GoDestroyHandler(defaultHandlerName)
}
func (s *gozerianServer) setDebug(d bool) {
s.debug = d
}
func (s *gozerianServer) getPort() int {
_, port, err := net.SplitHostPort(s.listener.Addr().String())
if err != nil {
return 0
}
portNum, err := strconv.Atoi(port)
if err != nil {
return 0
}
return portNum
}
type weaverHandler struct {
target string
debug bool
}
func (m *weaverHandler) ServeHTTP(resp http.ResponseWriter, req *http.Request) {
defer req.Body.Close()
// Although we have nice Go ways to call all these internal functions,
// use the public C API so that we can get good test coverage.
id := GoCreateRequest(defaultHandlerName)
defer GoFreeRequest(id)
rid := GoCreateResponse(defaultHandlerName)
defer GoFreeResponse(rid)
requestBody := &bytes.Buffer{}
done := m.processRequest(resp, req, id, rid, requestBody)
if !done {
m.processResponse(resp, req, id, rid, requestBody)
}
}
func (m *weaverHandler) processRequest(
resp http.ResponseWriter, req *http.Request,
id, rid uint32, requestBody *bytes.Buffer) bool {
reqHdrs := &bytes.Buffer{}
fmt.Fprintf(reqHdrs, "%s %s HTTP/1.1\r\n", req.Method, req.URL.Path)
req.Header.Write(reqHdrs)
cReqHdrs := C.CString(reqHdrs.String())
defer C.free(unsafe.Pointer(cReqHdrs))
GoBeginRequest(id, cReqHdrs)
var cmd string
proxying := true
writingRequest := false
responseCode := http.StatusOK
proxyHeaders := req.Header
//proxyPath := req.URL.Path
sentHeaders := false
for cmd != cmdDone && cmd != cmdErrr {
rawCmd := GoPollRequest(id, 1)
cmdBuf := C.GoString(rawCmd)
C.free(unsafe.Pointer(rawCmd))
cmd = cmdBuf[:4]
msg := cmdBuf[4:]
if m.debug {
fmt.Printf("Command: \"%s\"\n", cmd)
}
switch cmd {
case cmdErrr:
resp.WriteHeader(http.StatusInternalServerError)
resp.Write([]byte(msg))
return true
case cmdRbod:
requestBody.ReadFrom(req.Body)
ptr, len := sliceToPtr(requestBody.Bytes())
GoSendRequestBodyChunk(id, 1, ptr, len)
C.free(ptr)
case cmdWhdr:
if proxying {
parseHeaders(proxyHeaders, msg)
} else {
parseHeaders(resp.Header(), msg)
}
case cmdWURI:
//proxyPath = msg
case cmdWbod:
chunk := getChunkData(msg)
if proxying {
if !writingRequest {
requestBody.Reset()
writingRequest = true
}
requestBody.Write(chunk)
} else {
if !sentHeaders {
resp.WriteHeader(responseCode)
sentHeaders = true
}
resp.Write(chunk)
}
case cmdSwch:
proxying = false
responseCode, _ = strconv.Atoi(msg)
case cmdDone:
default:
sendHTTPError(fmt.Errorf("Unexpected command %s", cmd), resp)
return true
}
}
if !proxying {
// Request path decided immediately to send a response
if !sentHeaders {
resp.WriteHeader(responseCode)
}
return true
}
if requestBody.Len() == 0 {
requestBody.ReadFrom(req.Body)
}
return false
}
func (m *weaverHandler) processResponse(
resp http.ResponseWriter, req *http.Request,
id, rid uint32, requestBody *bytes.Buffer) {
// TODO in target proxy mode, actually get target headers
respHdrs := &bytes.Buffer{}
respHdrs.WriteString("Server: Weaver Test Main\r\n")
cRespHdrs := C.CString(respHdrs.String())
defer C.free(unsafe.Pointer(cRespHdrs))
GoBeginResponse(rid, id, http.StatusOK, cRespHdrs)
var cmd string
responseCode := http.StatusOK
sentHeaders := false
wroteBody := false
for cmd != cmdDone && cmd != cmdErrr {
rawCmd := GoPollResponse(rid, 1)
cmdBuf := C.GoString(rawCmd)
C.free(unsafe.Pointer(rawCmd))
cmd = cmdBuf[:4]
msg := cmdBuf[4:]
if m.debug {
fmt.Printf("Command: \"%s\"\n", cmd)
}
switch cmd {
case cmdErrr:
resp.WriteHeader(http.StatusInternalServerError)
resp.Write([]byte(msg))
return
case cmdWsta, cmdSwch:
responseCode, _ = strconv.Atoi(msg)
case cmdWhdr:
parseHeaders(resp.Header(), msg)
case cmdRbod:
ptr, len := sliceToPtr(requestBody.Bytes())
GoSendResponseBodyChunk(rid, 1, ptr, len)
C.free(ptr)
case cmdWbod:
if !sentHeaders {
resp.WriteHeader(responseCode)
sentHeaders = true
}
chunk := getChunkData(msg)
wroteBody = true
resp.Write(chunk)
case cmdDone:
default:
sendHTTPError(fmt.Errorf("Unexpected command %s", cmd), resp)
}
}
if m.target == "" {
// Pretend that we are a proxy for another server by echoing the request
if !sentHeaders {
resp.WriteHeader(http.StatusOK)
}
if !wroteBody {
requestBody.WriteTo(resp)
}
} else {
sendHTTPError(fmt.Errorf("Didn't implement proxying to target yet"), resp)
}
}
func getChunkData(rawID string) []byte {
id, err := strconv.ParseInt(rawID, 16, 32)
if err != nil {
return nil
}
return getChunkDataByID(int32(id))
}
func getChunkDataByID(id int32) []byte {
ptr := GoGetChunk(id)
len := GoGetChunkLength(id)
buf := C.GoBytes(ptr, C.int(len))
GoReleaseChunk(int32(id))
C.free(ptr)
return buf
}
func sendHTTPError(err error, resp http.ResponseWriter) {
fmt.Printf("Error: %s\n", err.Error())
resp.Header().Set("Content-Type", "text/plain")
resp.WriteHeader(http.StatusInternalServerError)
resp.Write([]byte(err.Error()))
}
func main() {
var port int
var target string
var testHandler bool
var handlerURI string
flag.IntVar(&port, "p", 0, "(required) Port to listen on")
flag.StringVar(&target, "u", "", "(optional) Target proxy URL")
flag.StringVar(&handlerURI, "h", "", "(optional) URL of handler to create")
flag.BoolVar(&testHandler, "t", false, "(optional) Install a set of test handlers")
flag.Parse()
if !flag.Parsed() {
flag.PrintDefaults()
os.Exit(2)
}
if testHandler {
handlerURI = TestHandlerURI
}
server, err := startGozerianServer(port, target, handlerURI)
if err != nil {
fmt.Printf("Cannot start server: %s\n", err)
os.Exit(3)
}
fmt.Printf("Listening on port %d\n", server.getPort())
doneChan := make(chan bool, 1)
signalChan := make(chan os.Signal, 1)
signal.Notify(signalChan, syscall.SIGINT)
signal.Notify(signalChan, syscall.SIGTERM)
go func() {
<-signalChan
doneChan <- true
}()
go server.run()
<-doneChan
server.stop()
}