File: json-parser.c

package info (click to toggle)
syslog-ng 4.8.1-6
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 20,456 kB
  • sloc: ansic: 177,631; python: 13,035; cpp: 11,611; makefile: 7,012; sh: 5,147; java: 3,651; xml: 3,344; yacc: 1,377; lex: 599; perl: 193; awk: 190; objc: 162
file content (421 lines) | stat: -rw-r--r-- 12,751 bytes parent folder | download | duplicates (2)
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
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
/*
 * Copyright (c) 2011-2014 Balabit
 * Copyright (c) 2011-2014 Gergely Nagy <algernon@balabit.hu>
 *
 * This program is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License version 2 as published
 * by the Free Software Foundation, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 *
 * As an additional exemption you are allowed to compile & link against the
 * OpenSSL libraries as published by the OpenSSL project. See the file
 * COPYING for details.
 */

#define JSON_C_VER_013 (13 << 8)

#include "json-parser.h"
#include "dot-notation.h"
#include "scratch-buffers.h"
#include "str-repr/encode.h"

#include <string.h>
#include <ctype.h>

#include <json.h>

#if (!defined(JSON_C_VERSION_NUM)) || (JSON_C_VERSION_NUM < JSON_C_VER_013)
#include <json_object_private.h>
#endif

typedef struct _JSONParser
{
  LogParser super;
  gchar *prefix;
  gchar *marker;
  gint marker_len;
  gchar *extract_prefix;
  gchar key_delimiter;
} JSONParser;

void
json_parser_set_prefix(LogParser *p, const gchar *prefix)
{
  JSONParser *self = (JSONParser *)p;

  g_free(self->prefix);
  self->prefix = g_strdup(prefix);
}

void
json_parser_set_marker(LogParser *p, const gchar *marker)
{
  JSONParser *self = (JSONParser *)p;

  g_free(self->marker);
  self->marker = g_strdup(marker);
  self->marker_len = marker ? strlen(marker) : 0;
}

void
json_parser_set_extract_prefix(LogParser *s, const gchar *extract_prefix)
{
  JSONParser *self = (JSONParser *) s;

  g_free(self->extract_prefix);
  self->extract_prefix = g_strdup(extract_prefix);
}

void
json_parser_set_key_delimiter(LogParser *s, gchar delimiter)
{
  JSONParser *self = (JSONParser *) s;

  self->key_delimiter = delimiter;
}

static void
json_parser_store_value(JSONParser *self,
                        const gchar *prefix, const gchar *obj_key,
                        GString *value, LogMessageValueType type,
                        LogMessage *msg)
{
  GString *key;

  key = scratch_buffers_alloc();
  if (prefix)
    {
      g_string_assign(key, prefix);
      g_string_append(key, obj_key);
      log_msg_set_value_by_name_with_type(msg, key->str, value->str, value->len, type);
    }
  else
    log_msg_set_value_by_name_with_type(msg, obj_key, value->str, value->len, type);
}

static void
json_parser_process_object(JSONParser *self,
                           struct json_object *jso,
                           const gchar *prefix,
                           LogMessage *msg);


static gboolean
json_parser_extract_string_from_simple_json_object(JSONParser *self,
                                                   struct json_object *jso,
                                                   GString *value,
                                                   LogMessageValueType *type)
{
  switch (json_object_get_type(jso))
    {
    case json_type_boolean:
      if (json_object_get_boolean(jso))
        g_string_assign(value, "true");
      else
        g_string_assign(value, "false");
      *type = LM_VT_BOOLEAN;
      return TRUE;
    case json_type_double:
      g_string_printf(value, "%f",
                      json_object_get_double(jso));
      *type = LM_VT_DOUBLE;
      return TRUE;
    case json_type_int:
      g_string_printf(value, "%"PRId64,
                      json_object_get_int64(jso));
      *type = LM_VT_INTEGER;
      return TRUE;
    case json_type_string:
      g_string_assign(value,
                      json_object_get_string(jso));
      *type = LM_VT_STRING;
      return TRUE;
    case json_type_null:

      /* null values are represented as an empty string (so when expands to
       * "nothing" in type unaware situations, while type-aware consumers
       * may reproduce it as a NULL).
       *
       * I was thinking about using a very specific string representation
       * (e.g.  "NULL" as a value), however if we encounter a null at a
       * place where we might also have a sub-object, and we explicitly
       * reference a field within that sub-object, we would get an empty
       * string in that case too (due to the key being unknown).  All in
       * all, the base case is I think to use an empty string as value, and
       * LM_VT_NULL as type.  Type aware consumers would ignore the string
       * anyway.
       */
      g_string_truncate(value, 0);
      *type = LM_VT_NULL;
      return TRUE;
    default:
      break;
    }
  return FALSE;
}

