forked from UnifiedPush/common-proxies
-
Notifications
You must be signed in to change notification settings - Fork 0
/
handler.go
216 lines (179 loc) · 4.96 KB
/
handler.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
package main
import (
"errors"
"io"
"io/ioutil"
"log"
"net/http"
"strconv"
"time"
phttp "github.com/hakobe/paranoidhttp"
"github.com/karmanyaahm/up_rewrite/config"
. "github.com/karmanyaahm/up_rewrite/config"
"github.com/karmanyaahm/up_rewrite/utils"
)
var normalClient *http.Client
var paranoidClient *http.Client
func init() {
paranoidClient, _, _ = phttp.NewClient()
paranoidClient.Timeout = 10 * time.Second
paranoidClient.CheckRedirect = func(_ *http.Request, _ []*http.Request) error {
return errors.New("NO redir")
}
normalClient = &http.Client{
CheckRedirect: func(_ *http.Request, _ []*http.Request) error {
return errors.New("NO redir")
},
Timeout: 2 * time.Second,
}
}
// function that runs on (almost) every http request
func bothHandler(f HttpHandler) HttpHandler {
return func(w http.ResponseWriter, r *http.Request) {
ConfigLock.RLock()
defer ConfigLock.RUnlock()
f(w, r)
}
}
func gatewayHandler(h Gateway) HttpHandler {
return func(w http.ResponseWriter, r *http.Request) {
var (
nread int
nwritten int64
respType string
reqs []*http.Request
)
topHandler:
switch r.Method {
case http.MethodGet:
w.Write(h.Get())
case http.MethodPost:
body, err := ioutil.ReadAll(io.LimitReader(r.Body, config.Config.MaxUPSize*2)) //gateways contain more than just UP stuff, so extra to be safe
r.Body.Close()
nread = len(body)
reqs, err = h.Req(body, *r)
if err != nil {
errHandle(err, w)
respType = "err"
break
}
resps := make([]*http.Response, len(reqs))
for i, req := range reqs {
nwritten += req.ContentLength
req.Header.Add("User-Agent", Config.GetUserAgent())
thisClient := paranoidClient
if utils.InStringSlice(config.Config.Gateway.AllowedHosts, req.URL.Host) {
thisClient = normalClient
}
if !CheckIfRewriteProxy(req.URL.String(), thisClient) {
errHandle(utils.NewProxyErrS(403, "Target is not a UP Server"), w)
respType = "err, not UP endpoint"
break topHandler
}
resps[i], err = thisClient.Do(req)
if err != nil {
resps[i] = nil
log.Println(err)
}
}
//process resp
h.Resp(resps, w)
respType = "forward"
default:
w.WriteHeader(http.StatusMethodNotAllowed)
respType = strconv.Itoa(http.StatusMethodNotAllowed)
}
prints := []interface{}{r.Method, r.URL.Path, r.RemoteAddr, nread, "bytes read;", nwritten, "bytes written;", r.UserAgent(), respType, ";"}
if Config.Verbose {
hosts := []interface{}{}
for _, i := range reqs {
hosts = append(hosts, i.Host)
}
prints = append(prints, hosts...)
}
log.Println(prints...)
return
}
}
func proxyHandler(h Proxy) HttpHandler {
versionWrite := versionHandler()
return func(w http.ResponseWriter, r *http.Request) {
var nread, code int = 0, 200
var respType string
switch r.Method {
case http.MethodGet:
versionWrite(w)
case http.MethodPost:
body, err := ioutil.ReadAll(io.LimitReader(r.Body, config.Config.MaxUPSize+1))
r.Body.Close()
// Read one extra above to be able to tell whether the request body exceeds or not here
nread = len(body)
if nread > int(config.Config.MaxUPSize) {
code = http.StatusRequestEntityTooLarge
break
}
reqs, err := h.Req(body, *r)
if errHandle(err, w) {
respType = "err"
break
}
var resp *http.Response
for _, req := range reqs {
resp, err = normalClient.Do(req)
if errHandle(err, w) {
respType = "err"
break
}
resperr := h.RespCode(resp)
code = utils.Max(code, resperr.Code)
if errHandle(err, w) {
respType = "err"
break
}
// logic here is that bigger code is worse and should be returned. If one request was ok (200) but one failed (400-500s), the larger one should be returned. It's not perfect, but 🤷
//read upto 4000 to be able to reuse conn then close
// this 4000 is arbritary and not related to the size limit
ioutil.ReadAll(io.LimitReader(r.Body, 4000))
resp.Body.Close()
}
respType = "forward"
default:
code = http.StatusMethodNotAllowed
respType = "method not allowed"
}
w.WriteHeader(code)
w.Header().Add("TTL", "0")
log.Println(r.Method, r.Host, r.URL.Path, r.RemoteAddr, nread, "bytes read;", r.UserAgent(), respType, code)
return
}
}
func errHandle(e error, w http.ResponseWriter) bool {
if e != nil {
if err, ok := e.(*utils.ProxyError); ok && (err.S.Error() != "") {
logV(err.Code, err.S.Error())
w.WriteHeader(err.Code)
return true
} else if e.Error() == "length" {
logV("Too long request")
w.WriteHeader(http.StatusRequestEntityTooLarge)
return true
} else if e.Error() == "Gateway URL" {
logV("Unknown URL to forward Gateway request to")
w.WriteHeader(http.StatusBadRequest)
return true
} else {
if Config.Verbose {
log.Print("panic-ish: ")
log.Println(e)
}
w.WriteHeader(http.StatusBadGateway)
return true
}
}
return false
}
func logV(args ...interface{}) {
if Config.Verbose {
log.Println(args...)
}
}