-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
322 lines (286 loc) · 7.99 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
package main
import (
"bytes"
"os"
"strings"
"time"
// "encoding/json"
"fmt"
"log"
"net"
"strconv"
"gopkg.in/yaml.v3"
)
func main() {
appConfig := GetAppConfig()
log.Println("config loaded")
port := 8888
addr := net.TCPAddr{
Port: port,
}
log.Printf("Listening on port %d", port)
listener, err := net.ListenTCP("tcp", &addr)
if err != nil {
log.Fatalln(err)
}
for {
conn, err := listener.Accept()
if err != nil {
log.Printf("Accept Error: %s \n", err)
}
log.Printf("Accepting connection: %s", conn.RemoteAddr())
go HandleConn(conn,appConfig)
}
}
type IncomingBuffer struct {
Offset uint16
Buffer []byte
}
func HandleConn(client net.Conn,app *AppConfig) {
now := time.Now()
defer func() {
log.Printf("Finished processing upstream request: %dms",time.Now().Sub(now).Milliseconds())
client.Close()
}()
//<shared>
var endOfFirstLine bool
data := make([]byte, 0)
bufferChan := make(chan IncomingBuffer)
endOfIncomingBufferStream := make(chan struct{},1)
clientHTTPInfo := &ClientRequestInfo{}
//<shared/>
//<upstream>
now = time.Now()
upstream, err := net.Dial("tcp", app.MirrorConfig.UpstreamAddr)
if err != nil {
log.Printf("Failed to connect to upstream: %s", err)
return
}
log.Printf("Connected to upstream. Time Taken: %dms",time.Now().Sub(now).Milliseconds())
//<upstream/>
//
// //<mirror>
go func() {
mirror, err := net.Dial("tcp", app.MirrorConfig.MirrorAddr)
if err != nil {
log.Printf("Failed to connect to upstream: %s", err)
return
}
cur := time.Now()
defer func() {
log.Printf("Finished processing mirror request: %dms",time.Now().Sub(cur).Milliseconds())
}()
log.Println("Connected to mirror")
uriModified := false
// bufferedData := []byte{}
select {
case buffer := <-bufferChan:
if clientHTTPInfo.Uri != "" && !uriModified {
for idx, buf := range buffer.Buffer {
// search for first \r and swap uri in the mirror
// possible error if first buffer does not contain the complete first line
if buf == '\r' {
if _, ok := app.MirrorConfig.URIMapping[clientHTTPInfo.Uri]; !ok {
// true since we dont need to modify & dont want this loop to run again
uriModified = true
break
}
// swapping uri
finalURI := app.MirrorConfig.URIMapping[clientHTTPInfo.Uri]
// log.Printf("Swapping URI for mirror prev:%s final: %s",clientHTTPInfo.Uri,finalURI)
// adjust offset according to the uri length diff
if uriLengthDiff := len([]byte(finalURI)) - len([]byte(clientHTTPInfo.Uri)); uriLengthDiff < 0 {
buffer.Offset -= uint16(-uriLengthDiff)
}else {
buffer.Offset += uint16(uriLengthDiff)
}
clientHTTPInfo.Uri = finalURI
endOfRequestLine := buffer.Buffer[idx:]
// log.Printf("after r: %s",string(endOfRequestLine))
requestLine := []byte(clientHTTPInfo.IntoRequest())
requestLine = append(requestLine,endOfRequestLine...)
uriModified = true
buffer.Buffer = requestLine
break
}
}
}
// log.Println(string(buffer.Buffer))
mirror.Write(buffer.Buffer[:buffer.Offset])
case <-endOfIncomingBufferStream:
log.Println("Finished reading client incoming buffer")
break
default:
}
for {
buffer := make([]byte, 1024)
_, err := mirror.Read(buffer)
if err != nil {
if err.Error() == "EOF" {
log.Println("Mirror Connection closed")
break
}
log.Printf("Mirror Error reading: %s", err)
break
}
}
}()
//<mirror/>
contentLength := 0
var endOfHeaders bool
headerEndIdx := 0
outer:
for {
buffer := make([]byte, 1024)
offset, err := client.Read(buffer)
if err != nil {
if err.Error() == "EOF" {
log.Println("Connection closed")
return
}
log.Printf("Error reading: %s", err)
break
}
if offset <= 0 {
continue
}
data = append(data, buffer[:offset]...)
if !endOfFirstLine {
for idx, b := range data {
if b == '\r' &&
len(data[idx:]) >= 2 &&
data[idx+1] == '\n' {
endOfFirstLine = true
}
}
}
// Extract URI & Request Method from first line
// yes i know i could used strings.Split
if endOfFirstLine && clientHTTPInfo.Method == "" {
prevWhiteSpaceIdx := 0
for i := 0; i <= len(data)-1; i++ {
if data[i] == ' ' && clientHTTPInfo.Method == "" {
clientHTTPInfo.Method = string(data[:i])
prevWhiteSpaceIdx = i
continue
}
if data[i] == ' ' &&
clientHTTPInfo.Method != "" &&
clientHTTPInfo.Uri == "" {
clientHTTPInfo.Uri = string(data[prevWhiteSpaceIdx+1 : i])
break
}
}
}
if !endOfHeaders && clientHTTPInfo.Method != "GET" {
headerEndIdx = bytes.Index(data, []byte("\r\n\r\n"))
if headerEndIdx != -1 {
endOfHeaders = true
}
// pushing index to actual end of header
headerEndIdx += 4
// if finished reading headers then search for contentLength value
if endOfHeaders && contentLength == 0 {
contentLengthHeader := "Content-Length: "
contentLengthHeaderKeyLength := len(contentLengthHeader)
// content length index
clIdx := bytes.Index(data[:headerEndIdx], []byte(contentLengthHeader))
if clIdx == -1 {
//write error message here for no content length header so invalid http request
log.Fatalln("invalid request, header 'Content-Length' not found")
}
begginningIdx := clIdx + contentLengthHeaderKeyLength
for idx, b := range data[begginningIdx:headerEndIdx] {
if b == '\r' {
log.Printf("reached end of content length, value: %s", string(data[begginningIdx:begginningIdx+idx]))
length, err := strconv.Atoi(string(data[begginningIdx : begginningIdx+idx]))
if err != nil {
//write error message here for no content length header so invalid http request
log.Fatalln("invalid request, failed to parse content length value to int")
}
contentLength = length
break
}
}
}
}
// send this buffer to this channels the mirror can send request too
bufferChan <- IncomingBuffer {
Buffer: buffer,
Offset: uint16(offset),
}
upstream.Write(buffer[:offset])
log.Printf("Writing \n%s",string(buffer[:offset]))
// checking if content length vaue matches the length after \r\n\r\n
if contentLength != 0 && len(data[headerEndIdx:]) == contentLength {
endOfIncomingBufferStream <- struct {}{}
for {
upstreamBuffer := make([]byte, 1024)
upstreamOffset, err := upstream.Read(upstreamBuffer)
if err != nil {
if err.Error() == "EOF" {
upstream.Close()
log.Println("Connection closed with upstream")
break outer
}
log.Printf("Error reading: %s", err)
break
}
if upstreamOffset > 0 {
log.Printf("read %d bytes",upstreamOffset)
// break
_, err := client.Write(upstreamBuffer[:upstreamOffset])
// if err != nil {
// break outer
// }
if err != nil {
log.Println("Client connection closed")
break outer
}
log.Printf("Error reading: %s", err)
break
}
}
break
}
}
return
// log.Println(string(data))
// clientJSONHttpInfo, _ := json.MarshalIndent(&clientHTTPInfo, " ", " ")
// log.Println(string(clientJSONHttpInfo))
}
func GetAppConfig() *AppConfig {
configPath := ""
for _, arg := range os.Args {
if strings.Contains(arg,"--config=") {
configPath = strings.Split(arg,"=")[1]
}
}
if configPath == "" {
log.Fatalln("Provide config file path. Example: --config=<file-path>")
}
fileBuffer, err := os.ReadFile(configPath)
if err != nil {
log.Fatalln(err)
}
appConfig := &AppConfig{}
if err := yaml.Unmarshal(fileBuffer,&appConfig); err != nil {
log.Fatalln(err)
}
return appConfig
}
type ClientRequestInfo struct {
Method string
Uri string
}
func (r ClientRequestInfo) IntoRequest() string {
return fmt.Sprintf("%s %s HTTP/1.1", r.Method, r.Uri)
}
type AppConfig struct {
MirrorConfig MirrorConfig `yaml:"mirror_config"`
}
type MirrorConfig struct {
UpstreamAddr string `yaml:"upstream_addr"`
MirrorAddr string `yaml:"mirror_addr"`
URIMapping map[string]string `yaml:"uri_mapping"`
}