File: csvparser.c

package info (click to toggle)
syslog-ng 3.3.5-4
  • links: PTS
  • area: main
  • in suites: wheezy
  • size: 14,120 kB
  • sloc: ansic: 60,880; sh: 12,423; yacc: 7,308; xml: 1,554; makefile: 1,242; python: 801; lex: 262; perl: 216; awk: 184
file content (413 lines) | stat: -rw-r--r-- 13,485 bytes parent folder | download
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
/*
 * Copyright (c) 2002-2010 BalaBit IT Ltd, Budapest, Hungary
 * Copyright (c) 1998-2010 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 library 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
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; 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 "logparser.h"

#include <string.h>

typedef struct _LogCSVParser
{
  LogColumnParser super;
  gchar *delimiters;
  gchar *quotes_start;
  gchar *quotes_end;
  gchar *null_value;
  guint32 flags;
} LogCSVParser;

#define LOG_CSV_PARSER_SINGLE_CHAR_DELIM 0x0100

void
log_csv_parser_set_flags(LogColumnParser *s, guint32 flags)
{
  LogCSVParser *self = (LogCSVParser *) s;

  self->flags = flags;
}

void
log_csv_parser_set_delimiters(LogColumnParser *s, const gchar *delimiters)
{
  LogCSVParser *self = (LogCSVParser *) s;

  if (self->delimiters)
    g_free(self->delimiters);
  self->delimiters = g_strdup(delimiters);
  if (strlen(delimiters) == 1)
    self->flags |= LOG_CSV_PARSER_SINGLE_CHAR_DELIM;
  else
    self->flags &= ~LOG_CSV_PARSER_SINGLE_CHAR_DELIM;
}

void
log_csv_parser_set_quotes(LogColumnParser *s, const gchar *quotes)
{
  LogCSVParser *self = (LogCSVParser *) s;

  if (self->quotes_start)
    g_free(self->quotes_start);
  if (self->quotes_end)
    g_free(self->quotes_end);
  self->quotes_start = g_strdup(quotes);
  self->quotes_end = g_strdup(quotes);
}

void
log_csv_parser_set_quote_pairs(LogColumnParser *s, const gchar *quote_pairs)
{
  LogCSVParser *self = (LogCSVParser *) s;
  gint i;

  if (self->quotes_start)
    g_free(self->quotes_start);
  if (self->quotes_end)
    g_free(self->quotes_end);

  self->quotes_start = g_malloc((strlen(quote_pairs) / 2) + 1);
  self->quotes_end = g_malloc((strlen(quote_pairs) / 2) + 1);

  for (i = 0; quote_pairs[i] && quote_pairs[i+1]; i += 2)
    {
      self->quotes_start[i / 2] = quote_pairs[i];
      self->quotes_end[i / 2] = quote_pairs[i + 1];
    }
  self->quotes_start[i / 2] = 0;
  self->quotes_end[i / 2] = 0;
}

void
log_csv_parser_set_null_value(LogColumnParser *s, const gchar *null_value)
{
  LogCSVParser *self = (LogCSVParser *) s;

  if (self->null_value)
    g_free(self->null_value);
  self->null_value = g_strdup(null_value);
}

static gboolean
log_csv_parser_process(LogParser *s, LogMessage *msg, const gchar *input)
{
  LogCSVParser *self = (LogCSVParser *) s;
  const gchar *src;
  GList *cur_column = self->super.columns;
  gint len;

  src = input;
  if ((self->flags & LOG_CSV_PARSER_ESCAPE_NONE) || ((self->flags & LOG_CSV_PARSER_ESCAPE_MASK) == 0))
    {
      /* no escaping, no need to keep state, we split input and trim if necessary */

      while (cur_column && *src)
        {
          const guchar *delim;
          guchar *quote;
          guchar current_quote;

          quote = (guchar *) strchr(self->quotes_start, *src);
          if (quote != NULL)
            {
              /* ok, quote character found */
              current_quote = self->quotes_end[quote - (guchar *) self->quotes_start];
              src++;
            }
          else
            {
              /* we didn't start with a quote character, no need for escaping, delimiter terminates */
              current_quote = 0;
            }

          if (self->flags & LOG_CSV_PARSER_STRIP_WHITESPACE)
            {
              while (*src == ' ' || *src == '\t')
                src++;
            }

          if (current_quote)
            {
              /* search for end of quote */
              delim = (guchar *) strchr(src, current_quote);

              if (delim &&
                  (((self->flags & LOG_CSV_PARSER_SINGLE_CHAR_DELIM) && *(delim + 1) == self->delimiters[0]) ||
                     strchr(self->delimiters, *(delim + 1)) != NULL))
                {
                  /* closing quote, and then a delimiter, everything is nice */
                  delim++;
                }
              else if (!delim)
                {
                  /* complete remaining string */
                  delim = (guchar *) src + strlen(src);
                }
            }
          else
            {
              if (self->flags & LOG_CSV_PARSER_SINGLE_CHAR_DELIM)
                {
                  delim = (guchar *) strchr(src, self->delimiters[0]);
                  if (!delim)
                    delim = (guchar *) src + strlen(src);
                }
              else
                {
                  delim = (guchar *) src + strcspn(src, self->delimiters);
                }
            }


          len = delim - (guchar *) src;
          /* move in front of the terminating quote character */
          if (current_quote && len > 0 && src[len - 1] == current_quote)
            len--;
          if (len > 0 && self->flags & LOG_CSV_PARSER_STRIP_WHITESPACE)
            {
              while (len > 0 && (src[len - 1] == ' ' || src[len - 1] == '\t'))
                len--;
            }
          if (self->null_value && strncmp(src, self->null_value, len) == 0)
            log_msg_set_value(msg, log_msg_get_value_handle((gchar *) cur_column->data), "", 0);
          else
            log_msg_set_value(msg, log_msg_get_value_handle((gchar *) cur_column->data), src, len);

          src = (gchar *) delim;
          if (*src)
            src++;
          cur_column = cur_column->next;

          if (cur_column && cur_column->next == NULL && self->flags & LOG_CSV_PARSER_GREEDY)
            {
              /* greedy mode, the last column gets it all, without taking escaping, quotes or anything into account */
              log_msg_set_value(msg, log_msg_get_value_handle((gchar *) cur_column->data), src, -1);
              cur_column = NULL;
              src = NULL;
              break;
            }
        }
    }
  else if (self->flags & (LOG_CSV_PARSER_ESCAPE_BACKSLASH+LOG_CSV_PARSER_ESCAPE_DOUBLE_CHAR))
    {
      /* stateful parser */
      gint state;
      enum
        {
          PS_COLUMN_START,
          PS_WHITESPACE,
          PS_VALUE,
          PS_DELIMITER,
          PS_EOS
        };
      gchar current_quote = 0;
      GString *current_value;
      gboolean store_value = FALSE;
      gchar *quote;

      current_value = g_string_sized_new(128);

      state = PS_COLUMN_START;
      while (cur_column && *src)
        {
          switch (state)
            {
            case PS_COLUMN_START:
              /* check for quote character */
              state = PS_WHITESPACE;
              quote = strchr(self->quotes_start, *src);
              if (quote != NULL)
                {
                  /* ok, quote character found */
                  current_quote = self->quotes_end[quote - self->quotes_start];
                }
              else
                {
                  /* we didn't start with a quote character, no need for escaping, delimiter terminates */
                  current_quote = 0;
                  /* don't skip to the next character */
                  continue;
                }
              break;
            case PS_WHITESPACE:
              if ((self->flags & LOG_CSV_PARSER_STRIP_WHITESPACE) && (*src == ' ' || *src == '\t'))
                {
                  break;
                }
              state = PS_VALUE;
              /* fallthrough */
            case PS_VALUE:
              if (current_quote)
                {
                  /* quoted value */
                  if ((self->flags & LOG_CSV_PARSER_ESCAPE_BACKSLASH) && *src == '\\' && *(src+1))
                    {
                      src++;
                      g_string_append_c(current_value, *src);
                      break;
                    }
                  else if (self->flags & LOG_CSV_PARSER_ESCAPE_DOUBLE_CHAR && *src == current_quote && *(src+1) == current_quote)
                    {
                      src++;
                      g_string_append_c(current_value, *src);
                      break;
                    }
                  if (*src == current_quote)
                    {
                      /* end of column */
                      current_quote = 0;
                      state = PS_DELIMITER;
                      break;
                    }
                  g_string_append_c(current_value, *src);
                }
              else
                {
                  /* unquoted value */
                  if (strchr(self->delimiters, *src))
                    {
                      state = PS_DELIMITER;
                      continue;
                    }
                  g_string_append_c(current_value, *src);
                }
              break;
            case PS_DELIMITER:
              store_value = TRUE;
              break;
            }
          src++;
          if (*src == 0 || store_value)
            {
              len = current_value->len;
              if (self->flags & LOG_CSV_PARSER_STRIP_WHITESPACE)
                {
                  while (len > 0 && (current_value->str[len-1] == ' ' || current_value->str[len-1] == '\t'))
                    len--;
                }
              if (self->null_value && strcmp(current_value->str, self->null_value) == 0)
                log_msg_set_value(msg, log_msg_get_value_handle((gchar *) cur_column->data), "", 0);
              else
                log_msg_set_value(msg, log_msg_get_value_handle((gchar *) cur_column->data), current_value->str, len);
              g_string_truncate(current_value, 0);
              cur_column = cur_column->next;
              state = PS_COLUMN_START;
              store_value = FALSE;

              if (cur_column && cur_column->next == NULL && self->flags & LOG_CSV_PARSER_GREEDY)
                {
                  /* greedy mode, the last column gets it all, without taking escaping, quotes or anything into account */
                  log_msg_set_value(msg, log_msg_get_value_handle((gchar *) cur_column->data), src, -1);
                  cur_column = NULL;
                  src = NULL;
                  break;
                }
            }
        }
      g_string_free(current_value, TRUE);
    }
  if ((cur_column || (src && *src)) && (self->flags & LOG_CSV_PARSER_DROP_INVALID))
    {
      /* there are unfilled variables, OR not all of the input was processed
       * and "drop-invalid" flag is specified */
      return FALSE;
    }
  return TRUE;
}

