Debian Codegraph @

src/ws/cockpitjson.c

raw
1 /*
2 * Copyright (C) 2014 Red Hat, Inc.
3 * SPDX-License-Identifier: LGPL-2.1-or-later
4 */
5
6 #include "config.h"
7
8 /* This gets logged as part of the (more verbose) protocol logging */
9 #ifdef G_LOG_DOMAIN
10 #undef G_LOG_DOMAIN
11 #endif
12 #define G_LOG_DOMAIN "cockpit-protocol"
13
14 #include "cockpitjson.h"
15
16 #include <math.h>
17 #include <string.h>
18
19 gboolean
20 cockpit_json_get_int (JsonObject *object,
21 const gchar *name,
22 gint64 defawlt,
23 gint64 *value)
24 {
25 JsonNode *node;
26
27 node = json_object_get_member (object, name);
28 if (!node)
29 {
30 if (value)
31 *value = defawlt;
32 return TRUE;
33 }
34 else if (json_node_get_value_type (node) == G_TYPE_INT64 ||
35 json_node_get_value_type (node) == G_TYPE_DOUBLE)
36 {
37 if (value)
38 *value = json_node_get_int (node);
39 return TRUE;
40 }
41 else
42 {
43 return FALSE;
44 }
45 }
46
47 gboolean
48 cockpit_json_get_bool (JsonObject *object,
49 const gchar *name,
50 gboolean defawlt,
51 gboolean *value)
52 {
53 JsonNode *node;
54
55 node = json_object_get_member (object, name);
56 if (!node)
57 {
58 if (value)
59 *value = defawlt;
60 return TRUE;
61 }
62 else if (json_node_get_value_type (node) == G_TYPE_BOOLEAN)
63 {
64 if (value)
65 *value = json_node_get_boolean (node);
66 return TRUE;
67 }
68 else
69 {
70 return FALSE;
71 }
72 }
73
74
75 gboolean
76 cockpit_json_get_string (JsonObject *options,
77 const gchar *name,
78 const gchar *defawlt,
79 const gchar **value)
80 {
81 JsonNode *node;
82
83 node = json_object_get_member (options, name);
84 if (!node)
85 {
86 if (value)
87 *value = defawlt;
88 return TRUE;
89 }
90 else if (json_node_get_value_type (node) == G_TYPE_STRING)
91 {
92 if (value)
93 *value = json_node_get_string (node);
94 return TRUE;
95 }
96 else
97 {
98 return FALSE;
99 }
100 }
101
102 gboolean
103 cockpit_json_get_object (JsonObject *options,
104 const gchar *member,
105 JsonObject *defawlt,
106 JsonObject **value)
107 {
108 JsonNode *node;
109
110 node = json_object_get_member (options, member);
111 if (!node)
112 {
113 if (value)
114 *value = defawlt;
115 return TRUE;
116 }
117 else if (json_node_get_node_type (node) == JSON_NODE_OBJECT)
118 {
119 if (value)
120 *value = json_node_get_object (node);
121 return TRUE;
122 }
123 else
124 {
125 return FALSE;
126 }
127 }
128
129 /**
130 * cockpit_json_get_strv:
131 * @options: the json object
132 * @member: the member name
133 * @defawlt: defawlt value
134 * @value: returned value
135 *
136 * Gets a string array member from a JSON object. Validates
137 * that the member is an array, and that all elements in the
138 * array are strings. If these fail, then will return %FALSE.
139 *
140 * If @member does not exist in @options, returns the values
141 * in @defawlt.
142 *
143 * The returned value in @value should be freed with g_free()
144 * but the actual strings are owned by the JSON object.
145 *
146 * Returns: %FALSE if invalid member, %TRUE if valid or missing.
147 */
148 gboolean
149 cockpit_json_get_strv (JsonObject *options,
150 const gchar *member,
151 const gchar **defawlt,
152 const gchar ***value)
153 {
154 gboolean valid = FALSE;
155 JsonArray *array;
156 JsonNode *node;
157 guint length, i;
158 const gchar **val = NULL;
159
160 node = json_object_get_member (options, member);
161 if (!node)
162 {
163 if (defawlt)
164 val = g_memdup2 (defawlt, sizeof (gchar *) * (g_strv_length ((gchar **)defawlt) + 1));
165 valid = TRUE;
166 }
167 else if (json_node_get_node_type (node) == JSON_NODE_ARRAY)
168 {
169 valid = TRUE;
170 array = json_node_get_array (node);
171 length = json_array_get_length (array);
172 val = g_new (const gchar *, length + 1);
173 for (i = 0; i < length; i++)
174 {
175 node = json_array_get_element (array, i);
176 if (json_node_get_value_type (node) == G_TYPE_STRING)
177 {
178 val[i] = json_node_get_string (node);
179 }
180 else
181 {
182 valid = FALSE;
183 break;
184 }
185 }
186 val[length] = NULL;
187 }
188
189 if (valid && value)
190 *value = val;
191 else
192 g_free (val);
193
194 return valid;
195 }
196
197 /**
198 * cockpit_json_parse:
199 * @data: string data to parse
200 * @length: length of @data or -1
201 * @error: optional location to return an error
202 *
203 * Parses JSON into a JsonNode.
204 *
205 * Returns: (transfer full): the parsed node or %NULL
206 */
207 JsonNode *
208 cockpit_json_parse (const gchar *data,
209 gssize length,
210 GError **error)
211 {
212 static GPrivate cached_parser = G_PRIVATE_INIT (g_object_unref);
213 JsonParser *parser;
214 JsonNode *root;
215
216 parser = g_private_get (&cached_parser);
217 if (parser == NULL)
218 {
219 parser = json_parser_new ();
220 g_private_set (&cached_parser, parser);
221 }
222
223 if (!json_parser_load_from_data (parser, data, length, error))
224 return NULL;
225
226 root = json_parser_steal_root (parser);
227 if (root == NULL)
228 {
229 g_set_error (error, JSON_PARSER_ERROR, JSON_PARSER_ERROR_PARSE,
230 "JSON data was empty");
231 return NULL;
232 }
233
234 return root;
235 }
236
237 /**
238 * cockpit_json_parse_object:
239 * @data: string data to parse
240 * @length: length of @data or -1
241 * @error: optional location to return an error
242 *
243 * Parses JSON GBytes into a JsonObject. This is a helper function
244 * combining cockpit_json_parse(), json_node_get_type() and
245 * json_node_get_object().
246 *
247 * Returns: (transfer full): the parsed object or %NULL
248 */
249 JsonObject *
250 cockpit_json_parse_object (const gchar *data,
251 gssize length,
252 GError **error)
253 {
254 JsonNode *node;
255 JsonObject *object;
256
257 node = cockpit_json_parse (data, length, error);
258 if (!node)
259 return NULL;
260
261 if (json_node_get_node_type (node) != JSON_NODE_OBJECT)
262 {
263 object = NULL;
264 g_set_error (error, JSON_PARSER_ERROR, JSON_PARSER_ERROR_UNKNOWN, "Not a JSON object");
265 }
266 else
267 {
268 object = json_node_dup_object (node);
269 }
270
271 json_node_free (node);
272 return object;
273 }
274
275 /**
276 * cockpit_json_parse_bytes:
277 * @data: data to parse
278 * @error: optional location to return an error
279 *
280 * Parses JSON GBytes into a JsonObject. This is a helper function
281 * combining cockpit_json_parse(), json_node_get_type() and
282 * json_node_get_object().
283 *
284 * Returns: (transfer full): the parsed object or %NULL
285 */
286 JsonObject *
287 cockpit_json_parse_bytes (GBytes *data,
288 GError **error)
289 {
290 gsize length = g_bytes_get_size (data);
291
292 if (length == 0)
293 {
294 g_set_error (error, JSON_PARSER_ERROR, JSON_PARSER_ERROR_PARSE,
295 "JSON data was empty");
296 return NULL;
297 }
298
299 return cockpit_json_parse_object (g_bytes_get_data (data, NULL), length, error);
300 }
301
302 /**
303 * cockpit_json_write_object:
304 * @object: object to write
305 * @length: optionally a location to return the length
306 *
307 * Encode a JsonObject to a string.
308 *
309 * Returns: (transfer full): the encoded data
310 */
311 static gchar *
312 cockpit_json_write_object (JsonObject *object,
313 gsize *length)
314 {
315 JsonNode *node;
316 gchar *ret;
317
318 node = json_node_new (JSON_NODE_OBJECT);
319 json_node_set_object (node, object);
320 ret = cockpit_json_write (node, length);
321 json_node_free (node);
322
323 return ret;
324 }
325
326 /**
327 * cockpit_json_write_bytes:
328 * @object: object to write
329 *
330 * Encode a JsonObject to a GBytes.
331 *
332 * Returns: (transfer full): the encoded data
333 */
334 GBytes *
335 cockpit_json_write_bytes (JsonObject *object)
336 {
337 gchar *data;
338 gsize length;
339
340 data = cockpit_json_write_object (object, &length);
341 return g_bytes_new_take (data, length);
342 }
343
344 /*
345 * HACK: JsonGenerator is completely borked, so we've copied it\
346 * here until we can rely on a fixed version.
347 *
348 * https://bugzilla.gnome.org/show_bug.cgi?id=727593
349 */
350
351 static gchar *dump_value (const gchar *name,
352 JsonNode *node,
353 gsize *length);
354 static gchar *dump_array (const gchar *name,
355 JsonArray *array,
356 gsize *length);
357 static gchar *dump_object (const gchar *name,
358 JsonObject *object,
359 gsize *length);
360
361 static gchar *
362 json_strescape (const gchar *str)
363 {
364 const gchar *p;
365 const gchar *end;
366 GString *output;
367 gsize len;
368
369 len = strlen (str);
370 end = str + len;
371 output = g_string_sized_new (len);
372
373 for (p = str; p < end; p++)
374 {
375 if (*p == '\\' || *p == '"')
376 {
377 g_string_append_c (output, '\\');
378 g_string_append_c (output, *p);
379 }
380 else if ((*p > 0 && *p < 0x1f) || *p == 0x7f)
381 {
382 switch (*p)
383 {
384 case '\b':
385 g_string_append (output, "\\b");
386 break;
387 case '\f':
388 g_string_append (output, "\\f");
389 break;
390 case '\n':
391 g_string_append (output, "\\n");
392 break;
393 case '\r':
394 g_string_append (output, "\\r");
395 break;
396 case '\t':
397 g_string_append (output, "\\t");
398 break;
399 default:
400 g_string_append_printf (output, "\\u00%02x", (guint)*p);
401 break;
402 }
403 }
404 else
405 {
406 g_string_append_c (output, *p);
407 }
408 }
409
410 return g_string_free (output, FALSE);
411 }
412
413 static gchar *
414 dump_value (const gchar *name,
415 JsonNode *node,
416 gsize *length)
417 {
418 g_autoptr(GString) buffer = g_string_new ("");
419
420 if (name)
421 g_string_append_printf (buffer, "\"%s\":", name);
422
423 GType type = json_node_get_value_type (node);
424 if (type == G_TYPE_INT64)
425 {
426 g_string_append_printf (buffer, "%" G_GINT64_FORMAT, json_node_get_int (node));
427 }
428 else if (type == G_TYPE_DOUBLE)
429 {
430 gchar buf[G_ASCII_DTOSTR_BUF_SIZE];
431 gdouble d = json_node_get_double (node);
432
433 if (fpclassify (d) == FP_NAN || fpclassify (d) == FP_INFINITE)
434 {
435 g_string_append (buffer, "null");
436 }
437 else
438 {
439 g_string_append (buffer, g_ascii_dtostr (buf, sizeof (buf), d));
440 }
441 }
442 else if (type == G_TYPE_BOOLEAN)
443 {
444 g_string_append (buffer, json_node_get_boolean (node) ? "true" : "false");
445 }
446 else if (type == G_TYPE_STRING)
447 {
448 gchar *tmp;
449
450 tmp = json_strescape (json_node_get_string (node));
451 g_string_append_c (buffer, '"');
452 g_string_append (buffer, tmp);
453 g_string_append_c (buffer, '"');
454
455 g_free (tmp);
456 }
457 else
458 {
459 if (length)
460 *length = 0;
461 g_return_val_if_reached (NULL);
462 }
463
464 if (length)
465 *length = buffer->len;
466
467 return g_string_free (g_steal_pointer (&buffer), FALSE);
468 }
469
470 static gchar *
471 dump_array (const gchar *name,
472 JsonArray *array,
473 gsize *length)
474 {
475 guint array_len = json_array_get_length (array);
476 guint i;
477 GString *buffer;
478
479 buffer = g_string_new ("");
480
481 if (name)
482 g_string_append_printf (buffer, "\"%s\":", name);
483
484 g_string_append_c (buffer, '[');
485
486 for (i = 0; i < array_len; i++)
487 {
488 JsonNode *cur = json_array_get_element (array, i);
489 gchar *value;
490
491 switch (JSON_NODE_TYPE (cur))
492 {
493 case JSON_NODE_NULL:
494 g_string_append (buffer, "null");
495 break;
496
497 case JSON_NODE_VALUE:
498 value = dump_value (NULL, cur, NULL);
499 g_string_append (buffer, value);
500 g_free (value);
501 break;
502
503 case JSON_NODE_ARRAY:
504 value = dump_array (NULL, json_node_get_array (cur), NULL);
505 g_string_append (buffer, value);
506 g_free (value);
507 break;
508
509 case JSON_NODE_OBJECT:
510 value = dump_object (NULL, json_node_get_object (cur), NULL);
511 g_string_append (buffer, value);
512 g_free (value);
513 break;
514 }
515
516 if ((i + 1) != array_len)
517 g_string_append_c (buffer, ',');
518 }
519
520 g_string_append_c (buffer, ']');
521
522 if (length)
523 *length = buffer->len;
524
525 return g_string_free (buffer, FALSE);
526 }
527
528 static gchar *
529 dump_object (const gchar *name,
530 JsonObject *object,
531 gsize *length)
532 {
533 GList *members, *l;
534 GString *buffer;
535
536 buffer = g_string_new ("");
537
538 if (name)
539 g_string_append_printf (buffer, "\"%s\":", name);
540
541 g_string_append_c (buffer, '{');
542
543 members = json_object_get_members (object);
544
545 for (l = members; l != NULL; l = l->next)
546 {
547 const gchar *member_name = l->data;
548 gchar *escaped_name = json_strescape (member_name);
549 JsonNode *cur = json_object_get_member (object, member_name);
550 gchar *value;
551
552 switch (JSON_NODE_TYPE (cur))
553 {
554 case JSON_NODE_NULL:
555 g_string_append_printf (buffer, "\"%s\":null", escaped_name);
556 break;
557
558 case JSON_NODE_VALUE:
559 value = dump_value (escaped_name, cur, NULL);
560 g_string_append (buffer, value);
561 g_free (value);
562 break;
563
564 case JSON_NODE_ARRAY:
565 value = dump_array (escaped_name, json_node_get_array (cur), NULL);
566 g_string_append (buffer, value);
567 g_free (value);
568 break;
569
570 case JSON_NODE_OBJECT:
571 value = dump_object (escaped_name, json_node_get_object (cur), NULL);
572 g_string_append (buffer, value);
573 g_free (value);
574 break;
575 }
576
577 if (l->next != NULL)
578 g_string_append_c (buffer, ',');
579
580 g_free (escaped_name);
581 }
582
583 g_list_free (members);
584
585 g_string_append_c (buffer, '}');
586
587 if (length)
588 *length = buffer->len;
589
590 return g_string_free (buffer, FALSE);
591 }
592
593 /**
594 * cockpit_json_write:
595 * @node: the node to encode
596 * @length: optional place to return length
597 *
598 * Encode a JsonNode to a string.
599 *
600 * Returns: (transfer full): the encoded string
601 */
602 gchar *
603 cockpit_json_write (JsonNode *node,
604 gsize *length)
605 {
606 gchar *retval = NULL;
607
608 if (!node)
609 {
610 if (length)
611 *length = 0;
612 return NULL;
613 }
614
615 switch (JSON_NODE_TYPE (node))
616 {
617 case JSON_NODE_ARRAY:
618 retval = dump_array (NULL, json_node_get_array (node), length);
619 break;
620
621 case JSON_NODE_OBJECT:
622 retval = dump_object (NULL, json_node_get_object (node), length);
623 break;
624
625 case JSON_NODE_NULL:
626 retval = g_strdup ("null");
627 if (length)
628 *length = 4;
629 break;
630
631 case JSON_NODE_VALUE:
632 retval = dump_value (NULL, node, length);
633 break;
634 }
635
636 return retval;
637 }
638
639 GHashTable *
640 cockpit_json_to_hash_table (JsonObject *object,
641 const gchar **fields)
642 {
643 gint i;
644 GHashTable *hash_table = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, g_free);
645
646 for (i = 0; fields[i] != NULL; i++)
647 {
648 const gchar *value;
649 if (!cockpit_json_get_string (object, fields[i], NULL, &value))
650 continue;
651
652 if (value)
653 g_hash_table_insert (hash_table, g_strdup (fields[i]), g_strdup (value));
654 }
655
656 return hash_table;
657 }