forked from ContentSquare/chproxy
-
Notifications
You must be signed in to change notification settings - Fork 0
/
utils.go
202 lines (181 loc) · 4.35 KB
/
utils.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
package main
import (
"bytes"
"compress/gzip"
"fmt"
"io"
"io/ioutil"
"net/http"
"sort"
"strings"
"github.com/Vertamedia/chproxy/chdecompressor"
"github.com/Vertamedia/chproxy/log"
)
func respondWith(rw http.ResponseWriter, err error, status int) {
log.ErrorWithCallDepth(err, 1)
rw.WriteHeader(status)
fmt.Fprintf(rw, "%s\n", err)
}
// getAuth retrieves auth credentials from request
// according to CH documentation @see "https://clickhouse.yandex/docs/en/interfaces/http/"
func getAuth(req *http.Request) (string, string) {
// check X-ClickHouse- headers
name := req.Header.Get("X-ClickHouse-User")
pass := req.Header.Get("X-ClickHouse-Key")
if name != "" {
return name, pass
}
// if header is empty - check basicAuth
if name, pass, ok := req.BasicAuth(); ok {
return name, pass
}
// if basicAuth is empty - check URL params `user` and `password`
params := req.URL.Query()
if name := params.Get("user"); name != "" {
pass := params.Get("password")
return name, pass
}
// if still no credentials - treat it as `default` user request
return "default", ""
}
// getQuerySnippet returns query snippet.
//
// getQuerySnippet must be called only for error reporting.
func getQuerySnippet(req *http.Request) string {
if req.Method == http.MethodGet {
return req.URL.Query().Get("query")
}
crc, ok := req.Body.(*cachedReadCloser)
if !ok {
crc = &cachedReadCloser{
ReadCloser: req.Body,
}
}
// 'read' request body, so it traps into to crc.
// Ignore any errors, since getQuerySnippet is called only
// during error reporting.
io.Copy(ioutil.Discard, crc)
data := crc.String()
u := getDecompressor(req)
if u == nil {
return data
}
bs := bytes.NewBufferString(data)
b, err := u.decompress(bs)
if err == nil {
return string(b)
}
// It is better to return partially decompressed data instead of an empty string.
if len(b) > 0 {
return string(b)
}
// The data failed to be decompressed. Return compressed data
// instead of an empty string.
return data
}
// getFullQuery returns full query from req.
func getFullQuery(req *http.Request) ([]byte, error) {
if req.Method == http.MethodGet {
return []byte(req.URL.Query().Get("query")), nil
}
data, err := ioutil.ReadAll(req.Body)
if err != nil {
return nil, err
}
// restore body for further reading
req.Body = ioutil.NopCloser(bytes.NewBuffer(data))
u := getDecompressor(req)
if u == nil {
return data, nil
}
br := bytes.NewReader(data)
b, err := u.decompress(br)
if err != nil {
return nil, fmt.Errorf("cannot uncompress query: %s", err)
}
return b, nil
}
// canCacheQuery returns true if q can be cached.
func canCacheQuery(q []byte) bool {
q = skipLeadingComments(q)
// Currently only SELECT queries may be cached.
if len(q) < len("SELECT") {
return false
}
q = bytes.ToUpper(q[:len("SELECT")])
return bytes.HasPrefix(q, []byte("SELECT"))
}
func skipLeadingComments(q []byte) []byte {
for len(q) > 0 {
switch q[0] {
case '\t', '\n', '\v', '\f', '\r', ' ':
q = q[1:]
case '-':
if len(q) < 2 || q[1] != '-' {
return q
}
// skip `-- comment`
n := bytes.IndexByte(q, '\n')
if n < 0 {
return nil
}
q = q[n+1:]
case '/':
if len(q) < 2 || q[1] != '*' {
return q
}
// skip `/* comment */`
for {
n := bytes.IndexByte(q, '*')
if n < 0 {
return nil
}
q = q[n+1:]
if len(q) == 0 {
return nil
}
if q[0] == '/' {
q = q[1:]
break
}
}
default:
return q
}
}
return nil
}
// splits header string in sorted slice
func sortHeader(header string) string {
h := strings.Split(header, ",")
for i, v := range h {
h[i] = strings.TrimSpace(v)
}
sort.Strings(h)
return strings.Join(h, ",")
}
func getDecompressor(req *http.Request) decompressor {
if req.Header.Get("Content-Encoding") == "gzip" {
return gzipDecompressor{}
}
if req.URL.Query().Get("decompress") == "1" {
return chDecompressor{}
}
return nil
}
type decompressor interface {
decompress(r io.Reader) ([]byte, error)
}
type gzipDecompressor struct{}
func (dc gzipDecompressor) decompress(r io.Reader) ([]byte, error) {
gr, err := gzip.NewReader(r)
if err != nil {
return nil, fmt.Errorf("cannot ungzip query: %s", err)
}
return ioutil.ReadAll(gr)
}
type chDecompressor struct{}
func (dc chDecompressor) decompress(r io.Reader) ([]byte, error) {
lr := chdecompressor.NewReader(r)
return ioutil.ReadAll(lr)
}