This repository has been archived by the owner on Aug 28, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 15
/
prepareQuery.go
97 lines (91 loc) · 1.72 KB
/
prepareQuery.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
package gqlshield
import "strings"
func prepareQuery(query []byte) ([]byte, error) {
if len(query) < 1 {
return nil, Error{
Code: ErrWrongInput,
Message: "invalid (empty) query",
}
}
// Hot-fix escaped quatation marks
query = []byte(strings.Replace(string(query), `\"`, `"`, -1))
start := int(-1)
shift := int(0)
tail := len(query)
inString := false
// shift over leading spaces
i := 0
LEADING_LOOP:
for ; i < len(query); i++ {
char := query[i]
if char == '\\' && i+1 < len(query) {
switch query[i+1] {
case 't':
// escaped tab
fallthrough
case 'n':
// escaped line-break
fallthrough
case 'r':
// escaped carriage return
i++
default:
break LEADING_LOOP
}
} else if char == ' ' || char == '\t' || char == '\n' {
} else {
break
}
}
tail -= i
for ; i < len(query); i++ {
char := query[i]
if !inString && char == '\\' && i+1 < len(query) {
switch query[i+1] {
case 't':
// escaped tab
fallthrough
case 'n':
// escaped line-break
fallthrough
case 'r':
// escaped carriage return
if start < 0 {
start = shift
}
i++
tail--
default:
}
} else if !inString && (char == ' ' || char == '\t' || char == '\n') {
if start < 0 {
// record shift start
start = shift
}
} else if start > -1 {
// shift over spaces
query[start] = ' '
delta := shift - start
if delta > 1 {
tail -= delta - 1
}
shift = start + 1
start = -1
}
if char == '"' {
inString = !inString
}
query[shift] = char
shift++
}
if start > -1 {
tail -= shift - start
}
if inString {
return nil, Error{
Code: ErrWrongInput,
Message: "unclosed string context",
}
}
return query[:tail], nil
}