File: csvparser.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 (406 lines) | stat: -rw-r--r-- 11,816 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
/*
 * Copyright (c) 2002-2015 Balabit
 * Copyright (c) 1998-2015 Balázs Scheidler
 *
 * 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.
 *
 */

#include "csvparser.h"
#include "scanner/csv-scanner/csv-scanner.h"
#include "parser/parser-expr.h"
#include "scratch-buffers.h"

#include <string.h>


CSVParserColumn *
csv_parser_column_new(const gchar *name, LogMessageValueType type)
{
  CSVParserColumn *self = g_new0(CSVParserColumn, 1);

  self->name = g_strdup(name);
  self->type = type;
  return self;
}

CSVParserColumn *
csv_parser_column_clone(CSVParserColumn *other)
{
  return csv_parser_column_new(other->name, other->type);
}

void
csv_parser_column_free(CSVParserColumn *self)
{
  g_free(self->name);
  g_free(self);
}

typedef struct _CSVParser
{
  LogParser super;
  CSVScannerOptions options;
  GList *columns;
  gchar *prefix;
  gint prefix_len;
  gint on_error;
} CSVParser;

#define CSV_PARSER_FLAGS_SHIFT 16
#define CSV_PARSER_FLAGS_MASK  0xFFFF0000
#define CSV_SCANNER_FLAGS_MASK 0xFFFF

#define CSV_PARSER_DIALECT_MASK              (0x7 << CSV_PARSER_FLAGS_SHIFT)
#define CSV_PARSER_ESCAPE_MODE_NONE          (1 << CSV_PARSER_FLAGS_SHIFT)
#define CSV_PARSER_ESCAPE_MODE_BACKSLASH     (2 << CSV_PARSER_FLAGS_SHIFT)
#define CSV_PARSER_ESCAPE_MODE_DOUBLE_CHAR   (4 << CSV_PARSER_FLAGS_SHIFT)
#define CSV_PARSER_DROP_INVALID              (8 << CSV_PARSER_FLAGS_SHIFT)

CSVScannerOptions *
csv_parser_get_scanner_options(LogParser *s)
{
  CSVParser *self = (CSVParser *) s;

  return &self->options;
}

void
csv_parser_set_columns(LogParser *s, GList *columns)
{
  CSVParser *self = (CSVParser *) s;

  self->columns = columns;
}

gboolean
csv_parser_set_flags(LogParser *s, guint32 flags)
{
  CSVParser *self = (CSVParser *) s;
  guint32 dialect = (flags & CSV_PARSER_DIALECT_MASK);
  guint32 scanner_flags = flags & CSV_SCANNER_FLAGS_MASK;

  csv_scanner_options_set_flags(&self->options, scanner_flags);
  switch (dialect)
    {
    case 0:
      break;
    case CSV_PARSER_ESCAPE_MODE_NONE:
      csv_scanner_options_set_dialect(&self->options, CSV_SCANNER_ESCAPE_NONE);
      break;
    case CSV_PARSER_ESCAPE_MODE_BACKSLASH:
      csv_scanner_options_set_dialect(&self->options, CSV_SCANNER_ESCAPE_BACKSLASH);
      break;
    case CSV_PARSER_ESCAPE_MODE_DOUBLE_CHAR:
      csv_scanner_options_set_dialect(&self->options, CSV_SCANNER_ESCAPE_DOUBLE_CHAR);
      break;
    default:
      return FALSE;
    }
  if (flags & CSV_PARSER_DROP_INVALID)
    csv_parser_set_drop_invalid((LogParser *) self, TRUE);
  return TRUE;
}

void
csv_parser_set_prefix(LogParser *s, const gchar *prefix)
{
  CSVParser *self = (CSVParser *) s;

  g_free(self->prefix);
  if (prefix)
    {
      self->prefix = g_strdup(prefix);
      self->prefix_len = strlen(prefix);
    }
  else
    {
      self->prefix = NULL;
      self->prefix_len = 0;
    }
}

void
csv_parser_set_drop_invalid(LogParser *s, gboolean drop_invalid)
{
  CSVParser *self = (CSVParser *) s;
  if (drop_invalid)
    self->on_error |= ON_ERROR_DROP_MESSAGE;
  else
    self->on_error &= ~ON_ERROR_DROP_MESSAGE;
}

