blob: 548013984166411cda4a1b214468cc56828828f8 [file] [log] [blame]
Nigel Tao1b073492020-02-16 22:11:36 +11001// Copyright 2020 The Wuffs Authors.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// https://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15// ----------------
16
17/*
Nigel Tao0cd2f982020-03-03 23:03:02 +110018jsonptr is a JSON formatter (pretty-printer) that supports the JSON Pointer
19(RFC 6901) query syntax. It reads UTF-8 JSON from stdin and writes
20canonicalized, formatted UTF-8 JSON to stdout.
21
22See the "const char* usage" string below for details.
23
24----
25
26JSON Pointer (and this program's implementation) is one of many JSON query
27languages and JSON tools, such as jq, jql and JMESPath. This one is relatively
28simple and fewer-featured compared to those others.
29
30One benefit of simplicity is that this program's JSON and JSON Pointer
31implementations do not dynamically allocate or free memory (yet it does not
32require that the entire input fits in memory at once). They are therefore
33trivially protected against certain bug classes: memory leaks, double-frees and
34use-after-frees.
35
36The core JSON implementation is also written in the Wuffs programming language
37(and then transpiled to C/C++), which is memory-safe but also guards against
38integer arithmetic overflows.
39
Nigel Taofe0cbbd2020-03-05 22:01:30 +110040For defense in depth, on Linux, this program also self-imposes a
41SECCOMP_MODE_STRICT sandbox before reading (or otherwise processing) its input
42or writing its output. Under this sandbox, the only permitted system calls are
43read, write, exit and sigreturn.
44
Nigel Tao0cd2f982020-03-03 23:03:02 +110045All together, this program aims to safely handle untrusted JSON files without
46fear of security bugs such as remote code execution.
47
48----
Nigel Tao1b073492020-02-16 22:11:36 +110049
Nigel Taoc5b3a9e2020-02-24 11:54:35 +110050As of 2020-02-24, this program passes all 318 "test_parsing" cases from the
51JSON test suite (https://github.com/nst/JSONTestSuite), an appendix to the
52"Parsing JSON is a Minefield" article (http://seriot.ch/parsing_json.php) that
53was first published on 2016-10-26 and updated on 2018-03-30.
54
Nigel Tao0cd2f982020-03-03 23:03:02 +110055After modifying this program, run "build-example.sh example/jsonptr/" and then
56"script/run-json-test-suite.sh" to catch correctness regressions.
57
58----
59
Nigel Tao1b073492020-02-16 22:11:36 +110060This example program differs from most other example Wuffs programs in that it
61is written in C++, not C.
62
63$CXX jsonptr.cc && ./a.out < ../../test/data/github-tags.json; rm -f a.out
64
65for a C++ compiler $CXX, such as clang++ or g++.
66*/
67
Nigel Taofe0cbbd2020-03-05 22:01:30 +110068#include <errno.h>
Nigel Tao01abc842020-03-06 21:42:33 +110069#include <fcntl.h>
70#include <stdio.h>
Nigel Tao9cc2c252020-02-23 17:05:49 +110071#include <string.h>
Nigel Taofe0cbbd2020-03-05 22:01:30 +110072#include <unistd.h>
Nigel Tao1b073492020-02-16 22:11:36 +110073
74// Wuffs ships as a "single file C library" or "header file library" as per
75// https://github.com/nothings/stb/blob/master/docs/stb_howto.txt
76//
77// To use that single file as a "foo.c"-like implementation, instead of a
78// "foo.h"-like header, #define WUFFS_IMPLEMENTATION before #include'ing or
79// compiling it.
80#define WUFFS_IMPLEMENTATION
81
82// Defining the WUFFS_CONFIG__MODULE* macros are optional, but it lets users of
83// release/c/etc.c whitelist which parts of Wuffs to build. That file contains
84// the entire Wuffs standard library, implementing a variety of codecs and file
85// formats. Without this macro definition, an optimizing compiler or linker may
86// very well discard Wuffs code for unused codecs, but listing the Wuffs
87// modules we use makes that process explicit. Preprocessing means that such
88// code simply isn't compiled.
89#define WUFFS_CONFIG__MODULES
90#define WUFFS_CONFIG__MODULE__BASE
91#define WUFFS_CONFIG__MODULE__JSON
92
93// If building this program in an environment that doesn't easily accommodate
94// relative includes, you can use the script/inline-c-relative-includes.go
95// program to generate a stand-alone C++ file.
96#include "../../release/c/wuffs-unsupported-snapshot.c"
97
Nigel Taofe0cbbd2020-03-05 22:01:30 +110098#if defined(__linux__)
99#include <linux/prctl.h>
100#include <linux/seccomp.h>
101#include <sys/prctl.h>
102#include <sys/syscall.h>
103#define WUFFS_EXAMPLE_USE_SECCOMP
104#endif
105
Nigel Tao2cf76db2020-02-27 22:42:01 +1100106#define TRY(error_msg) \
107 do { \
108 const char* z = error_msg; \
109 if (z) { \
110 return z; \
111 } \
112 } while (false)
113
114static const char* eod = "main: end of data";
115
Nigel Tao0cd2f982020-03-03 23:03:02 +1100116static const char* usage =
Nigel Tao01abc842020-03-06 21:42:33 +1100117 "Usage: jsonptr -flags input.json\n"
Nigel Tao0cd2f982020-03-03 23:03:02 +1100118 "\n"
Nigel Tao52c4d6a2020-03-08 21:12:38 +1100119 "Flags:\n"
Nigel Tao3690e832020-03-12 16:52:26 +1100120 " -c -compact-output\n"
Nigel Tao52c4d6a2020-03-08 21:12:38 +1100121 " -i=NUM -indent=NUM\n"
122 " -o=NUM -max-output-depth=NUM\n"
123 " -q=STR -query=STR\n"
Nigel Taod6fdfb12020-03-11 12:24:14 +1100124 " -s -strict-json-pointer-syntax\n"
Nigel Tao52c4d6a2020-03-08 21:12:38 +1100125 " -t -tabs\n"
126 " -fail-if-unsandboxed\n"
127 "\n"
Nigel Tao01abc842020-03-06 21:42:33 +1100128 "The input.json filename is optional. If absent, it reads from stdin.\n"
Nigel Tao0cd2f982020-03-03 23:03:02 +1100129 "\n"
Nigel Tao52c4d6a2020-03-08 21:12:38 +1100130 "----\n"
131 "\n"
Nigel Tao0cd2f982020-03-03 23:03:02 +1100132 "jsonptr is a JSON formatter (pretty-printer) that supports the JSON\n"
133 "Pointer (RFC 6901) query syntax. It reads UTF-8 JSON from stdin and\n"
134 "writes canonicalized, formatted UTF-8 JSON to stdout.\n"
135 "\n"
136 "Canonicalized means that e.g. \"abc\\u000A\\tx\\u0177z\" is re-written\n"
137 "as \"abc\\n\\txŷz\". It does not sort object keys, nor does it reject\n"
Nigel Tao01abc842020-03-06 21:42:33 +1100138 "duplicate keys. Canonicalization does not imply Unicode normalization.\n"
Nigel Tao0cd2f982020-03-03 23:03:02 +1100139 "\n"
140 "Formatted means that arrays' and objects' elements are indented, each\n"
Nigel Tao3690e832020-03-12 16:52:26 +1100141 "on its own line. Configure this with the -c / -compact-output, -i=NUM /\n"
Nigel Tao52c4d6a2020-03-08 21:12:38 +1100142 "-indent=NUM (for NUM ranging from 0 to 8) and -t / -tabs flags.\n"
Nigel Tao0cd2f982020-03-03 23:03:02 +1100143 "\n"
Nigel Tao52c4d6a2020-03-08 21:12:38 +1100144 "----\n"
145 "\n"
146 "The -q=STR or -query=STR flag gives an optional JSON Pointer query, to\n"
Nigel Taofe0cbbd2020-03-05 22:01:30 +1100147 "print a subset of the input. For example, given RFC 6901 section 5's\n"
Nigel Tao01abc842020-03-06 21:42:33 +1100148 "sample input (https://tools.ietf.org/rfc/rfc6901.txt), this command:\n"
149 " jsonptr -query=/foo/1 rfc-6901-json-pointer.json\n"
Nigel Tao0cd2f982020-03-03 23:03:02 +1100150 "will print:\n"
151 " \"baz\"\n"
152 "\n"
153 "An absent query is equivalent to the empty query, which identifies the\n"
Nigel Tao52c4d6a2020-03-08 21:12:38 +1100154 "entire input (the root value). Unlike a file system, the \"/\" query\n"
155 "does not identify the root. Instead, it identifies the child (the value\n"
156 "in a key-value pair) of the root whose key is the empty string.\n"
157 "Similarly, \"/foo\" and \"/foo/\" identify two different nodes.\n"
Nigel Tao0cd2f982020-03-03 23:03:02 +1100158 "\n"
159 "If the query found a valid JSON value, this program will return a zero\n"
160 "exit code even if the rest of the input isn't valid JSON. If the query\n"
161 "did not find a value, or found an invalid one, this program returns a\n"
162 "non-zero exit code, but may still print partial output to stdout.\n"
163 "\n"
Nigel Tao01abc842020-03-06 21:42:33 +1100164 "The JSON specification (https://json.org/) permits implementations that\n"
Nigel Tao0cd2f982020-03-03 23:03:02 +1100165 "allow duplicate keys, as this one does. This JSON Pointer implementation\n"
166 "is also greedy, following the first match for each fragment without\n"
167 "back-tracking. For example, the \"/foo/bar\" query will fail if the root\n"
168 "object has multiple \"foo\" children but the first one doesn't have a\n"
Nigel Taofe0cbbd2020-03-05 22:01:30 +1100169 "\"bar\" child, even if later ones do.\n"
170 "\n"
Nigel Taod6fdfb12020-03-11 12:24:14 +1100171 "The -s or -strict-json-pointer-syntax flag restricts the -query=STR\n"
172 "string to exactly RFC 6901, with only two escape sequences: \"~0\" and\n"
173 "\"~1\" for \"~\" and \"/\". Without this flag, this program also lets\n"
174 "\"~n\" and \"~r\" escape the New Line and Carriage Return ASCII control\n"
175 "characters, which can work better with line oriented Unix tools that\n"
176 "assume exactly one value (i.e. one JSON Pointer string) per line.\n"
177 "\n"
Nigel Tao52c4d6a2020-03-08 21:12:38 +1100178 "----\n"
179 "\n"
180 "The -o=NUM or -max-output-depth=NUM flag gives the maximum (inclusive)\n"
181 "output depth. JSON containers ([] arrays and {} objects) can hold other\n"
182 "containers. When this flag is set, containers at depth NUM are replaced\n"
183 "with \"[…]\" or \"{…}\". A bare -o or -max-output-depth is equivalent to\n"
Nigel Taod6fdfb12020-03-11 12:24:14 +1100184 "-o=1. The flag's absence is equivalent to an unlimited output depth.\n"
Nigel Tao52c4d6a2020-03-08 21:12:38 +1100185 "\n"
186 "The -max-output-depth flag only affects the program's output. It doesn't\n"
187 "affect whether or not the input is considered valid JSON. The JSON\n"
188 "specification permits implementations to set their own maximum input\n"
189 "depth. This JSON implementation sets it to 1024.\n"
190 "\n"
191 "Depth is measured in terms of nested containers. It is unaffected by the\n"
192 "number of spaces or tabs used to indent.\n"
193 "\n"
194 "When both -max-output-depth and -query are set, the output depth is\n"
195 "measured from when the query resolves, not from the input root. The\n"
196 "input depth (measured from the root) is still limited to 1024.\n"
197 "\n"
198 "----\n"
199 "\n"
Nigel Taofe0cbbd2020-03-05 22:01:30 +1100200 "The -fail-if-unsandboxed flag causes the program to exit if it does not\n"
201 "self-impose a sandbox. On Linux, it self-imposes a SECCOMP_MODE_STRICT\n"
Nigel Tao52c4d6a2020-03-08 21:12:38 +1100202 "sandbox, regardless of whether this flag was set.";
Nigel Tao0cd2f982020-03-03 23:03:02 +1100203
Nigel Tao2cf76db2020-02-27 22:42:01 +1100204// ----
205
Nigel Taofe0cbbd2020-03-05 22:01:30 +1100206bool sandboxed = false;
207
Nigel Tao01abc842020-03-06 21:42:33 +1100208int input_file_descriptor = 0; // A 0 default means stdin.
209
Nigel Tao2cf76db2020-02-27 22:42:01 +1100210#define MAX_INDENT 8
Nigel Tao107f0ef2020-03-01 21:35:02 +1100211#define INDENT_SPACES_STRING " "
Nigel Tao6e7d1412020-03-06 09:21:35 +1100212#define INDENT_TAB_STRING "\t"
Nigel Tao107f0ef2020-03-01 21:35:02 +1100213
Nigel Taofdac24a2020-03-06 21:53:08 +1100214#ifndef DST_BUFFER_ARRAY_SIZE
215#define DST_BUFFER_ARRAY_SIZE (32 * 1024)
Nigel Tao1b073492020-02-16 22:11:36 +1100216#endif
Nigel Taofdac24a2020-03-06 21:53:08 +1100217#ifndef SRC_BUFFER_ARRAY_SIZE
218#define SRC_BUFFER_ARRAY_SIZE (32 * 1024)
Nigel Tao1b073492020-02-16 22:11:36 +1100219#endif
Nigel Taofdac24a2020-03-06 21:53:08 +1100220#ifndef TOKEN_BUFFER_ARRAY_SIZE
221#define TOKEN_BUFFER_ARRAY_SIZE (4 * 1024)
Nigel Tao1b073492020-02-16 22:11:36 +1100222#endif
223
Nigel Taofdac24a2020-03-06 21:53:08 +1100224uint8_t dst_array[DST_BUFFER_ARRAY_SIZE];
225uint8_t src_array[SRC_BUFFER_ARRAY_SIZE];
226wuffs_base__token tok_array[TOKEN_BUFFER_ARRAY_SIZE];
Nigel Tao1b073492020-02-16 22:11:36 +1100227
228wuffs_base__io_buffer dst;
229wuffs_base__io_buffer src;
230wuffs_base__token_buffer tok;
231
Nigel Tao2cf76db2020-02-27 22:42:01 +1100232// curr_token_end_src_index is the src.data.ptr index of the end of the current
233// token. An invariant is that (curr_token_end_src_index <= src.meta.ri).
234size_t curr_token_end_src_index;
235
Nigel Tao0cd2f982020-03-03 23:03:02 +1100236uint32_t depth;
Nigel Tao2cf76db2020-02-27 22:42:01 +1100237
238enum class context {
239 none,
240 in_list_after_bracket,
241 in_list_after_value,
242 in_dict_after_brace,
243 in_dict_after_key,
244 in_dict_after_value,
245} ctx;
246
Nigel Tao0cd2f982020-03-03 23:03:02 +1100247bool //
248in_dict_before_key() {
249 return (ctx == context::in_dict_after_brace) ||
250 (ctx == context::in_dict_after_value);
251}
252
Nigel Tao52c4d6a2020-03-08 21:12:38 +1100253uint32_t suppress_write_dst;
Nigel Tao0cd2f982020-03-03 23:03:02 +1100254bool wrote_to_dst;
255
Nigel Tao1b073492020-02-16 22:11:36 +1100256wuffs_json__decoder dec;
Nigel Tao1b073492020-02-16 22:11:36 +1100257
Nigel Tao0cd2f982020-03-03 23:03:02 +1100258// ----
259
260// Query is a JSON Pointer query. After initializing with a NUL-terminated C
261// string, its multiple fragments are consumed as the program walks the JSON
262// data from stdin. For example, letting "$" denote a NUL, suppose that we
263// started with a query string of "/apple/banana/12/durian" and are currently
Nigel Taob48ee752020-03-13 09:27:33 +1100264// trying to match the second fragment, "banana", so that Query::m_depth is 2:
Nigel Tao0cd2f982020-03-03 23:03:02 +1100265//
266// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
267// / a p p l e / b a n a n a / 1 2 / d u r i a n $
268// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
269// ^ ^
Nigel Taob48ee752020-03-13 09:27:33 +1100270// m_frag_i m_frag_k
Nigel Tao0cd2f982020-03-03 23:03:02 +1100271//
Nigel Taob48ee752020-03-13 09:27:33 +1100272// The two pointers m_frag_i and m_frag_k (abbreviated as mfi and mfk) are the
273// start (inclusive) and end (exclusive) of the query fragment. They satisfy
274// (mfi <= mfk) and may be equal if the fragment empty (note that "" is a valid
275// JSON object key).
Nigel Tao0cd2f982020-03-03 23:03:02 +1100276//
Nigel Taob48ee752020-03-13 09:27:33 +1100277// The m_frag_j (mfj) pointer moves between these two, or is nullptr. An
278// invariant is that (((mfi <= mfj) && (mfj <= mfk)) || (mfj == nullptr)).
Nigel Tao0cd2f982020-03-03 23:03:02 +1100279//
280// Wuffs' JSON tokenizer can portray a single JSON string as multiple Wuffs
281// tokens, as backslash-escaped values within that JSON string may each get
282// their own token.
283//
Nigel Taob48ee752020-03-13 09:27:33 +1100284// At the start of each object key (a JSON string), mfj is set to mfi.
Nigel Tao0cd2f982020-03-03 23:03:02 +1100285//
Nigel Taob48ee752020-03-13 09:27:33 +1100286// While mfj remains non-nullptr, each token's unescaped contents are then
287// compared to that part of the fragment from mfj to mfk. If it is a prefix
288// (including the case of an exact match), then mfj is advanced by the
289// unescaped length. Otherwise, mfj is set to nullptr.
Nigel Tao0cd2f982020-03-03 23:03:02 +1100290//
291// Comparison accounts for JSON Pointer's escaping notation: "~0" and "~1" in
292// the query (not the JSON value) are unescaped to "~" and "/" respectively.
Nigel Taob48ee752020-03-13 09:27:33 +1100293// "~n" and "~r" are also unescaped to "\n" and "\r". The program is
294// responsible for calling Query::validate (with a strict_json_pointer_syntax
295// argument) before otherwise using this class.
Nigel Tao0cd2f982020-03-03 23:03:02 +1100296//
Nigel Taob48ee752020-03-13 09:27:33 +1100297// The mfj pointer therefore advances from mfi to mfk, or drops out, as we
298// incrementally match the object key with the query fragment. For example, if
299// we have already matched the "ban" of "banana", then we would accept any of
300// an "ana" token, an "a" token or a "\u0061" token, amongst others. They would
301// advance mfj by 3, 1 or 1 bytes respectively.
Nigel Tao0cd2f982020-03-03 23:03:02 +1100302//
Nigel Taob48ee752020-03-13 09:27:33 +1100303// mfj
Nigel Tao0cd2f982020-03-03 23:03:02 +1100304// v
305// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
306// / a p p l e / b a n a n a / 1 2 / d u r i a n $
307// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
308// ^ ^
Nigel Taob48ee752020-03-13 09:27:33 +1100309// mfi mfk
Nigel Tao0cd2f982020-03-03 23:03:02 +1100310//
311// At the end of each object key (or equivalently, at the start of each object
Nigel Taob48ee752020-03-13 09:27:33 +1100312// value), if mfj is non-nullptr and equal to (but not less than) mfk then we
313// have a fragment match: the query fragment equals the object key. If there is
314// a next fragment (in this example, "12") we move the frag_etc pointers to its
315// start and end and increment Query::m_depth. Otherwise, we have matched the
316// complete query, and the upcoming JSON value is the result of that query.
Nigel Tao0cd2f982020-03-03 23:03:02 +1100317//
318// The discussion above centers on object keys. If the query fragment is
319// numeric then it can also match as an array index: the string fragment "12"
320// will match an array's 13th element (starting counting from zero). See RFC
321// 6901 for its precise definition of an "array index" number.
322//
Nigel Taob48ee752020-03-13 09:27:33 +1100323// Array index fragment match is represented by the Query::m_array_index field,
Nigel Tao0cd2f982020-03-03 23:03:02 +1100324// whose type (wuffs_base__result_u64) is a result type. An error result means
325// that the fragment is not an array index. A value result holds the number of
326// list elements remaining. When matching a query fragment in an array (instead
327// of in an object), each element ticks this number down towards zero. At zero,
328// the upcoming JSON value is the one that matches the query fragment.
329class Query {
330 private:
Nigel Taob48ee752020-03-13 09:27:33 +1100331 uint8_t* m_frag_i;
332 uint8_t* m_frag_j;
333 uint8_t* m_frag_k;
Nigel Tao0cd2f982020-03-03 23:03:02 +1100334
Nigel Taob48ee752020-03-13 09:27:33 +1100335 uint32_t m_depth;
Nigel Tao0cd2f982020-03-03 23:03:02 +1100336
Nigel Taob48ee752020-03-13 09:27:33 +1100337 wuffs_base__result_u64 m_array_index;
Nigel Tao0cd2f982020-03-03 23:03:02 +1100338
339 public:
340 void reset(char* query_c_string) {
Nigel Taob48ee752020-03-13 09:27:33 +1100341 m_frag_i = (uint8_t*)query_c_string;
342 m_frag_j = (uint8_t*)query_c_string;
343 m_frag_k = (uint8_t*)query_c_string;
344 m_depth = 0;
345 m_array_index.status.repr = "#main: not an array index query fragment";
346 m_array_index.value = 0;
Nigel Tao0cd2f982020-03-03 23:03:02 +1100347 }
348
Nigel Taob48ee752020-03-13 09:27:33 +1100349 void restart_fragment(bool enable) { m_frag_j = enable ? m_frag_i : nullptr; }
Nigel Tao0cd2f982020-03-03 23:03:02 +1100350
Nigel Taob48ee752020-03-13 09:27:33 +1100351 bool is_at(uint32_t depth) { return m_depth == depth; }
Nigel Tao0cd2f982020-03-03 23:03:02 +1100352
353 // tick returns whether the fragment is a valid array index whose value is
354 // zero. If valid but non-zero, it decrements it and returns false.
355 bool tick() {
Nigel Taob48ee752020-03-13 09:27:33 +1100356 if (m_array_index.status.is_ok()) {
357 if (m_array_index.value == 0) {
Nigel Tao0cd2f982020-03-03 23:03:02 +1100358 return true;
359 }
Nigel Taob48ee752020-03-13 09:27:33 +1100360 m_array_index.value--;
Nigel Tao0cd2f982020-03-03 23:03:02 +1100361 }
362 return false;
363 }
364
365 // next_fragment moves to the next fragment, returning whether it existed.
366 bool next_fragment() {
Nigel Taob48ee752020-03-13 09:27:33 +1100367 uint8_t* k = m_frag_k;
368 uint32_t d = m_depth;
Nigel Tao0cd2f982020-03-03 23:03:02 +1100369
370 this->reset(nullptr);
371
372 if (!k || (*k != '/')) {
373 return false;
374 }
375 k++;
376
377 bool all_digits = true;
378 uint8_t* i = k;
379 while ((*k != '\x00') && (*k != '/')) {
380 all_digits = all_digits && ('0' <= *k) && (*k <= '9');
381 k++;
382 }
Nigel Taob48ee752020-03-13 09:27:33 +1100383 m_frag_i = i;
384 m_frag_j = i;
385 m_frag_k = k;
386 m_depth = d + 1;
Nigel Tao0cd2f982020-03-03 23:03:02 +1100387 if (all_digits) {
388 // wuffs_base__parse_number_u64 rejects leading zeroes, e.g. "00", "07".
Nigel Taob48ee752020-03-13 09:27:33 +1100389 m_array_index =
Nigel Tao0cd2f982020-03-03 23:03:02 +1100390 wuffs_base__parse_number_u64(wuffs_base__make_slice_u8(i, k - i));
391 }
392 return true;
393 }
394
Nigel Taob48ee752020-03-13 09:27:33 +1100395 bool matched_all() { return m_frag_k == nullptr; }
Nigel Tao52c4d6a2020-03-08 21:12:38 +1100396
Nigel Taob48ee752020-03-13 09:27:33 +1100397 bool matched_fragment() { return m_frag_j && (m_frag_j == m_frag_k); }
Nigel Tao0cd2f982020-03-03 23:03:02 +1100398
399 void incremental_match_slice(uint8_t* ptr, size_t len) {
Nigel Taob48ee752020-03-13 09:27:33 +1100400 if (!m_frag_j) {
Nigel Tao0cd2f982020-03-03 23:03:02 +1100401 return;
402 }
Nigel Taob48ee752020-03-13 09:27:33 +1100403 uint8_t* j = m_frag_j;
Nigel Tao0cd2f982020-03-03 23:03:02 +1100404 while (true) {
405 if (len == 0) {
Nigel Taob48ee752020-03-13 09:27:33 +1100406 m_frag_j = j;
Nigel Tao0cd2f982020-03-03 23:03:02 +1100407 return;
408 }
409
410 if (*j == '\x00') {
411 break;
412
413 } else if (*j == '~') {
414 j++;
415 if (*j == '0') {
416 if (*ptr != '~') {
417 break;
418 }
419 } else if (*j == '1') {
420 if (*ptr != '/') {
421 break;
422 }
Nigel Taod6fdfb12020-03-11 12:24:14 +1100423 } else if (*j == 'n') {
424 if (*ptr != '\n') {
425 break;
426 }
427 } else if (*j == 'r') {
428 if (*ptr != '\r') {
429 break;
430 }
Nigel Tao0cd2f982020-03-03 23:03:02 +1100431 } else {
432 break;
433 }
434
435 } else if (*j != *ptr) {
436 break;
437 }
438
439 j++;
440 ptr++;
441 len--;
442 }
Nigel Taob48ee752020-03-13 09:27:33 +1100443 m_frag_j = nullptr;
Nigel Tao0cd2f982020-03-03 23:03:02 +1100444 }
445
446 void incremental_match_code_point(uint32_t code_point) {
Nigel Taob48ee752020-03-13 09:27:33 +1100447 if (!m_frag_j) {
Nigel Tao0cd2f982020-03-03 23:03:02 +1100448 return;
449 }
450 uint8_t u[WUFFS_BASE__UTF_8__BYTE_LENGTH__MAX_INCL];
451 size_t n = wuffs_base__utf_8__encode(
452 wuffs_base__make_slice_u8(&u[0],
453 WUFFS_BASE__UTF_8__BYTE_LENGTH__MAX_INCL),
454 code_point);
455 if (n > 0) {
456 this->incremental_match_slice(&u[0], n);
457 }
458 }
459
460 // validate returns whether the (ptr, len) arguments form a valid JSON
461 // Pointer. In particular, it must be valid UTF-8, and either be empty or
462 // start with a '/'. Any '~' within must immediately be followed by either
Nigel Taod6fdfb12020-03-11 12:24:14 +1100463 // '0' or '1'. If strict_json_pointer_syntax is false, a '~' may also be
464 // followed by either 'n' or 'r'.
465 static bool validate(char* query_c_string,
466 size_t length,
467 bool strict_json_pointer_syntax) {
Nigel Tao0cd2f982020-03-03 23:03:02 +1100468 if (length <= 0) {
469 return true;
470 }
471 if (query_c_string[0] != '/') {
472 return false;
473 }
474 wuffs_base__slice_u8 s =
475 wuffs_base__make_slice_u8((uint8_t*)query_c_string, length);
476 bool previous_was_tilde = false;
477 while (s.len > 0) {
478 wuffs_base__utf_8__next__output o = wuffs_base__utf_8__next(s);
479 if (!o.is_valid()) {
480 return false;
481 }
Nigel Taod6fdfb12020-03-11 12:24:14 +1100482
483 if (previous_was_tilde) {
484 switch (o.code_point) {
485 case '0':
486 case '1':
487 break;
488 case 'n':
489 case 'r':
490 if (strict_json_pointer_syntax) {
491 return false;
492 }
493 break;
494 default:
495 return false;
496 }
Nigel Tao0cd2f982020-03-03 23:03:02 +1100497 }
498 previous_was_tilde = o.code_point == '~';
Nigel Taod6fdfb12020-03-11 12:24:14 +1100499
Nigel Tao0cd2f982020-03-03 23:03:02 +1100500 s.ptr += o.byte_length;
501 s.len -= o.byte_length;
502 }
503 return !previous_was_tilde;
504 }
505} query;
506
507// ----
508
Nigel Tao68920952020-03-03 11:25:18 +1100509struct {
510 int remaining_argc;
511 char** remaining_argv;
512
Nigel Tao3690e832020-03-12 16:52:26 +1100513 bool compact_output;
Nigel Taofe0cbbd2020-03-05 22:01:30 +1100514 bool fail_if_unsandboxed;
Nigel Tao68920952020-03-03 11:25:18 +1100515 size_t indent;
Nigel Tao52c4d6a2020-03-08 21:12:38 +1100516 uint32_t max_output_depth;
Nigel Tao0cd2f982020-03-03 23:03:02 +1100517 char* query_c_string;
Nigel Taod6fdfb12020-03-11 12:24:14 +1100518 bool strict_json_pointer_syntax;
Nigel Tao68920952020-03-03 11:25:18 +1100519 bool tabs;
520} flags = {0};
521
522const char* //
523parse_flags(int argc, char** argv) {
Nigel Tao6e7d1412020-03-06 09:21:35 +1100524 flags.indent = 4;
Nigel Tao52c4d6a2020-03-08 21:12:38 +1100525 flags.max_output_depth = 0xFFFFFFFF;
Nigel Tao68920952020-03-03 11:25:18 +1100526
527 int c = (argc > 0) ? 1 : 0; // Skip argv[0], the program name.
528 for (; c < argc; c++) {
529 char* arg = argv[c];
530 if (*arg++ != '-') {
531 break;
532 }
533
534 // A double-dash "--foo" is equivalent to a single-dash "-foo". As special
535 // cases, a bare "-" is not a flag (some programs may interpret it as
536 // stdin) and a bare "--" means to stop parsing flags.
537 if (*arg == '\x00') {
538 break;
539 } else if (*arg == '-') {
540 arg++;
541 if (*arg == '\x00') {
542 c++;
543 break;
544 }
545 }
546
Nigel Tao3690e832020-03-12 16:52:26 +1100547 if (!strcmp(arg, "c") || !strcmp(arg, "compact-output")) {
548 flags.compact_output = true;
Nigel Tao68920952020-03-03 11:25:18 +1100549 continue;
550 }
Nigel Taofe0cbbd2020-03-05 22:01:30 +1100551 if (!strcmp(arg, "fail-if-unsandboxed")) {
552 flags.fail_if_unsandboxed = true;
553 continue;
554 }
Nigel Tao68920952020-03-03 11:25:18 +1100555 if (!strncmp(arg, "i=", 2) || !strncmp(arg, "indent=", 7)) {
556 while (*arg++ != '=') {
557 }
558 if (('0' <= arg[0]) && (arg[0] <= '8') && (arg[1] == '\x00')) {
559 flags.indent = arg[0] - '0';
Nigel Tao68920952020-03-03 11:25:18 +1100560 continue;
561 }
Nigel Tao0cd2f982020-03-03 23:03:02 +1100562 return usage;
563 }
Nigel Tao52c4d6a2020-03-08 21:12:38 +1100564 if (!strcmp(arg, "o") || !strcmp(arg, "max-output-depth")) {
565 flags.max_output_depth = 1;
566 continue;
567 } else if (!strncmp(arg, "o=", 2) ||
568 !strncmp(arg, "max-output-depth=", 16)) {
569 while (*arg++ != '=') {
570 }
571 wuffs_base__result_u64 u = wuffs_base__parse_number_u64(
572 wuffs_base__make_slice_u8((uint8_t*)arg, strlen(arg)));
573 if (wuffs_base__status__is_ok(&u.status) && (u.value <= 0xFFFFFFFF)) {
574 flags.max_output_depth = (uint32_t)(u.value);
575 continue;
576 }
577 return usage;
578 }
Nigel Tao0cd2f982020-03-03 23:03:02 +1100579 if (!strncmp(arg, "q=", 2) || !strncmp(arg, "query=", 6)) {
580 while (*arg++ != '=') {
581 }
Nigel Taod6fdfb12020-03-11 12:24:14 +1100582 flags.query_c_string = arg;
583 continue;
584 }
585 if (!strcmp(arg, "s") || !strcmp(arg, "strict-json-pointer-syntax")) {
586 flags.strict_json_pointer_syntax = true;
587 continue;
Nigel Tao68920952020-03-03 11:25:18 +1100588 }
589 if (!strcmp(arg, "t") || !strcmp(arg, "tabs")) {
590 flags.tabs = true;
591 continue;
592 }
593
Nigel Tao0cd2f982020-03-03 23:03:02 +1100594 return usage;
Nigel Tao68920952020-03-03 11:25:18 +1100595 }
596
Nigel Taod6fdfb12020-03-11 12:24:14 +1100597 if (flags.query_c_string &&
598 !Query::validate(flags.query_c_string, strlen(flags.query_c_string),
599 flags.strict_json_pointer_syntax)) {
600 return "main: bad JSON Pointer (RFC 6901) syntax for the -query=STR flag";
601 }
602
Nigel Tao68920952020-03-03 11:25:18 +1100603 flags.remaining_argc = argc - c;
604 flags.remaining_argv = argv + c;
Nigel Tao0cd2f982020-03-03 23:03:02 +1100605 return nullptr;
Nigel Tao68920952020-03-03 11:25:18 +1100606}
607
Nigel Tao2cf76db2020-02-27 22:42:01 +1100608const char* //
609initialize_globals(int argc, char** argv) {
Nigel Tao2cf76db2020-02-27 22:42:01 +1100610 dst = wuffs_base__make_io_buffer(
Nigel Taofdac24a2020-03-06 21:53:08 +1100611 wuffs_base__make_slice_u8(dst_array, DST_BUFFER_ARRAY_SIZE),
Nigel Tao2cf76db2020-02-27 22:42:01 +1100612 wuffs_base__empty_io_buffer_meta());
Nigel Tao1b073492020-02-16 22:11:36 +1100613
Nigel Tao2cf76db2020-02-27 22:42:01 +1100614 src = wuffs_base__make_io_buffer(
Nigel Taofdac24a2020-03-06 21:53:08 +1100615 wuffs_base__make_slice_u8(src_array, SRC_BUFFER_ARRAY_SIZE),
Nigel Tao2cf76db2020-02-27 22:42:01 +1100616 wuffs_base__empty_io_buffer_meta());
617
618 tok = wuffs_base__make_token_buffer(
Nigel Taofdac24a2020-03-06 21:53:08 +1100619 wuffs_base__make_slice_token(tok_array, TOKEN_BUFFER_ARRAY_SIZE),
Nigel Tao2cf76db2020-02-27 22:42:01 +1100620 wuffs_base__empty_token_buffer_meta());
621
622 curr_token_end_src_index = 0;
623
Nigel Tao2cf76db2020-02-27 22:42:01 +1100624 depth = 0;
625
626 ctx = context::none;
627
Nigel Tao68920952020-03-03 11:25:18 +1100628 TRY(parse_flags(argc, argv));
Nigel Taofe0cbbd2020-03-05 22:01:30 +1100629 if (flags.fail_if_unsandboxed && !sandboxed) {
630 return "main: unsandboxed";
631 }
Nigel Tao01abc842020-03-06 21:42:33 +1100632 const int stdin_fd = 0;
633 if (flags.remaining_argc > ((input_file_descriptor != stdin_fd) ? 1 : 0)) {
Nigel Tao0cd2f982020-03-03 23:03:02 +1100634 return usage;
Nigel Tao107f0ef2020-03-01 21:35:02 +1100635 }
636
Nigel Tao0cd2f982020-03-03 23:03:02 +1100637 query.reset(flags.query_c_string);
638
639 // If the query is non-empty, suprress writing to stdout until we've
640 // completed the query.
Nigel Tao52c4d6a2020-03-08 21:12:38 +1100641 suppress_write_dst = query.next_fragment() ? 1 : 0;
Nigel Tao0cd2f982020-03-03 23:03:02 +1100642 wrote_to_dst = false;
643
Nigel Tao2cf76db2020-02-27 22:42:01 +1100644 return dec.initialize(sizeof__wuffs_json__decoder(), WUFFS_VERSION, 0)
645 .message();
646}
Nigel Tao1b073492020-02-16 22:11:36 +1100647
648// ----
649
Nigel Taofe0cbbd2020-03-05 22:01:30 +1100650// ignore_return_value suppresses errors from -Wall -Werror.
651static void //
652ignore_return_value(int ignored) {}
653
Nigel Tao2914bae2020-02-26 09:40:30 +1100654const char* //
655read_src() {
Nigel Taoa8406922020-02-19 12:22:00 +1100656 if (src.meta.closed) {
Nigel Tao9cc2c252020-02-23 17:05:49 +1100657 return "main: internal error: read requested on a closed source";
Nigel Taoa8406922020-02-19 12:22:00 +1100658 }
Nigel Tao1b073492020-02-16 22:11:36 +1100659 src.compact();
660 if (src.meta.wi >= src.data.len) {
661 return "main: src buffer is full";
662 }
Nigel Taofe0cbbd2020-03-05 22:01:30 +1100663 while (true) {
Nigel Tao01abc842020-03-06 21:42:33 +1100664 ssize_t n = read(input_file_descriptor, src.data.ptr + src.meta.wi,
665 src.data.len - src.meta.wi);
Nigel Taofe0cbbd2020-03-05 22:01:30 +1100666 if (n >= 0) {
667 src.meta.wi += n;
668 src.meta.closed = n == 0;
669 break;
670 } else if (errno != EINTR) {
671 return strerror(errno);
672 }
Nigel Tao1b073492020-02-16 22:11:36 +1100673 }
674 return nullptr;
675}
676
Nigel Tao2914bae2020-02-26 09:40:30 +1100677const char* //
678flush_dst() {
Nigel Taofe0cbbd2020-03-05 22:01:30 +1100679 while (true) {
680 size_t n = dst.meta.wi - dst.meta.ri;
681 if (n == 0) {
682 break;
Nigel Tao1b073492020-02-16 22:11:36 +1100683 }
Nigel Taofe0cbbd2020-03-05 22:01:30 +1100684 const int stdout_fd = 1;
685 ssize_t i = write(stdout_fd, dst.data.ptr + dst.meta.ri, n);
686 if (i >= 0) {
687 dst.meta.ri += i;
688 } else if (errno != EINTR) {
689 return strerror(errno);
690 }
Nigel Tao1b073492020-02-16 22:11:36 +1100691 }
Nigel Taofe0cbbd2020-03-05 22:01:30 +1100692 dst.compact();
Nigel Tao1b073492020-02-16 22:11:36 +1100693 return nullptr;
694}
695
Nigel Tao2914bae2020-02-26 09:40:30 +1100696const char* //
697write_dst(const void* s, size_t n) {
Nigel Tao52c4d6a2020-03-08 21:12:38 +1100698 if (suppress_write_dst > 0) {
Nigel Tao0cd2f982020-03-03 23:03:02 +1100699 return nullptr;
700 }
Nigel Tao1b073492020-02-16 22:11:36 +1100701 const uint8_t* p = static_cast<const uint8_t*>(s);
702 while (n > 0) {
703 size_t i = dst.writer_available();
704 if (i == 0) {
705 const char* z = flush_dst();
706 if (z) {
707 return z;
708 }
709 i = dst.writer_available();
710 if (i == 0) {
711 return "main: dst buffer is full";
712 }
713 }
714
715 if (i > n) {
716 i = n;
717 }
718 memcpy(dst.data.ptr + dst.meta.wi, p, i);
719 dst.meta.wi += i;
720 p += i;
721 n -= i;
Nigel Tao0cd2f982020-03-03 23:03:02 +1100722 wrote_to_dst = true;
Nigel Tao1b073492020-02-16 22:11:36 +1100723 }
724 return nullptr;
725}
726
727// ----
728
Nigel Tao2914bae2020-02-26 09:40:30 +1100729uint8_t //
730hex_digit(uint8_t nibble) {
Nigel Taob5461bd2020-02-21 14:13:37 +1100731 nibble &= 0x0F;
732 if (nibble <= 9) {
733 return '0' + nibble;
734 }
735 return ('A' - 10) + nibble;
736}
737
Nigel Tao2914bae2020-02-26 09:40:30 +1100738const char* //
Nigel Tao3b486982020-02-27 15:05:59 +1100739handle_unicode_code_point(uint32_t ucp) {
740 if (ucp < 0x0020) {
741 switch (ucp) {
742 case '\b':
743 return write_dst("\\b", 2);
744 case '\f':
745 return write_dst("\\f", 2);
746 case '\n':
747 return write_dst("\\n", 2);
748 case '\r':
749 return write_dst("\\r", 2);
750 case '\t':
751 return write_dst("\\t", 2);
752 default: {
753 // Other bytes less than 0x0020 are valid UTF-8 but not valid in a
754 // JSON string. They need to remain escaped.
755 uint8_t esc6[6];
756 esc6[0] = '\\';
757 esc6[1] = 'u';
758 esc6[2] = '0';
759 esc6[3] = '0';
760 esc6[4] = hex_digit(ucp >> 4);
761 esc6[5] = hex_digit(ucp >> 0);
762 return write_dst(&esc6[0], 6);
763 }
764 }
765
Nigel Taob9ad34f2020-03-03 12:44:01 +1100766 } else if (ucp == '\"') {
767 return write_dst("\\\"", 2);
768
769 } else if (ucp == '\\') {
770 return write_dst("\\\\", 2);
771
772 } else {
773 uint8_t u[WUFFS_BASE__UTF_8__BYTE_LENGTH__MAX_INCL];
774 size_t n = wuffs_base__utf_8__encode(
775 wuffs_base__make_slice_u8(&u[0],
776 WUFFS_BASE__UTF_8__BYTE_LENGTH__MAX_INCL),
777 ucp);
778 if (n > 0) {
779 return write_dst(&u[0], n);
Nigel Tao3b486982020-02-27 15:05:59 +1100780 }
Nigel Tao3b486982020-02-27 15:05:59 +1100781 }
782
Nigel Tao2cf76db2020-02-27 22:42:01 +1100783 return "main: internal error: unexpected Unicode code point";
Nigel Tao3b486982020-02-27 15:05:59 +1100784}
785
786const char* //
Nigel Tao2cf76db2020-02-27 22:42:01 +1100787handle_token(wuffs_base__token t) {
788 do {
789 uint64_t vbc = t.value_base_category();
790 uint64_t vbd = t.value_base_detail();
791 uint64_t len = t.length();
Nigel Tao1b073492020-02-16 22:11:36 +1100792
793 // Handle ']' or '}'.
Nigel Tao9f7a2502020-02-23 09:42:02 +1100794 if ((vbc == WUFFS_BASE__TOKEN__VBC__STRUCTURE) &&
Nigel Tao2cf76db2020-02-27 22:42:01 +1100795 (vbd & WUFFS_BASE__TOKEN__VBD__STRUCTURE__POP)) {
Nigel Tao0cd2f982020-03-03 23:03:02 +1100796 if (query.is_at(depth)) {
797 return "main: no match for query";
798 }
Nigel Tao1b073492020-02-16 22:11:36 +1100799 if (depth <= 0) {
800 return "main: internal error: inconsistent depth";
801 }
802 depth--;
803
Nigel Tao52c4d6a2020-03-08 21:12:38 +1100804 if (query.matched_all() && (depth >= flags.max_output_depth)) {
805 suppress_write_dst--;
806 // '…' is U+2026 HORIZONTAL ELLIPSIS, which is 3 UTF-8 bytes.
807 TRY(write_dst((vbd & WUFFS_BASE__TOKEN__VBD__STRUCTURE__FROM_LIST)
808 ? "\"[…]\""
809 : "\"{…}\"",
810 7));
811 } else {
812 // Write preceding whitespace.
813 if ((ctx != context::in_list_after_bracket) &&
Nigel Tao3690e832020-03-12 16:52:26 +1100814 (ctx != context::in_dict_after_brace) && !flags.compact_output) {
Nigel Tao52c4d6a2020-03-08 21:12:38 +1100815 TRY(write_dst("\n", 1));
816 for (uint32_t i = 0; i < depth; i++) {
817 TRY(write_dst(flags.tabs ? INDENT_TAB_STRING : INDENT_SPACES_STRING,
818 flags.tabs ? 1 : flags.indent));
819 }
Nigel Tao1b073492020-02-16 22:11:36 +1100820 }
Nigel Tao52c4d6a2020-03-08 21:12:38 +1100821
822 TRY(write_dst(
823 (vbd & WUFFS_BASE__TOKEN__VBD__STRUCTURE__FROM_LIST) ? "]" : "}",
824 1));
Nigel Tao1b073492020-02-16 22:11:36 +1100825 }
826
Nigel Tao9f7a2502020-02-23 09:42:02 +1100827 ctx = (vbd & WUFFS_BASE__TOKEN__VBD__STRUCTURE__TO_LIST)
828 ? context::in_list_after_value
829 : context::in_dict_after_key;
Nigel Tao1b073492020-02-16 22:11:36 +1100830 goto after_value;
831 }
832
Nigel Taod1c928a2020-02-28 12:43:53 +1100833 // Write preceding whitespace and punctuation, if it wasn't ']', '}' or a
834 // continuation of a multi-token chain.
Nigel Tao0cd2f982020-03-03 23:03:02 +1100835 if (!t.link_prev()) {
836 if (ctx == context::in_dict_after_key) {
Nigel Tao3690e832020-03-12 16:52:26 +1100837 TRY(write_dst(": ", flags.compact_output ? 1 : 2));
Nigel Tao0cd2f982020-03-03 23:03:02 +1100838 } else if (ctx != context::none) {
839 if ((ctx != context::in_list_after_bracket) &&
840 (ctx != context::in_dict_after_brace)) {
841 TRY(write_dst(",", 1));
Nigel Tao107f0ef2020-03-01 21:35:02 +1100842 }
Nigel Tao3690e832020-03-12 16:52:26 +1100843 if (!flags.compact_output) {
Nigel Tao0cd2f982020-03-03 23:03:02 +1100844 TRY(write_dst("\n", 1));
845 for (size_t i = 0; i < depth; i++) {
Nigel Tao6e7d1412020-03-06 09:21:35 +1100846 TRY(write_dst(flags.tabs ? INDENT_TAB_STRING : INDENT_SPACES_STRING,
847 flags.tabs ? 1 : flags.indent));
Nigel Tao0cd2f982020-03-03 23:03:02 +1100848 }
849 }
850 }
851
Nigel Tao52c4d6a2020-03-08 21:12:38 +1100852 bool query_matched_fragment = false;
Nigel Tao0cd2f982020-03-03 23:03:02 +1100853 if (query.is_at(depth)) {
854 switch (ctx) {
855 case context::in_list_after_bracket:
856 case context::in_list_after_value:
Nigel Tao52c4d6a2020-03-08 21:12:38 +1100857 query_matched_fragment = query.tick();
Nigel Tao0cd2f982020-03-03 23:03:02 +1100858 break;
859 case context::in_dict_after_key:
Nigel Tao52c4d6a2020-03-08 21:12:38 +1100860 query_matched_fragment = query.matched_fragment();
Nigel Tao0cd2f982020-03-03 23:03:02 +1100861 break;
862 }
863 }
Nigel Tao52c4d6a2020-03-08 21:12:38 +1100864 if (!query_matched_fragment) {
Nigel Tao0cd2f982020-03-03 23:03:02 +1100865 // No-op.
866 } else if (!query.next_fragment()) {
867 // There is no next fragment. We have matched the complete query, and
868 // the upcoming JSON value is the result of that query.
869 //
870 // Un-suppress writing to stdout and reset the ctx and depth as if we
871 // were about to decode a top-level value. This makes any subsequent
872 // indentation be relative to this point, and we will return eod after
873 // the upcoming JSON value is complete.
Nigel Tao52c4d6a2020-03-08 21:12:38 +1100874 if (suppress_write_dst != 1) {
875 return "main: internal error: inconsistent suppress_write_dst";
876 }
877 suppress_write_dst = 0;
Nigel Tao0cd2f982020-03-03 23:03:02 +1100878 ctx = context::none;
879 depth = 0;
880 } else if ((vbc != WUFFS_BASE__TOKEN__VBC__STRUCTURE) ||
881 !(vbd & WUFFS_BASE__TOKEN__VBD__STRUCTURE__PUSH)) {
882 // The query has moved on to the next fragment but the upcoming JSON
883 // value is not a container.
884 return "main: no match for query";
Nigel Tao1b073492020-02-16 22:11:36 +1100885 }
886 }
887
888 // Handle the token itself: either a container ('[' or '{') or a simple
Nigel Tao85fba7f2020-02-29 16:28:06 +1100889 // value: string (a chain of raw or escaped parts), literal or number.
Nigel Tao1b073492020-02-16 22:11:36 +1100890 switch (vbc) {
Nigel Tao85fba7f2020-02-29 16:28:06 +1100891 case WUFFS_BASE__TOKEN__VBC__STRUCTURE:
Nigel Tao52c4d6a2020-03-08 21:12:38 +1100892 if (query.matched_all() && (depth >= flags.max_output_depth)) {
893 suppress_write_dst++;
894 } else {
895 TRY(write_dst(
896 (vbd & WUFFS_BASE__TOKEN__VBD__STRUCTURE__TO_LIST) ? "[" : "{",
897 1));
898 }
Nigel Tao85fba7f2020-02-29 16:28:06 +1100899 depth++;
900 ctx = (vbd & WUFFS_BASE__TOKEN__VBD__STRUCTURE__TO_LIST)
901 ? context::in_list_after_bracket
902 : context::in_dict_after_brace;
903 return nullptr;
904
Nigel Tao2cf76db2020-02-27 22:42:01 +1100905 case WUFFS_BASE__TOKEN__VBC__STRING:
Nigel Taod1c928a2020-02-28 12:43:53 +1100906 if (!t.link_prev()) {
Nigel Tao2cf76db2020-02-27 22:42:01 +1100907 TRY(write_dst("\"", 1));
Nigel Tao0cd2f982020-03-03 23:03:02 +1100908 query.restart_fragment(in_dict_before_key() && query.is_at(depth));
Nigel Tao2cf76db2020-02-27 22:42:01 +1100909 }
Nigel Taocb37a562020-02-28 09:56:24 +1100910
911 if (vbd & WUFFS_BASE__TOKEN__VBD__STRING__CONVERT_0_DST_1_SRC_DROP) {
912 // No-op.
913 } else if (vbd &
914 WUFFS_BASE__TOKEN__VBD__STRING__CONVERT_1_DST_1_SRC_COPY) {
Nigel Tao0cd2f982020-03-03 23:03:02 +1100915 uint8_t* ptr = src.data.ptr + curr_token_end_src_index - len;
916 TRY(write_dst(ptr, len));
917 query.incremental_match_slice(ptr, len);
Nigel Taocb37a562020-02-28 09:56:24 +1100918 } else {
919 return "main: internal error: unexpected string-token conversion";
920 }
921
Nigel Taod1c928a2020-02-28 12:43:53 +1100922 if (t.link_next()) {
Nigel Tao2cf76db2020-02-27 22:42:01 +1100923 return nullptr;
924 }
925 TRY(write_dst("\"", 1));
926 goto after_value;
927
928 case WUFFS_BASE__TOKEN__VBC__UNICODE_CODE_POINT:
Nigel Tao0cd2f982020-03-03 23:03:02 +1100929 if (!t.link_prev() || !t.link_next()) {
930 return "main: internal error: unexpected unlinked token";
931 }
932 TRY(handle_unicode_code_point(vbd));
933 query.incremental_match_code_point(vbd);
934 return nullptr;
Nigel Tao2cf76db2020-02-27 22:42:01 +1100935
Nigel Tao85fba7f2020-02-29 16:28:06 +1100936 case WUFFS_BASE__TOKEN__VBC__LITERAL:
Nigel Tao2cf76db2020-02-27 22:42:01 +1100937 case WUFFS_BASE__TOKEN__VBC__NUMBER:
938 TRY(write_dst(src.data.ptr + curr_token_end_src_index - len, len));
939 goto after_value;
Nigel Tao1b073492020-02-16 22:11:36 +1100940 }
941
942 // Return an error if we didn't match the (vbc, vbd) pair.
Nigel Tao2cf76db2020-02-27 22:42:01 +1100943 return "main: internal error: unexpected token";
944 } while (0);
Nigel Tao1b073492020-02-16 22:11:36 +1100945
Nigel Tao2cf76db2020-02-27 22:42:01 +1100946 // Book-keeping after completing a value (whether a container value or a
947 // simple value). Empty parent containers are no longer empty. If the parent
948 // container is a "{...}" object, toggle between keys and values.
949after_value:
950 if (depth == 0) {
951 return eod;
952 }
953 switch (ctx) {
954 case context::in_list_after_bracket:
955 ctx = context::in_list_after_value;
956 break;
957 case context::in_dict_after_brace:
958 ctx = context::in_dict_after_key;
959 break;
960 case context::in_dict_after_key:
961 ctx = context::in_dict_after_value;
962 break;
963 case context::in_dict_after_value:
964 ctx = context::in_dict_after_key;
965 break;
966 }
967 return nullptr;
968}
969
970const char* //
971main1(int argc, char** argv) {
972 TRY(initialize_globals(argc, argv));
973
974 while (true) {
975 wuffs_base__status status = dec.decode_tokens(&tok, &src);
976
977 while (tok.meta.ri < tok.meta.wi) {
978 wuffs_base__token t = tok.data.ptr[tok.meta.ri++];
979 uint64_t n = t.length();
980 if ((src.meta.ri - curr_token_end_src_index) < n) {
981 return "main: internal error: inconsistent src indexes";
982 }
983 curr_token_end_src_index += n;
984
985 if (t.value() == 0) {
986 continue;
987 }
988
989 const char* z = handle_token(t);
990 if (z == nullptr) {
991 continue;
992 } else if (z == eod) {
Nigel Tao0cd2f982020-03-03 23:03:02 +1100993 goto end_of_data;
Nigel Tao2cf76db2020-02-27 22:42:01 +1100994 }
995 return z;
Nigel Tao1b073492020-02-16 22:11:36 +1100996 }
Nigel Tao2cf76db2020-02-27 22:42:01 +1100997
998 if (status.repr == nullptr) {
Nigel Tao0cd2f982020-03-03 23:03:02 +1100999 return "main: internal error: unexpected end of token stream";
Nigel Tao2cf76db2020-02-27 22:42:01 +11001000 } else if (status.repr == wuffs_base__suspension__short_read) {
1001 if (curr_token_end_src_index != src.meta.ri) {
1002 return "main: internal error: inconsistent src indexes";
1003 }
1004 TRY(read_src());
1005 curr_token_end_src_index = src.meta.ri;
1006 } else if (status.repr == wuffs_base__suspension__short_write) {
1007 tok.compact();
1008 } else {
1009 return status.message();
Nigel Tao1b073492020-02-16 22:11:36 +11001010 }
1011 }
Nigel Tao0cd2f982020-03-03 23:03:02 +11001012end_of_data:
1013
1014 // With a non-empty query, don't try to consume trailing whitespace or
1015 // confirm that we've processed all the tokens.
1016 if (flags.query_c_string && *flags.query_c_string) {
1017 return nullptr;
1018 }
Nigel Tao6b161af2020-02-24 11:01:48 +11001019
Nigel Tao6b161af2020-02-24 11:01:48 +11001020 // Consume an optional whitespace trailer. This isn't part of the JSON spec,
1021 // but it works better with line oriented Unix tools (such as "echo 123 |
1022 // jsonptr" where it's "echo", not "echo -n") or hand-edited JSON files which
1023 // can accidentally contain trailing whitespace.
1024 //
1025 // A whitespace trailer is zero or more ' ' and then zero or one '\n'.
1026 while (true) {
1027 if (src.meta.ri < src.meta.wi) {
1028 uint8_t c = src.data.ptr[src.meta.ri];
1029 if (c == ' ') {
1030 src.meta.ri++;
1031 continue;
1032 } else if (c == '\n') {
1033 src.meta.ri++;
1034 break;
1035 }
1036 // The "exhausted the input" check below will fail.
1037 break;
1038 } else if (src.meta.closed) {
1039 break;
1040 }
1041 TRY(read_src());
1042 }
1043
1044 // Check that we've exhausted the input.
Nigel Taofe0cbbd2020-03-05 22:01:30 +11001045 if ((src.meta.ri == src.meta.wi) && !src.meta.closed) {
1046 TRY(read_src());
1047 }
Nigel Tao6b161af2020-02-24 11:01:48 +11001048 if ((src.meta.ri < src.meta.wi) || !src.meta.closed) {
1049 return "main: valid JSON followed by further (unexpected) data";
1050 }
1051
1052 // Check that we've used all of the decoded tokens, other than trailing
1053 // filler tokens. For example, a bare `"foo"` string is valid JSON, but even
1054 // without a trailing '\n', the Wuffs JSON parser emits a filler token for
1055 // the final '\"'.
1056 for (; tok.meta.ri < tok.meta.wi; tok.meta.ri++) {
1057 if (tok.data.ptr[tok.meta.ri].value_base_category() !=
1058 WUFFS_BASE__TOKEN__VBC__FILLER) {
1059 return "main: internal error: decoded OK but unprocessed tokens remain";
1060 }
1061 }
1062
1063 return nullptr;
Nigel Tao1b073492020-02-16 22:11:36 +11001064}
1065
Nigel Tao2914bae2020-02-26 09:40:30 +11001066int //
1067compute_exit_code(const char* status_msg) {
Nigel Tao9cc2c252020-02-23 17:05:49 +11001068 if (!status_msg) {
1069 return 0;
1070 }
Nigel Tao01abc842020-03-06 21:42:33 +11001071 size_t n;
1072 if (status_msg == usage) {
1073 n = strlen(status_msg);
1074 } else {
Nigel Tao9cc2c252020-02-23 17:05:49 +11001075 n = strnlen(status_msg, 2047);
Nigel Tao01abc842020-03-06 21:42:33 +11001076 if (n >= 2047) {
1077 status_msg = "main: internal error: error message is too long";
1078 n = strnlen(status_msg, 2047);
1079 }
Nigel Tao9cc2c252020-02-23 17:05:49 +11001080 }
Nigel Taofe0cbbd2020-03-05 22:01:30 +11001081 const int stderr_fd = 2;
1082 ignore_return_value(write(stderr_fd, status_msg, n));
1083 ignore_return_value(write(stderr_fd, "\n", 1));
Nigel Tao9cc2c252020-02-23 17:05:49 +11001084 // Return an exit code of 1 for regular (forseen) errors, e.g. badly
1085 // formatted or unsupported input.
1086 //
1087 // Return an exit code of 2 for internal (exceptional) errors, e.g. defensive
1088 // run-time checks found that an internal invariant did not hold.
1089 //
1090 // Automated testing, including badly formatted inputs, can therefore
1091 // discriminate between expected failure (exit code 1) and unexpected failure
1092 // (other non-zero exit codes). Specifically, exit code 2 for internal
1093 // invariant violation, exit code 139 (which is 128 + SIGSEGV on x86_64
1094 // linux) for a segmentation fault (e.g. null pointer dereference).
1095 return strstr(status_msg, "internal error:") ? 2 : 1;
1096}
1097
Nigel Tao2914bae2020-02-26 09:40:30 +11001098int //
1099main(int argc, char** argv) {
Nigel Tao01abc842020-03-06 21:42:33 +11001100 // Look for an input filename (the first non-flag argument) in argv. If there
1101 // is one, open it (but do not read from it) before we self-impose a sandbox.
1102 //
1103 // Flags start with "-", unless it comes after a bare "--" arg.
1104 {
1105 bool dash_dash = false;
1106 int a;
1107 for (a = 1; a < argc; a++) {
1108 char* arg = argv[a];
1109 if ((arg[0] == '-') && !dash_dash) {
1110 dash_dash = (arg[1] == '-') && (arg[2] == '\x00');
1111 continue;
1112 }
1113 input_file_descriptor = open(arg, O_RDONLY);
1114 if (input_file_descriptor < 0) {
1115 fprintf(stderr, "%s: %s\n", arg, strerror(errno));
1116 return 1;
1117 }
1118 break;
1119 }
1120 }
1121
Nigel Taofe0cbbd2020-03-05 22:01:30 +11001122#if defined(WUFFS_EXAMPLE_USE_SECCOMP)
1123 prctl(PR_SET_SECCOMP, SECCOMP_MODE_STRICT);
1124 sandboxed = true;
1125#endif
1126
Nigel Tao0cd2f982020-03-03 23:03:02 +11001127 const char* z = main1(argc, argv);
1128 if (wrote_to_dst) {
1129 const char* z1 = write_dst("\n", 1);
1130 const char* z2 = flush_dst();
1131 z = z ? z : (z1 ? z1 : z2);
1132 }
1133 int exit_code = compute_exit_code(z);
Nigel Taofe0cbbd2020-03-05 22:01:30 +11001134
1135#if defined(WUFFS_EXAMPLE_USE_SECCOMP)
1136 // Call SYS_exit explicitly, instead of calling SYS_exit_group implicitly by
1137 // either calling _exit or returning from main. SECCOMP_MODE_STRICT allows
1138 // only SYS_exit.
1139 syscall(SYS_exit, exit_code);
1140#endif
Nigel Tao9cc2c252020-02-23 17:05:49 +11001141 return exit_code;
Nigel Tao1b073492020-02-16 22:11:36 +11001142}