-
Notifications
You must be signed in to change notification settings - Fork 11
/
handler.go
284 lines (248 loc) · 7.53 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
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
package main
import (
"errors"
"io"
"log"
"net"
"net/http"
"strconv"
"time"
phttp "github.com/hakobe/paranoidhttp"
"codeberg.org/UnifiedPush/common-proxies/config"
. "codeberg.org/UnifiedPush/common-proxies/config"
"codeberg.org/UnifiedPush/common-proxies/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
)
switch r.Method {
case http.MethodGet:
w.Write(h.Get())
case http.MethodPost:
body, err := io.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
url := req.URL
req.Header.Add("User-Agent", Config.GetUserAgent())
thisClient := paranoidClient
if utils.InStringSlice(config.Config.Gateway.AllowedHosts, req.URL.Host) {
thisClient = normalClient
}
cacheStatus := getEndpointStatus(url)
if cacheStatus == Refused {
log.Println("handler: req to", req.Host, ", URL is cached as refused")
resps[i] = &http.Response{
StatusCode: 404,
Request: req,
}
} else if cacheStatus == TemporaryUnavailable {
log.Println("handler: req to", req.Host, ", URL is cached as temp unavailable")
resps[i] = &http.Response{
StatusCode: 429,
Request: req,
}
} else {
resps[i], err = thisClient.Do(req)
if err != nil {
var netErr net.Error
var dnsErr *net.DNSError
switch {
case errors.As(err, &dnsErr):
// This is a workaround to make the tests work with woodpecker
if dnsErr.IsNotFound || req.URL.Host == "doesnotexist.unifiedpush.org" {
log.Println("handler: req to", req.Host, ", caching URL as refused (Domain not found)")
resps[i] = &http.Response{
StatusCode: 404,
Request: req,
}
setHostStatus(url, Refused)
} else {
log.Println("handler: req to", req.Host, ", caching URL as temp unavailable. DNSError:", dnsErr)
resps[i] = &http.Response{
StatusCode: 429,
Request: req,
}
setHostStatus(url, TemporaryUnavailable)
}
case errors.As(err, &netErr) && netErr.Timeout():
log.Println("handler: req to", req.Host, ", caching URL as temp unavailable (Timeout error)")
resps[i] = &http.Response{
StatusCode: 429,
Request: req,
}
setHostStatus(url, TemporaryUnavailable)
default:
// This can be:
// - unsupported protocol
// - bad ip
// - invalid tls certif
log.Println("handler: req to", req.Host, ", caching URL as refused. Err:", err)
resps[i] = &http.Response{
StatusCode: 404,
Request: req,
}
setHostStatus(url, Refused)
}
} else {
sc := resps[i].StatusCode
switch {
case sc == 404:
log.Println("handler: req to", req.Host, ", caching URL as refused (Status= 404)")
setEndpointStatus(url, Refused)
case sc == 429:
log.Println("handler: req to", req.Host, ", caching URL as temp unavailable (Status= 429)")
setEndpointStatus(url, TemporaryUnavailable)
case sc == 413:
log.Println("handler: req to", req.Host, ", Request was too long (Status= 413)")
// ntfy does not return 201
case sc == 201 || sc == 200:
// DO nothing
case sc > 499:
log.Println("handler: req to", req.Host, ", caching URL as temp unavailable (Status=", sc, ")")
setEndpointStatus(url, TemporaryUnavailable)
default:
log.Println("handler: req to", req.Host, ", caching URL as refused. Unexpected status code. (Status=", sc, ")")
resps[i].StatusCode = 404
setEndpointStatus(url, Refused)
}
}
}
}
//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 := io.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
io.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...)
}
}