static const gchar *
_format_key_for_prefix(GString *scratch, const gchar *key, const gint prefix_len)
{
  g_string_truncate(scratch, prefix_len);
  g_string_append(scratch, key);
  return scratch->str;
}

static const gchar *
_return_key(GString *scratch, const gchar *key, const gint prefix_len)
{
  return key;
}

typedef const gchar *(*key_formatter_t)(GString *scratch, const gchar *key, const gint prefix_len);

static key_formatter_t
dispatch_key_formatter(gchar *prefix)
{
  return prefix ? _format_key_for_prefix : _return_key;
}

gboolean
_should_drop_message(CSVParser *self)
{
  return (self->on_error & ON_ERROR_DROP_MESSAGE);
}

static gboolean
_process_column_on_invalid_type_cast(CSVParser *self, LogMessageValueType *current_type)
{
  if(self->on_error & ON_ERROR_FALLBACK_TO_STRING)
    {
      if (!(self->on_error & ON_ERROR_SILENT))
        {
          msg_debug("csv-parser: error casting value to the type specified, trying string type because on-error(\"fallback-to-string\") was specified");
        }
      *current_type = LM_VT_STRING;
      return TRUE;
    }
  else if (self->on_error & ON_ERROR_DROP_PROPERTY)
    {
      if (!(self->on_error & ON_ERROR_SILENT))
        {
          msg_debug("csv-parser: error casting value to the type specified, dropping property because on-error(\"drop-property\") was specified");
        }
    }
  return FALSE;
}

static gboolean
_process_column(CSVParser *self, CSVScanner *scanner, LogMessage *msg, CSVParserColumn *current_column,
                GString *key_scratch)
{

  LogMessageValueType current_column_type = current_column->type;
  const gchar *current_value = csv_scanner_get_current_value(scanner);
  GError *error = NULL;
  key_formatter_t _key_formatter = dispatch_key_formatter(self->prefix);
  gboolean should_set_value = TRUE;

  if (!type_cast_validate(current_value, -1, current_column_type, &error))
    {
      if (!(self->on_error & ON_ERROR_SILENT))
        {
          msg_debug("csv-parser: error casting value to the type specified",
                    evt_tag_str("error", error->message)
                   );
        }
      g_clear_error(&error);

      gboolean need_drop = type_cast_drop_helper(self->on_error, current_value, -1,
                                                 log_msg_value_type_to_str(current_column_type));
      if (need_drop)
        {
          return FALSE;
        }

      should_set_value = _process_column_on_invalid_type_cast(self, &current_column_type);
    }

  if (should_set_value)
    {
      log_msg_set_value_by_name_with_type(msg,
                                          _key_formatter(key_scratch, current_column->name, self->prefix_len),
                                          csv_scanner_get_current_value(scanner),
                                          csv_scanner_get_current_value_len(scanner),
                                          current_column_type);
    }
  return TRUE;

}

static gboolean
_iterate_columns(CSVParser *self, CSVScanner *scanner, LogMessage *msg)
{
  GString *key_scratch = scratch_buffers_alloc();
  GList *column_l = self->columns;
  if (self->prefix)
    g_string_assign(key_scratch, self->prefix);

  gint match_index = 1;

  while (csv_scanner_scan_next(scanner))
    {
      if (self->columns)
        {
          CSVParserColumn *current_column = column_l->data;
          if (!_process_column(self, scanner, msg, current_column, key_scratch))
            {
              return FALSE;
            }
          column_l = g_list_next(column_l);
        }
      else
        {
          if (match_index == 1)
            log_msg_unset_match(msg, 0);
          log_msg_set_match_with_type(msg,
                                      match_index, csv_scanner_get_current_value(scanner),
                                      csv_scanner_get_current_value_len(scanner),
                                      LM_VT_STRING);
          match_index++;
        }
    }
  return TRUE;
}

