forked from txtdirect/txtdirect
-
Notifications
You must be signed in to change notification settings - Fork 0
/
path.go
376 lines (323 loc) · 10.8 KB
/
path.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
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
/*
Copyright 2019 - The TXTDirect Authors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package txtdirect
import (
"context"
"fmt"
"log"
"net/http"
"reflect"
"regexp"
"sort"
"strconv"
"strings"
"time"
)
// Path contains the data that are needed to redirect path requests
type Path struct {
rw http.ResponseWriter
req *http.Request
c Config
path string
rec Record
}
// RegexRecord holds the TXT record and re= field of a predefined regex record
type RegexRecord struct {
Position int
TXT string
Regex string
Submatches []string
}
// PathRegex is the default regex to parse request's path
// It can be replaced using the re= field in the records
var PathRegex = regexp.MustCompile("\\/([A-Za-z0-9-._~!$'()*+,;=:@]+)")
// FromRegex parses the from= field
var FromRegex = regexp.MustCompile("\\/\\$(\\d+)")
// GroupRegex parses the re= field to find the regex groups
var GroupRegex = regexp.MustCompile("P<[a-zA-Z]+[a-zA-Z0-9]*>")
// GroupOrderRegex finds the order of regex groups inside re=
var GroupOrderRegex = regexp.MustCompile("P<([a-zA-Z]+[a-zA-Z0-9]*)>")
// NewPath returns an instance of Path struct using the given data
func NewPath(w http.ResponseWriter, r *http.Request, path string, rec Record, c Config) *Path {
return &Path{
rw: w,
req: r,
path: path,
rec: rec,
c: c,
}
}
// Redirect finds and returns the final record
func (p *Path) Redirect() *Record {
zone, from, pathSlice, err := zoneFromPath(p.req, p.rec)
rec, err := getFinalRecord(zone, from, p.c, p.rw, p.req, pathSlice)
*p.req = *rec.addToContext(p.req)
if err != nil {
log.Print("Fallback is triggered because an error has occurred: ", err)
fallback(p.rw, p.req, "to", p.rec.Code, p.c)
return nil
}
if rec.Type == "path" {
if last := p.lastPathRecord(); last != nil && reflect.DeepEqual(rec, *last) {
if rec.Code == http.StatusMovedPermanently {
p.rw.Header().Add("Cache-Control", fmt.Sprintf("max-age=%d", Status301CacheAge))
}
http.Redirect(p.rw, p.req, rec.To, rec.Code)
return nil
}
p.rec = rec
return p.Redirect()
}
return &rec
}
// RedirectRoot redirects the request to record's root= field
// if the path is empty or "/". If the root= field is empty too
// fallback will be triggered.
func (p *Path) RedirectRoot() error {
if p.rec.Root == "" {
fallback(p.rw, p.req, "to", p.rec.Code, p.c)
return nil
}
log.Printf("[txtdirect]: %s > %s", UpstreamZone(p.req)+p.req.URL.Path, p.rec.Root)
if p.rec.Code == http.StatusMovedPermanently {
p.rw.Header().Add("Cache-Control", fmt.Sprintf("max-age=%d", Status301CacheAge))
}
p.rw.Header().Add("Status-Code", strconv.Itoa(p.rec.Code))
http.Redirect(p.rw, p.req, p.rec.Root, p.rec.Code)
return nil
}
// SpecificRecord finds the most specific match using the custom regexes from subzones
// It goes through all the custom regexes specified in each subzone and uses the
// most specific match to return the final record.
func (p *Path) SpecificRecord() (*Record, error) {
// Iterate subzones and parse the records
regexes, err := p.fetchRegexes()
if err != nil {
return nil, err
}
// Find the most specific regex
record, err := p.specificMatch(regexes)
if err != nil {
return nil, err
}
return record, nil
}
func (p *Path) specificMatch(regexes []RegexRecord) (*Record, error) {
var specificZone RegexRecord
// Run each regex on the path and list them in a map
for _, zone := range regexes {
// Compile the regex and find the path submatches
regex, err := regexp.Compile(zone.Regex)
if err != nil {
return nil, fmt.Errorf("Couldn't compile the regex: %s", err.Error())
}
matches := regex.FindAllStringSubmatch(p.path, -1)
if len(matches) == 0 {
continue
}
zone.Submatches = matches[0]
// Use the next regex if it has more matches
if len(zone.Submatches) > len(specificZone.Submatches) {
specificZone = zone
}
}
// Add the most specific match's path slice to the request context to use in placeholders
*p.req = *p.req.WithContext(context.WithValue(p.req.Context(), "regexMatches", specificZone.Submatches))
// Parse the specific regex record
var rec Record
var err error
if rec, err = ParseRecord(specificZone.TXT, p.rw, p.req, p.c); err != nil {
return nil, fmt.Errorf("Could not parse record: %s", err)
}
return &rec, nil
}
func (p *Path) fetchRegexes() ([]RegexRecord, error) {
regexes := []RegexRecord{}
for i, loop := 1, true; loop != false; i++ {
// Send a DNS query to each predefined regex record
txts, err := query(fmt.Sprintf("%d.%s", i, UpstreamZone(p.req)), p.req.Context(), p.c)
if err != nil && len(regexes) >= 1 {
break
}
if err != nil {
return nil, fmt.Errorf("Couldn't fetch the subzones for predefined regex: %s", err.Error())
}
// All predefined regex records should contain the re= field (even non-path records)
if !strings.Contains(txts[0], "re=") {
return nil, fmt.Errorf("Couldn't find the re= field in records: %s", err.Error())
}
// Extract the re= field from record and add it to the regex slice
regexes = append(regexes, RegexRecord{
Position: i,
TXT: txts[0],
Regex: strings.TrimPrefix(strings.Split(txts[0][strings.Index(txts[0], "re="):], ";")[0], "re="),
})
}
sort.Slice(regexes, func(i, j int) bool {
return regexes[i].Position < regexes[j].Position
})
return regexes, nil
}
// zoneFromPath generates a DNS zone with the given request's path and host
// It will use custom regex to parse the path if it's provided in
// the given record.
func zoneFromPath(r *http.Request, rec Record) (string, int, []string, error) {
path := r.URL.Path
// Only add request query to path if the custom regex needs it. Unless it
// might cause problems on custom regexes that don't need query to generate
// the zone
if strings.Contains(rec.Re, "?query") {
path = fmt.Sprintf("%s?%s", path, r.URL.RawQuery)
}
pathSubmatchs := PathRegex.FindAllStringSubmatch(path, -1)
// Use the custom regex to parse request's path
if rec.Re != "" {
// Compile the record regex and find path submatches
CustomRegex, err := regexp.Compile(rec.Re)
if err != nil {
log.Printf("<%s> [txtdirect]: the given regex doesn't work as expected: %s", time.Now().String(), rec.Re)
}
pathSubmatchs = CustomRegex.FindAllStringSubmatch(path, -1)
// Only generate the zone if the custom regex contains a group
if GroupRegex.MatchString(rec.Re) {
pathSlice := []string{}
unordered := make(map[string]string)
for _, item := range pathSubmatchs[0] {
pathSlice = append(pathSlice, item)
}
// Order the path slice using groups order in custom regex
order := GroupOrderRegex.FindAllStringSubmatch(rec.Re, -1)
for i, group := range order {
unordered[group[1]] = pathSlice[i+1]
}
url := sortMap(unordered)
*r = *r.WithContext(context.WithValue(r.Context(), "regexMatches", unordered))
url = normalize(url)
reverse(url)
from := len(pathSlice)
url = append(url, UpstreamZone(r))
url = append([]string{basezone}, url...)
return strings.Join(url, "."), from, pathSlice, nil
}
}
pathSlice := []string{}
for _, v := range pathSubmatchs {
pathSlice = append(pathSlice, v[1])
}
*r = *r.WithContext(context.WithValue(r.Context(), "regexMatches", pathSlice))
if len(pathSlice) < 1 && rec.Re != "" {
return "", 0, []string{}, fmt.Errorf("custom regex doesn't work on %s", path)
}
pathSlice = normalize(pathSlice)
from := len(pathSlice)
if rec.From != "" {
fromSubmatch := FromRegex.FindAllStringSubmatch(rec.From, -1)
if len(fromSubmatch) != len(pathSlice) {
return "", 0, []string{}, fmt.Errorf("length of path doesn't match with length of from= in record")
}
fromSlice := make(map[int]string)
for k, v := range fromSubmatch {
index, _ := strconv.Atoi(v[1])
fromSlice[index] = pathSlice[k]
}
keys := []int{}
for k := range fromSlice {
keys = append(keys, k)
}
if len(keys) != len(pathSlice) {
return "", 0, []string{}, fmt.Errorf("length of path doesn't match with length of from= in record")
}
generatedPath := []string{}
sort.Sort(sort.Reverse(sort.IntSlice(keys)))
for _, k := range keys {
generatedPath = append(generatedPath, fromSlice[k])
}
url := append(generatedPath, UpstreamZone(r))
url = append([]string{basezone}, url...)
return strings.Join(url, "."), from, pathSlice, nil
}
ps := pathSlice
reverse(pathSlice)
url := append(pathSlice, UpstreamZone(r))
url = append([]string{basezone}, url...)
return strings.Join(url, "."), from, ps, nil
}
// getFinalRecord finds the final TXT record for the given zone.
// It will try wildcards if the first zone return error
func getFinalRecord(zone string, from int, c Config, w http.ResponseWriter, r *http.Request, pathSlice []string) (Record, error) {
txts, err := query(zone, r.Context(), c)
if err != nil {
// if nothing found, jump into wildcards
for i := 1; i <= from && len(txts) == 0; i++ {
zoneSlice := strings.Split(zone, ".")
zoneSlice[i] = "_"
zone = strings.Join(zoneSlice, ".")
txts, err = query(zone, r.Context(), c)
}
}
if err != nil || len(txts) == 0 {
return Record{}, fmt.Errorf("could not get TXT record: %s", err)
}
txts[0], err = parsePlaceholders(txts[0], r, pathSlice)
var rec Record
if rec, err = ParseRecord(txts[0], w, r, c); err != nil {
return rec, fmt.Errorf("could not parse record: %s", err)
}
if rec.Type == "path" {
records := r.Context().Value("records").([]Record)
parent := records[len(records)-1]
// Use the parent's custom regex if available
if rec.Re == "" && parent.Re != "" {
rec.Re = parent.Re
}
return rec, nil
}
return rec, nil
}
// reverse reverses the order of the array
func reverse(input []string) {
last := len(input) - 1
for i := 0; i < len(input)/2; i++ {
input[i], input[last-i] = input[last-i], input[i]
}
}
func sortMap(m map[string]string) []string {
var keys []string
var result []string
for k := range m {
keys = append(keys, k)
}
sort.Strings(keys)
for _, k := range keys {
result = append(result, m[k])
}
return result
}
// Normalize the path to follow RFC1034 rules
func normalize(input []string) []string {
var result []string
for _, value := range input {
if strings.ContainsAny(value, ".") {
value = strings.Replace(value, ".", "-", -1)
}
result = append(result, value)
}
return result
}
func (p *Path) lastPathRecord() *Record {
records := p.req.Context().Value("records").([]Record)
if len(records) < 2 {
return nil
}
return &records[len(records)-1]
}