aboutsummaryrefslogtreecommitdiffstats
path: root/src/wgtpkg-mustach.c
blob: 4251427c0acf8520f73a80228f263aa2f74920af (plain)
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
/*
 Author: José Bollo <jobol@nonadev.net>
 Author: José Bollo <jose.bollo@iot.bzh>

 https://gitlab.com/jobol/mustach

 Licensed under the Apache License, Version 2.0 (the "License");
 you may not use this file except in compliance with the License.
 You may obtain a copy of the License at

     http://www.apache.org/licenses/LICENSE-2.0

 Unless required by applicable law or agreed to in writing, software
 distributed under the License is distributed on an "AS IS" BASIS,
 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 See the License for the specific language governing permissions and
 limitations under the License.
*/

#define _GNU_SOURCE

#include <stdio.h>
#include <string.h>
#include <errno.h>

#include <json-c/json.h>

#include "mustach.h"
#include "verbose.h"

#define MAX_DEPTH 256

/*
 * exploration state when instanciating mustache
 */
struct expl {
	struct json_object *root;
	int depth;
	struct {
		struct json_object *cont;
		struct json_object *obj;
		int index, count;
	} stack[MAX_DEPTH];
};

/*
 * Scan a key=val text.
 * If the sign = is found, drop it and returns a pointer to the value.
 * If the sign = is not here, returns NULL.
 * Replace any \= of the key by its unescaped version =.
 */
static char *keyval(char *read, int isptr)
{
	char *write, c;

	c = *(write = read);
	while (c && c != '=') {
		if (isptr) {
			if (c == '~' && read[1] == '=') {
				c = *++read;
			}
		} else {
			if (c == '\\') {
				switch (read[1]) {
				case '\\': *write++ = c; /*@fallthrough@*/
				case '=': c = *++read; /*@fallthrough@*/
				default: break;
				}
			}
		}
		*write++ = c;
		c = *++read;
	}
	*write = 0;
	return c == '=' ? ++read : NULL;
}

/*
 * Returns the unescaped version of the first component
 * and update 'name' to point the next components if any.
 */
static char *first(char **name, int isptr)
{
	char *r, *read, *write, c;

	c = *(read = *name);
	if (!c)
		r = NULL;
	else {
		r = write = read;
		if (isptr) {
			while (c && c != '/') {
				if (c == '~') {
					switch(read[1]) {
					case '1': c = '/'; /*@fallthrough@*/
					case '0': read++; /*@fallthrough@*/
					default: break;
					}
				}
				*write++ = c;
				c = *++read;
			}
		} else {
			while (c && c != '.') {
				if (c == '\\' && (read[1] == '.' || read[1] == '\\'))
					c = *++read;
				*write++ = c;
				c = *++read;
			}
		}
		*write = 0;
		*name = read + !!c;
	}
	return r;
}

/*
 * Returns the unescaped version of the first value
 * and update 'val' to point the next value if any.
 */
static char *value(char **val)
{
	char *r, *read, *write, c;

	c = *(read = *val);
	if (!c)
		r = NULL;
	else {
		r = write = read;
		while (c && c != '|') {
			if (c == '\\' && (read[1] == '|' || read[1] == '\\'))
				c = *++read;
			*write++ = c;
			c = *++read;
		}
		*write = 0;
		*val = read + !!c;
	}
	return r;
}

/*
 * Replace the last occurence of ':' followed by
 * any character not being '*' by ':*', the
 * globalisation of the key.
 * Returns NULL if no globalisation is done
 * or else the key globalized.
 */
static char *globalize(char *key)
{
	char *f, *r;

	f = NULL;
	for (r = key; *r ; r++) {
		if (r[0] == ':' && r[1] && r[1] != '*')
			f = r;
	}
	if (f) {
		f[1] = '*';
		f[2] = 0;
		f = key;
	}
	return f;
}

/*
 * find the object of 'name'
 */
static struct json_object *find(struct expl *e, const char *name)
{
	int i, isptr;
	struct json_object *o, *r;
	char *n, *c, *v;

	/* get a local key */
	n = strdupa(name);

	/* is it a JSON pointer? */
	isptr = n[0] == '/';
	n += isptr;

	/* extract its value */
	v = keyval(n, isptr);