static LogPipe *
log_csv_parser_clone(LogProcessPipe *s)
{
  LogCSVParser *self = (LogCSVParser *) s;
  LogCSVParser *cloned;
  GList *l;

  cloned = (LogCSVParser *) log_csv_parser_new();
  g_free(cloned->delimiters);
  g_free(cloned->quotes_start);
  g_free(cloned->quotes_end);

  cloned->delimiters = g_strdup(self->delimiters);
  cloned->quotes_start = g_strdup(self->quotes_start);
  cloned->quotes_end = g_strdup(self->quotes_end);
  cloned->null_value = self->null_value ? g_strdup(self->null_value) : NULL;
  cloned->flags = self->flags;

  cloned->super.super.template = log_template_ref(self->super.super.template);
  for (l = self->super.columns; l; l = l->next)
    {
      cloned->super.columns = g_list_append(cloned->super.columns, g_strdup(l->data));
    }
  return &cloned->super.super.super.super;
}

static void
log_csv_parser_free(LogPipe *s)
{
  LogCSVParser *self = (LogCSVParser *) s;

  if (self->quotes_start)
    g_free(self->quotes_start);
  if (self->quotes_end)
    g_free(self->quotes_end);
  if (self->null_value)
    g_free(self->null_value);
  if (self->delimiters)
    g_free(self->delimiters);
  log_column_parser_free_method(s);
}

