-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathswitch.go
More file actions
194 lines (181 loc) · 4.81 KB
/
switch.go
File metadata and controls
194 lines (181 loc) · 4.81 KB
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
// Copyright 2021 - 2023 PurpleSec Team
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published
// by the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <https://www.gnu.org/licenses/>.
//
package switchproxy
import (
"context"
"errors"
"io"
"net"
"net/http"
"net/url"
"path"
"strings"
"time"
// Import unsafe to use "fastrand" function
_ "unsafe"
)
const table = "0123456789ABCDEF"
// Result is a struct that contains the data of the resulting Switch
// operation to be passed to Handlers.
type Result struct {
Headers http.Header `json:"headers"`
IP string `json:"ip"`
UUID string `json:"uuid"`
Path string `json:"path"`
Method string `json:"method"`
URL string `json:"url"`
Content []byte `json:"content"`
Status uint16 `json:"status"`
}
// Switch is a struct that represents a connection between proxy services.
// This struct contains mapping and functions to capture input and output.
type Switch struct {
Pre Handler
Post Handler
client *http.Client
rewrite map[string]string
url.URL
timeout time.Duration
}
// Handler is a function alias that can be passed a Result for processing.
type Handler func(Result)
//go:linkname fastRand runtime.fastrand
func fastRand() uint32
func newUUID() string {
var b [64]byte
for i := 0; i < 64; i += 2 {
v := byte(fastRand() & 0xFF)
if v < 16 {
b[i], b[i+1] = '0', table[v&0x0F]
}
b[i], b[i+1] = table[v>>4], table[v&0x0F]
}
return string(b[:])
}
// IsResponse is a function that returns true if the Result is for a response.
func (r Result) IsResponse() bool {
return len(r.Method) > 0 && r.Status > 0
}
// Rewrite adds a URL rewrite from the Switch.
//
// If a URL starts with the 'from' parameter, it will be replaced with the 'to'
// parameter, only if starting with on the URL path.
func (s *Switch) Rewrite(from, to string) {
s.rewrite[from] = to
}
// RemoveRewrite removes the URL rewrite from the Switch.
func (s *Switch) RemoveRewrite(from string) {
delete(s.rewrite, from)
}
// NewSwitch creates a switching context that allows the connection to be proxied
// to the specified server.
func NewSwitch(target string) (*Switch, error) {
return NewSwitchTimeout(target, DefaultTimeout)
}
// NewSwitchTimeout creates a switching context that allows the connection to be
// proxied to the specified server.
//
// This function will set the specified timeout.
func NewSwitchTimeout(target string, t time.Duration) (*Switch, error) {
u, err := url.Parse(target)
if err != nil {
return nil, errors.New("unable to resolve URL: " + err.Error())
}
if !u.IsAbs() {
u.Scheme = "http"
}
s := &Switch{
URL: *u,
client: &http.Client{
Timeout: t,
Transport: &http.Transport{
Proxy: http.ProxyFromEnvironment,
DialContext: (&net.Dialer{
Timeout: t,
KeepAlive: t,
}).DialContext,
IdleConnTimeout: t,
TLSHandshakeTimeout: t,
ExpectContinueTimeout: t,
ResponseHeaderTimeout: t,
},
},
timeout: t,
rewrite: make(map[string]string),
}
return s, nil
}
func (s Switch) process(x context.Context, r *http.Request, t *transfer) (int, http.Header, error) {
s.Path = r.URL.Path
s.User = r.URL.User
s.Opaque = r.URL.Opaque
s.Fragment = r.URL.Fragment
s.RawQuery = r.URL.RawQuery
s.ForceQuery = r.URL.ForceQuery
for k, v := range s.rewrite {
if strings.HasPrefix(s.Path, k) {
s.Path = path.Join(v, s.Path[len(k):])
}
}
f := func() {}
if s.timeout > 0 {
x, f = context.WithTimeout(x, s.timeout)
}
q, err := http.NewRequestWithContext(x, r.Method, s.String(), t.in)
if err != nil {
f()
return 0, nil, err
}
u := newUUID()
if s.Pre != nil {
s.Pre(Result{
IP: r.RemoteAddr,
URL: s.String(),
UUID: u,
Path: s.Path,
Method: r.Method,
Content: t.data,
Headers: r.Header,
})
}
q.Header, q.Trailer = r.Header, r.Trailer
q.TransferEncoding = r.TransferEncoding
o, err := s.client.Do(q)
if err != nil {
f()
return 0, nil, err
}
if _, err := io.Copy(t.out, o.Body); err != nil {
f()
o.Body.Close()
return 0, nil, err
}
if s.Post != nil {
s.Post(Result{
IP: r.RemoteAddr,
URL: s.String(),
Path: s.Path,
UUID: u,
Status: uint16(o.StatusCode),
Method: r.Method,
Content: t.out.Bytes(),
Headers: o.Header,
})
}
f()
o.Body.Close()
return o.StatusCode, o.Header, nil
}