static gboolean
json_parser_extract_value_from_simple_json_object(JSONParser *self,
                                                  struct json_object *jso,
                                                  const gchar *prefix, const gchar *obj_key,
                                                  LogMessage *msg)
{
  GString *value = scratch_buffers_alloc();
  LogMessageValueType type = LM_VT_STRING;

  if (!json_parser_extract_string_from_simple_json_object(self, jso, value, &type))
    return FALSE;
  json_parser_store_value(self, prefix, obj_key, value, type, msg);
  return TRUE;
}

static gboolean
json_parser_extract_values_from_complex_json_object(JSONParser *self,
                                                    struct json_object *jso,
                                                    const gchar *prefix, const gchar *obj_key,
                                                    LogMessage *msg)
{
  switch (json_object_get_type(jso))
    {
    case json_type_object:
    {
      GString *key = scratch_buffers_alloc();
      if (prefix)
        g_string_assign(key, prefix);
      g_string_append(key, obj_key);
      g_string_append_c(key, self->key_delimiter);
      json_parser_process_object(self, jso, key->str, msg);
      return TRUE;
    }
    case json_type_array:
    {
      GString *value = scratch_buffers_alloc();
      LogMessageValueType type = LM_VT_LIST;

      g_string_truncate(value, 0);

      for (gint i = 0; i < json_object_array_length(jso); i++)
        {
          struct json_object *el = json_object_array_get_idx(jso, i);
          if (json_object_get_type(el) == json_type_string)
            {
              const gchar *element_value = json_object_get_string(el);
              if (i != 0)
                g_string_append_c(value, ',');
              str_repr_encode_append(value, element_value, -1, NULL);
            }
          else
            {
              /* unknown type, encode the entire array as JSON */
              g_string_assign(value, json_object_to_json_string_ext(jso, JSON_C_TO_STRING_PLAIN));
              type = LM_VT_JSON;
              break;
            }
        }

      json_parser_store_value(self, prefix, obj_key, value, type, msg);
      return TRUE;
    }
    default:
      break;
    }
  return FALSE;
}


static void
json_parser_process_attribute(JSONParser *self,
                              struct json_object *jso,
                              const gchar *prefix,
                              const gchar *obj_key,
                              LogMessage *msg)
{
  ScratchBuffersMarker marker;
  scratch_buffers_mark(&marker);

  if (!json_parser_extract_value_from_simple_json_object(self, jso, prefix, obj_key, msg) &&
      !json_parser_extract_values_from_complex_json_object(self, jso, prefix, obj_key, msg))
    {
      msg_debug("JSON parser encountered an unknown type, skipping",
                evt_tag_str("key", obj_key),
                evt_tag_int("type", json_object_get_type(jso)));
    }


  scratch_buffers_reclaim_marked(marker);
}

static void
json_parser_process_object(JSONParser *self,
                           struct json_object *jso,
                           const gchar *prefix,
                           LogMessage *msg)
{
  struct json_object_iter itr;

  json_object_object_foreachC(jso, itr)
  {
    json_parser_process_attribute(self, itr.val, prefix, itr.key, msg);
  }
}

static void
json_parser_process_array(JSONParser *self,
                          struct json_object *jso,
                          const gchar *prefix,
                          LogMessage *msg)
{
  gint i;

  log_msg_unset_match(msg, 0);
  for (i = 0; i < json_object_array_length(jso) && i < LOGMSG_MAX_MATCHES; i++)
    {
      struct json_object *el = json_object_array_get_idx(jso, i);
      GString *element_value = scratch_buffers_alloc();
      LogMessageValueType element_type;

      if (json_parser_extract_string_from_simple_json_object(self, el, element_value, &element_type))
        {
          log_msg_set_match_with_type(msg, i + 1, element_value->str, element_value->len, element_type);
        }
      else
        {
          /* unknown type, encode the entire value as JSON */
          log_msg_set_match_with_type(msg, i + 1, json_object_to_json_string_ext(el, JSON_C_TO_STRING_PLAIN), -1, LM_VT_JSON);
        }
    }
  log_msg_truncate_matches(msg, i + 1);
}

