|
| 1 | +package main |
| 2 | + |
| 3 | +import ( |
| 4 | + "bytes" |
| 5 | + "io" |
| 6 | + "log" |
| 7 | + "regexp" |
| 8 | + "sync" |
| 9 | + |
| 10 | + "github.com/gofiber/fiber/v2/utils" |
| 11 | +) |
| 12 | + |
| 13 | +// TODO ReplaceRegexReader |
| 14 | + |
| 15 | +// TODO test Large characters |
| 16 | +const URLRegexp = `(\/\/([A-Za-z0-9]+(-[a-z0-9]+)*\.)+(arpa|root|aero|biz|cat|com|coop|edu|gov|info|int|jobs|mil|mobi|museum|name|net|org|pro|tel|travel|ac|ad|ae|af|ag|ai|al|am|an|ao|aq|ar|as|at|au|aw|ax|az|ba|bb|bd|be|bf|bg|bh|bi|bj|bm|bn|bo|br|bs|bt|bv|bw|by|bz|ca|cc|cd|cf|cg|ch|ci|ck|cl|cm|cn|co|cr|cu|cv|cx|cy|cz|dev|de|dj|dk|dm|do|dz|ec|ee|eg|er|es|et|eu|fi|fj|fk|fm|fo|fr|ga|gb|gd|ge|gf|gg|gh|gi|gl|gm|gn|gp|gq|gr|gs|gt|gu|gw|gy|hk|hm|hn|hr|ht|hu|id|ie|il|im|in|io|iq|ir|is|it|je|jm|jo|jp|ke|kg|kh|ki|km|kn|kr|kw|ky|kz|la|lb|lc|li|lk|lr|ls|lt|lu|lv|ly|ma|mc|md|mg|mh|mk|ml|mm|mn|mo|mp|mq|mr|ms|mt|mu|mv|mw|mx|my|mz|na|nc|ne|nf|ng|ni|nl|no|np|nr|nu|nz|om|pa|pe|pf|pg|ph|pk|pl|pm|pn|pr|ps|pt|pw|py|qa|re|ro|ru|rw|sa|sb|sc|sd|se|sg|sh|si|sj|sk|sl|sm|sn|so|sr|st|su|sv|sy|sz|tc|td|tf|tg|th|tj|tk|tl|tm|tn|to|tp|tr|tt|tv|tw|tz|ua|ug|uk|um|us|uy|uz|va|vc|ve|vg|vi|vn|vu|wf|ws|ye|yt|yu|za|zm|zw))` |
| 17 | +const PartialURLRegexp = `(\/(\/([A-Za-z0-9]+(-[A-Za-z0-9])*)?)?$)` |
| 18 | + |
| 19 | +var ( |
| 20 | + urlRegexp = regexp.MustCompile(URLRegexp) |
| 21 | + partialURLRegexp = regexp.MustCompile(PartialURLRegexp) |
| 22 | + buffPool = newBufferPool() |
| 23 | +) |
| 24 | + |
| 25 | +type BufferPool struct { |
| 26 | + pool sync.Pool |
| 27 | +} |
| 28 | + |
| 29 | +func newBufferPool() *BufferPool { |
| 30 | + return &BufferPool{ |
| 31 | + pool: sync.Pool{ |
| 32 | + New: func() interface{} { |
| 33 | + return new(bytes.Buffer) |
| 34 | + }, |
| 35 | + }, |
| 36 | + } |
| 37 | +} |
| 38 | + |
| 39 | +func (p *BufferPool) Get() *bytes.Buffer { |
| 40 | + return p.pool.Get().(*bytes.Buffer) |
| 41 | +} |
| 42 | + |
| 43 | +func (p *BufferPool) Put(buff *bytes.Buffer) { |
| 44 | + buff.Reset() |
| 45 | + p.pool.Put(buff) |
| 46 | +} |
| 47 | + |
| 48 | +type RegexProcessor interface { |
| 49 | + // Process reads next n bytes from r into the buff, processes it and writes into w. |
| 50 | + // Returns io.EOF when no more input is available. It discards bytes from the buffer |
| 51 | + // that were written to w. |
| 52 | + Process(w io.Writer, r io.Reader, n int, buff *bytes.Buffer) error |
| 53 | + // ProcessAll reads all bytes from r, processes it and writes into w. |
| 54 | + // A successful ProcessAll returns err == nil, not err == io.EOF. |
| 55 | + // Because ProcessAll is defined to read from src until EOF, |
| 56 | + // it does not treat an EOF from Read as an error to be reported. |
| 57 | + ProcessAll(w io.Writer, r io.Reader) error |
| 58 | +} |
| 59 | + |
| 60 | +func newURLRegexProcessor(convertDomain convertDomainFunc) RegexProcessor { |
| 61 | + return ®exProcessor{ |
| 62 | + re: urlRegexp, |
| 63 | + partialSuffixRegexp: partialURLRegexp, |
| 64 | + convertDomain: convertDomain, |
| 65 | + } |
| 66 | +} |
| 67 | + |
| 68 | +// TODO remove integrity attribute |
| 69 | +func newHTMLRegexProcessor(conv DomainConverter, jsHookScript string) RegexProcessor { |
| 70 | + htmlRegexp := regexp.MustCompile(URLRegexp + `|(crossorigin="anonymous")|(rel="manifest")|(<head>)`) |
| 71 | + return ®exProcessor{ |
| 72 | + re: htmlRegexp, |
| 73 | + partialSuffixRegexp: partialURLRegexp, |
| 74 | + convertDomain: func(domain string) string { |
| 75 | + return conv.ToProxyDomain(domain) |
| 76 | + }, |
| 77 | + replaceMap: map[string]string{ |
| 78 | + `crossorigin="anonymous"`: "", |
| 79 | + `rel="manifest"`: `rel="manifest" crossorigin="use-credentials"`, |
| 80 | + `<head>`: `<head><script>` + jsHookScript + `</script>`, |
| 81 | + }, |
| 82 | + } |
| 83 | +} |
| 84 | + |
| 85 | +type convertDomainFunc func(domain string) string |
| 86 | + |
| 87 | +type regexProcessor struct { |
| 88 | + re *regexp.Regexp |
| 89 | + partialSuffixRegexp *regexp.Regexp |
| 90 | + replaceMap map[string]string |
| 91 | + convertDomain convertDomainFunc |
| 92 | +} |
| 93 | + |
| 94 | +//nolint:errcheck |
| 95 | +func (p *regexProcessor) Process(w io.Writer, r io.Reader, count int, buff *bytes.Buffer) error { |
| 96 | + n, err := buff.ReadFrom(io.LimitReader(r, int64(count))) |
| 97 | + if n == 0 { |
| 98 | + err = io.EOF |
| 99 | + } |
| 100 | + bytearr := buff.Bytes() |
| 101 | + foundIndex := p.re.FindAllIndex(bytearr, -1) |
| 102 | + start := 0 |
| 103 | + for _, pair := range foundIndex { |
| 104 | + w.Write(bytearr[start:pair[0]]) |
| 105 | + // handle case: //bbc.ae -> ro |
| 106 | + if pair[1] == count { |
| 107 | + start = pair[0] |
| 108 | + break |
| 109 | + } |
| 110 | + |
| 111 | + found := string(bytearr[pair[0]:pair[1]]) |
| 112 | + if replaced, ok := p.replaceMap[found]; ok { |
| 113 | + w.Write(utils.UnsafeBytes(replaced)) |
| 114 | + } else { |
| 115 | + w.Write([]byte("//")) |
| 116 | + w.Write([]byte(p.convertDomain(found[2:]))) |
| 117 | + } |
| 118 | + start = pair[1] |
| 119 | + } |
| 120 | + // advance the buffer by the number of processed bytes |
| 121 | + if start > 0 { |
| 122 | + p.advanceBuffer(buff, start) |
| 123 | + } else { |
| 124 | + pair := p.partialSuffixRegexp.FindIndex(bytearr) |
| 125 | + if pair != nil { |
| 126 | + w.Write(buff.Bytes()[:pair[0]]) |
| 127 | + p.advanceBuffer(buff, pair[0]) |
| 128 | + } else { |
| 129 | + w.Write(buff.Bytes()) |
| 130 | + buff.Reset() |
| 131 | + } |
| 132 | + } |
| 133 | + return err |
| 134 | +} |
| 135 | + |
| 136 | +// advanceBuffer advances the buff buffer by the num bytes |
| 137 | +func (*regexProcessor) advanceBuffer(buff *bytes.Buffer, num int) { |
| 138 | + buff.Next(num) |
| 139 | + // move buffer from num offset to 0 |
| 140 | + bytearr := buff.Bytes() |
| 141 | + buff.Reset() |
| 142 | + buff.Write(bytearr) |
| 143 | +} |
| 144 | + |
| 145 | +//nolint:errcheck |
| 146 | +func (p *regexProcessor) ProcessAll(w io.Writer, r io.Reader) (err error) { |
| 147 | + buff := buffPool.Get() |
| 148 | + defer buffPool.Put(buff) |
| 149 | + const bufSize = 4096 |
| 150 | + for { |
| 151 | + if err = p.Process(w, r, bufSize, buff); err != nil { |
| 152 | + w.Write(buff.Bytes()) |
| 153 | + if err != io.EOF { |
| 154 | + log.Println("io error", err) |
| 155 | + } else { |
| 156 | + err = nil |
| 157 | + } |
| 158 | + return |
| 159 | + } |
| 160 | + } |
| 161 | +} |
0 commit comments