AWS IoT Firmware
Firmware code for AWS IoT Devices
frozen.h
1 
6 /*
7  * Copyright (c) 2004-2013 Sergey Lyubka <valenok@gmail.com>
8  * Copyright (c) 2018 Cesanta Software Limited
9  * All rights reserved
10  *
11  * Licensed under the Apache License, Version 2.0 (the ""License"");
12  * you may not use this file except in compliance with the License.
13  * You may obtain a copy of the License at
14  *
15  * http://www.apache.org/licenses/LICENSE-2.0
16  *
17  * Unless required by applicable law or agreed to in writing, software
18  * distributed under the License is distributed on an ""AS IS"" BASIS,
19  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
20  * See the License for the specific language governing permissions and
21  * limitations under the License.
22  */
23 
24 #ifndef CS_FROZEN_FROZEN_H_
25 #define CS_FROZEN_FROZEN_H_
26 
27 #ifdef __cplusplus
28 extern "C" {
29 #endif /* __cplusplus */
30 
31 #include <stdarg.h>
32 #include <stddef.h>
33 #include <stdio.h>
34 
35 #if defined(_WIN32) && _MSC_VER < 1700
36 typedef int bool;
37 enum { false = 0, true = 1 };
38 #else
39 #include <stdbool.h>
40 #endif
41 
42 /* JSON token type */
43 enum json_token_type {
44  JSON_TYPE_INVALID = 0, /* memsetting to 0 should create INVALID value */
45  JSON_TYPE_STRING,
46  JSON_TYPE_NUMBER,
47  JSON_TYPE_TRUE,
48  JSON_TYPE_FALSE,
49  JSON_TYPE_NULL,
50  JSON_TYPE_OBJECT_START,
51  JSON_TYPE_OBJECT_END,
52  JSON_TYPE_ARRAY_START,
53  JSON_TYPE_ARRAY_END,
54 
55  JSON_TYPES_CNT
56 };
57 
58 /*
59  * Structure containing token type and value. Used in `json_walk()` and
60  * `json_scanf()` with the format specifier `%T`.
61  */
62 struct json_token {
63  const char *ptr; /* Points to the beginning of the value */
64  int len; /* Value length */
65  enum json_token_type type; /* Type of the token, possible values are above */
66 };
67 
68 #define JSON_INVALID_TOKEN \
69  { 0, 0, JSON_TYPE_INVALID }
70 
71 /* Error codes */
72 #define JSON_STRING_INVALID -1
73 #define JSON_STRING_INCOMPLETE -2
74 
75 /*
76  * Callback-based SAX-like API.
77  *
78  * Property name and length is given only if it's available: i.e. if current
79  * event is an object's property. In other cases, `name` is `NULL`. For
80  * example, name is never given:
81  * - For the first value in the JSON string;
82  * - For events JSON_TYPE_OBJECT_END and JSON_TYPE_ARRAY_END
83  *
84  * E.g. for the input `{ "foo": 123, "bar": [ 1, 2, { "baz": true } ] }`,
85  * the sequence of callback invocations will be as follows:
86  *
87  * - type: JSON_TYPE_OBJECT_START, name: NULL, path: "", value: NULL
88  * - type: JSON_TYPE_NUMBER, name: "foo", path: ".foo", value: "123"
89  * - type: JSON_TYPE_ARRAY_START, name: "bar", path: ".bar", value: NULL
90  * - type: JSON_TYPE_NUMBER, name: "0", path: ".bar[0]", value: "1"
91  * - type: JSON_TYPE_NUMBER, name: "1", path: ".bar[1]", value: "2"
92  * - type: JSON_TYPE_OBJECT_START, name: "2", path: ".bar[2]", value: NULL
93  * - type: JSON_TYPE_TRUE, name: "baz", path: ".bar[2].baz", value: "true"
94  * - type: JSON_TYPE_OBJECT_END, name: NULL, path: ".bar[2]", value: "{ \"baz\":
95  *true }"
96  * - type: JSON_TYPE_ARRAY_END, name: NULL, path: ".bar", value: "[ 1, 2, {
97  *\"baz\": true } ]"
98  * - type: JSON_TYPE_OBJECT_END, name: NULL, path: "", value: "{ \"foo\": 123,
99  *\"bar\": [ 1, 2, { \"baz\": true } ] }"
100  */
101 typedef void (*json_walk_callback_t)(void *callback_data, const char *name,
102  size_t name_len, const char *path,
103  const struct json_token *token);
104 
105 /*
106  * Parse `json_string`, invoking `callback` in a way similar to SAX parsers;
107  * see `json_walk_callback_t`.
108  * Return number of processed bytes, or a negative error code.
109  */
110 int json_walk(const char *json_string, int json_string_length,
111  json_walk_callback_t callback, void *callback_data);
112 
113 /*
114  * JSON generation API.
115  * struct json_out abstracts output, allowing alternative printing plugins.
116  */
117 struct json_out {
118  int (*printer)(struct json_out *, const char *str, size_t len);
119  union {
120  struct {
121  char *buf;
122  size_t size;
123  size_t len;
124  } buf;
125  void *data;
126  FILE *fp;
127  } u;
128 };
129 
130 extern int json_printer_buf(struct json_out *, const char *, size_t);
131 extern int json_printer_file(struct json_out *, const char *, size_t);
132 
133 #define JSON_OUT_BUF(buf, len) \
134  { \
135  json_printer_buf, { \
136  { buf, len, 0 } \
137  } \
138  }
139 #define JSON_OUT_FILE(fp) \
140  { \
141  json_printer_file, { \
142  { (char *) fp, 0, 0 } \
143  } \
144  }
145 
146 typedef int (*json_printf_callback_t)(struct json_out *, va_list *ap);
147 
148 /*
149  * Generate formatted output into a given sting buffer.
150  * This is a superset of printf() function, with extra format specifiers:
151  * - `%B` print json boolean, `true` or `false`. Accepts an `int`.
152  * - `%Q` print quoted escaped string or `null`. Accepts a `const char *`.
153  * - `%.*Q` same as `%Q`, but with length. Accepts `int`, `const char *`
154  * - `%V` print quoted base64-encoded string. Accepts a `const char *`, `int`.
155  * - `%H` print quoted hex-encoded string. Accepts a `int`, `const char *`.
156  * - `%M` invokes a json_printf_callback_t function. That callback function
157  * can consume more parameters.
158  *
159  * Return number of bytes printed. If the return value is bigger than the
160  * supplied buffer, that is an indicator of overflow. In the overflow case,
161  * overflown bytes are not printed.
162  */
163 int json_printf(struct json_out *, const char *fmt, ...);
164 int json_vprintf(struct json_out *, const char *fmt, va_list ap);
165 
166 /*
167  * Same as json_printf, but prints to a file.
168  * File is created if does not exist. File is truncated if already exists.
169  */
170 int json_fprintf(const char *file_name, const char *fmt, ...);
171 int json_vfprintf(const char *file_name, const char *fmt, va_list ap);
172 
173 /*
174  * Print JSON into an allocated 0-terminated string.
175  * Return allocated string, or NULL on error.
176  * Example:
177  *
178  * ```c
179  * char *str = json_asprintf("{a:%H}", 3, "abc");
180  * printf("%s\n", str); // Prints "616263"
181  * free(str);
182  * ```
183  */
184 char *json_asprintf(const char *fmt, ...);
185 char *json_vasprintf(const char *fmt, va_list ap);
186 
187 /*
188  * Helper %M callback that prints contiguous C arrays.
189  * Consumes void *array_ptr, size_t array_size, size_t elem_size, char *fmt
190  * Return number of bytes printed.
191  */
192 int json_printf_array(struct json_out *, va_list *ap);
193 
194 /*
195  * Scan JSON string `str`, performing scanf-like conversions according to `fmt`.
196  * This is a `scanf()` - like function, with following differences:
197  *
198  * 1. Object keys in the format string may be not quoted, e.g. "{key: %d}"
199  * 2. Order of keys in an object is irrelevant.
200  * 3. Several extra format specifiers are supported:
201  * - %B: consumes `int *` (or `char *`, if `sizeof(bool) == sizeof(char)`),
202  * expects boolean `true` or `false`.
203  * - %Q: consumes `char **`, expects quoted, JSON-encoded string. Scanned
204  * string is malloc-ed, caller must free() the string.
205  * - %V: consumes `char **`, `int *`. Expects base64-encoded string.
206  * Result string is base64-decoded, malloced and NUL-terminated.
207  * The length of result string is stored in `int *` placeholder.
208  * Caller must free() the result.
209  * - %H: consumes `int *`, `char **`.
210  * Expects a hex-encoded string, e.g. "fa014f".
211  * Result string is hex-decoded, malloced and NUL-terminated.
212  * The length of the result string is stored in `int *` placeholder.
213  * Caller must free() the result.
214  * - %M: consumes custom scanning function pointer and
215  * `void *user_data` parameter - see json_scanner_t definition.
216  * - %T: consumes `struct json_token *`, fills it out with matched token.
217  *
218  * Return number of elements successfully scanned & converted.
219  * Negative number means scan error.
220  */
221 int json_scanf(const char *str, int str_len, const char *fmt, ...);
222 int json_vscanf(const char *str, int str_len, const char *fmt, va_list ap);
223 
224 /* json_scanf's %M handler */
225 typedef void (*json_scanner_t)(const char *str, int len, void *user_data);
226 
227 /*
228  * Helper function to scan array item with given path and index.
229  * Fills `token` with the matched JSON token.
230  * Return -1 if no array element found, otherwise non-negative token length.
231  */
232 int json_scanf_array_elem(const char *s, int len, const char *path, int index,
233  struct json_token *token);
234 
235 /*
236  * Unescape JSON-encoded string src,slen into dst, dlen.
237  * src and dst may overlap.
238  * If destination buffer is too small (or zero-length), result string is not
239  * written but the length is counted nevertheless (similar to snprintf).
240  * Return the length of unescaped string in bytes.
241  */
242 int json_unescape(const char *src, int slen, char *dst, int dlen);
243 
244 /*
245  * Escape a string `str`, `str_len` into the printer `out`.
246  * Return the number of bytes printed.
247  */
248 int json_escape(struct json_out *out, const char *str, size_t str_len);
249 
250 /*
251  * Read the whole file in memory.
252  * Return malloc-ed file content, or NULL on error. The caller must free().
253  */
254 char *json_fread(const char *file_name);
255 
256 /*
257  * Update given JSON string `s,len` by changing the value at given `json_path`.
258  * The result is saved to `out`. If `json_fmt` == NULL, that deletes the key.
259  * If path is not present, missing keys are added. Array path without an
260  * index pushes a value to the end of an array.
261  * Return 1 if the string was changed, 0 otherwise.
262  *
263  * Example: s is a JSON string { "a": 1, "b": [ 2 ] }
264  * json_setf(s, len, out, ".a", "7"); // { "a": 7, "b": [ 2 ] }
265  * json_setf(s, len, out, ".b", "7"); // { "a": 1, "b": 7 }
266  * json_setf(s, len, out, ".b[]", "7"); // { "a": 1, "b": [ 2,7 ] }
267  * json_setf(s, len, out, ".b", NULL); // { "a": 1 }
268  */
269 int json_setf(const char *s, int len, struct json_out *out,
270  const char *json_path, const char *json_fmt, ...);
271 
272 int json_vsetf(const char *s, int len, struct json_out *out,
273  const char *json_path, const char *json_fmt, va_list ap);
274 
275 /*
276  * Pretty-print JSON string `s,len` into `out`.
277  * Return number of processed bytes in `s`.
278  */
279 int json_prettify(const char *s, int len, struct json_out *out);
280 
281 /*
282  * Prettify JSON file `file_name`.
283  * Return number of processed bytes, or negative number of error.
284  * On error, file content is not modified.
285  */
286 int json_prettify_file(const char *file_name);
287 
288 /*
289  * Iterate over an object at given JSON `path`.
290  * On each iteration, fill the `key` and `val` tokens. It is OK to pass NULL
291  * for `key`, or `val`, in which case they won't be populated.
292  * Return an opaque value suitable for the next iteration, or NULL when done.
293  *
294  * Example:
295  *
296  * ```c
297  * void *h = NULL;
298  * struct json_token key, val;
299  * while ((h = json_next_key(s, len, h, ".foo", &key, &val)) != NULL) {
300  * printf("[%.*s] -> [%.*s]\n", key.len, key.ptr, val.len, val.ptr);
301  * }
302  * ```
303  */
304 void *json_next_key(const char *s, int len, void *handle, const char *path,
305  struct json_token *key, struct json_token *val);
306 
307 /*
308  * Iterate over an array at given JSON `path`.
309  * Similar to `json_next_key`, but fills array index `idx` instead of `key`.
310  */
311 void *json_next_elem(const char *s, int len, void *handle, const char *path,
312  int *idx, struct json_token *val);
313 
314 #ifdef __cplusplus
315 }
316 #endif /* __cplusplus */
317 
318 #endif /* CS_FROZEN_FROZEN_H_ */
319 
320 
Definition: frozen.h:62
Definition: frozen.h:117