static gboolean
json_parser_extract(JSONParser *self, struct json_object *jso, LogMessage *msg)
{
  if (self->extract_prefix)
    jso = json_extract(jso, self->extract_prefix);

  if (!jso)
    return FALSE;

  if (json_object_is_type(jso, json_type_object))
    {
      json_parser_process_object(self, jso, self->prefix, msg);
      return TRUE;
    }
  if (json_object_is_type(jso, json_type_array))
    {
      json_parser_process_array(self, jso, self->prefix, msg);
      return TRUE;
    }
  return FALSE;
}

#ifndef JSON_C_VERSION
const char *
json_tokener_error_desc(enum json_tokener_error err)
{
  return json_tokener_errors[err];
}
#endif

static gboolean
json_parser_process(LogParser *s, LogMessage **pmsg, const LogPathOptions *path_options, const gchar *input,
                    gsize input_len)
{
  JSONParser *self = (JSONParser *) s;
  struct json_object *jso;
  struct json_tokener *tok;

  msg_trace("json-parser message processing started",
            evt_tag_str("input", input),
            evt_tag_str("prefix", self->prefix),
            evt_tag_str("marker", self->marker),
            evt_tag_msg_reference(*pmsg));
  if (self->marker)
    {
      if (strncmp(input, self->marker, self->marker_len) != 0)
        {
          msg_debug("json-parser(): no marker at the beginning of the message, skipping JSON parsing ",
                    evt_tag_str("input", input),
                    evt_tag_str("marker", self->marker));
          return FALSE;
        }
      input += self->marker_len;

      while (isspace(*input))
        input++;
    }

  tok = json_tokener_new();
  jso = json_tokener_parse_ex(tok, input, input_len);
  if (tok->err != json_tokener_success || !jso)
    {
      msg_debug("json-parser(): failed to parse JSON payload",
                evt_tag_str("input", input),
                tok->err != json_tokener_success ? evt_tag_str ("json_error", json_tokener_error_desc(tok->err)) : NULL);
      json_tokener_free (tok);
      return FALSE;
    }
  json_tokener_free(tok);

  log_msg_make_writable(pmsg, path_options);
  if (!json_parser_extract(self, jso, *pmsg))
    {
      msg_debug("json-parser(): failed to extract JSON members into name-value pairs. The parsed/extracted JSON payload was not an object",
                evt_tag_str("input", input),
                evt_tag_str("extract_prefix", self->extract_prefix));
      json_object_put(jso);
      return FALSE;
    }
  json_object_put(jso);

  return TRUE;
}

static LogPipe *
json_parser_clone(LogPipe *s)
{
  JSONParser *self = (JSONParser *) s;
  LogParser *cloned;

  cloned = json_parser_new(s->cfg);
  log_parser_clone_settings(&self->super, cloned);
  json_parser_set_prefix(cloned, self->prefix);
  json_parser_set_marker(cloned, self->marker);
  json_parser_set_extract_prefix(cloned, self->extract_prefix);
  json_parser_set_key_delimiter(cloned, self->key_delimiter);

  return &cloned->super;
}

static void
json_parser_free(LogPipe *s)
{
  JSONParser *self = (JSONParser *)s;

  g_free(self->prefix);
  g_free(self->marker);
  g_free(self->extract_prefix);
  log_parser_free_method(s);
}

LogParser *
json_parser_new(GlobalConfig *cfg)
{
  JSONParser *self = g_new0(JSONParser, 1);

  log_parser_init_instance(&self->super, cfg);
  self->super.super.free_fn = json_parser_free;
  self->super.super.clone = json_parser_clone;
  self->super.process = json_parser_process;
  self->key_delimiter = '.';

  return &self->super;
}