jshn: fix missing usage for -p and -o arguments
[project/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 if (obj)
182 json_object_put(obj);
183 fprintf(stderr, "Failed to parse message data\n");
184 return 1;
185 }
186 fprintf(stdout, "json_init;\n");
187 add_json_object(obj);
188 fflush(stdout);
189 json_object_put(obj);
190
191 return 0;
192 }
193
194 static char *getenv_avl(const char *key)
195 {
196 struct env_var *var = avl_find_element(&env_vars, key, var, avl);
197 return var ? var->val : NULL;
198 }
199
200 static char *get_keys(const char *prefix)
201 {
202 char *keys;
203
204 keys = alloca(var_prefix_len + strlen(prefix) + sizeof("K_") + 1);
205 sprintf(keys, "%sK_%s", var_prefix, prefix);
206 return getenv_avl(keys);
207 }
208
209 static void get_var(const char *prefix, const char **name, char **var, char **type)
210 {
211 char *tmpname, *varname;
212
213 tmpname = alloca(var_prefix_len + strlen(prefix) + 1 + strlen(*name) + 1 + sizeof("T_"));
214
215 sprintf(tmpname, "%s%s_%s", var_prefix, prefix, *name);
216 *var = getenv_avl(tmpname);
217
218 sprintf(tmpname, "%sT_%s_%s", var_prefix, prefix, *name);
219 *type = getenv_avl(tmpname);
220
221 sprintf(tmpname, "%sN_%s_%s", var_prefix, prefix, *name);
222 varname = getenv_avl(tmpname);
223 if (varname)
224 *name = varname;
225 }
226
227 static json_object *jshn_add_objects(json_object *obj, const char *prefix, bool array);
228
229 static void jshn_add_object_var(json_object *obj, bool array, const char *prefix, const char *name)
230 {
231 json_object *new;
232 char *var, *type;
233
234 get_var(prefix, &name, &var, &type);
235 if (!var || !type)
236 return;
237
238 if (!strcmp(type, "array")) {
239 new = json_object_new_array();
240 jshn_add_objects(new, var, true);
241 } else if (!strcmp(type, "object")) {
242 new = json_object_new_object();
243 jshn_add_objects(new, var, false);
244 } else if (!strcmp(type, "string")) {
245 new = json_object_new_string(var);
246 } else if (!strcmp(type, "int")) {
247 new = json_object_new_int64(atoll(var));
248 } else if (!strcmp(type, "double")) {
249 new = json_object_new_double(strtod(var, NULL));
250 } else if (!strcmp(type, "boolean")) {
251 new = json_object_new_boolean(!!atoi(var));
252 } else if (!strcmp(type, "null")) {
253 new = NULL;
254 } else {
255 return;
256 }
257
258 if (array)
259 json_object_array_add(obj, new);
260 else
261 json_object_object_add(obj, name, new);
262 }
263
264 static json_object *jshn_add_objects(json_object *obj, const char *prefix, bool array)
265 {
266 char *keys, *key, *brk;
267
268 keys = get_keys(prefix);
269 if (!keys || !obj)
270 goto out;
271
272 for (key = strtok_r(keys, " ", &brk); key;
273 key = strtok_r(NULL, " ", &brk)) {
274 jshn_add_object_var(obj, array, prefix, key);
275 }
276
277 out:
278 return obj;
279 }
280
281 static int jshn_format(bool no_newline, bool indent, FILE *stream)
282 {
283 json_object *obj;
284 const char *output;
285 char *blobmsg_output = NULL;
286 int ret = -1;
287
288 if (!(obj = json_object_new_object()))
289 return -1;
290
291 jshn_add_objects(obj, "J_V", false);
292 if (!(output = json_object_to_json_string(obj)))
293 goto out;
294
295 if (indent) {
296 blob_buf_init(&b, 0);
297 if (!blobmsg_add_json_from_string(&b, output))
298 goto out;
299 if (!(blobmsg_output = blobmsg_format_json_indent(b.head, 1, 0)))
300 goto out;
301 output = blobmsg_output;
302 }
303 fprintf(stream, "%s%s", output, no_newline ? "" : "\n");
304 free(blobmsg_output);
305 ret = 0;
306
307 out:
308 json_object_put(obj);
309 return ret;
310 }
311
312 static int usage(const char *progname)
313 {
314 fprintf(stderr, "Usage: %s [-n] [-i] -r <message>|-R <file>|-o <file>|-p <prefix>|-w\n", progname);
315 return 2;
316 }
317
318 static int avl_strcmp_var(const void *k1, const void *k2, void *ptr)
319 {
320 const char *s1 = k1;
321 const char *s2 = k2;
322 char c1, c2;
323
324 while (*s1 && *s1 == *s2) {
325 s1++;
326 s2++;
327 }
328
329 c1 = *s1;
330 c2 = *s2;
331 if (c1 == '=')
332 c1 = 0;
333 if (c2 == '=')
334 c2 = 0;
335
336 return c1 - c2;
337 }
338
339 static int jshn_parse_file(const char *path)
340 {
341 struct stat sb;
342 int ret = 0;
343 char *fbuf;
344 int fd;
345
346 if ((fd = open(path, O_RDONLY)) == -1) {
347 fprintf(stderr, "Error opening %s\n", path);
348 return 3;
349 }
350
351 if (fstat(fd, &sb) == -1) {
352 fprintf(stderr, "Error getting size of %s\n", path);
353 close(fd);
354 return 3;
355 }
356
357 if (!(fbuf = calloc(1, sb.st_size+1))) {
358 fprintf(stderr, "Error allocating memory for %s\n", path);
359 close(fd);
360 return 3;
361 }
362
363 if (read(fd, fbuf, sb.st_size) != sb.st_size) {
364 fprintf(stderr, "Error reading %s\n", path);
365 free(fbuf);
366 close(fd);
367 return 3;
368 }
369
370 ret = jshn_parse(fbuf);
371 free(fbuf);
372 close(fd);
373
374 return ret;
375 }
376
377 static int jshn_format_file(const char *path, bool no_newline, bool indent)
378 {
379 FILE *fp = NULL;
380 int ret = 0;
381
382 fp = fopen(path, "w");
383 if (!fp) {
384 fprintf(stderr, "Error opening %s\n", path);
385 return 3;
386 }
387
388 ret = jshn_format(no_newline, indent, fp);
389 fclose(fp);
390
391 return ret;
392 }
393
394 int main(int argc, char **argv)
395 {
396 extern char **environ;
397 bool no_newline = false;
398 bool indent = false;
399 struct env_var *vars;
400 int i;
401 int ret = 0;
402 int ch;
403
404 avl_init(&env_vars, avl_strcmp_var, false, NULL);
405 for (i = 0; environ[i]; i++);
406
407 vars = calloc(i, sizeof(*vars));
408 if (!vars) {
409 fprintf(stderr, "%m\n");
410 return -1;
411 }
412 for (i = 0; environ[i]; i++) {
413 char *c;
414
415 vars[i].avl.key = environ[i];
416 c = strchr(environ[i], '=');
417 if (!c)
418 continue;
419
420 vars[i].val = c + 1;
421 avl_insert(&env_vars, &vars[i].avl);
422 }
423
424 while ((ch = getopt(argc, argv, "p:nir:R:o:w")) != -1) {
425 switch(ch) {
426 case 'p':
427 var_prefix = optarg;
428 var_prefix_len = strlen(var_prefix);
429 break;
430 case 'r':
431 ret = jshn_parse(optarg);
432 goto exit;
433 case 'R':
434 ret = jshn_parse_file(optarg);
435 goto exit;
436 case 'w':
437 ret = jshn_format(no_newline, indent, stdout);
438 goto exit;
439 case 'o':
440 ret = jshn_format_file(optarg, no_newline, indent);
441 goto exit;
442 case 'n':
443 no_newline = true;
444 break;
445 case 'i':
446 indent = true;
447 break;
448 default:
449 free(vars);
450 return usage(argv[0]);
451 }
452 }
453
454 free(vars);
455 return usage(argv[0]);
456
457 exit:
458 free(vars);
459 return ret;
460 }