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 377 378
|
//
// Copyright 2006-2019 WebPKI.org (http://webpki.org).
//
// 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
//
// https://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.
//
// This package transforms JSON data in UTF-8 according to:
// https://tools.ietf.org/html/draft-rundgren-json-canonicalization-scheme-02
package jsoncanonicalizer
import (
"errors"
"container/list"
"fmt"
"strconv"
"strings"
"unicode/utf16"
)
type nameValueType struct {
name string
sortKey []uint16
value string
}
// JSON standard escapes (modulo \u)
var asciiEscapes = []byte{'\\', '"', 'b', 'f', 'n', 'r', 't'}
var binaryEscapes = []byte{'\\', '"', '\b', '\f', '\n', '\r', '\t'}
// JSON literals
var literals = []string{"true", "false", "null"}
func Transform(jsonData []byte) (result []byte, e error) {
// JSON data MUST be UTF-8 encoded
var jsonDataLength int = len(jsonData)
// Current pointer in jsonData
var index int = 0
// "Forward" declarations are needed for closures referring each other
var parseElement func() string
var parseSimpleType func() string
var parseQuotedString func() string
var parseObject func() string
var parseArray func() string
var globalError error = nil
checkError := func(e error) {
// We only honor the first reported error
if globalError == nil {
globalError = e
}
}
setError := func(msg string) {
checkError(errors.New(msg))
}
isWhiteSpace := func(c byte) bool {
return c == 0x20 || c == 0x0a || c == 0x0d || c == 0x09
}
nextChar := func() byte {
if index < jsonDataLength {
c := jsonData[index]
if c > 0x7f {
setError("Unexpected non-ASCII character")
}
index++
return c
}
setError("Unexpected EOF reached")
return '"'
}
scan := func() byte {
for {
c := nextChar()
if isWhiteSpace(c) {
continue;
}
return c
}
}
scanFor := func(expected byte) {
c := scan()
if c != expected {
setError("Expected '" + string(expected) + "' but got '" + string(c) + "'")
}
}
getUEscape := func() rune {
start := index
nextChar()
nextChar()
nextChar()
nextChar()
if globalError != nil {
return 0
}
u16, err := strconv.ParseUint(string(jsonData[start:index]), 16, 64)
checkError(err)
return rune(u16)
}
testNextNonWhiteSpaceChar := func() byte {
save := index
c := scan()
index = save
return c
}
decorateString := func(rawUTF8 string) string {
var quotedString strings.Builder
quotedString.WriteByte('"')
CoreLoop:
for _, c := range []byte(rawUTF8) {
// Is this within the JSON standard escapes?
for i, esc := range binaryEscapes {
if esc == c {
quotedString.WriteByte('\\')
quotedString.WriteByte(asciiEscapes[i])
continue CoreLoop
}
}
if c < 0x20 {
// Other ASCII control characters must be escaped with \uhhhh
quotedString.WriteString(fmt.Sprintf("\\u%04x", c))
} else {
quotedString.WriteByte(c)
}
}
quotedString.WriteByte('"')
return quotedString.String()
}
parseQuotedString = func() string {
var rawString strings.Builder
CoreLoop:
for globalError == nil {
var c byte
if index < jsonDataLength {
c = jsonData[index]
index++
} else {
nextChar()
break
}
if (c == '"') {
break;
}
if c < ' ' {
setError("Unterminated string literal")
} else if c == '\\' {
// Escape sequence
c = nextChar()
if c == 'u' {
// The \u escape
firstUTF16 := getUEscape()
if utf16.IsSurrogate(firstUTF16) {
// If the first UTF-16 code unit has a certain value there must be
// another succeeding UTF-16 code unit as well
if nextChar() != '\\' || nextChar() != 'u' {
setError("Missing surrogate")
} else {
// Output the UTF-32 code point as UTF-8
rawString.WriteRune(utf16.DecodeRune(firstUTF16, getUEscape()))
}
} else {
// Single UTF-16 code identical to UTF-32. Output as UTF-8
rawString.WriteRune(firstUTF16)
}
} else if c == '/' {
// Benign but useless escape
rawString.WriteByte('/')
} else {
// The JSON standard escapes
for i, esc := range asciiEscapes {
if esc == c {
rawString.WriteByte(binaryEscapes[i])
continue CoreLoop
}
}
setError("Unexpected escape: \\" + string(c))
}
} else {
// Just an ordinary ASCII character alternatively a UTF-8 byte
// outside of ASCII.
// Note that properly formatted UTF-8 never clashes with ASCII
// making byte per byte search for ASCII break characters work
// as expected.
rawString.WriteByte(c)
}
}
return rawString.String()
}
parseSimpleType = func() string {
var token strings.Builder
index--
for globalError == nil {
c := testNextNonWhiteSpaceChar()
if c == ',' || c == ']' || c == '}' {
break;
}
c = nextChar()
if isWhiteSpace(c) {
break
}
token.WriteByte(c)
}
if token.Len() == 0 {
setError("Missing argument")
}
value := token.String()
// Is it a JSON literal?
for _, literal := range literals {
if literal == value {
return literal
}
}
// Apparently not so we assume that it is a I-JSON number
ieeeF64, err := strconv.ParseFloat(value, 64)
checkError(err)
value, err = NumberToJSON(ieeeF64)
checkError(err)
return value
}
parseElement = func() string {
switch scan() {
case '{':
return parseObject()
case '"':
return decorateString(parseQuotedString())
case '[':
return parseArray()
default:
return parseSimpleType()
}
}
parseArray = func() string {
var arrayData strings.Builder
arrayData.WriteByte('[')
var next bool = false
for globalError == nil && testNextNonWhiteSpaceChar() != ']' {
if next {
scanFor(',')
arrayData.WriteByte(',')
} else {
next = true
}
arrayData.WriteString(parseElement())
}
scan()
arrayData.WriteByte(']')
return arrayData.String()
}
lexicographicallyPrecedes := func(sortKey []uint16, e *list.Element) bool {
// Find the minimum length of the sortKeys
oldSortKey := e.Value.(nameValueType).sortKey
minLength := len(oldSortKey)
if minLength > len(sortKey) {
minLength = len(sortKey)
}
for q := 0; q < minLength; q++ {
diff := int(sortKey[q]) - int(oldSortKey[q])
if diff < 0 {
// Smaller => Precedes
return true
} else if diff > 0 {
// Bigger => No match
return false
}
// Still equal => Continue
}
// The sortKeys compared equal up to minLength
if len(sortKey) < len(oldSortKey) {
// Shorter => Precedes
return true
}
if len(sortKey) == len(oldSortKey) {
setError("Duplicate key: " + e.Value.(nameValueType).name)
}
// Longer => No match
return false
}
parseObject = func() string {
nameValueList := list.New()
var next bool = false
CoreLoop:
for globalError == nil && testNextNonWhiteSpaceChar() != '}' {
if next {
scanFor(',')
}
next = true
scanFor('"')
rawUTF8 := parseQuotedString()
if globalError != nil {
break;
}
// Sort keys on UTF-16 code units
// Since UTF-8 doesn't have endianess this is just a value transformation
// In the Go case the transformation is UTF-8 => UTF-32 => UTF-16
sortKey := utf16.Encode([]rune(rawUTF8))
scanFor(':')
nameValue := nameValueType{rawUTF8, sortKey, parseElement()}
for e := nameValueList.Front(); e != nil; e = e.Next() {
// Check if the key is smaller than a previous key
if lexicographicallyPrecedes(sortKey, e) {
// Precedes => Insert before and exit sorting
nameValueList.InsertBefore(nameValue, e)
continue CoreLoop
}
// Continue searching for a possibly succeeding sortKey
// (which is straightforward since the list is ordered)
}
// The sortKey is either the first or is succeeding all previous sortKeys
nameValueList.PushBack(nameValue)
}
// Scan away '}'
scan()
// Now everything is sorted so we can properly serialize the object
var objectData strings.Builder
objectData.WriteByte('{')
next = false
for e := nameValueList.Front(); e != nil; e = e.Next() {
if next {
objectData.WriteByte(',')
}
next = true
nameValue := e.Value.(nameValueType)
objectData.WriteString(decorateString(nameValue.name))
objectData.WriteByte(':')
objectData.WriteString(nameValue.value)
}
objectData.WriteByte('}')
return objectData.String()
}
/////////////////////////////////////////////////
// This is where Transform actually begins... //
/////////////////////////////////////////////////
var transformed string
if testNextNonWhiteSpaceChar() == '[' {
scan()
transformed = parseArray()
} else {
scanFor('{')
transformed = parseObject()
}
for index < jsonDataLength {
if !isWhiteSpace(jsonData[index]) {
setError("Improperly terminated JSON object")
break;
}
index++
}
return []byte(transformed), globalError
}
|