	/* search the first component for each valid globalisation */
	i = e->depth;
	c = first(&n, isptr);
	while (c) {
		if (i < 0) {
			/* next globalisation */
			i = e->depth;
			c = globalize(c);
		}
		else if (json_object_object_get_ex(e->stack[i].obj, c, &o)) {

			/* found the root, search the subcomponents */
			c = first(&n, isptr);
			while(c) {
				while (!json_object_object_get_ex(o, c, &r)) {
					c = globalize(c);
					if (!c)
						return NULL;
				}
				o = r;
				c = first(&n, isptr);
			}

			/* check the value if requested */
			if (v) {
				i = v[0] == '!';
				v += i;
				do {
					c = value(&v);
				} while (c && strcmp(c, json_object_get_string(o)));
				if (i != !c)
					o = NULL;
			}
			return o;
		}
		i--;
	}
	return NULL;
}

static int start(void *closure)
{
	struct expl *e = closure;
	e->depth = 0;
	e->stack[0].cont = NULL;
	e->stack[0].obj = e->root;
	e->stack[0].index = 0;
	e->stack[0].count = 1;
	return 0;
}

static void print(FILE *file, const char *string, int escape)
{
	if (!escape)
		fputs(string, file);
	else if (*string)
		do {
			switch(*string) {
			case '%': fputs("%%", file); break;
			case '\n': fputs("\\n\\\n", file); break;
			default: putc(*string, file); break;
			}
		} while(*++string);
}

static int put(void *closure, const char *name, int escape, FILE *file)
{
	struct expl *e = closure;
	struct json_object *o = find(e, name);
	if (o)
		print(file, json_object_get_string(o), escape);
	return 0;
}

static int enter(void *closure, const char *name)
{
	struct expl *e = closure;
	struct json_object *o = find(e, name);
	if (++e->depth >= MAX_DEPTH)
		return MUSTACH_ERROR_TOO_DEPTH;
	if (json_object_is_type(o, json_type_array)) {
		e->stack[e->depth].count = json_object_array_length(o);
		if (e->stack[e->depth].count == 0) {
			e->depth--;
			return 0;
		}
		e->stack[e->depth].cont = o;
		e->stack[e->depth].obj = json_object_array_get_idx(o, 0);
		e->stack[e->depth].index = 0;
	} else if (json_object_is_type(o, json_type_object) || json_object_get_boolean(o)) {
		e->stack[e->depth].count = 1;
		e->stack[e->depth].cont = NULL;
		e->stack[e->depth].obj = o;
		e->stack[e->depth].index = 0;
	} else {
		e->depth--;
		return 0;
	}
	return 1;
}

static int next(void *closure)
{
	struct expl *e = closure;
	if (e->depth <= 0)
		return MUSTACH_ERROR_CLOSING;
	e->stack[e->depth].index++;
	if (e->stack[e->depth].index >= e->stack[e->depth].count)
		return 0;
	e->stack[e->depth].obj = json_object_array_get_idx(e->stack[e->depth].cont, e->stack[e->depth].index);
	return 1;
}

static int leave(void *closure)
{
	struct expl *e = closure;
	if (e->depth <= 0)
		return MUSTACH_ERROR_CLOSING;
	e->depth--;
	return 0;
}

static struct mustach_itf itf = {
	.start = start,
	.put = put,
	.enter = enter,
	.next = next,
	.leave = leave
};

/*
 * Apply the object 'root' to the mustache 'template'.
 * In case of success, the function returns 0, the pointer
 * 'result' receives the allocated instanciation and
 * the pointer 'size' its size. Note that the real size
 * is one byte more to effectively store the terminating
 * null.
 * In case of error, it returns a negative error code.
 */
int apply_mustach(const char *template, struct json_object *root, char **result, size_t *size)
{
	int rc;
	struct expl e;

	e.root = root;
	rc = mustach(template, &itf, &e, result, size);
	if (rc < 0) {
		static const char *msgs[] = {
			"SYSTEM",
			"UNEXPECTED_END",
			"EMPTY_TAG",
			"TAG_TOO_LONG",
			"BAD_SEPARATORS",
			"TOO_DEPTH",
			"CLOSING",
			"BAD_UNESCAPE_TAG"
		};

		rc = -(rc + 1);
		ERROR("mustach error found: MUSTACH_ERROR_%s",
			rc < 0 || rc >= (int)(sizeof msgs / sizeof * msgs) ? "???" : msgs[rc]);
		rc = -1;
		errno = EINVAL;
	}
	return rc;
}