static gboolean
csv_parser_process(LogParser *s, LogMessage **pmsg, const LogPathOptions *path_options, const gchar *input,
                   gsize input_len)
{
  CSVParser *self = (CSVParser *) s;
  LogMessage *msg = log_msg_make_writable(pmsg, path_options);

  msg_trace("csv-parser message processing started",
            evt_tag_str ("input", input),
            evt_tag_str ("prefix", self->prefix),
            evt_tag_msg_reference(msg));
  CSVScanner scanner;
  csv_scanner_init(&scanner, &self->options, input);

  gboolean result = TRUE;

  if (!_iterate_columns(self, &scanner, msg))
    result = FALSE;
  if (!csv_scanner_is_scan_complete(&scanner))
    result = FALSE;

  if (_should_drop_message(self) && !result && !(self->on_error & ON_ERROR_SILENT))
    {
      msg_debug("csv-parser() failed",
                evt_tag_str("error",
                            "csv-parser() failed to parse its input and drop-invalid(yes) or on-error(\"drop-message\") was specified"),
                evt_tag_str("input", input));
    }
  else
    result = TRUE;
  csv_scanner_deinit(&scanner);

  return result;
}

static LogPipe *
csv_parser_clone(LogPipe *s)
{
  CSVParser *self = (CSVParser *) s;
  CSVParser *cloned;

  cloned = (CSVParser *) csv_parser_new(s->cfg);
  log_parser_clone_settings(&self->super, &cloned->super);
  cloned->columns = g_list_copy_deep(self->columns, (GCopyFunc) csv_parser_column_clone, NULL);
  csv_scanner_options_copy(&cloned->options, &self->options);
  csv_parser_set_prefix(&cloned->super, self->prefix);
  csv_parser_set_on_error(&cloned->super, self->on_error);
  return &cloned->super.super;
}

static void
csv_parser_free(LogPipe *s)
{
  CSVParser *self = (CSVParser *) s;

  csv_scanner_options_clean(&self->options);
  g_free(self->prefix);
  log_parser_free_method(s);
}

static gboolean
csv_parser_init(LogPipe *s)
{
  CSVParser *self = (CSVParser *) s;

  csv_scanner_options_set_expected_columns(&self->options, g_list_length(self->columns));
  if (!csv_scanner_options_validate(&self->options))
    return FALSE;

  return log_parser_init_method(s);
}

/*
 * Parse comma-separated values from a log message.
 */
LogParser *
csv_parser_new(GlobalConfig *cfg)
{
  CSVParser *self = g_new0(CSVParser, 1);

  log_parser_init_instance(&self->super, cfg);
  self->super.super.init = csv_parser_init;
  self->super.super.free_fn = csv_parser_free;
  self->super.super.clone = csv_parser_clone;
  self->super.process = csv_parser_process;

  csv_scanner_options_set_delimiters(&self->options, " ");
  csv_scanner_options_set_quote_pairs(&self->options, "\"\"''");
  csv_scanner_options_set_flags(&self->options, CSV_SCANNER_STRIP_WHITESPACE);
  csv_scanner_options_set_dialect(&self->options, CSV_SCANNER_ESCAPE_NONE);
  return &self->super;
}

guint32
csv_parser_lookup_flag(const gchar *flag)
{
  if (strcmp(flag, "escape-none") == 0)
    return CSV_PARSER_ESCAPE_MODE_NONE;
  else if (strcmp(flag, "escape-backslash") == 0)
    return CSV_PARSER_ESCAPE_MODE_BACKSLASH;
  else if (strcmp(flag, "escape-double-char") == 0)
    return CSV_PARSER_ESCAPE_MODE_DOUBLE_CHAR;
  else if (strcmp(flag, "strip-whitespace") == 0)
    return CSV_SCANNER_STRIP_WHITESPACE;
  else if (strcmp(flag, "greedy") == 0)
    return CSV_SCANNER_GREEDY;
  else if (strcmp(flag, "drop-invalid") == 0)
    return CSV_PARSER_DROP_INVALID;
  return 0;
}

gint
csv_parser_lookup_dialect(const gchar *flag)
{
  if (strcmp(flag, "escape-none") == 0)
    return CSV_SCANNER_ESCAPE_NONE;
  else if (strcmp(flag, "escape-backslash") == 0)
    return CSV_SCANNER_ESCAPE_BACKSLASH;
  else if (strcmp(flag, "escape-backslash-with-sequences") == 0)
    return CSV_SCANNER_ESCAPE_BACKSLASH_WITH_SEQUENCES;
  else if (strcmp(flag, "escape-double-char") == 0)
    return CSV_SCANNER_ESCAPE_DOUBLE_CHAR;
  return -1;
}

void
csv_parser_set_on_error(LogParser *s, gint on_error)
{
  CSVParser *self = (CSVParser *) s;
  self->on_error = on_error;
}