/*
 * Parse comma-separated values from a log message.
 */
LogColumnParser *
log_csv_parser_new(void)
{
  LogCSVParser *self = g_new0(LogCSVParser, 1);

  log_column_parser_init_instance(&self->super);
  self->super.super.super.super.free_fn = log_csv_parser_free;
  self->super.super.super.clone = log_csv_parser_clone;
  self->super.super.process = log_csv_parser_process;
  log_csv_parser_set_delimiters(&self->super, " ");
  log_csv_parser_set_quote_pairs(&self->super, "\"\"''");
  self->flags = LOG_CSV_PARSER_STRIP_WHITESPACE | LOG_CSV_PARSER_ESCAPE_NONE;
  return &self->super;
}

gint
log_csv_parser_lookup_flag(const gchar *flag)
{
  if (strcmp(flag, "escape-none") == 0)
    return LOG_CSV_PARSER_ESCAPE_NONE;
  else if (strcmp(flag, "escape-backslash") == 0)
    return LOG_CSV_PARSER_ESCAPE_BACKSLASH;
  else if (strcmp(flag, "escape-double-char") == 0)
    return LOG_CSV_PARSER_ESCAPE_DOUBLE_CHAR;
  else if (strcmp(flag, "strip-whitespace") == 0)
    return LOG_CSV_PARSER_STRIP_WHITESPACE;
  else if (strcmp(flag, "greedy") == 0)
    return LOG_CSV_PARSER_GREEDY;
  else if (strcmp(flag, "drop-invalid") == 0)
    return LOG_CSV_PARSER_DROP_INVALID;
  msg_error("Unknown CSV parser flag", evt_tag_str("flag", flag), NULL);
  return 0;
}