matcher.c: properly handle negative array indizes
[oweals/jsonpath.git] / main.c
1 /*
2  * Copyright (C) 2013-2014 Jo-Philipp Wich <jow@openwrt.org>
3  *
4  * Permission to use, copy, modify, and/or distribute this software for any
5  * purpose with or without fee is hereby granted, provided that the above
6  * copyright notice and this permission notice appear in all copies.
7  *
8  * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
9  * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
10  * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
11  * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
12  * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
13  * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
14  * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
15  */
16
17 #include <stdio.h>
18 #include <stdbool.h>
19 #include <unistd.h>
20 #include <errno.h>
21
22 #ifdef JSONC
23         #include <json.h>
24 #else
25         #include <json-c/json.h>
26 #endif
27
28 #include <libubox/list.h>
29
30 #include "lexer.h"
31 #include "parser.h"
32 #include "matcher.h"
33
34
35 struct match_item {
36         struct json_object *jsobj;
37         struct list_head list;
38 };
39
40 static struct json_object *
41 parse_json(FILE *fd, const char *source, const char **error)
42 {
43         int len;
44         char buf[256];
45         struct json_object *obj = NULL;
46         struct json_tokener *tok = json_tokener_new();
47         enum json_tokener_error err = json_tokener_continue;
48
49         if (!tok)
50                 return NULL;
51
52         if (source)
53         {
54                 obj = json_tokener_parse_ex(tok, source, strlen(source));
55                 err = json_tokener_get_error(tok);
56         }
57         else
58         {
59                 while ((len = fread(buf, 1, sizeof(buf), fd)) > 0)
60                 {
61                         obj = json_tokener_parse_ex(tok, buf, len);
62                         err = json_tokener_get_error(tok);
63
64                         if (!err || err != json_tokener_continue)
65                                 break;
66                 }
67         }
68
69         json_tokener_free(tok);
70
71         if (err)
72         {
73                 if (err == json_tokener_continue)
74                         err = json_tokener_error_parse_eof;
75
76                 *error = json_tokener_error_desc(err);
77                 return NULL;
78         }
79
80         return obj;
81 }
82
83 static void
84 print_string(const char *s)
85 {
86         const char *p;
87
88         printf("'");
89
90         for (p = s; *p; p++)
91         {
92                 if (*p == '\'')
93                         printf("'\"'\"'");
94                 else
95                         printf("%c", *p);
96         }
97
98         printf("'");
99 }
100
101 static void
102 print_separator(const char *sep, int *sc, int sl)
103 {
104         if (*sc > 0)
105         {
106                 switch (sep[(*sc - 1) % sl])
107                 {
108                 case '"':
109                         printf("'\"'");
110                         break;
111
112                 case '\'':
113                         printf("\"'\"");
114                         break;
115
116                 case ' ':
117                         printf("\\ ");
118                         break;
119
120                 default:
121                         printf("%c", sep[(*sc - 1) % sl]);
122                 }
123         }
124
125         (*sc)++;
126 }
127
128 static void
129 export_value(struct list_head *matches, const char *prefix, const char *sep)
130 {
131         int n, len;
132         int sc = 0, sl = strlen(sep);
133         struct match_item *item;
134
135         if (list_empty(matches))
136                 return;
137
138         if (prefix)
139         {
140                 printf("export %s=", prefix);
141
142                 list_for_each_entry(item, matches, list)
143                 {
144                         switch (json_object_get_type(item->jsobj))
145                         {
146                         case json_type_object:
147                                 ; /* a label can only be part of a statement */
148                                 json_object_object_foreach(item->jsobj, key, val)
149                                 {
150                                         if (!val)
151                                                 continue;
152
153                                         print_separator(sep, &sc, sl);
154                                         print_string(key);
155                                 }
156                                 break;
157
158                         case json_type_array:
159                                 for (n = 0, len = json_object_array_length(item->jsobj);
160                                      n < len; n++)
161                                 {
162                                         print_separator(sep, &sc, sl);
163                                         printf("%d", n);
164                                 }
165                                 break;
166
167                         case json_type_boolean:
168                                 print_separator(sep, &sc, sl);
169                                 printf("%d", json_object_get_boolean(item->jsobj));
170                                 break;
171
172                         case json_type_int:
173                                 print_separator(sep, &sc, sl);
174                                 printf("%d", json_object_get_int(item->jsobj));
175                                 break;
176
177                         case json_type_double:
178                                 print_separator(sep, &sc, sl);
179                                 printf("%f", json_object_get_double(item->jsobj));
180                                 break;
181
182                         case json_type_string:
183                                 print_separator(sep, &sc, sl);
184                                 print_string(json_object_get_string(item->jsobj));
185                                 break;
186
187                         case json_type_null:
188                                 break;
189                         }
190                 }
191
192                 printf("; ");
193         }
194         else
195         {
196                 list_for_each_entry(item, matches, list)
197                 {
198                         switch (json_object_get_type(item->jsobj))
199                         {
200                         case json_type_object:
201                         case json_type_array:
202                         case json_type_boolean:
203                         case json_type_int:
204                         case json_type_double:
205                                 printf("%s\n", json_object_to_json_string(item->jsobj));
206                                 break;
207
208                         case json_type_string:
209                                 printf("%s\n", json_object_get_string(item->jsobj));
210                                 break;
211
212                         case json_type_null:
213                                 break;
214                         }
215                 }
216         }
217 }
218
219 static void
220 export_type(struct list_head *matches, const char *prefix)
221 {
222         bool first = true;
223         struct match_item *item;
224         const char *types[] = {
225                 "null",
226                 "boolean",
227                 "double",
228                 "int",
229                 "object",
230                 "array",
231                 "string"
232         };
233
234         if (list_empty(matches))
235                 return;
236
237         if (prefix)
238                 printf("export %s=", prefix);
239
240         list_for_each_entry(item, matches, list)
241         {
242                 if (!first)
243                         printf("\\ ");
244
245                 printf("%s", types[json_object_get_type(item->jsobj)]);
246                 first = false;
247         }
248
249         if (prefix)
250                 printf("; ");
251         else
252                 printf("\n");
253 }
254
255 static void
256 match_cb(struct json_object *res, void *priv)
257 {
258         struct list_head *h = priv;
259         struct match_item *i = calloc(1, sizeof(*i));
260
261         if (i)
262         {
263                 i->jsobj = res;
264                 list_add_tail(&i->list, h);
265         }
266 }
267
268 static void
269 print_error(struct jp_state *state, char *expr)
270 {
271         int i;
272         bool first = true;
273
274         fprintf(stderr, "Syntax error: ");
275
276         switch (state->error_code)
277         {
278         case -4:
279                 fprintf(stderr, "Unexpected character\n");
280                 break;
281
282         case -3:
283                 fprintf(stderr, "String or label literal too long\n");
284                 break;
285
286         case -2:
287                 fprintf(stderr, "Invalid escape sequence\n");
288                 break;
289
290         case -1:
291                 fprintf(stderr, "Unterminated string\n");
292                 break;
293
294         default:
295                 for (i = 0; i < sizeof(state->error_code) * 8; i++)
296                 {
297                         if (state->error_code & (1 << i))
298                         {
299                                 fprintf(stderr,
300                                         first ? "Expecting %s" : " or %s", tokennames[i]);
301
302                                 first = false;
303                         }
304                 }
305
306                 fprintf(stderr, "\n");
307                 break;
308         }
309
310         fprintf(stderr, "In expression %s\n", expr);
311         fprintf(stderr, "Near here ----");
312
313         for (i = 0; i < state->error_pos; i++)
314                 fprintf(stderr, "-");
315
316         fprintf(stderr, "^\n");
317 }
318
319 static bool
320 filter_json(int opt, struct json_object *jsobj, char *expr, const char *sep)
321 {
322         struct jp_state *state;
323         const char *prefix = NULL;
324         struct list_head matches;
325         struct match_item *item, *tmp;
326         struct json_object *res = NULL;
327
328         state = jp_parse(expr);
329
330         if (!state)
331         {
332                 fprintf(stderr, "Out of memory\n");
333                 goto out;
334         }
335         else if (state->error_code)
336         {
337                 print_error(state, expr);
338                 goto out;
339         }
340
341         INIT_LIST_HEAD(&matches);
342
343         res = jp_match(state->path, jsobj, match_cb, &matches);
344         prefix = (state->path->type == T_LABEL) ? state->path->str : NULL;
345
346         switch (opt)
347         {
348         case 't':
349                 export_type(&matches, prefix);
350                 break;
351
352         default:
353                 export_value(&matches, prefix, sep);
354                 break;
355         }
356
357         list_for_each_entry_safe(item, tmp, &matches, list)
358                 free(item);
359
360 out:
361         if (state)
362                 jp_free(state);
363
364         return !!res;
365 }
366
367 int main(int argc, char **argv)
368 {
369         int opt, rv = 0;
370         FILE *input = stdin;
371         struct json_object *jsobj = NULL;
372         const char *jserr = NULL, *source = NULL, *separator = " ";
373
374         while ((opt = getopt(argc, argv, "i:s:e:t:F:q")) != -1)
375         {
376                 switch (opt)
377                 {
378                 case 'i':
379                         input = fopen(optarg, "r");
380
381                         if (!input)
382                         {
383                                 fprintf(stderr, "Failed to open %s: %s\n",
384                                                 optarg, strerror(errno));
385
386                                 rv = 125;
387                                 goto out;
388                         }
389
390                         break;
391
392                 case 's':
393                         source = optarg;
394                         break;
395
396                 case 'F':
397                         if (optarg && *optarg)
398                                 separator = optarg;
399                         break;
400
401                 case 't':
402                 case 'e':
403                         if (!jsobj)
404                         {
405                                 jsobj = parse_json(input, source, &jserr);
406
407                                 if (!jsobj)
408                                 {
409                                         fprintf(stderr, "Failed to parse json data: %s\n",
410                                                 jserr);
411
412                                         rv = 126;
413                                         goto out;
414                                 }
415                         }
416
417                         if (!filter_json(opt, jsobj, optarg, separator))
418                                 rv = 1;
419
420                         break;
421
422                 case 'q':
423                         fclose(stderr);
424                         break;
425                 }
426         }
427
428 out:
429         if (jsobj)
430                 json_object_put(jsobj);
431
432         if (input != stdin)
433                 fclose(input);
434
435         return rv;
436 }