libubox, jshn: add option to write output to a file
[oweals/libubox.git] / jshn.c
1 /*
2  * Copyright (C) 2011-2013 Felix Fietkau <nbd@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 #ifdef JSONC
17         #include <json.h>
18 #else
19         #include <json/json.h>
20 #endif
21
22 #include <string.h>
23 #include <stdlib.h>
24 #include <stdio.h>
25 #include <stdbool.h>
26 #include <ctype.h>
27 #include <getopt.h>
28 #include <sys/stat.h>
29 #include <fcntl.h>
30 #include <inttypes.h>
31 #include "list.h"
32
33 #include "avl.h"
34 #include "blob.h"
35 #include "blobmsg_json.h"
36
37 #define MAX_VARLEN      256
38
39 static struct avl_tree env_vars;
40 static struct blob_buf b = { 0 };
41
42 static const char *var_prefix = "";
43 static int var_prefix_len = 0;
44
45 static int add_json_element(const char *key, json_object *obj);
46
47 struct env_var {
48         struct avl_node avl;
49         char *val;
50 };
51
52 static int add_json_object(json_object *obj)
53 {
54         int ret = 0;
55
56         json_object_object_foreach(obj, key, val) {
57                 ret = add_json_element(key, val);
58                 if (ret)
59                         break;
60         }
61         return ret;
62 }
63
64 static int add_json_array(struct array_list *a)
65 {
66         char seq[12];
67         int i, len;
68         int ret;
69
70         for (i = 0, len = array_list_length(a); i < len; i++) {
71                 sprintf(seq, "%d", i);
72                 ret = add_json_element(seq, array_list_get_idx(a, i));
73                 if (ret)
74                         return ret;
75         }
76
77         return 0;
78 }
79
80 static void add_json_string(const char *str)
81 {
82         char *ptr = (char *) str;
83         int len;
84         char *c;
85
86         while ((c = strchr(ptr, '\'')) != NULL) {
87                 len = c - ptr;
88                 if (len > 0)
89                         fwrite(ptr, len, 1, stdout);
90                 ptr = c + 1;
91                 c = "'\\''";
92                 fwrite(c, strlen(c), 1, stdout);
93         }
94         len = strlen(ptr);
95         if (len > 0)
96                 fwrite(ptr, len, 1, stdout);
97 }
98
99 static void write_key_string(const char *key)
100 {
101         while (*key) {
102                 putc(isalnum(*key) ? *key : '_', stdout);
103                 key++;
104         }
105 }
106
107 static int add_json_element(const char *key, json_object *obj)
108 {
109         char *type;
110
111         switch (json_object_get_type(obj)) {
112         case json_type_object:
113                 type = "object";
114                 break;
115         case json_type_array:
116                 type = "array";
117                 break;
118         case json_type_string:
119                 type = "string";
120                 break;
121         case json_type_boolean:
122                 type = "boolean";
123                 break;
124         case json_type_int:
125                 type = "int";
126                 break;
127         case json_type_double:
128                 type = "double";
129                 break;
130         case json_type_null:
131                 type = "null";
132                 break;
133         default:
134                 return -1;
135         }
136
137         fprintf(stdout, "json_add_%s '", type);
138         write_key_string(key);
139
140         switch (json_object_get_type(obj)) {
141         case json_type_object:
142                 fprintf(stdout, "';\n");
143                 add_json_object(obj);
144                 fprintf(stdout, "json_close_object;\n");
145                 break;
146         case json_type_array:
147                 fprintf(stdout, "';\n");
148                 add_json_array(json_object_get_array(obj));
149                 fprintf(stdout, "json_close_array;\n");
150                 break;
151         case json_type_string:
152                 fprintf(stdout, "' '");
153                 add_json_string(json_object_get_string(obj));
154                 fprintf(stdout, "';\n");
155                 break;
156         case json_type_boolean:
157                 fprintf(stdout, "' %d;\n", json_object_get_boolean(obj));
158                 break;
159         case json_type_int:
160                 fprintf(stdout, "' %"PRId64";\n", json_object_get_int64(obj));
161                 break;
162         case json_type_double:
163                 fprintf(stdout, "' %lf;\n", json_object_get_double(obj));
164                 break;
165         case json_type_null:
166                 fprintf(stdout, "';\n");
167                 break;
168         default:
169                 return -1;
170         }
171
172         return 0;
173 }
174
175 static int jshn_parse(const char *str)
176 {
177         json_object *obj;
178
179         obj = json_tokener_parse(str);
180         if (!obj || json_object_get_type(obj) != json_type_object) {
181                 fprintf(stderr, "Failed to parse message data\n");
182                 return 1;
183         }
184         fprintf(stdout, "json_init;\n");
185         add_json_object(obj);
186         fflush(stdout);
187
188         return 0;
189 }
190
191 static char *getenv_avl(const char *key)
192 {
193         struct env_var *var = avl_find_element(&env_vars, key, var, avl);
194         return var ? var->val : NULL;
195 }
196
197 static char *get_keys(const char *prefix)
198 {
199         char *keys;
200
201         keys = alloca(var_prefix_len + strlen(prefix) + sizeof("K_") + 1);
202         sprintf(keys, "%sK_%s", var_prefix, prefix);
203         return getenv_avl(keys);
204 }
205
206 static void get_var(const char *prefix, const char **name, char **var, char **type)
207 {
208         char *tmpname, *varname;
209
210         tmpname = alloca(var_prefix_len + strlen(prefix) + 1 + strlen(*name) + 1 + sizeof("T_"));
211
212         sprintf(tmpname, "%s%s_%s", var_prefix, prefix, *name);
213         *var = getenv_avl(tmpname);
214
215         sprintf(tmpname, "%sT_%s_%s", var_prefix, prefix, *name);
216         *type = getenv_avl(tmpname);
217
218         sprintf(tmpname, "%sN_%s_%s", var_prefix, prefix, *name);
219         varname = getenv_avl(tmpname);
220         if (varname)
221                 *name = varname;
222 }
223
224 static json_object *jshn_add_objects(json_object *obj, const char *prefix, bool array);
225
226 static void jshn_add_object_var(json_object *obj, bool array, const char *prefix, const char *name)
227 {
228         json_object *new;
229         char *var, *type;
230
231         get_var(prefix, &name, &var, &type);
232         if (!var || !type)
233                 return;
234
235         if (!strcmp(type, "array")) {
236                 new = json_object_new_array();
237                 jshn_add_objects(new, var, true);
238         } else if (!strcmp(type, "object")) {
239                 new = json_object_new_object();
240                 jshn_add_objects(new, var, false);
241         } else if (!strcmp(type, "string")) {
242                 new = json_object_new_string(var);
243         } else if (!strcmp(type, "int")) {
244                 new = json_object_new_int64(atoll(var));
245         } else if (!strcmp(type, "double")) {
246                 new = json_object_new_double(strtod(var, NULL));
247         } else if (!strcmp(type, "boolean")) {
248                 new = json_object_new_boolean(!!atoi(var));
249         } else if (!strcmp(type, "null")) {
250                 new = NULL;
251         } else {
252                 return;
253         }
254
255         if (array)
256                 json_object_array_add(obj, new);
257         else
258                 json_object_object_add(obj, name, new);
259 }
260
261 static json_object *jshn_add_objects(json_object *obj, const char *prefix, bool array)
262 {
263         char *keys, *key, *brk;
264
265         keys = get_keys(prefix);
266         if (!keys || !obj)
267                 goto out;
268
269         for (key = strtok_r(keys, " ", &brk); key;
270              key = strtok_r(NULL, " ", &brk)) {
271                 jshn_add_object_var(obj, array, prefix, key);
272         }
273
274 out:
275         return obj;
276 }
277
278 static int jshn_format(bool no_newline, bool indent, FILE *stream)
279 {
280         json_object *obj;
281         const char *output;
282         char *blobmsg_output = NULL;
283         int ret = -1;
284
285         if (!(obj = json_object_new_object()))
286                 return -1;
287
288         jshn_add_objects(obj, "J_V", false);
289         if (!(output = json_object_to_json_string(obj)))
290                 goto out;
291
292         if (indent) {
293                 blob_buf_init(&b, 0);
294                 if (!blobmsg_add_json_from_string(&b, output))
295                         goto out;
296                 if (!(blobmsg_output = blobmsg_format_json_indent(b.head, 1, 0)))
297                         goto out;
298                 output = blobmsg_output;
299         }
300         fprintf(stream, "%s%s", output, no_newline ? "" : "\n");
301         free(blobmsg_output);
302         ret = 0;
303
304 out:
305         json_object_put(obj);
306         return ret;
307 }
308
309 static int usage(const char *progname)
310 {
311         fprintf(stderr, "Usage: %s [-n] [-i] -r <message>|-R <file>|-w\n", progname);
312         return 2;
313 }
314
315 static int avl_strcmp_var(const void *k1, const void *k2, void *ptr)
316 {
317         const char *s1 = k1;
318         const char *s2 = k2;
319         char c1, c2;
320
321         while (*s1 && *s1 == *s2) {
322                 s1++;
323                 s2++;
324         }
325
326         c1 = *s1;
327         c2 = *s2;
328         if (c1 == '=')
329                 c1 = 0;
330         if (c2 == '=')
331                 c2 = 0;
332
333         return c1 - c2;
334 }
335
336 int main(int argc, char **argv)
337 {
338         extern char **environ;
339         bool no_newline = false;
340         bool indent = false;
341         struct env_var *vars;
342         int i;
343         int ch;
344         int fd;
345         FILE *fp = NULL;
346         struct stat sb;
347         char *fbuf;
348         int ret;
349
350         avl_init(&env_vars, avl_strcmp_var, false, NULL);
351         for (i = 0; environ[i]; i++);
352
353         vars = calloc(i, sizeof(*vars));
354         if (!vars) {
355                 fprintf(stderr, "%m\n");
356                 return -1;
357         }
358         for (i = 0; environ[i]; i++) {
359                 char *c;
360
361                 vars[i].avl.key = environ[i];
362                 c = strchr(environ[i], '=');
363                 if (!c)
364                         continue;
365
366                 vars[i].val = c + 1;
367                 avl_insert(&env_vars, &vars[i].avl);
368         }
369
370         while ((ch = getopt(argc, argv, "p:nir:R:o:w")) != -1) {
371                 switch(ch) {
372                 case 'p':
373                         var_prefix = optarg;
374                         var_prefix_len = strlen(var_prefix);
375                         break;
376                 case 'r':
377                         return jshn_parse(optarg);
378                 case 'R':
379                         if ((fd = open(optarg, O_RDONLY)) == -1) {
380                                 fprintf(stderr, "Error opening %s\n", optarg);
381                                 return 3;
382                         }
383                         if (fstat(fd, &sb) == -1) {
384                                 fprintf(stderr, "Error getting size of %s\n", optarg);
385                                 close(fd);
386                                 return 3;
387                         }
388                         if (!(fbuf = malloc(sb.st_size))) {
389                                 fprintf(stderr, "Error allocating memory for %s\n", optarg);
390                                 close(fd);
391                                 return 3;
392                         }
393                         if (read(fd, fbuf, sb.st_size) != sb.st_size) {
394                                 fprintf(stderr, "Error reading %s\n", optarg);
395                                 free(fbuf);
396                                 close(fd);
397                                 return 3;
398                         }
399                         ret = jshn_parse(fbuf);
400                         free(fbuf);
401                         close(fd);
402                         return ret;
403                 case 'w':
404                         return jshn_format(no_newline, indent, stdout);
405                 case 'o':
406                         fp = fopen(optarg, "w");
407                         if (!fp) {
408                                 fprintf(stderr, "Error opening %s\n", optarg);
409                                 return 3;
410                         }
411                         jshn_format(no_newline, indent, fp);
412                         fclose(fp);
413                         return 0;
414                 case 'n':
415                         no_newline = true;
416                         break;
417                 case 'i':
418                         indent = true;
419                         break;
420                 default:
421                         return usage(argv[0]);
422                 }
423         }
424         return usage(argv[0]);
425 }