1262395Sbapt/* Copyright (c) 2013, Vsevolod Stakhov
2290071Sbapt * Copyright (c) 2015 Allan Jude <allanjude@freebsd.org>
3262395Sbapt * All rights reserved.
4262395Sbapt *
5262395Sbapt * Redistribution and use in source and binary forms, with or without
6262395Sbapt * modification, are permitted provided that the following conditions are met:
7262395Sbapt *       * Redistributions of source code must retain the above copyright
8262395Sbapt *         notice, this list of conditions and the following disclaimer.
9262395Sbapt *       * Redistributions in binary form must reproduce the above copyright
10262395Sbapt *         notice, this list of conditions and the following disclaimer in the
11262395Sbapt *         documentation and/or other materials provided with the distribution.
12262395Sbapt *
13262395Sbapt * THIS SOFTWARE IS PROVIDED ''AS IS'' AND ANY
14262395Sbapt * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
15262395Sbapt * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
16262395Sbapt * DISCLAIMED. IN NO EVENT SHALL AUTHOR BE LIABLE FOR ANY
17262395Sbapt * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
18262395Sbapt * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
19262395Sbapt * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
20262395Sbapt * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
21262395Sbapt * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
22262395Sbapt * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
23262395Sbapt */
24262395Sbapt
25262395Sbapt#include "ucl.h"
26262395Sbapt#include "ucl_internal.h"
27262395Sbapt#include "ucl_chartable.h"
28279549Sbapt#include "kvec.h"
29314278Sbapt#include <limits.h>
30290071Sbapt#include <stdarg.h>
31298166Sbapt#include <stdio.h> /* for snprintf */
32262395Sbapt
33279549Sbapt#ifndef _WIN32
34275223Sbapt#include <glob.h>
35314278Sbapt#include <sys/param.h>
36314278Sbapt#else
37314278Sbapt#ifndef NBBY
38314278Sbapt#define NBBY 8
39279549Sbapt#endif
40314278Sbapt#endif
41275223Sbapt
42263648Sbapt#ifdef HAVE_LIBGEN_H
43262395Sbapt#include <libgen.h> /* For dirname */
44263648Sbapt#endif
45262395Sbapt
46279549Sbapttypedef kvec_t(ucl_object_t *) ucl_array_t;
47279549Sbapt
48279549Sbapt#define UCL_ARRAY_GET(ar, obj) ucl_array_t *ar = \
49279549Sbapt	(ucl_array_t *)((obj) != NULL ? (obj)->value.av : NULL)
50279549Sbapt
51262395Sbapt#ifdef HAVE_OPENSSL
52262395Sbapt#include <openssl/err.h>
53262395Sbapt#include <openssl/sha.h>
54262395Sbapt#include <openssl/rsa.h>
55262395Sbapt#include <openssl/ssl.h>
56262395Sbapt#include <openssl/evp.h>
57262395Sbapt#endif
58262395Sbapt
59263648Sbapt#ifdef CURL_FOUND
60298166Sbapt/* Seems to be broken */
61298166Sbapt#define CURL_DISABLE_TYPECHECK 1
62263648Sbapt#include <curl/curl.h>
63263648Sbapt#endif
64263648Sbapt#ifdef HAVE_FETCH_H
65263648Sbapt#include <fetch.h>
66263648Sbapt#endif
67263648Sbapt
68262975Sbapt#ifdef _WIN32
69262975Sbapt#include <windows.h>
70262975Sbapt
71263648Sbapt#ifndef PROT_READ
72262975Sbapt#define PROT_READ       1
73263648Sbapt#endif
74263648Sbapt#ifndef PROT_WRITE
75262975Sbapt#define PROT_WRITE      2
76263648Sbapt#endif
77263648Sbapt#ifndef PROT_READWRITE
78262975Sbapt#define PROT_READWRITE  3
79263648Sbapt#endif
80263648Sbapt#ifndef MAP_SHARED
81262975Sbapt#define MAP_SHARED      1
82263648Sbapt#endif
83263648Sbapt#ifndef MAP_PRIVATE
84262975Sbapt#define MAP_PRIVATE     2
85263648Sbapt#endif
86263648Sbapt#ifndef MAP_FAILED
87262975Sbapt#define MAP_FAILED      ((void *) -1)
88263648Sbapt#endif
89262975Sbapt
90263648Sbaptstatic void *ucl_mmap(char *addr, size_t length, int prot, int access, int fd, off_t offset)
91262975Sbapt{
92262975Sbapt	void *map = NULL;
93262975Sbapt	HANDLE handle = INVALID_HANDLE_VALUE;
94262975Sbapt
95262975Sbapt	switch (prot) {
96262975Sbapt	default:
97262975Sbapt	case PROT_READ:
98262975Sbapt		{
99262975Sbapt			handle = CreateFileMapping((HANDLE) _get_osfhandle(fd), 0, PAGE_READONLY, 0, length, 0);
100262975Sbapt			if (!handle) break;
101262975Sbapt			map = (void *) MapViewOfFile(handle, FILE_MAP_READ, 0, 0, length);
102262975Sbapt			CloseHandle(handle);
103262975Sbapt			break;
104262975Sbapt		}
105262975Sbapt	case PROT_WRITE:
106262975Sbapt		{
107262975Sbapt			handle = CreateFileMapping((HANDLE) _get_osfhandle(fd), 0, PAGE_READWRITE, 0, length, 0);
108262975Sbapt			if (!handle) break;
109262975Sbapt			map = (void *) MapViewOfFile(handle, FILE_MAP_WRITE, 0, 0, length);
110262975Sbapt			CloseHandle(handle);
111262975Sbapt			break;
112262975Sbapt		}
113262975Sbapt	case PROT_READWRITE:
114262975Sbapt		{
115262975Sbapt			handle = CreateFileMapping((HANDLE) _get_osfhandle(fd), 0, PAGE_READWRITE, 0, length, 0);
116262975Sbapt			if (!handle) break;
117262975Sbapt			map = (void *) MapViewOfFile(handle, FILE_MAP_ALL_ACCESS, 0, 0, length);
118262975Sbapt			CloseHandle(handle);
119262975Sbapt			break;
120262975Sbapt		}
121262975Sbapt	}
122262975Sbapt	if (map == (void *) NULL) {
123262975Sbapt		return (void *) MAP_FAILED;
124262975Sbapt	}
125262975Sbapt	return (void *) ((char *) map + offset);
126262975Sbapt}
127262975Sbapt
128263648Sbaptstatic int ucl_munmap(void *map,size_t length)
129262975Sbapt{
130262975Sbapt	if (!UnmapViewOfFile(map)) {
131262975Sbapt		return(-1);
132262975Sbapt	}
133262975Sbapt	return(0);
134262975Sbapt}
135262975Sbapt
136263648Sbaptstatic char* ucl_realpath(const char *path, char *resolved_path) {
137262975Sbapt    char *p;
138262975Sbapt    char tmp[MAX_PATH + 1];
139262975Sbapt    strncpy(tmp, path, sizeof(tmp)-1);
140262975Sbapt    p = tmp;
141262975Sbapt    while(*p) {
142262975Sbapt        if (*p == '/') *p = '\\';
143262975Sbapt        p++;
144262975Sbapt    }
145262975Sbapt    return _fullpath(resolved_path, tmp, MAX_PATH);
146262975Sbapt}
147263648Sbapt#else
148263648Sbapt#define ucl_mmap mmap
149263648Sbapt#define ucl_munmap munmap
150263648Sbapt#define ucl_realpath realpath
151262975Sbapt#endif
152262975Sbapt
153264789Sbapttypedef void (*ucl_object_dtor) (ucl_object_t *obj);
154264789Sbaptstatic void ucl_object_free_internal (ucl_object_t *obj, bool allow_rec,
155264789Sbapt		ucl_object_dtor dtor);
156264789Sbaptstatic void ucl_object_dtor_unref (ucl_object_t *obj);
157262395Sbapt
158262395Sbaptstatic void
159264789Sbaptucl_object_dtor_free (ucl_object_t *obj)
160262395Sbapt{
161264789Sbapt	if (obj->trash_stack[UCL_TRASH_KEY] != NULL) {
162264789Sbapt		UCL_FREE (obj->hh.keylen, obj->trash_stack[UCL_TRASH_KEY]);
163264789Sbapt	}
164264789Sbapt	if (obj->trash_stack[UCL_TRASH_VALUE] != NULL) {
165264789Sbapt		UCL_FREE (obj->len, obj->trash_stack[UCL_TRASH_VALUE]);
166264789Sbapt	}
167275223Sbapt	/* Do not free ephemeral objects */
168275223Sbapt	if ((obj->flags & UCL_OBJECT_EPHEMERAL) == 0) {
169275223Sbapt		if (obj->type != UCL_USERDATA) {
170275223Sbapt			UCL_FREE (sizeof (ucl_object_t), obj);
171275223Sbapt		}
172275223Sbapt		else {
173275223Sbapt			struct ucl_object_userdata *ud = (struct ucl_object_userdata *)obj;
174275223Sbapt			if (ud->dtor) {
175275223Sbapt				ud->dtor (obj->value.ud);
176275223Sbapt			}
177275223Sbapt			UCL_FREE (sizeof (*ud), obj);
178275223Sbapt		}
179275223Sbapt	}
180264789Sbapt}
181264789Sbapt
182264789Sbapt/*
183264789Sbapt * This is a helper function that performs exactly the same as
184264789Sbapt * `ucl_object_unref` but it doesn't iterate over elements allowing
185264789Sbapt * to use it for individual elements of arrays and multiple values
186264789Sbapt */
187264789Sbaptstatic void
188264789Sbaptucl_object_dtor_unref_single (ucl_object_t *obj)
189264789Sbapt{
190264789Sbapt	if (obj != NULL) {
191264789Sbapt#ifdef HAVE_ATOMIC_BUILTINS
192264789Sbapt		unsigned int rc = __sync_sub_and_fetch (&obj->ref, 1);
193264789Sbapt		if (rc == 0) {
194264789Sbapt#else
195264789Sbapt		if (--obj->ref == 0) {
196264789Sbapt#endif
197264789Sbapt			ucl_object_free_internal (obj, false, ucl_object_dtor_unref);
198264789Sbapt		}
199264789Sbapt	}
200264789Sbapt}
201264789Sbapt
202264789Sbaptstatic void
203264789Sbaptucl_object_dtor_unref (ucl_object_t *obj)
204264789Sbapt{
205264789Sbapt	if (obj->ref == 0) {
206264789Sbapt		ucl_object_dtor_free (obj);
207264789Sbapt	}
208264789Sbapt	else {
209264789Sbapt		/* This may cause dtor unref being called one more time */
210264789Sbapt		ucl_object_dtor_unref_single (obj);
211264789Sbapt	}
212264789Sbapt}
213264789Sbapt
214264789Sbaptstatic void
215264789Sbaptucl_object_free_internal (ucl_object_t *obj, bool allow_rec, ucl_object_dtor dtor)
216264789Sbapt{
217279549Sbapt	ucl_object_t *tmp, *sub;
218262395Sbapt
219262395Sbapt	while (obj != NULL) {
220262395Sbapt		if (obj->type == UCL_ARRAY) {
221279549Sbapt			UCL_ARRAY_GET (vec, obj);
222279549Sbapt			unsigned int i;
223279549Sbapt
224279549Sbapt			if (vec != NULL) {
225279549Sbapt				for (i = 0; i < vec->n; i ++) {
226279549Sbapt					sub = kv_A (*vec, i);
227279549Sbapt					if (sub != NULL) {
228279549Sbapt						tmp = sub;
229279549Sbapt						while (sub) {
230279549Sbapt							tmp = sub->next;
231279549Sbapt							dtor (sub);
232279549Sbapt							sub = tmp;
233279549Sbapt						}
234279549Sbapt					}
235279549Sbapt				}
236279549Sbapt				kv_destroy (*vec);
237279549Sbapt				UCL_FREE (sizeof (*vec), vec);
238262395Sbapt			}
239290071Sbapt			obj->value.av = NULL;
240262395Sbapt		}
241262395Sbapt		else if (obj->type == UCL_OBJECT) {
242262395Sbapt			if (obj->value.ov != NULL) {
243298166Sbapt				ucl_hash_destroy (obj->value.ov, (ucl_hash_free_func)dtor);
244262395Sbapt			}
245290071Sbapt			obj->value.ov = NULL;
246262395Sbapt		}
247262395Sbapt		tmp = obj->next;
248264789Sbapt		dtor (obj);
249262395Sbapt		obj = tmp;
250262395Sbapt
251262395Sbapt		if (!allow_rec) {
252262395Sbapt			break;
253262395Sbapt		}
254262395Sbapt	}
255262395Sbapt}
256262395Sbapt
257262395Sbaptvoid
258262395Sbaptucl_object_free (ucl_object_t *obj)
259262395Sbapt{
260264789Sbapt	ucl_object_free_internal (obj, true, ucl_object_dtor_free);
261262395Sbapt}
262262395Sbapt
263262395Sbaptsize_t
264262395Sbaptucl_unescape_json_string (char *str, size_t len)
265262395Sbapt{
266262395Sbapt	char *t = str, *h = str;
267262395Sbapt	int i, uval;
268262395Sbapt
269263648Sbapt	if (len <= 1) {
270263648Sbapt		return len;
271263648Sbapt	}
272262395Sbapt	/* t is target (tortoise), h is source (hare) */
273262395Sbapt
274262395Sbapt	while (len) {
275262395Sbapt		if (*h == '\\') {
276262395Sbapt			h ++;
277290071Sbapt
278290071Sbapt			if (len == 1) {
279290071Sbapt				/*
280290071Sbapt				 * If \ is last, then do not try to go further
281290071Sbapt				 * Issue: #74
282290071Sbapt				 */
283290071Sbapt				len --;
284290071Sbapt				*t++ = '\\';
285290071Sbapt				continue;
286290071Sbapt			}
287290071Sbapt
288262395Sbapt			switch (*h) {
289262395Sbapt			case 'n':
290262395Sbapt				*t++ = '\n';
291262395Sbapt				break;
292262395Sbapt			case 'r':
293262395Sbapt				*t++ = '\r';
294262395Sbapt				break;
295262395Sbapt			case 'b':
296262395Sbapt				*t++ = '\b';
297262395Sbapt				break;
298262395Sbapt			case 't':
299262395Sbapt				*t++ = '\t';
300262395Sbapt				break;
301262395Sbapt			case 'f':
302262395Sbapt				*t++ = '\f';
303262395Sbapt				break;
304262395Sbapt			case '\\':
305262395Sbapt				*t++ = '\\';
306262395Sbapt				break;
307262395Sbapt			case '"':
308262395Sbapt				*t++ = '"';
309262395Sbapt				break;
310262395Sbapt			case 'u':
311262395Sbapt				/* Unicode escape */
312262395Sbapt				uval = 0;
313298166Sbapt				h ++; /* u character */
314298166Sbapt				len --;
315298166Sbapt
316263648Sbapt				if (len > 3) {
317263648Sbapt					for (i = 0; i < 4; i++) {
318263648Sbapt						uval <<= 4;
319263648Sbapt						if (isdigit (h[i])) {
320263648Sbapt							uval += h[i] - '0';
321263648Sbapt						}
322263648Sbapt						else if (h[i] >= 'a' && h[i] <= 'f') {
323263648Sbapt							uval += h[i] - 'a' + 10;
324263648Sbapt						}
325263648Sbapt						else if (h[i] >= 'A' && h[i] <= 'F') {
326263648Sbapt							uval += h[i] - 'A' + 10;
327263648Sbapt						}
328263648Sbapt						else {
329263648Sbapt							break;
330263648Sbapt						}
331262395Sbapt					}
332298166Sbapt
333263648Sbapt					/* Encode */
334263648Sbapt					if(uval < 0x80) {
335263648Sbapt						t[0] = (char)uval;
336263648Sbapt						t ++;
337262395Sbapt					}
338263648Sbapt					else if(uval < 0x800) {
339263648Sbapt						t[0] = 0xC0 + ((uval & 0x7C0) >> 6);
340263648Sbapt						t[1] = 0x80 + ((uval & 0x03F));
341263648Sbapt						t += 2;
342262395Sbapt					}
343263648Sbapt					else if(uval < 0x10000) {
344263648Sbapt						t[0] = 0xE0 + ((uval & 0xF000) >> 12);
345263648Sbapt						t[1] = 0x80 + ((uval & 0x0FC0) >> 6);
346263648Sbapt						t[2] = 0x80 + ((uval & 0x003F));
347263648Sbapt						t += 3;
348263648Sbapt					}
349298166Sbapt#if 0
350298166Sbapt					/* It's not actually supported now */
351263648Sbapt					else if(uval <= 0x10FFFF) {
352263648Sbapt						t[0] = 0xF0 + ((uval & 0x1C0000) >> 18);
353263648Sbapt						t[1] = 0x80 + ((uval & 0x03F000) >> 12);
354263648Sbapt						t[2] = 0x80 + ((uval & 0x000FC0) >> 6);
355263648Sbapt						t[3] = 0x80 + ((uval & 0x00003F));
356263648Sbapt						t += 4;
357263648Sbapt					}
358298166Sbapt#endif
359263648Sbapt					else {
360263648Sbapt						*t++ = '?';
361263648Sbapt					}
362298166Sbapt
363298166Sbapt					/* Consume 4 characters of source */
364298166Sbapt					h += 4;
365298166Sbapt					len -= 4;
366298166Sbapt
367298166Sbapt					if (len > 0) {
368298166Sbapt						len --; /* for '\' character */
369298166Sbapt					}
370298166Sbapt					continue;
371262395Sbapt				}
372262395Sbapt				else {
373263648Sbapt					*t++ = 'u';
374262395Sbapt				}
375262395Sbapt				break;
376262395Sbapt			default:
377262395Sbapt				*t++ = *h;
378262395Sbapt				break;
379262395Sbapt			}
380262395Sbapt			h ++;
381262395Sbapt			len --;
382262395Sbapt		}
383262395Sbapt		else {
384262395Sbapt			*t++ = *h++;
385262395Sbapt		}
386290071Sbapt
387290071Sbapt		if (len > 0) {
388290071Sbapt			len --;
389290071Sbapt		}
390262395Sbapt	}
391262395Sbapt	*t = '\0';
392262395Sbapt
393262395Sbapt	return (t - str);
394262395Sbapt}
395262395Sbapt
396264789Sbaptchar *
397264789Sbaptucl_copy_key_trash (const ucl_object_t *obj)
398262395Sbapt{
399264789Sbapt	ucl_object_t *deconst;
400264789Sbapt
401263648Sbapt	if (obj == NULL) {
402263648Sbapt		return NULL;
403263648Sbapt	}
404262395Sbapt	if (obj->trash_stack[UCL_TRASH_KEY] == NULL && obj->key != NULL) {
405264789Sbapt		deconst = __DECONST (ucl_object_t *, obj);
406264789Sbapt		deconst->trash_stack[UCL_TRASH_KEY] = malloc (obj->keylen + 1);
407264789Sbapt		if (deconst->trash_stack[UCL_TRASH_KEY] != NULL) {
408264789Sbapt			memcpy (deconst->trash_stack[UCL_TRASH_KEY], obj->key, obj->keylen);
409264789Sbapt			deconst->trash_stack[UCL_TRASH_KEY][obj->keylen] = '\0';
410262395Sbapt		}
411264789Sbapt		deconst->key = obj->trash_stack[UCL_TRASH_KEY];
412264789Sbapt		deconst->flags |= UCL_OBJECT_ALLOCATED_KEY;
413262395Sbapt	}
414262395Sbapt
415262395Sbapt	return obj->trash_stack[UCL_TRASH_KEY];
416262395Sbapt}
417262395Sbapt
418264789Sbaptchar *
419264789Sbaptucl_copy_value_trash (const ucl_object_t *obj)
420262395Sbapt{
421264789Sbapt	ucl_object_t *deconst;
422264789Sbapt
423263648Sbapt	if (obj == NULL) {
424263648Sbapt		return NULL;
425263648Sbapt	}
426262395Sbapt	if (obj->trash_stack[UCL_TRASH_VALUE] == NULL) {
427264789Sbapt		deconst = __DECONST (ucl_object_t *, obj);
428262395Sbapt		if (obj->type == UCL_STRING) {
429264789Sbapt
430262395Sbapt			/* Special case for strings */
431290071Sbapt			if (obj->flags & UCL_OBJECT_BINARY) {
432290071Sbapt				deconst->trash_stack[UCL_TRASH_VALUE] = malloc (obj->len);
433290071Sbapt				if (deconst->trash_stack[UCL_TRASH_VALUE] != NULL) {
434290071Sbapt					memcpy (deconst->trash_stack[UCL_TRASH_VALUE],
435290071Sbapt							obj->value.sv,
436290071Sbapt							obj->len);
437290071Sbapt					deconst->value.sv = obj->trash_stack[UCL_TRASH_VALUE];
438290071Sbapt				}
439262395Sbapt			}
440290071Sbapt			else {
441290071Sbapt				deconst->trash_stack[UCL_TRASH_VALUE] = malloc (obj->len + 1);
442290071Sbapt				if (deconst->trash_stack[UCL_TRASH_VALUE] != NULL) {
443290071Sbapt					memcpy (deconst->trash_stack[UCL_TRASH_VALUE],
444290071Sbapt							obj->value.sv,
445290071Sbapt							obj->len);
446290071Sbapt					deconst->trash_stack[UCL_TRASH_VALUE][obj->len] = '\0';
447290071Sbapt					deconst->value.sv = obj->trash_stack[UCL_TRASH_VALUE];
448290071Sbapt				}
449290071Sbapt			}
450262395Sbapt		}
451262395Sbapt		else {
452262395Sbapt			/* Just emit value in json notation */
453264789Sbapt			deconst->trash_stack[UCL_TRASH_VALUE] = ucl_object_emit_single_json (obj);
454264789Sbapt			deconst->len = strlen (obj->trash_stack[UCL_TRASH_VALUE]);
455262395Sbapt		}
456264789Sbapt		deconst->flags |= UCL_OBJECT_ALLOCATED_VALUE;
457262395Sbapt	}
458298166Sbapt
459262395Sbapt	return obj->trash_stack[UCL_TRASH_VALUE];
460262395Sbapt}
461262395Sbapt
462290071Sbaptucl_object_t*
463262395Sbaptucl_parser_get_object (struct ucl_parser *parser)
464262395Sbapt{
465262395Sbapt	if (parser->state != UCL_STATE_ERROR && parser->top_obj != NULL) {
466262395Sbapt		return ucl_object_ref (parser->top_obj);
467262395Sbapt	}
468262395Sbapt
469262395Sbapt	return NULL;
470262395Sbapt}
471262395Sbapt
472290071Sbaptvoid
473262395Sbaptucl_parser_free (struct ucl_parser *parser)
474262395Sbapt{
475262395Sbapt	struct ucl_stack *stack, *stmp;
476262395Sbapt	struct ucl_macro *macro, *mtmp;
477262395Sbapt	struct ucl_chunk *chunk, *ctmp;
478262395Sbapt	struct ucl_pubkey *key, *ktmp;
479262395Sbapt	struct ucl_variable *var, *vtmp;
480290071Sbapt	ucl_object_t *tr, *trtmp;
481262395Sbapt
482263648Sbapt	if (parser == NULL) {
483263648Sbapt		return;
484263648Sbapt	}
485263648Sbapt
486262395Sbapt	if (parser->top_obj != NULL) {
487262395Sbapt		ucl_object_unref (parser->top_obj);
488262395Sbapt	}
489262395Sbapt
490290071Sbapt	if (parser->includepaths != NULL) {
491290071Sbapt		ucl_object_unref (parser->includepaths);
492290071Sbapt	}
493290071Sbapt
494262395Sbapt	LL_FOREACH_SAFE (parser->stack, stack, stmp) {
495262395Sbapt		free (stack);
496262395Sbapt	}
497262395Sbapt	HASH_ITER (hh, parser->macroes, macro, mtmp) {
498262395Sbapt		free (macro->name);
499262395Sbapt		HASH_DEL (parser->macroes, macro);
500262395Sbapt		UCL_FREE (sizeof (struct ucl_macro), macro);
501262395Sbapt	}
502262395Sbapt	LL_FOREACH_SAFE (parser->chunks, chunk, ctmp) {
503262395Sbapt		UCL_FREE (sizeof (struct ucl_chunk), chunk);
504262395Sbapt	}
505262395Sbapt	LL_FOREACH_SAFE (parser->keys, key, ktmp) {
506262395Sbapt		UCL_FREE (sizeof (struct ucl_pubkey), key);
507262395Sbapt	}
508262395Sbapt	LL_FOREACH_SAFE (parser->variables, var, vtmp) {
509262395Sbapt		free (var->value);
510262395Sbapt		free (var->var);
511262395Sbapt		UCL_FREE (sizeof (struct ucl_variable), var);
512262395Sbapt	}
513290071Sbapt	LL_FOREACH_SAFE (parser->trash_objs, tr, trtmp) {
514290071Sbapt		ucl_object_free_internal (tr, false, ucl_object_dtor_free);
515290071Sbapt	}
516262395Sbapt
517262395Sbapt	if (parser->err != NULL) {
518275223Sbapt		utstring_free (parser->err);
519262395Sbapt	}
520262395Sbapt
521275223Sbapt	if (parser->cur_file) {
522275223Sbapt		free (parser->cur_file);
523275223Sbapt	}
524275223Sbapt
525298166Sbapt	if (parser->comments) {
526298166Sbapt		ucl_object_unref (parser->comments);
527298166Sbapt	}
528298166Sbapt
529262395Sbapt	UCL_FREE (sizeof (struct ucl_parser), parser);
530262395Sbapt}
531262395Sbapt
532290071Sbaptconst char *
533262395Sbaptucl_parser_get_error(struct ucl_parser *parser)
534262395Sbapt{
535263648Sbapt	if (parser == NULL) {
536263648Sbapt		return NULL;
537263648Sbapt	}
538263648Sbapt
539290071Sbapt	if (parser->err == NULL) {
540262395Sbapt		return NULL;
541290071Sbapt	}
542262395Sbapt
543290071Sbapt	return utstring_body (parser->err);
544262395Sbapt}
545262395Sbapt
546290071Sbaptint
547290071Sbaptucl_parser_get_error_code(struct ucl_parser *parser)
548290071Sbapt{
549290071Sbapt	if (parser == NULL) {
550290071Sbapt		return 0;
551290071Sbapt	}
552290071Sbapt
553290071Sbapt	return parser->err_code;
554290071Sbapt}
555290071Sbapt
556290071Sbaptunsigned
557290071Sbaptucl_parser_get_column(struct ucl_parser *parser)
558290071Sbapt{
559290071Sbapt	if (parser == NULL || parser->chunks == NULL) {
560290071Sbapt		return 0;
561290071Sbapt	}
562290071Sbapt
563290071Sbapt	return parser->chunks->column;
564290071Sbapt}
565290071Sbapt
566290071Sbaptunsigned
567290071Sbaptucl_parser_get_linenum(struct ucl_parser *parser)
568290071Sbapt{
569290071Sbapt	if (parser == NULL || parser->chunks == NULL) {
570290071Sbapt		return 0;
571290071Sbapt	}
572290071Sbapt
573290071Sbapt	return parser->chunks->line;
574290071Sbapt}
575290071Sbapt
576290071Sbaptvoid
577279549Sbaptucl_parser_clear_error(struct ucl_parser *parser)
578279549Sbapt{
579279549Sbapt	if (parser != NULL && parser->err != NULL) {
580279549Sbapt		utstring_free(parser->err);
581279549Sbapt		parser->err = NULL;
582290071Sbapt		parser->err_code = 0;
583279549Sbapt	}
584279549Sbapt}
585279549Sbapt
586290071Sbaptbool
587262395Sbaptucl_pubkey_add (struct ucl_parser *parser, const unsigned char *key, size_t len)
588262395Sbapt{
589262395Sbapt#ifndef HAVE_OPENSSL
590262395Sbapt	ucl_create_err (&parser->err, "cannot check signatures without openssl");
591262395Sbapt	return false;
592262395Sbapt#else
593262395Sbapt# if (OPENSSL_VERSION_NUMBER < 0x10000000L)
594262395Sbapt	ucl_create_err (&parser->err, "cannot check signatures, openssl version is unsupported");
595262395Sbapt	return EXIT_FAILURE;
596262395Sbapt# else
597262395Sbapt	struct ucl_pubkey *nkey;
598262395Sbapt	BIO *mem;
599262395Sbapt
600262395Sbapt	mem = BIO_new_mem_buf ((void *)key, len);
601262395Sbapt	nkey = UCL_ALLOC (sizeof (struct ucl_pubkey));
602263648Sbapt	if (nkey == NULL) {
603263648Sbapt		ucl_create_err (&parser->err, "cannot allocate memory for key");
604263648Sbapt		return false;
605263648Sbapt	}
606262395Sbapt	nkey->key = PEM_read_bio_PUBKEY (mem, &nkey->key, NULL, NULL);
607262395Sbapt	BIO_free (mem);
608262395Sbapt	if (nkey->key == NULL) {
609262395Sbapt		UCL_FREE (sizeof (struct ucl_pubkey), nkey);
610262395Sbapt		ucl_create_err (&parser->err, "%s",
611262395Sbapt				ERR_error_string (ERR_get_error (), NULL));
612262395Sbapt		return false;
613262395Sbapt	}
614262395Sbapt	LL_PREPEND (parser->keys, nkey);
615262395Sbapt# endif
616262395Sbapt#endif
617262395Sbapt	return true;
618262395Sbapt}
619262395Sbapt
620262395Sbapt#ifdef CURL_FOUND
621262395Sbaptstruct ucl_curl_cbdata {
622262395Sbapt	unsigned char *buf;
623262395Sbapt	size_t buflen;
624262395Sbapt};
625262395Sbapt
626262395Sbaptstatic size_t
627262395Sbaptucl_curl_write_callback (void* contents, size_t size, size_t nmemb, void* ud)
628262395Sbapt{
629262395Sbapt	struct ucl_curl_cbdata *cbdata = ud;
630262395Sbapt	size_t realsize = size * nmemb;
631262395Sbapt
632262395Sbapt	cbdata->buf = realloc (cbdata->buf, cbdata->buflen + realsize + 1);
633262395Sbapt	if (cbdata->buf == NULL) {
634262395Sbapt		return 0;
635262395Sbapt	}
636262395Sbapt
637262395Sbapt	memcpy (&(cbdata->buf[cbdata->buflen]), contents, realsize);
638262395Sbapt	cbdata->buflen += realsize;
639262395Sbapt	cbdata->buf[cbdata->buflen] = 0;
640262395Sbapt
641262395Sbapt	return realsize;
642262395Sbapt}
643262395Sbapt#endif
644262395Sbapt
645262395Sbapt/**
646262395Sbapt * Fetch a url and save results to the memory buffer
647262395Sbapt * @param url url to fetch
648262395Sbapt * @param len length of url
649262395Sbapt * @param buf target buffer
650262395Sbapt * @param buflen target length
651262395Sbapt * @return
652262395Sbapt */
653298166Sbaptbool
654262395Sbaptucl_fetch_url (const unsigned char *url, unsigned char **buf, size_t *buflen,
655262395Sbapt		UT_string **err, bool must_exist)
656262395Sbapt{
657262395Sbapt
658262395Sbapt#ifdef HAVE_FETCH_H
659262395Sbapt	struct url *fetch_url;
660262395Sbapt	struct url_stat us;
661262395Sbapt	FILE *in;
662262395Sbapt
663262395Sbapt	fetch_url = fetchParseURL (url);
664262395Sbapt	if (fetch_url == NULL) {
665262395Sbapt		ucl_create_err (err, "invalid URL %s: %s",
666262395Sbapt				url, strerror (errno));
667262395Sbapt		return false;
668262395Sbapt	}
669262395Sbapt	if ((in = fetchXGet (fetch_url, &us, "")) == NULL) {
670262395Sbapt		if (!must_exist) {
671262395Sbapt			ucl_create_err (err, "cannot fetch URL %s: %s",
672262395Sbapt				url, strerror (errno));
673262395Sbapt		}
674262395Sbapt		fetchFreeURL (fetch_url);
675262395Sbapt		return false;
676262395Sbapt	}
677262395Sbapt
678262395Sbapt	*buflen = us.size;
679262395Sbapt	*buf = malloc (*buflen);
680262395Sbapt	if (*buf == NULL) {
681262395Sbapt		ucl_create_err (err, "cannot allocate buffer for URL %s: %s",
682262395Sbapt				url, strerror (errno));
683262395Sbapt		fclose (in);
684262395Sbapt		fetchFreeURL (fetch_url);
685262395Sbapt		return false;
686262395Sbapt	}
687262395Sbapt
688262395Sbapt	if (fread (*buf, *buflen, 1, in) != 1) {
689262395Sbapt		ucl_create_err (err, "cannot read URL %s: %s",
690262395Sbapt				url, strerror (errno));
691262395Sbapt		fclose (in);
692262395Sbapt		fetchFreeURL (fetch_url);
693262395Sbapt		return false;
694262395Sbapt	}
695262395Sbapt
696262395Sbapt	fetchFreeURL (fetch_url);
697262395Sbapt	return true;
698262395Sbapt#elif defined(CURL_FOUND)
699262395Sbapt	CURL *curl;
700262395Sbapt	int r;
701262395Sbapt	struct ucl_curl_cbdata cbdata;
702262395Sbapt
703262395Sbapt	curl = curl_easy_init ();
704262395Sbapt	if (curl == NULL) {
705262395Sbapt		ucl_create_err (err, "CURL interface is broken");
706262395Sbapt		return false;
707262395Sbapt	}
708262395Sbapt	if ((r = curl_easy_setopt (curl, CURLOPT_URL, url)) != CURLE_OK) {
709262395Sbapt		ucl_create_err (err, "invalid URL %s: %s",
710262395Sbapt				url, curl_easy_strerror (r));
711262395Sbapt		curl_easy_cleanup (curl);
712262395Sbapt		return false;
713262395Sbapt	}
714262395Sbapt	curl_easy_setopt (curl, CURLOPT_WRITEFUNCTION, ucl_curl_write_callback);
715298166Sbapt	cbdata.buf = NULL;
716298166Sbapt	cbdata.buflen = 0;
717262395Sbapt	curl_easy_setopt (curl, CURLOPT_WRITEDATA, &cbdata);
718262395Sbapt
719262395Sbapt	if ((r = curl_easy_perform (curl)) != CURLE_OK) {
720262395Sbapt		if (!must_exist) {
721262395Sbapt			ucl_create_err (err, "error fetching URL %s: %s",
722262395Sbapt				url, curl_easy_strerror (r));
723262395Sbapt		}
724262395Sbapt		curl_easy_cleanup (curl);
725262395Sbapt		if (cbdata.buf) {
726262395Sbapt			free (cbdata.buf);
727262395Sbapt		}
728262395Sbapt		return false;
729262395Sbapt	}
730262395Sbapt	*buf = cbdata.buf;
731262395Sbapt	*buflen = cbdata.buflen;
732262395Sbapt
733262395Sbapt	return true;
734262395Sbapt#else
735262395Sbapt	ucl_create_err (err, "URL support is disabled");
736262395Sbapt	return false;
737262395Sbapt#endif
738262395Sbapt}
739262395Sbapt
740262395Sbapt/**
741262395Sbapt * Fetch a file and save results to the memory buffer
742262395Sbapt * @param filename filename to fetch
743262395Sbapt * @param len length of filename
744262395Sbapt * @param buf target buffer
745262395Sbapt * @param buflen target length
746262395Sbapt * @return
747262395Sbapt */
748298166Sbaptbool
749262395Sbaptucl_fetch_file (const unsigned char *filename, unsigned char **buf, size_t *buflen,
750262395Sbapt		UT_string **err, bool must_exist)
751262395Sbapt{
752262395Sbapt	int fd;
753262395Sbapt	struct stat st;
754262395Sbapt
755262395Sbapt	if (stat (filename, &st) == -1 || !S_ISREG (st.st_mode)) {
756262395Sbapt		if (must_exist) {
757262395Sbapt			ucl_create_err (err, "cannot stat file %s: %s",
758262395Sbapt					filename, strerror (errno));
759262395Sbapt		}
760262395Sbapt		return false;
761262395Sbapt	}
762262395Sbapt	if (st.st_size == 0) {
763262395Sbapt		/* Do not map empty files */
764298166Sbapt		*buf = NULL;
765262395Sbapt		*buflen = 0;
766262395Sbapt	}
767262395Sbapt	else {
768262395Sbapt		if ((fd = open (filename, O_RDONLY)) == -1) {
769262395Sbapt			ucl_create_err (err, "cannot open file %s: %s",
770262395Sbapt					filename, strerror (errno));
771262395Sbapt			return false;
772262395Sbapt		}
773263648Sbapt		if ((*buf = ucl_mmap (NULL, st.st_size, PROT_READ, MAP_SHARED, fd, 0)) == MAP_FAILED) {
774262395Sbapt			close (fd);
775262395Sbapt			ucl_create_err (err, "cannot mmap file %s: %s",
776262395Sbapt					filename, strerror (errno));
777298166Sbapt			*buf = NULL;
778298166Sbapt
779262395Sbapt			return false;
780262395Sbapt		}
781262395Sbapt		*buflen = st.st_size;
782262395Sbapt		close (fd);
783262395Sbapt	}
784262395Sbapt
785262395Sbapt	return true;
786262395Sbapt}
787262395Sbapt
788262395Sbapt
789262395Sbapt#if (defined(HAVE_OPENSSL) && OPENSSL_VERSION_NUMBER >= 0x10000000L)
790262395Sbaptstatic inline bool
791262395Sbaptucl_sig_check (const unsigned char *data, size_t datalen,
792262395Sbapt		const unsigned char *sig, size_t siglen, struct ucl_parser *parser)
793262395Sbapt{
794262395Sbapt	struct ucl_pubkey *key;
795262395Sbapt	char dig[EVP_MAX_MD_SIZE];
796262395Sbapt	unsigned int diglen;
797262395Sbapt	EVP_PKEY_CTX *key_ctx;
798262395Sbapt	EVP_MD_CTX *sign_ctx = NULL;
799262395Sbapt
800262395Sbapt	sign_ctx = EVP_MD_CTX_create ();
801262395Sbapt
802262395Sbapt	LL_FOREACH (parser->keys, key) {
803262395Sbapt		key_ctx = EVP_PKEY_CTX_new (key->key, NULL);
804262395Sbapt		if (key_ctx != NULL) {
805262395Sbapt			if (EVP_PKEY_verify_init (key_ctx) <= 0) {
806262395Sbapt				EVP_PKEY_CTX_free (key_ctx);
807262395Sbapt				continue;
808262395Sbapt			}
809262395Sbapt			if (EVP_PKEY_CTX_set_rsa_padding (key_ctx, RSA_PKCS1_PADDING) <= 0) {
810262395Sbapt				EVP_PKEY_CTX_free (key_ctx);
811262395Sbapt				continue;
812262395Sbapt			}
813262395Sbapt			if (EVP_PKEY_CTX_set_signature_md (key_ctx, EVP_sha256 ()) <= 0) {
814262395Sbapt				EVP_PKEY_CTX_free (key_ctx);
815262395Sbapt				continue;
816262395Sbapt			}
817262395Sbapt			EVP_DigestInit (sign_ctx, EVP_sha256 ());
818262395Sbapt			EVP_DigestUpdate (sign_ctx, data, datalen);
819262395Sbapt			EVP_DigestFinal (sign_ctx, dig, &diglen);
820262395Sbapt
821262395Sbapt			if (EVP_PKEY_verify (key_ctx, sig, siglen, dig, diglen) == 1) {
822262395Sbapt				EVP_MD_CTX_destroy (sign_ctx);
823262395Sbapt				EVP_PKEY_CTX_free (key_ctx);
824262395Sbapt				return true;
825262395Sbapt			}
826262395Sbapt
827262395Sbapt			EVP_PKEY_CTX_free (key_ctx);
828262395Sbapt		}
829262395Sbapt	}
830262395Sbapt
831262395Sbapt	EVP_MD_CTX_destroy (sign_ctx);
832262395Sbapt
833262395Sbapt	return false;
834262395Sbapt}
835262395Sbapt#endif
836262395Sbapt
837290071Sbaptstruct ucl_include_params {
838290071Sbapt	bool check_signature;
839290071Sbapt	bool must_exist;
840290071Sbapt	bool use_glob;
841290071Sbapt	bool use_prefix;
842290071Sbapt	bool soft_fail;
843290071Sbapt	bool allow_glob;
844290071Sbapt	unsigned priority;
845290071Sbapt	enum ucl_duplicate_strategy strat;
846290071Sbapt	enum ucl_parse_type parse_type;
847290071Sbapt	const char *prefix;
848290071Sbapt	const char *target;
849290071Sbapt};
850290071Sbapt
851262395Sbapt/**
852262395Sbapt * Include an url to configuration
853262395Sbapt * @param data
854262395Sbapt * @param len
855262395Sbapt * @param parser
856262395Sbapt * @param err
857262395Sbapt * @return
858262395Sbapt */
859262395Sbaptstatic bool
860262395Sbaptucl_include_url (const unsigned char *data, size_t len,
861290071Sbapt		struct ucl_parser *parser,
862290071Sbapt		struct ucl_include_params *params)
863262395Sbapt{
864262395Sbapt
865262395Sbapt	bool res;
866262395Sbapt	unsigned char *buf = NULL;
867262395Sbapt	size_t buflen = 0;
868262395Sbapt	struct ucl_chunk *chunk;
869262395Sbapt	char urlbuf[PATH_MAX];
870262395Sbapt	int prev_state;
871262395Sbapt
872262395Sbapt	snprintf (urlbuf, sizeof (urlbuf), "%.*s", (int)len, data);
873262395Sbapt
874290071Sbapt	if (!ucl_fetch_url (urlbuf, &buf, &buflen, &parser->err, params->must_exist)) {
875298166Sbapt		return !params->must_exist;
876262395Sbapt	}
877262395Sbapt
878290071Sbapt	if (params->check_signature) {
879262395Sbapt#if (defined(HAVE_OPENSSL) && OPENSSL_VERSION_NUMBER >= 0x10000000L)
880262395Sbapt		unsigned char *sigbuf = NULL;
881262395Sbapt		size_t siglen = 0;
882262395Sbapt		/* We need to check signature first */
883262395Sbapt		snprintf (urlbuf, sizeof (urlbuf), "%.*s.sig", (int)len, data);
884262395Sbapt		if (!ucl_fetch_url (urlbuf, &sigbuf, &siglen, &parser->err, true)) {
885262395Sbapt			return false;
886262395Sbapt		}
887262395Sbapt		if (!ucl_sig_check (buf, buflen, sigbuf, siglen, parser)) {
888262395Sbapt			ucl_create_err (&parser->err, "cannot verify url %s: %s",
889262395Sbapt							urlbuf,
890262395Sbapt							ERR_error_string (ERR_get_error (), NULL));
891262395Sbapt			if (siglen > 0) {
892263648Sbapt				ucl_munmap (sigbuf, siglen);
893262395Sbapt			}
894262395Sbapt			return false;
895262395Sbapt		}
896262395Sbapt		if (siglen > 0) {
897263648Sbapt			ucl_munmap (sigbuf, siglen);
898262395Sbapt		}
899262395Sbapt#endif
900262395Sbapt	}
901262395Sbapt
902262395Sbapt	prev_state = parser->state;
903262395Sbapt	parser->state = UCL_STATE_INIT;
904262395Sbapt
905290071Sbapt	res = ucl_parser_add_chunk_full (parser, buf, buflen, params->priority,
906290071Sbapt			params->strat, params->parse_type);
907262395Sbapt	if (res == true) {
908262395Sbapt		/* Remove chunk from the stack */
909262395Sbapt		chunk = parser->chunks;
910262395Sbapt		if (chunk != NULL) {
911262395Sbapt			parser->chunks = chunk->next;
912262395Sbapt			UCL_FREE (sizeof (struct ucl_chunk), chunk);
913262395Sbapt		}
914262395Sbapt	}
915262395Sbapt
916262395Sbapt	parser->state = prev_state;
917262395Sbapt	free (buf);
918262395Sbapt
919262395Sbapt	return res;
920262395Sbapt}
921262395Sbapt
922262395Sbapt/**
923275223Sbapt * Include a single file to the parser
924262395Sbapt * @param data
925262395Sbapt * @param len
926262395Sbapt * @param parser
927275223Sbapt * @param check_signature
928275223Sbapt * @param must_exist
929275223Sbapt * @param allow_glob
930275223Sbapt * @param priority
931262395Sbapt * @return
932262395Sbapt */
933262395Sbaptstatic bool
934275223Sbaptucl_include_file_single (const unsigned char *data, size_t len,
935290071Sbapt		struct ucl_parser *parser, struct ucl_include_params *params)
936262395Sbapt{
937262395Sbapt	bool res;
938262395Sbapt	struct ucl_chunk *chunk;
939262395Sbapt	unsigned char *buf = NULL;
940290071Sbapt	char *old_curfile, *ext;
941290071Sbapt	size_t buflen = 0;
942262395Sbapt	char filebuf[PATH_MAX], realbuf[PATH_MAX];
943262395Sbapt	int prev_state;
944275223Sbapt	struct ucl_variable *cur_var, *tmp_var, *old_curdir = NULL,
945275223Sbapt			*old_filename = NULL;
946290071Sbapt	ucl_object_t *nest_obj = NULL, *old_obj = NULL, *new_obj = NULL;
947290071Sbapt	ucl_hash_t *container = NULL;
948290071Sbapt	struct ucl_stack *st = NULL;
949262395Sbapt
950262395Sbapt	snprintf (filebuf, sizeof (filebuf), "%.*s", (int)len, data);
951263648Sbapt	if (ucl_realpath (filebuf, realbuf) == NULL) {
952290071Sbapt		if (params->soft_fail) {
953290071Sbapt			return false;
954290071Sbapt		}
955290071Sbapt		if (!params->must_exist) {
956262395Sbapt			return true;
957262395Sbapt		}
958262395Sbapt		ucl_create_err (&parser->err, "cannot open file %s: %s",
959262395Sbapt									filebuf,
960262395Sbapt									strerror (errno));
961262395Sbapt		return false;
962262395Sbapt	}
963262395Sbapt
964275223Sbapt	if (parser->cur_file && strcmp (realbuf, parser->cur_file) == 0) {
965275223Sbapt		/* We are likely including the file itself */
966290071Sbapt		if (params->soft_fail) {
967290071Sbapt			return false;
968290071Sbapt		}
969290071Sbapt
970275223Sbapt		ucl_create_err (&parser->err, "trying to include the file %s from itself",
971275223Sbapt				realbuf);
972275223Sbapt		return false;
973275223Sbapt	}
974275223Sbapt
975290071Sbapt	if (!ucl_fetch_file (realbuf, &buf, &buflen, &parser->err, params->must_exist)) {
976290071Sbapt		if (params->soft_fail) {
977290071Sbapt			return false;
978290071Sbapt		}
979301339Sbapt
980290071Sbapt		return (!params->must_exist || false);
981262395Sbapt	}
982262395Sbapt
983290071Sbapt	if (params->check_signature) {
984262395Sbapt#if (defined(HAVE_OPENSSL) && OPENSSL_VERSION_NUMBER >= 0x10000000L)
985262395Sbapt		unsigned char *sigbuf = NULL;
986262395Sbapt		size_t siglen = 0;
987262395Sbapt		/* We need to check signature first */
988262395Sbapt		snprintf (filebuf, sizeof (filebuf), "%s.sig", realbuf);
989262395Sbapt		if (!ucl_fetch_file (filebuf, &sigbuf, &siglen, &parser->err, true)) {
990262395Sbapt			return false;
991262395Sbapt		}
992262395Sbapt		if (!ucl_sig_check (buf, buflen, sigbuf, siglen, parser)) {
993262395Sbapt			ucl_create_err (&parser->err, "cannot verify file %s: %s",
994262395Sbapt							filebuf,
995262395Sbapt							ERR_error_string (ERR_get_error (), NULL));
996298166Sbapt			if (sigbuf) {
997263648Sbapt				ucl_munmap (sigbuf, siglen);
998262395Sbapt			}
999262395Sbapt			return false;
1000262395Sbapt		}
1001298166Sbapt		if (sigbuf) {
1002263648Sbapt			ucl_munmap (sigbuf, siglen);
1003262395Sbapt		}
1004262395Sbapt#endif
1005262395Sbapt	}
1006262395Sbapt
1007275223Sbapt	old_curfile = parser->cur_file;
1008275223Sbapt	parser->cur_file = strdup (realbuf);
1009275223Sbapt
1010275223Sbapt	/* Store old file vars */
1011275223Sbapt	DL_FOREACH_SAFE (parser->variables, cur_var, tmp_var) {
1012275223Sbapt		if (strcmp (cur_var->var, "CURDIR") == 0) {
1013275223Sbapt			old_curdir = cur_var;
1014275223Sbapt			DL_DELETE (parser->variables, cur_var);
1015275223Sbapt		}
1016275223Sbapt		else if (strcmp (cur_var->var, "FILENAME") == 0) {
1017275223Sbapt			old_filename = cur_var;
1018275223Sbapt			DL_DELETE (parser->variables, cur_var);
1019275223Sbapt		}
1020275223Sbapt	}
1021275223Sbapt
1022262395Sbapt	ucl_parser_set_filevars (parser, realbuf, false);
1023262395Sbapt
1024262395Sbapt	prev_state = parser->state;
1025262395Sbapt	parser->state = UCL_STATE_INIT;
1026262395Sbapt
1027290071Sbapt	if (params->use_prefix && params->prefix == NULL) {
1028290071Sbapt		/* Auto generate a key name based on the included filename */
1029290071Sbapt		params->prefix = basename (realbuf);
1030290071Sbapt		ext = strrchr (params->prefix, '.');
1031290071Sbapt		if (ext != NULL && (strcmp (ext, ".conf") == 0 || strcmp (ext, ".ucl") == 0)) {
1032290071Sbapt			/* Strip off .conf or .ucl */
1033290071Sbapt			*ext = '\0';
1034290071Sbapt		}
1035290071Sbapt	}
1036290071Sbapt	if (params->prefix != NULL) {
1037290071Sbapt		/* This is a prefixed include */
1038290071Sbapt		container = parser->stack->obj->value.ov;
1039290071Sbapt
1040290071Sbapt		old_obj = __DECONST (ucl_object_t *, ucl_hash_search (container,
1041290071Sbapt				params->prefix, strlen (params->prefix)));
1042290071Sbapt
1043290071Sbapt		if (strcasecmp (params->target, "array") == 0 && old_obj == NULL) {
1044290071Sbapt			/* Create an array with key: prefix */
1045290071Sbapt			old_obj = ucl_object_new_full (UCL_ARRAY, params->priority);
1046290071Sbapt			old_obj->key = params->prefix;
1047290071Sbapt			old_obj->keylen = strlen (params->prefix);
1048290071Sbapt			ucl_copy_key_trash(old_obj);
1049290071Sbapt			old_obj->prev = old_obj;
1050290071Sbapt			old_obj->next = NULL;
1051290071Sbapt
1052290071Sbapt			container = ucl_hash_insert_object (container, old_obj,
1053290071Sbapt					parser->flags & UCL_PARSER_KEY_LOWERCASE);
1054290071Sbapt			parser->stack->obj->len ++;
1055290071Sbapt
1056290071Sbapt			nest_obj = ucl_object_new_full (UCL_OBJECT, params->priority);
1057290071Sbapt			nest_obj->prev = nest_obj;
1058290071Sbapt			nest_obj->next = NULL;
1059290071Sbapt
1060290071Sbapt			ucl_array_append (old_obj, nest_obj);
1061290071Sbapt		}
1062290071Sbapt		else if (old_obj == NULL) {
1063290071Sbapt			/* Create an object with key: prefix */
1064290071Sbapt			nest_obj = ucl_object_new_full (UCL_OBJECT, params->priority);
1065298166Sbapt
1066298166Sbapt			if (nest_obj == NULL) {
1067298166Sbapt				ucl_create_err (&parser->err, "cannot allocate memory for an object");
1068298166Sbapt				if (buf) {
1069298166Sbapt					ucl_munmap (buf, buflen);
1070298166Sbapt				}
1071298166Sbapt
1072298166Sbapt				return false;
1073298166Sbapt			}
1074298166Sbapt
1075290071Sbapt			nest_obj->key = params->prefix;
1076290071Sbapt			nest_obj->keylen = strlen (params->prefix);
1077290071Sbapt			ucl_copy_key_trash(nest_obj);
1078290071Sbapt			nest_obj->prev = nest_obj;
1079290071Sbapt			nest_obj->next = NULL;
1080290071Sbapt
1081290071Sbapt			container = ucl_hash_insert_object (container, nest_obj,
1082290071Sbapt					parser->flags & UCL_PARSER_KEY_LOWERCASE);
1083290071Sbapt			parser->stack->obj->len ++;
1084290071Sbapt		}
1085290071Sbapt		else if (strcasecmp (params->target, "array") == 0 ||
1086290071Sbapt				ucl_object_type(old_obj) == UCL_ARRAY) {
1087290071Sbapt			if (ucl_object_type(old_obj) == UCL_ARRAY) {
1088290071Sbapt				/* Append to the existing array */
1089290071Sbapt				nest_obj = ucl_object_new_full (UCL_OBJECT, params->priority);
1090298166Sbapt				if (nest_obj == NULL) {
1091298166Sbapt					ucl_create_err (&parser->err, "cannot allocate memory for an object");
1092298166Sbapt					if (buf) {
1093298166Sbapt						ucl_munmap (buf, buflen);
1094298166Sbapt					}
1095298166Sbapt
1096298166Sbapt					return false;
1097298166Sbapt				}
1098290071Sbapt				nest_obj->prev = nest_obj;
1099290071Sbapt				nest_obj->next = NULL;
1100290071Sbapt
1101290071Sbapt				ucl_array_append (old_obj, nest_obj);
1102290071Sbapt			}
1103290071Sbapt			else {
1104290071Sbapt				/* Convert the object to an array */
1105290071Sbapt				new_obj = ucl_object_typed_new (UCL_ARRAY);
1106298166Sbapt				if (new_obj == NULL) {
1107298166Sbapt					ucl_create_err (&parser->err, "cannot allocate memory for an object");
1108298166Sbapt					if (buf) {
1109298166Sbapt						ucl_munmap (buf, buflen);
1110298166Sbapt					}
1111298166Sbapt
1112298166Sbapt					return false;
1113298166Sbapt				}
1114290071Sbapt				new_obj->key = old_obj->key;
1115290071Sbapt				new_obj->keylen = old_obj->keylen;
1116290071Sbapt				new_obj->flags |= UCL_OBJECT_MULTIVALUE;
1117290071Sbapt				new_obj->prev = new_obj;
1118290071Sbapt				new_obj->next = NULL;
1119290071Sbapt
1120290071Sbapt				nest_obj = ucl_object_new_full (UCL_OBJECT, params->priority);
1121298166Sbapt				if (nest_obj == NULL) {
1122298166Sbapt					ucl_create_err (&parser->err, "cannot allocate memory for an object");
1123298166Sbapt					if (buf) {
1124298166Sbapt						ucl_munmap (buf, buflen);
1125298166Sbapt					}
1126298166Sbapt
1127298166Sbapt					return false;
1128298166Sbapt				}
1129290071Sbapt				nest_obj->prev = nest_obj;
1130290071Sbapt				nest_obj->next = NULL;
1131290071Sbapt
1132290071Sbapt				ucl_array_append (new_obj, old_obj);
1133290071Sbapt				ucl_array_append (new_obj, nest_obj);
1134290071Sbapt				ucl_hash_replace (container, old_obj, new_obj);
1135290071Sbapt			}
1136290071Sbapt		}
1137290071Sbapt		else {
1138290071Sbapt			if (ucl_object_type (old_obj) == UCL_OBJECT) {
1139290071Sbapt				/* Append to existing Object*/
1140290071Sbapt				nest_obj = old_obj;
1141290071Sbapt			}
1142290071Sbapt			else {
1143290071Sbapt				/* The key is not an object */
1144290071Sbapt				ucl_create_err (&parser->err,
1145290071Sbapt						"Conflicting type for key: %s",
1146290071Sbapt						params->prefix);
1147298166Sbapt				if (buf) {
1148298166Sbapt					ucl_munmap (buf, buflen);
1149298166Sbapt				}
1150298166Sbapt
1151290071Sbapt				return false;
1152290071Sbapt			}
1153290071Sbapt		}
1154290071Sbapt
1155290071Sbapt		 /* Put all of the content of the include inside that object */
1156290071Sbapt		parser->stack->obj->value.ov = container;
1157290071Sbapt
1158298166Sbapt		st = UCL_ALLOC (sizeof (struct ucl_stack));
1159298166Sbapt		if (st == NULL) {
1160298166Sbapt			ucl_create_err (&parser->err, "cannot allocate memory for an object");
1161298166Sbapt			ucl_object_unref (nest_obj);
1162298166Sbapt
1163298166Sbapt			if (buf) {
1164298166Sbapt				ucl_munmap (buf, buflen);
1165290071Sbapt			}
1166298166Sbapt
1167298166Sbapt			return false;
1168290071Sbapt		}
1169298166Sbapt		st->obj = nest_obj;
1170298166Sbapt		st->level = parser->stack->level;
1171298166Sbapt		LL_PREPEND (parser->stack, st);
1172298166Sbapt		parser->cur_obj = nest_obj;
1173290071Sbapt	}
1174290071Sbapt
1175290071Sbapt	res = ucl_parser_add_chunk_full (parser, buf, buflen, params->priority,
1176290071Sbapt			params->strat, params->parse_type);
1177301339Sbapt
1178301339Sbapt	if (!res) {
1179301339Sbapt		if (!params->must_exist) {
1180301339Sbapt			/* Free error */
1181301339Sbapt			utstring_free (parser->err);
1182301339Sbapt			parser->err = NULL;
1183301339Sbapt			res = true;
1184301339Sbapt		}
1185275223Sbapt	}
1186275223Sbapt
1187290071Sbapt	/* Stop nesting the include, take 1 level off the stack */
1188290071Sbapt	if (params->prefix != NULL && nest_obj != NULL) {
1189290071Sbapt		parser->stack = st->next;
1190290071Sbapt		UCL_FREE (sizeof (struct ucl_stack), st);
1191290071Sbapt	}
1192290071Sbapt
1193275223Sbapt	/* Remove chunk from the stack */
1194275223Sbapt	chunk = parser->chunks;
1195275223Sbapt	if (chunk != NULL) {
1196275223Sbapt		parser->chunks = chunk->next;
1197275223Sbapt		UCL_FREE (sizeof (struct ucl_chunk), chunk);
1198275223Sbapt		parser->recursion --;
1199275223Sbapt	}
1200275223Sbapt
1201275223Sbapt	/* Restore old file vars */
1202290071Sbapt	if (parser->cur_file) {
1203290071Sbapt		free (parser->cur_file);
1204290071Sbapt	}
1205290071Sbapt
1206275223Sbapt	parser->cur_file = old_curfile;
1207275223Sbapt	DL_FOREACH_SAFE (parser->variables, cur_var, tmp_var) {
1208275223Sbapt		if (strcmp (cur_var->var, "CURDIR") == 0 && old_curdir) {
1209275223Sbapt			DL_DELETE (parser->variables, cur_var);
1210275223Sbapt			free (cur_var->var);
1211275223Sbapt			free (cur_var->value);
1212275223Sbapt			UCL_FREE (sizeof (struct ucl_variable), cur_var);
1213262395Sbapt		}
1214275223Sbapt		else if (strcmp (cur_var->var, "FILENAME") == 0 && old_filename) {
1215275223Sbapt			DL_DELETE (parser->variables, cur_var);
1216275223Sbapt			free (cur_var->var);
1217275223Sbapt			free (cur_var->value);
1218275223Sbapt			UCL_FREE (sizeof (struct ucl_variable), cur_var);
1219275223Sbapt		}
1220262395Sbapt	}
1221275223Sbapt	if (old_filename) {
1222275223Sbapt		DL_APPEND (parser->variables, old_filename);
1223275223Sbapt	}
1224275223Sbapt	if (old_curdir) {
1225275223Sbapt		DL_APPEND (parser->variables, old_curdir);
1226275223Sbapt	}
1227262395Sbapt
1228262395Sbapt	parser->state = prev_state;
1229262395Sbapt
1230262395Sbapt	if (buflen > 0) {
1231263648Sbapt		ucl_munmap (buf, buflen);
1232262395Sbapt	}
1233262395Sbapt
1234262395Sbapt	return res;
1235262395Sbapt}
1236262395Sbapt
1237262395Sbapt/**
1238275223Sbapt * Include a file to configuration
1239275223Sbapt * @param data
1240275223Sbapt * @param len
1241275223Sbapt * @param parser
1242275223Sbapt * @param err
1243275223Sbapt * @return
1244275223Sbapt */
1245275223Sbaptstatic bool
1246275223Sbaptucl_include_file (const unsigned char *data, size_t len,
1247290071Sbapt		struct ucl_parser *parser, struct ucl_include_params *params)
1248275223Sbapt{
1249275223Sbapt	const unsigned char *p = data, *end = data + len;
1250275223Sbapt	bool need_glob = false;
1251275223Sbapt	int cnt = 0;
1252275223Sbapt	char glob_pattern[PATH_MAX];
1253275223Sbapt	size_t i;
1254275223Sbapt
1255279549Sbapt#ifndef _WIN32
1256290071Sbapt	if (!params->allow_glob) {
1257290071Sbapt		return ucl_include_file_single (data, len, parser, params);
1258275223Sbapt	}
1259275223Sbapt	else {
1260275223Sbapt		/* Check for special symbols in a filename */
1261275223Sbapt		while (p != end) {
1262275223Sbapt			if (*p == '*' || *p == '?') {
1263275223Sbapt				need_glob = true;
1264275223Sbapt				break;
1265275223Sbapt			}
1266275223Sbapt			p ++;
1267275223Sbapt		}
1268275223Sbapt		if (need_glob) {
1269279549Sbapt			glob_t globbuf;
1270275223Sbapt			memset (&globbuf, 0, sizeof (globbuf));
1271290071Sbapt			ucl_strlcpy (glob_pattern, (const char *)data,
1272290071Sbapt				(len + 1 < sizeof (glob_pattern) ? len + 1 : sizeof (glob_pattern)));
1273275223Sbapt			if (glob (glob_pattern, 0, NULL, &globbuf) != 0) {
1274290071Sbapt				return (!params->must_exist || false);
1275275223Sbapt			}
1276275223Sbapt			for (i = 0; i < globbuf.gl_pathc; i ++) {
1277275223Sbapt				if (!ucl_include_file_single ((unsigned char *)globbuf.gl_pathv[i],
1278290071Sbapt						strlen (globbuf.gl_pathv[i]), parser, params)) {
1279290071Sbapt					if (params->soft_fail) {
1280290071Sbapt						continue;
1281290071Sbapt					}
1282275223Sbapt					globfree (&globbuf);
1283275223Sbapt					return false;
1284275223Sbapt				}
1285275223Sbapt				cnt ++;
1286275223Sbapt			}
1287275223Sbapt			globfree (&globbuf);
1288275223Sbapt
1289290071Sbapt			if (cnt == 0 && params->must_exist) {
1290275223Sbapt				ucl_create_err (&parser->err, "cannot match any files for pattern %s",
1291275223Sbapt					glob_pattern);
1292275223Sbapt				return false;
1293275223Sbapt			}
1294275223Sbapt		}
1295275223Sbapt		else {
1296290071Sbapt			return ucl_include_file_single (data, len, parser, params);
1297275223Sbapt		}
1298275223Sbapt	}
1299279549Sbapt#else
1300279549Sbapt	/* Win32 compilers do not support globbing. Therefore, for Win32,
1301279549Sbapt	   treat allow_glob/need_glob as a NOOP and just return */
1302290071Sbapt	return ucl_include_file_single (data, len, parser, params);
1303279549Sbapt#endif
1304298166Sbapt
1305275223Sbapt	return true;
1306275223Sbapt}
1307275223Sbapt
1308275223Sbapt/**
1309275223Sbapt * Common function to handle .*include* macros
1310275223Sbapt * @param data
1311275223Sbapt * @param len
1312275223Sbapt * @param args
1313275223Sbapt * @param parser
1314275223Sbapt * @param default_try
1315275223Sbapt * @param default_sign
1316275223Sbapt * @return
1317275223Sbapt */
1318275223Sbaptstatic bool
1319275223Sbaptucl_include_common (const unsigned char *data, size_t len,
1320275223Sbapt		const ucl_object_t *args, struct ucl_parser *parser,
1321275223Sbapt		bool default_try,
1322275223Sbapt		bool default_sign)
1323275223Sbapt{
1324298166Sbapt	bool allow_url = false, search = false;
1325290071Sbapt	const char *duplicate;
1326275223Sbapt	const ucl_object_t *param;
1327290071Sbapt	ucl_object_iter_t it = NULL, ip = NULL;
1328290071Sbapt	char ipath[PATH_MAX];
1329290071Sbapt	struct ucl_include_params params;
1330275223Sbapt
1331275223Sbapt	/* Default values */
1332290071Sbapt	params.soft_fail = default_try;
1333290071Sbapt	params.allow_glob = false;
1334290071Sbapt	params.check_signature = default_sign;
1335290071Sbapt	params.use_prefix = false;
1336290071Sbapt	params.target = "object";
1337290071Sbapt	params.prefix = NULL;
1338290071Sbapt	params.priority = 0;
1339290071Sbapt	params.parse_type = UCL_PARSE_UCL;
1340290071Sbapt	params.strat = UCL_DUPLICATE_APPEND;
1341290071Sbapt	params.must_exist = !default_try;
1342275223Sbapt
1343275223Sbapt	/* Process arguments */
1344275223Sbapt	if (args != NULL && args->type == UCL_OBJECT) {
1345298166Sbapt		while ((param = ucl_object_iterate (args, &it, true)) != NULL) {
1346275223Sbapt			if (param->type == UCL_BOOLEAN) {
1347290071Sbapt				if (strncmp (param->key, "try", param->keylen) == 0) {
1348290071Sbapt					params.must_exist = !ucl_object_toboolean (param);
1349275223Sbapt				}
1350290071Sbapt				else if (strncmp (param->key, "sign", param->keylen) == 0) {
1351290071Sbapt					params.check_signature = ucl_object_toboolean (param);
1352275223Sbapt				}
1353290071Sbapt				else if (strncmp (param->key, "glob", param->keylen) == 0) {
1354290071Sbapt					params.allow_glob = ucl_object_toboolean (param);
1355275223Sbapt				}
1356290071Sbapt				else if (strncmp (param->key, "url", param->keylen) == 0) {
1357290071Sbapt					allow_url = ucl_object_toboolean (param);
1358275223Sbapt				}
1359290071Sbapt				else if (strncmp (param->key, "prefix", param->keylen) == 0) {
1360290071Sbapt					params.use_prefix = ucl_object_toboolean (param);
1361290071Sbapt				}
1362275223Sbapt			}
1363290071Sbapt			else if (param->type == UCL_STRING) {
1364290071Sbapt				if (strncmp (param->key, "key", param->keylen) == 0) {
1365290071Sbapt					params.prefix = ucl_object_tostring (param);
1366290071Sbapt				}
1367290071Sbapt				else if (strncmp (param->key, "target", param->keylen) == 0) {
1368290071Sbapt					params.target = ucl_object_tostring (param);
1369290071Sbapt				}
1370290071Sbapt				else if (strncmp (param->key, "duplicate", param->keylen) == 0) {
1371290071Sbapt					duplicate = ucl_object_tostring (param);
1372290071Sbapt
1373290071Sbapt					if (strcmp (duplicate, "append") == 0) {
1374290071Sbapt						params.strat = UCL_DUPLICATE_APPEND;
1375290071Sbapt					}
1376290071Sbapt					else if (strcmp (duplicate, "merge") == 0) {
1377290071Sbapt						params.strat = UCL_DUPLICATE_MERGE;
1378290071Sbapt					}
1379290071Sbapt					else if (strcmp (duplicate, "rewrite") == 0) {
1380290071Sbapt						params.strat = UCL_DUPLICATE_REWRITE;
1381290071Sbapt					}
1382290071Sbapt					else if (strcmp (duplicate, "error") == 0) {
1383290071Sbapt						params.strat = UCL_DUPLICATE_ERROR;
1384290071Sbapt					}
1385290071Sbapt				}
1386290071Sbapt			}
1387290071Sbapt			else if (param->type == UCL_ARRAY) {
1388290071Sbapt				if (strncmp (param->key, "path", param->keylen) == 0) {
1389290071Sbapt					ucl_set_include_path (parser, __DECONST(ucl_object_t *, param));
1390290071Sbapt				}
1391290071Sbapt			}
1392275223Sbapt			else if (param->type == UCL_INT) {
1393290071Sbapt				if (strncmp (param->key, "priority", param->keylen) == 0) {
1394290071Sbapt					params.priority = ucl_object_toint (param);
1395275223Sbapt				}
1396275223Sbapt			}
1397275223Sbapt		}
1398275223Sbapt	}
1399275223Sbapt
1400290071Sbapt	if (parser->includepaths == NULL) {
1401290071Sbapt		if (allow_url && ucl_strnstr (data, "://", len) != NULL) {
1402290071Sbapt			/* Globbing is not used for URL's */
1403290071Sbapt			return ucl_include_url (data, len, parser, &params);
1404290071Sbapt		}
1405290071Sbapt		else if (data != NULL) {
1406290071Sbapt			/* Try to load a file */
1407290071Sbapt			return ucl_include_file (data, len, parser, &params);
1408290071Sbapt		}
1409275223Sbapt	}
1410290071Sbapt	else {
1411290071Sbapt		if (allow_url && ucl_strnstr (data, "://", len) != NULL) {
1412290071Sbapt			/* Globbing is not used for URL's */
1413290071Sbapt			return ucl_include_url (data, len, parser, &params);
1414290071Sbapt		}
1415290071Sbapt
1416290071Sbapt		ip = ucl_object_iterate_new (parser->includepaths);
1417290071Sbapt		while ((param = ucl_object_iterate_safe (ip, true)) != NULL) {
1418290071Sbapt			if (ucl_object_type(param) == UCL_STRING) {
1419290071Sbapt				snprintf (ipath, sizeof (ipath), "%s/%.*s", ucl_object_tostring(param),
1420290071Sbapt						(int)len, data);
1421290071Sbapt				if ((search = ucl_include_file (ipath, strlen (ipath),
1422290071Sbapt						parser, &params))) {
1423290071Sbapt					if (!params.allow_glob) {
1424290071Sbapt						break;
1425290071Sbapt					}
1426290071Sbapt				}
1427290071Sbapt			}
1428290071Sbapt		}
1429290071Sbapt		ucl_object_iterate_free (ip);
1430290071Sbapt		if (search == true) {
1431290071Sbapt			return true;
1432290071Sbapt		}
1433290071Sbapt		else {
1434290071Sbapt			ucl_create_err (&parser->err,
1435290071Sbapt					"cannot find file: %.*s in search path",
1436290071Sbapt					(int)len, data);
1437290071Sbapt			return false;
1438290071Sbapt		}
1439275223Sbapt	}
1440275223Sbapt
1441275223Sbapt	return false;
1442275223Sbapt}
1443275223Sbapt
1444275223Sbapt/**
1445262395Sbapt * Handle include macro
1446262395Sbapt * @param data include data
1447262395Sbapt * @param len length of data
1448290071Sbapt * @param args UCL object representing arguments to the macro
1449262395Sbapt * @param ud user data
1450262395Sbapt * @return
1451262395Sbapt */
1452290071Sbaptbool
1453275223Sbaptucl_include_handler (const unsigned char *data, size_t len,
1454275223Sbapt		const ucl_object_t *args, void* ud)
1455262395Sbapt{
1456262395Sbapt	struct ucl_parser *parser = ud;
1457262395Sbapt
1458275223Sbapt	return ucl_include_common (data, len, args, parser, false, false);
1459262395Sbapt}
1460262395Sbapt
1461262395Sbapt/**
1462262395Sbapt * Handle includes macro
1463262395Sbapt * @param data include data
1464262395Sbapt * @param len length of data
1465290071Sbapt * @param args UCL object representing arguments to the macro
1466262395Sbapt * @param ud user data
1467262395Sbapt * @return
1468262395Sbapt */
1469290071Sbaptbool
1470275223Sbaptucl_includes_handler (const unsigned char *data, size_t len,
1471275223Sbapt		const ucl_object_t *args, void* ud)
1472262395Sbapt{
1473262395Sbapt	struct ucl_parser *parser = ud;
1474262395Sbapt
1475275223Sbapt	return ucl_include_common (data, len, args, parser, false, true);
1476262395Sbapt}
1477262395Sbapt
1478290071Sbapt/**
1479290071Sbapt * Handle tryinclude macro
1480290071Sbapt * @param data include data
1481290071Sbapt * @param len length of data
1482290071Sbapt * @param args UCL object representing arguments to the macro
1483290071Sbapt * @param ud user data
1484290071Sbapt * @return
1485290071Sbapt */
1486290071Sbaptbool
1487275223Sbaptucl_try_include_handler (const unsigned char *data, size_t len,
1488275223Sbapt		const ucl_object_t *args, void* ud)
1489262395Sbapt{
1490262395Sbapt	struct ucl_parser *parser = ud;
1491262395Sbapt
1492275223Sbapt	return ucl_include_common (data, len, args, parser, true, false);
1493262395Sbapt}
1494262395Sbapt
1495290071Sbapt/**
1496290071Sbapt * Handle priority macro
1497290071Sbapt * @param data include data
1498290071Sbapt * @param len length of data
1499290071Sbapt * @param args UCL object representing arguments to the macro
1500290071Sbapt * @param ud user data
1501290071Sbapt * @return
1502290071Sbapt */
1503290071Sbaptbool
1504290071Sbaptucl_priority_handler (const unsigned char *data, size_t len,
1505290071Sbapt		const ucl_object_t *args, void* ud)
1506290071Sbapt{
1507290071Sbapt	struct ucl_parser *parser = ud;
1508290071Sbapt	unsigned priority = 255;
1509290071Sbapt	const ucl_object_t *param;
1510290071Sbapt	bool found = false;
1511290071Sbapt	char *value = NULL, *leftover = NULL;
1512290071Sbapt	ucl_object_iter_t it = NULL;
1513290071Sbapt
1514290071Sbapt	if (parser == NULL) {
1515290071Sbapt		return false;
1516290071Sbapt	}
1517290071Sbapt
1518290071Sbapt	/* Process arguments */
1519290071Sbapt	if (args != NULL && args->type == UCL_OBJECT) {
1520298166Sbapt		while ((param = ucl_object_iterate (args, &it, true)) != NULL) {
1521290071Sbapt			if (param->type == UCL_INT) {
1522290071Sbapt				if (strncmp (param->key, "priority", param->keylen) == 0) {
1523290071Sbapt					priority = ucl_object_toint (param);
1524290071Sbapt					found = true;
1525290071Sbapt				}
1526290071Sbapt			}
1527290071Sbapt		}
1528290071Sbapt	}
1529290071Sbapt
1530290071Sbapt	if (len > 0) {
1531290071Sbapt		value = malloc(len + 1);
1532290071Sbapt		ucl_strlcpy(value, (const char *)data, len + 1);
1533290071Sbapt		priority = strtol(value, &leftover, 10);
1534290071Sbapt		if (*leftover != '\0') {
1535290071Sbapt			ucl_create_err (&parser->err, "Invalid priority value in macro: %s",
1536290071Sbapt				value);
1537290071Sbapt			free(value);
1538290071Sbapt			return false;
1539290071Sbapt		}
1540290071Sbapt		free(value);
1541290071Sbapt		found = true;
1542290071Sbapt	}
1543290071Sbapt
1544290071Sbapt	if (found == true) {
1545290071Sbapt		parser->chunks->priority = priority;
1546290071Sbapt		return true;
1547290071Sbapt	}
1548290071Sbapt
1549290071Sbapt	ucl_create_err (&parser->err, "Unable to parse priority macro");
1550290071Sbapt	return false;
1551290071Sbapt}
1552290071Sbapt
1553290071Sbapt/**
1554290071Sbapt * Handle load macro
1555290071Sbapt * @param data include data
1556290071Sbapt * @param len length of data
1557290071Sbapt * @param args UCL object representing arguments to the macro
1558290071Sbapt * @param ud user data
1559290071Sbapt * @return
1560290071Sbapt */
1561290071Sbaptbool
1562290071Sbaptucl_load_handler (const unsigned char *data, size_t len,
1563290071Sbapt		const ucl_object_t *args, void* ud)
1564290071Sbapt{
1565290071Sbapt	struct ucl_parser *parser = ud;
1566290071Sbapt	const ucl_object_t *param;
1567290071Sbapt	ucl_object_t *obj, *old_obj;
1568290071Sbapt	ucl_object_iter_t it = NULL;
1569290071Sbapt	bool try_load, multiline, test;
1570290071Sbapt	const char *target, *prefix;
1571290071Sbapt	char *load_file, *tmp;
1572290071Sbapt	unsigned char *buf;
1573290071Sbapt	size_t buflen;
1574290071Sbapt	unsigned priority;
1575290071Sbapt	int64_t iv;
1576298166Sbapt	ucl_object_t *container = NULL;
1577290071Sbapt	enum ucl_string_flags flags;
1578290071Sbapt
1579290071Sbapt	/* Default values */
1580290071Sbapt	try_load = false;
1581290071Sbapt	multiline = false;
1582290071Sbapt	test = false;
1583290071Sbapt	target = "string";
1584290071Sbapt	prefix = NULL;
1585290071Sbapt	load_file = NULL;
1586290071Sbapt	buf = NULL;
1587290071Sbapt	buflen = 0;
1588290071Sbapt	priority = 0;
1589290071Sbapt	obj = NULL;
1590290071Sbapt	old_obj = NULL;
1591290071Sbapt	flags = 0;
1592290071Sbapt
1593290071Sbapt	if (parser == NULL) {
1594290071Sbapt		return false;
1595290071Sbapt	}
1596290071Sbapt
1597290071Sbapt	/* Process arguments */
1598290071Sbapt	if (args != NULL && args->type == UCL_OBJECT) {
1599298166Sbapt		while ((param = ucl_object_iterate (args, &it, true)) != NULL) {
1600290071Sbapt			if (param->type == UCL_BOOLEAN) {
1601290071Sbapt				if (strncmp (param->key, "try", param->keylen) == 0) {
1602290071Sbapt					try_load = ucl_object_toboolean (param);
1603290071Sbapt				}
1604290071Sbapt				else if (strncmp (param->key, "multiline", param->keylen) == 0) {
1605290071Sbapt					multiline = ucl_object_toboolean (param);
1606290071Sbapt				}
1607290071Sbapt				else if (strncmp (param->key, "escape", param->keylen) == 0) {
1608290071Sbapt					test = ucl_object_toboolean (param);
1609290071Sbapt					if (test) {
1610290071Sbapt						flags |= UCL_STRING_ESCAPE;
1611290071Sbapt					}
1612290071Sbapt				}
1613290071Sbapt				else if (strncmp (param->key, "trim", param->keylen) == 0) {
1614290071Sbapt					test = ucl_object_toboolean (param);
1615290071Sbapt					if (test) {
1616290071Sbapt						flags |= UCL_STRING_TRIM;
1617290071Sbapt					}
1618290071Sbapt				}
1619290071Sbapt			}
1620290071Sbapt			else if (param->type == UCL_STRING) {
1621290071Sbapt				if (strncmp (param->key, "key", param->keylen) == 0) {
1622290071Sbapt					prefix = ucl_object_tostring (param);
1623290071Sbapt				}
1624290071Sbapt				else if (strncmp (param->key, "target", param->keylen) == 0) {
1625290071Sbapt					target = ucl_object_tostring (param);
1626290071Sbapt				}
1627290071Sbapt			}
1628290071Sbapt			else if (param->type == UCL_INT) {
1629290071Sbapt				if (strncmp (param->key, "priority", param->keylen) == 0) {
1630290071Sbapt					priority = ucl_object_toint (param);
1631290071Sbapt				}
1632290071Sbapt			}
1633290071Sbapt		}
1634290071Sbapt	}
1635290071Sbapt
1636298166Sbapt	if (prefix == NULL || strlen (prefix) == 0) {
1637290071Sbapt		ucl_create_err (&parser->err, "No Key specified in load macro");
1638290071Sbapt		return false;
1639290071Sbapt	}
1640290071Sbapt
1641290071Sbapt	if (len > 0) {
1642298166Sbapt		load_file = malloc (len + 1);
1643298166Sbapt		if (!load_file) {
1644298166Sbapt			ucl_create_err (&parser->err, "cannot allocate memory for suffix");
1645298166Sbapt
1646298166Sbapt			return false;
1647298166Sbapt		}
1648298166Sbapt
1649298166Sbapt		snprintf (load_file, len + 1, "%.*s", (int)len, data);
1650298166Sbapt
1651298166Sbapt		if (!ucl_fetch_file (load_file, &buf, &buflen, &parser->err,
1652298166Sbapt				!try_load)) {
1653298166Sbapt			free (load_file);
1654298166Sbapt
1655290071Sbapt			return (try_load || false);
1656290071Sbapt		}
1657290071Sbapt
1658298166Sbapt		free (load_file);
1659298166Sbapt		container = parser->stack->obj;
1660298166Sbapt		old_obj = __DECONST (ucl_object_t *, ucl_object_lookup (container,
1661298166Sbapt				prefix));
1662298166Sbapt
1663290071Sbapt		if (old_obj != NULL) {
1664290071Sbapt			ucl_create_err (&parser->err, "Key %s already exists", prefix);
1665298166Sbapt			if (buf) {
1666298166Sbapt				ucl_munmap (buf, buflen);
1667298166Sbapt			}
1668298166Sbapt
1669290071Sbapt			return false;
1670290071Sbapt		}
1671290071Sbapt
1672290071Sbapt		if (strcasecmp (target, "string") == 0) {
1673290071Sbapt			obj = ucl_object_fromstring_common (buf, buflen, flags);
1674290071Sbapt			ucl_copy_value_trash (obj);
1675290071Sbapt			if (multiline) {
1676290071Sbapt				obj->flags |= UCL_OBJECT_MULTILINE;
1677290071Sbapt			}
1678290071Sbapt		}
1679290071Sbapt		else if (strcasecmp (target, "int") == 0) {
1680298166Sbapt			tmp = malloc (buflen + 1);
1681298166Sbapt
1682298166Sbapt			if (tmp == NULL) {
1683298166Sbapt				ucl_create_err (&parser->err, "Memory allocation failed");
1684298166Sbapt				if (buf) {
1685298166Sbapt					ucl_munmap (buf, buflen);
1686298166Sbapt				}
1687298166Sbapt
1688298166Sbapt				return false;
1689298166Sbapt			}
1690298166Sbapt
1691298166Sbapt			snprintf (tmp, buflen + 1, "%.*s", (int)buflen, buf);
1692298166Sbapt			iv = strtoll (tmp, NULL, 10);
1693298166Sbapt			obj = ucl_object_fromint (iv);
1694298166Sbapt			free (tmp);
1695290071Sbapt		}
1696290071Sbapt
1697298166Sbapt		if (buf) {
1698290071Sbapt			ucl_munmap (buf, buflen);
1699290071Sbapt		}
1700290071Sbapt
1701290071Sbapt		if (obj != NULL) {
1702290071Sbapt			obj->key = prefix;
1703290071Sbapt			obj->keylen = strlen (prefix);
1704298166Sbapt			ucl_copy_key_trash (obj);
1705290071Sbapt			obj->prev = obj;
1706290071Sbapt			obj->next = NULL;
1707290071Sbapt			ucl_object_set_priority (obj, priority);
1708298166Sbapt			ucl_object_insert_key (container, obj, obj->key, obj->keylen, false);
1709290071Sbapt		}
1710298166Sbapt
1711290071Sbapt		return true;
1712290071Sbapt	}
1713290071Sbapt
1714290071Sbapt	ucl_create_err (&parser->err, "Unable to parse load macro");
1715290071Sbapt	return false;
1716290071Sbapt}
1717290071Sbapt
1718290071Sbaptbool
1719290071Sbaptucl_inherit_handler (const unsigned char *data, size_t len,
1720290071Sbapt		const ucl_object_t *args, const ucl_object_t *ctx, void* ud)
1721290071Sbapt{
1722290071Sbapt	const ucl_object_t *parent, *cur;
1723290071Sbapt	ucl_object_t *target, *copy;
1724290071Sbapt	ucl_object_iter_t it = NULL;
1725290071Sbapt	bool replace = false;
1726290071Sbapt	struct ucl_parser *parser = ud;
1727290071Sbapt
1728298166Sbapt	parent = ucl_object_lookup_len (ctx, data, len);
1729290071Sbapt
1730290071Sbapt	/* Some sanity checks */
1731290071Sbapt	if (parent == NULL || ucl_object_type (parent) != UCL_OBJECT) {
1732290071Sbapt		ucl_create_err (&parser->err, "Unable to find inherited object %*.s",
1733290071Sbapt				(int)len, data);
1734290071Sbapt		return false;
1735290071Sbapt	}
1736290071Sbapt
1737290071Sbapt	if (parser->stack == NULL || parser->stack->obj == NULL ||
1738290071Sbapt			ucl_object_type (parser->stack->obj) != UCL_OBJECT) {
1739290071Sbapt		ucl_create_err (&parser->err, "Invalid inherit context");
1740290071Sbapt		return false;
1741290071Sbapt	}
1742290071Sbapt
1743290071Sbapt	target = parser->stack->obj;
1744290071Sbapt
1745298166Sbapt	if (args && (cur = ucl_object_lookup (args, "replace")) != NULL) {
1746290071Sbapt		replace = ucl_object_toboolean (cur);
1747290071Sbapt	}
1748290071Sbapt
1749298166Sbapt	while ((cur = ucl_object_iterate (parent, &it, true))) {
1750290071Sbapt		/* We do not replace existing keys */
1751298166Sbapt		if (!replace && ucl_object_lookup_len (target, cur->key, cur->keylen)) {
1752290071Sbapt			continue;
1753290071Sbapt		}
1754290071Sbapt
1755290071Sbapt		copy = ucl_object_copy (cur);
1756290071Sbapt
1757290071Sbapt		if (!replace) {
1758290071Sbapt			copy->flags |= UCL_OBJECT_INHERITED;
1759290071Sbapt		}
1760290071Sbapt
1761290071Sbapt		ucl_object_insert_key (target, copy, copy->key,
1762290071Sbapt				copy->keylen, false);
1763290071Sbapt	}
1764290071Sbapt
1765290071Sbapt	return true;
1766290071Sbapt}
1767290071Sbapt
1768290071Sbaptbool
1769262395Sbaptucl_parser_set_filevars (struct ucl_parser *parser, const char *filename, bool need_expand)
1770262395Sbapt{
1771262395Sbapt	char realbuf[PATH_MAX], *curdir;
1772262395Sbapt
1773262395Sbapt	if (filename != NULL) {
1774262395Sbapt		if (need_expand) {
1775263648Sbapt			if (ucl_realpath (filename, realbuf) == NULL) {
1776262395Sbapt				return false;
1777262395Sbapt			}
1778262395Sbapt		}
1779262395Sbapt		else {
1780262395Sbapt			ucl_strlcpy (realbuf, filename, sizeof (realbuf));
1781262395Sbapt		}
1782262395Sbapt
1783262395Sbapt		/* Define variables */
1784262395Sbapt		ucl_parser_register_variable (parser, "FILENAME", realbuf);
1785262395Sbapt		curdir = dirname (realbuf);
1786262395Sbapt		ucl_parser_register_variable (parser, "CURDIR", curdir);
1787262395Sbapt	}
1788262395Sbapt	else {
1789262395Sbapt		/* Set everything from the current dir */
1790262395Sbapt		curdir = getcwd (realbuf, sizeof (realbuf));
1791262395Sbapt		ucl_parser_register_variable (parser, "FILENAME", "undef");
1792262395Sbapt		ucl_parser_register_variable (parser, "CURDIR", curdir);
1793262395Sbapt	}
1794262395Sbapt
1795262395Sbapt	return true;
1796262395Sbapt}
1797262395Sbapt
1798290071Sbaptbool
1799307790Sbaptucl_parser_add_file_full (struct ucl_parser *parser, const char *filename,
1800307790Sbapt		unsigned priority, enum ucl_duplicate_strategy strat,
1801307790Sbapt		enum ucl_parse_type parse_type)
1802262395Sbapt{
1803262395Sbapt	unsigned char *buf;
1804262395Sbapt	size_t len;
1805262395Sbapt	bool ret;
1806262395Sbapt	char realbuf[PATH_MAX];
1807262395Sbapt
1808263648Sbapt	if (ucl_realpath (filename, realbuf) == NULL) {
1809262395Sbapt		ucl_create_err (&parser->err, "cannot open file %s: %s",
1810262395Sbapt				filename,
1811262395Sbapt				strerror (errno));
1812262395Sbapt		return false;
1813262395Sbapt	}
1814262395Sbapt
1815262395Sbapt	if (!ucl_fetch_file (realbuf, &buf, &len, &parser->err, true)) {
1816262395Sbapt		return false;
1817262395Sbapt	}
1818262395Sbapt
1819275223Sbapt	if (parser->cur_file) {
1820275223Sbapt		free (parser->cur_file);
1821275223Sbapt	}
1822275223Sbapt	parser->cur_file = strdup (realbuf);
1823262395Sbapt	ucl_parser_set_filevars (parser, realbuf, false);
1824307790Sbapt	ret = ucl_parser_add_chunk_full (parser, buf, len, priority, strat,
1825307790Sbapt			parse_type);
1826262395Sbapt
1827262395Sbapt	if (len > 0) {
1828263648Sbapt		ucl_munmap (buf, len);
1829262395Sbapt	}
1830262395Sbapt
1831262395Sbapt	return ret;
1832262395Sbapt}
1833262395Sbapt
1834290071Sbaptbool
1835307790Sbaptucl_parser_add_file_priority (struct ucl_parser *parser, const char *filename,
1836307790Sbapt		unsigned priority)
1837307790Sbapt{
1838307790Sbapt	if (parser == NULL) {
1839307790Sbapt		return false;
1840307790Sbapt	}
1841307790Sbapt
1842307790Sbapt	return ucl_parser_add_file_full(parser, filename, priority,
1843307790Sbapt			UCL_DUPLICATE_APPEND, UCL_PARSE_UCL);
1844307790Sbapt}
1845307790Sbapt
1846307790Sbaptbool
1847290071Sbaptucl_parser_add_file (struct ucl_parser *parser, const char *filename)
1848275223Sbapt{
1849290071Sbapt	if (parser == NULL) {
1850290071Sbapt		return false;
1851290071Sbapt	}
1852290071Sbapt
1853307790Sbapt	return ucl_parser_add_file_full(parser, filename,
1854307790Sbapt			parser->default_priority, UCL_DUPLICATE_APPEND,
1855307790Sbapt			UCL_PARSE_UCL);
1856290071Sbapt}
1857290071Sbapt
1858314278Sbapt
1859290071Sbaptbool
1860314278Sbaptucl_parser_add_fd_full (struct ucl_parser *parser, int fd,
1861314278Sbapt		unsigned priority, enum ucl_duplicate_strategy strat,
1862314278Sbapt		enum ucl_parse_type parse_type)
1863290071Sbapt{
1864275223Sbapt	unsigned char *buf;
1865275223Sbapt	size_t len;
1866275223Sbapt	bool ret;
1867275223Sbapt	struct stat st;
1868275223Sbapt
1869275223Sbapt	if (fstat (fd, &st) == -1) {
1870275223Sbapt		ucl_create_err (&parser->err, "cannot stat fd %d: %s",
1871275223Sbapt			fd, strerror (errno));
1872275223Sbapt		return false;
1873275223Sbapt	}
1874301339Sbapt	if (st.st_size == 0) {
1875301339Sbapt		return true;
1876301339Sbapt	}
1877275223Sbapt	if ((buf = ucl_mmap (NULL, st.st_size, PROT_READ, MAP_SHARED, fd, 0)) == MAP_FAILED) {
1878275223Sbapt		ucl_create_err (&parser->err, "cannot mmap fd %d: %s",
1879275223Sbapt			fd, strerror (errno));
1880275223Sbapt		return false;
1881275223Sbapt	}
1882275223Sbapt
1883275223Sbapt	if (parser->cur_file) {
1884275223Sbapt		free (parser->cur_file);
1885275223Sbapt	}
1886275223Sbapt	parser->cur_file = NULL;
1887275223Sbapt	len = st.st_size;
1888314278Sbapt	ret = ucl_parser_add_chunk_full (parser, buf, len, priority, strat,
1889314278Sbapt			parse_type);
1890275223Sbapt
1891275223Sbapt	if (len > 0) {
1892275223Sbapt		ucl_munmap (buf, len);
1893275223Sbapt	}
1894275223Sbapt
1895275223Sbapt	return ret;
1896275223Sbapt}
1897275223Sbapt
1898290071Sbaptbool
1899314278Sbaptucl_parser_add_fd_priority (struct ucl_parser *parser, int fd,
1900314278Sbapt		unsigned priority)
1901314278Sbapt{
1902314278Sbapt	if (parser == NULL) {
1903314278Sbapt		return false;
1904314278Sbapt	}
1905314278Sbapt
1906314278Sbapt	return ucl_parser_add_fd_full(parser, fd, parser->default_priority,
1907314278Sbapt			UCL_DUPLICATE_APPEND, UCL_PARSE_UCL);
1908314278Sbapt}
1909314278Sbapt
1910314278Sbaptbool
1911290071Sbaptucl_parser_add_fd (struct ucl_parser *parser, int fd)
1912290071Sbapt{
1913290071Sbapt	if (parser == NULL) {
1914290071Sbapt		return false;
1915290071Sbapt	}
1916290071Sbapt
1917290071Sbapt	return ucl_parser_add_fd_priority(parser, fd, parser->default_priority);
1918290071Sbapt}
1919290071Sbapt
1920262395Sbaptsize_t
1921262395Sbaptucl_strlcpy (char *dst, const char *src, size_t siz)
1922262395Sbapt{
1923262395Sbapt	char *d = dst;
1924262395Sbapt	const char *s = src;
1925262395Sbapt	size_t n = siz;
1926262395Sbapt
1927262395Sbapt	/* Copy as many bytes as will fit */
1928262395Sbapt	if (n != 0) {
1929262395Sbapt		while (--n != 0) {
1930262395Sbapt			if ((*d++ = *s++) == '\0') {
1931262395Sbapt				break;
1932262395Sbapt			}
1933262395Sbapt		}
1934262395Sbapt	}
1935262395Sbapt
1936262395Sbapt	if (n == 0 && siz != 0) {
1937262395Sbapt		*d = '\0';
1938262395Sbapt	}
1939262395Sbapt
1940262395Sbapt	return (s - src - 1);    /* count does not include NUL */
1941262395Sbapt}
1942262395Sbapt
1943262395Sbaptsize_t
1944262395Sbaptucl_strlcpy_unsafe (char *dst, const char *src, size_t siz)
1945262395Sbapt{
1946262395Sbapt	memcpy (dst, src, siz - 1);
1947262395Sbapt	dst[siz - 1] = '\0';
1948262395Sbapt
1949262395Sbapt	return siz - 1;
1950262395Sbapt}
1951262395Sbapt
1952262395Sbaptsize_t
1953262395Sbaptucl_strlcpy_tolower (char *dst, const char *src, size_t siz)
1954262395Sbapt{
1955262395Sbapt	char *d = dst;
1956262395Sbapt	const char *s = src;
1957262395Sbapt	size_t n = siz;
1958262395Sbapt
1959262395Sbapt	/* Copy as many bytes as will fit */
1960262395Sbapt	if (n != 0) {
1961262395Sbapt		while (--n != 0) {
1962262395Sbapt			if ((*d++ = tolower (*s++)) == '\0') {
1963262395Sbapt				break;
1964262395Sbapt			}
1965262395Sbapt		}
1966262395Sbapt	}
1967262395Sbapt
1968262395Sbapt	if (n == 0 && siz != 0) {
1969262395Sbapt		*d = '\0';
1970262395Sbapt	}
1971262395Sbapt
1972262395Sbapt	return (s - src);    /* count does not include NUL */
1973262395Sbapt}
1974262395Sbapt
1975290071Sbapt/*
1976290071Sbapt * Find the first occurrence of find in s
1977290071Sbapt */
1978290071Sbaptchar *
1979290071Sbaptucl_strnstr (const char *s, const char *find, int len)
1980290071Sbapt{
1981290071Sbapt	char c, sc;
1982290071Sbapt	int mlen;
1983290071Sbapt
1984290071Sbapt	if ((c = *find++) != 0) {
1985290071Sbapt		mlen = strlen (find);
1986290071Sbapt		do {
1987290071Sbapt			do {
1988290071Sbapt				if ((sc = *s++) == 0 || len-- == 0)
1989290071Sbapt					return (NULL);
1990290071Sbapt			} while (sc != c);
1991290071Sbapt		} while (strncmp (s, find, mlen) != 0);
1992290071Sbapt		s--;
1993290071Sbapt	}
1994290071Sbapt	return ((char *)s);
1995290071Sbapt}
1996290071Sbapt
1997290071Sbapt/*
1998290071Sbapt * Find the first occurrence of find in s, ignore case.
1999290071Sbapt */
2000290071Sbaptchar *
2001290071Sbaptucl_strncasestr (const char *s, const char *find, int len)
2002290071Sbapt{
2003290071Sbapt	char c, sc;
2004290071Sbapt	int mlen;
2005290071Sbapt
2006290071Sbapt	if ((c = *find++) != 0) {
2007290071Sbapt		c = tolower (c);
2008290071Sbapt		mlen = strlen (find);
2009290071Sbapt		do {
2010290071Sbapt			do {
2011290071Sbapt				if ((sc = *s++) == 0 || len-- == 0)
2012290071Sbapt					return (NULL);
2013290071Sbapt			} while (tolower (sc) != c);
2014290071Sbapt		} while (strncasecmp (s, find, mlen) != 0);
2015290071Sbapt		s--;
2016290071Sbapt	}
2017290071Sbapt	return ((char *)s);
2018290071Sbapt}
2019290071Sbapt
2020262395Sbaptucl_object_t *
2021262395Sbaptucl_object_fromstring_common (const char *str, size_t len, enum ucl_string_flags flags)
2022262395Sbapt{
2023262395Sbapt	ucl_object_t *obj;
2024262395Sbapt	const char *start, *end, *p, *pos;
2025262395Sbapt	char *dst, *d;
2026262395Sbapt	size_t escaped_len;
2027262395Sbapt
2028262395Sbapt	if (str == NULL) {
2029262395Sbapt		return NULL;
2030262395Sbapt	}
2031262395Sbapt
2032262395Sbapt	obj = ucl_object_new ();
2033262395Sbapt	if (obj) {
2034262395Sbapt		if (len == 0) {
2035262395Sbapt			len = strlen (str);
2036262395Sbapt		}
2037262395Sbapt		if (flags & UCL_STRING_TRIM) {
2038262395Sbapt			/* Skip leading spaces */
2039262395Sbapt			for (start = str; (size_t)(start - str) < len; start ++) {
2040262395Sbapt				if (!ucl_test_character (*start, UCL_CHARACTER_WHITESPACE_UNSAFE)) {
2041262395Sbapt					break;
2042262395Sbapt				}
2043262395Sbapt			}
2044262395Sbapt			/* Skip trailing spaces */
2045262395Sbapt			for (end = str + len - 1; end > start; end --) {
2046262395Sbapt				if (!ucl_test_character (*end, UCL_CHARACTER_WHITESPACE_UNSAFE)) {
2047262395Sbapt					break;
2048262395Sbapt				}
2049262395Sbapt			}
2050262395Sbapt			end ++;
2051262395Sbapt		}
2052262395Sbapt		else {
2053262395Sbapt			start = str;
2054262395Sbapt			end = str + len;
2055262395Sbapt		}
2056262395Sbapt
2057262395Sbapt		obj->type = UCL_STRING;
2058262395Sbapt		if (flags & UCL_STRING_ESCAPE) {
2059262395Sbapt			for (p = start, escaped_len = 0; p < end; p ++, escaped_len ++) {
2060262395Sbapt				if (ucl_test_character (*p, UCL_CHARACTER_JSON_UNSAFE)) {
2061262395Sbapt					escaped_len ++;
2062262395Sbapt				}
2063262395Sbapt			}
2064262395Sbapt			dst = malloc (escaped_len + 1);
2065262395Sbapt			if (dst != NULL) {
2066262395Sbapt				for (p = start, d = dst; p < end; p ++, d ++) {
2067262395Sbapt					if (ucl_test_character (*p, UCL_CHARACTER_JSON_UNSAFE)) {
2068262395Sbapt						switch (*p) {
2069262395Sbapt						case '\n':
2070262395Sbapt							*d++ = '\\';
2071262395Sbapt							*d = 'n';
2072262395Sbapt							break;
2073262395Sbapt						case '\r':
2074262395Sbapt							*d++ = '\\';
2075262395Sbapt							*d = 'r';
2076262395Sbapt							break;
2077262395Sbapt						case '\b':
2078262395Sbapt							*d++ = '\\';
2079262395Sbapt							*d = 'b';
2080262395Sbapt							break;
2081262395Sbapt						case '\t':
2082262395Sbapt							*d++ = '\\';
2083262395Sbapt							*d = 't';
2084262395Sbapt							break;
2085262395Sbapt						case '\f':
2086262395Sbapt							*d++ = '\\';
2087262395Sbapt							*d = 'f';
2088262395Sbapt							break;
2089262395Sbapt						case '\\':
2090262395Sbapt							*d++ = '\\';
2091262395Sbapt							*d = '\\';
2092262395Sbapt							break;
2093262395Sbapt						case '"':
2094262395Sbapt							*d++ = '\\';
2095262395Sbapt							*d = '"';
2096262395Sbapt							break;
2097262395Sbapt						}
2098262395Sbapt					}
2099262395Sbapt					else {
2100262395Sbapt						*d = *p;
2101262395Sbapt					}
2102262395Sbapt				}
2103262395Sbapt				*d = '\0';
2104262395Sbapt				obj->value.sv = dst;
2105262395Sbapt				obj->trash_stack[UCL_TRASH_VALUE] = dst;
2106262395Sbapt				obj->len = escaped_len;
2107262395Sbapt			}
2108262395Sbapt		}
2109262395Sbapt		else {
2110262395Sbapt			dst = malloc (end - start + 1);
2111262395Sbapt			if (dst != NULL) {
2112262395Sbapt				ucl_strlcpy_unsafe (dst, start, end - start + 1);
2113262395Sbapt				obj->value.sv = dst;
2114262395Sbapt				obj->trash_stack[UCL_TRASH_VALUE] = dst;
2115262395Sbapt				obj->len = end - start;
2116262395Sbapt			}
2117262395Sbapt		}
2118262395Sbapt		if ((flags & UCL_STRING_PARSE) && dst != NULL) {
2119262395Sbapt			/* Parse what we have */
2120262395Sbapt			if (flags & UCL_STRING_PARSE_BOOLEAN) {
2121262395Sbapt				if (!ucl_maybe_parse_boolean (obj, dst, obj->len) && (flags & UCL_STRING_PARSE_NUMBER)) {
2122262395Sbapt					ucl_maybe_parse_number (obj, dst, dst + obj->len, &pos,
2123262395Sbapt							flags & UCL_STRING_PARSE_DOUBLE,
2124263648Sbapt							flags & UCL_STRING_PARSE_BYTES,
2125263648Sbapt							flags & UCL_STRING_PARSE_TIME);
2126262395Sbapt				}
2127262395Sbapt			}
2128262395Sbapt			else {
2129262395Sbapt				ucl_maybe_parse_number (obj, dst, dst + obj->len, &pos,
2130262395Sbapt						flags & UCL_STRING_PARSE_DOUBLE,
2131263648Sbapt						flags & UCL_STRING_PARSE_BYTES,
2132263648Sbapt						flags & UCL_STRING_PARSE_TIME);
2133262395Sbapt			}
2134262395Sbapt		}
2135262395Sbapt	}
2136262395Sbapt
2137262395Sbapt	return obj;
2138262395Sbapt}
2139262395Sbapt
2140264789Sbaptstatic bool
2141262395Sbaptucl_object_insert_key_common (ucl_object_t *top, ucl_object_t *elt,
2142262395Sbapt		const char *key, size_t keylen, bool copy_key, bool merge, bool replace)
2143262395Sbapt{
2144264789Sbapt	ucl_object_t *found, *tmp;
2145264789Sbapt	const ucl_object_t *cur;
2146262395Sbapt	ucl_object_iter_t it = NULL;
2147262395Sbapt	const char *p;
2148264789Sbapt	int ret = true;
2149262395Sbapt
2150262395Sbapt	if (elt == NULL || key == NULL) {
2151264789Sbapt		return false;
2152262395Sbapt	}
2153262395Sbapt
2154262395Sbapt	if (top == NULL) {
2155264789Sbapt		return false;
2156262395Sbapt	}
2157262395Sbapt
2158262395Sbapt	if (top->type != UCL_OBJECT) {
2159262395Sbapt		/* It is possible to convert NULL type to an object */
2160262395Sbapt		if (top->type == UCL_NULL) {
2161262395Sbapt			top->type = UCL_OBJECT;
2162262395Sbapt		}
2163262395Sbapt		else {
2164262395Sbapt			/* Refuse converting of other object types */
2165264789Sbapt			return false;
2166262395Sbapt		}
2167262395Sbapt	}
2168262395Sbapt
2169262395Sbapt	if (top->value.ov == NULL) {
2170279549Sbapt		top->value.ov = ucl_hash_create (false);
2171262395Sbapt	}
2172262395Sbapt
2173262395Sbapt	if (keylen == 0) {
2174262395Sbapt		keylen = strlen (key);
2175262395Sbapt	}
2176262395Sbapt
2177262395Sbapt	for (p = key; p < key + keylen; p ++) {
2178262395Sbapt		if (ucl_test_character (*p, UCL_CHARACTER_UCL_UNSAFE)) {
2179262395Sbapt			elt->flags |= UCL_OBJECT_NEED_KEY_ESCAPE;
2180262395Sbapt			break;
2181262395Sbapt		}
2182262395Sbapt	}
2183262395Sbapt
2184275223Sbapt	/* workaround for some use cases */
2185275223Sbapt	if (elt->trash_stack[UCL_TRASH_KEY] != NULL &&
2186275223Sbapt			key != (const char *)elt->trash_stack[UCL_TRASH_KEY]) {
2187275223Sbapt		/* Remove copied key */
2188275223Sbapt		free (elt->trash_stack[UCL_TRASH_KEY]);
2189275223Sbapt		elt->trash_stack[UCL_TRASH_KEY] = NULL;
2190275223Sbapt		elt->flags &= ~UCL_OBJECT_ALLOCATED_KEY;
2191275223Sbapt	}
2192275223Sbapt
2193262395Sbapt	elt->key = key;
2194262395Sbapt	elt->keylen = keylen;
2195262395Sbapt
2196262395Sbapt	if (copy_key) {
2197262395Sbapt		ucl_copy_key_trash (elt);
2198262395Sbapt	}
2199262395Sbapt
2200264789Sbapt	found = __DECONST (ucl_object_t *, ucl_hash_search_obj (top->value.ov, elt));
2201262395Sbapt
2202275223Sbapt	if (found == NULL) {
2203279549Sbapt		top->value.ov = ucl_hash_insert_object (top->value.ov, elt, false);
2204263648Sbapt		top->len ++;
2205264789Sbapt		if (replace) {
2206264789Sbapt			ret = false;
2207264789Sbapt		}
2208262395Sbapt	}
2209262395Sbapt	else {
2210262395Sbapt		if (replace) {
2211275223Sbapt			ucl_hash_replace (top->value.ov, found, elt);
2212262395Sbapt			ucl_object_unref (found);
2213262395Sbapt		}
2214262395Sbapt		else if (merge) {
2215262395Sbapt			if (found->type != UCL_OBJECT && elt->type == UCL_OBJECT) {
2216262395Sbapt				/* Insert old elt to new one */
2217264789Sbapt				ucl_object_insert_key_common (elt, found, found->key,
2218264789Sbapt						found->keylen, copy_key, false, false);
2219262395Sbapt				ucl_hash_delete (top->value.ov, found);
2220279549Sbapt				top->value.ov = ucl_hash_insert_object (top->value.ov, elt, false);
2221262395Sbapt			}
2222262395Sbapt			else if (found->type == UCL_OBJECT && elt->type != UCL_OBJECT) {
2223262395Sbapt				/* Insert new to old */
2224264789Sbapt				ucl_object_insert_key_common (found, elt, elt->key,
2225264789Sbapt						elt->keylen, copy_key, false, false);
2226262395Sbapt			}
2227262395Sbapt			else if (found->type == UCL_OBJECT && elt->type == UCL_OBJECT) {
2228262395Sbapt				/* Mix two hashes */
2229298166Sbapt				while ((cur = ucl_object_iterate (elt, &it, true)) != NULL) {
2230264789Sbapt					tmp = ucl_object_ref (cur);
2231264789Sbapt					ucl_object_insert_key_common (found, tmp, cur->key,
2232264789Sbapt							cur->keylen, copy_key, false, false);
2233262395Sbapt				}
2234262395Sbapt				ucl_object_unref (elt);
2235262395Sbapt			}
2236262395Sbapt			else {
2237262395Sbapt				/* Just make a list of scalars */
2238262395Sbapt				DL_APPEND (found, elt);
2239262395Sbapt			}
2240262395Sbapt		}
2241262395Sbapt		else {
2242262395Sbapt			DL_APPEND (found, elt);
2243262395Sbapt		}
2244262395Sbapt	}
2245262395Sbapt
2246264789Sbapt	return ret;
2247262395Sbapt}
2248262395Sbapt
2249262975Sbaptbool
2250264789Sbaptucl_object_delete_keyl (ucl_object_t *top, const char *key, size_t keylen)
2251262975Sbapt{
2252262975Sbapt	ucl_object_t *found;
2253262975Sbapt
2254263648Sbapt	if (top == NULL || key == NULL) {
2255263648Sbapt		return false;
2256263648Sbapt	}
2257263648Sbapt
2258298166Sbapt	found = __DECONST (ucl_object_t *, ucl_object_lookup_len (top, key, keylen));
2259262975Sbapt
2260263648Sbapt	if (found == NULL) {
2261262975Sbapt		return false;
2262263648Sbapt	}
2263262975Sbapt
2264264789Sbapt	ucl_hash_delete (top->value.ov, found);
2265262975Sbapt	ucl_object_unref (found);
2266262975Sbapt	top->len --;
2267262975Sbapt
2268262975Sbapt	return true;
2269262975Sbapt}
2270262975Sbapt
2271262975Sbaptbool
2272264789Sbaptucl_object_delete_key (ucl_object_t *top, const char *key)
2273262975Sbapt{
2274290071Sbapt	return ucl_object_delete_keyl (top, key, strlen (key));
2275262975Sbapt}
2276262975Sbapt
2277263648Sbaptucl_object_t*
2278263648Sbaptucl_object_pop_keyl (ucl_object_t *top, const char *key, size_t keylen)
2279263648Sbapt{
2280264789Sbapt	const ucl_object_t *found;
2281263648Sbapt
2282263648Sbapt	if (top == NULL || key == NULL) {
2283263648Sbapt		return false;
2284263648Sbapt	}
2285298166Sbapt	found = ucl_object_lookup_len (top, key, keylen);
2286263648Sbapt
2287263648Sbapt	if (found == NULL) {
2288263648Sbapt		return NULL;
2289263648Sbapt	}
2290264789Sbapt	ucl_hash_delete (top->value.ov, found);
2291263648Sbapt	top->len --;
2292263648Sbapt
2293264789Sbapt	return __DECONST (ucl_object_t *, found);
2294263648Sbapt}
2295263648Sbapt
2296263648Sbaptucl_object_t*
2297263648Sbaptucl_object_pop_key (ucl_object_t *top, const char *key)
2298263648Sbapt{
2299290071Sbapt	return ucl_object_pop_keyl (top, key, strlen (key));
2300263648Sbapt}
2301263648Sbapt
2302264789Sbaptbool
2303262395Sbaptucl_object_insert_key (ucl_object_t *top, ucl_object_t *elt,
2304262395Sbapt		const char *key, size_t keylen, bool copy_key)
2305262395Sbapt{
2306262395Sbapt	return ucl_object_insert_key_common (top, elt, key, keylen, copy_key, false, false);
2307262395Sbapt}
2308262395Sbapt
2309264789Sbaptbool
2310262395Sbaptucl_object_insert_key_merged (ucl_object_t *top, ucl_object_t *elt,
2311262395Sbapt		const char *key, size_t keylen, bool copy_key)
2312262395Sbapt{
2313262395Sbapt	return ucl_object_insert_key_common (top, elt, key, keylen, copy_key, true, false);
2314262395Sbapt}
2315262395Sbapt
2316264789Sbaptbool
2317262395Sbaptucl_object_replace_key (ucl_object_t *top, ucl_object_t *elt,
2318262395Sbapt		const char *key, size_t keylen, bool copy_key)
2319262395Sbapt{
2320262395Sbapt	return ucl_object_insert_key_common (top, elt, key, keylen, copy_key, false, true);
2321262395Sbapt}
2322262395Sbapt
2323275223Sbaptbool
2324275223Sbaptucl_object_merge (ucl_object_t *top, ucl_object_t *elt, bool copy)
2325275223Sbapt{
2326275223Sbapt	ucl_object_t *cur = NULL, *cp = NULL, *found = NULL;
2327275223Sbapt	ucl_object_iter_t iter = NULL;
2328275223Sbapt
2329275223Sbapt	if (top == NULL || top->type != UCL_OBJECT || elt == NULL || elt->type != UCL_OBJECT) {
2330275223Sbapt		return false;
2331275223Sbapt	}
2332275223Sbapt
2333275223Sbapt	/* Mix two hashes */
2334275223Sbapt	while ((cur = (ucl_object_t*)ucl_hash_iterate (elt->value.ov, &iter))) {
2335275223Sbapt		if (copy) {
2336275223Sbapt			cp = ucl_object_copy (cur);
2337275223Sbapt		}
2338275223Sbapt		else {
2339275223Sbapt			cp = ucl_object_ref (cur);
2340275223Sbapt		}
2341275223Sbapt		found = __DECONST(ucl_object_t *, ucl_hash_search (top->value.ov, cp->key, cp->keylen));
2342275223Sbapt		if (found == NULL) {
2343275223Sbapt			/* The key does not exist */
2344279549Sbapt			top->value.ov = ucl_hash_insert_object (top->value.ov, cp, false);
2345275223Sbapt			top->len ++;
2346275223Sbapt		}
2347275223Sbapt		else {
2348275223Sbapt			/* The key already exists, replace it */
2349275223Sbapt			ucl_hash_replace (top->value.ov, found, cp);
2350275223Sbapt			ucl_object_unref (found);
2351275223Sbapt		}
2352275223Sbapt	}
2353275223Sbapt
2354275223Sbapt	return true;
2355275223Sbapt}
2356275223Sbapt
2357264789Sbaptconst ucl_object_t *
2358298166Sbaptucl_object_lookup_len (const ucl_object_t *obj, const char *key, size_t klen)
2359262395Sbapt{
2360264789Sbapt	const ucl_object_t *ret;
2361264789Sbapt	ucl_object_t srch;
2362262395Sbapt
2363262395Sbapt	if (obj == NULL || obj->type != UCL_OBJECT || key == NULL) {
2364262395Sbapt		return NULL;
2365262395Sbapt	}
2366262395Sbapt
2367262395Sbapt	srch.key = key;
2368262395Sbapt	srch.keylen = klen;
2369262395Sbapt	ret = ucl_hash_search_obj (obj->value.ov, &srch);
2370262395Sbapt
2371262395Sbapt	return ret;
2372262395Sbapt}
2373262395Sbapt
2374264789Sbaptconst ucl_object_t *
2375298166Sbaptucl_object_lookup (const ucl_object_t *obj, const char *key)
2376262395Sbapt{
2377290071Sbapt	if (key == NULL) {
2378262395Sbapt		return NULL;
2379290071Sbapt	}
2380262395Sbapt
2381298166Sbapt	return ucl_object_lookup_len (obj, key, strlen (key));
2382262395Sbapt}
2383262395Sbapt
2384264789Sbaptconst ucl_object_t*
2385298166Sbaptucl_object_lookup_any (const ucl_object_t *obj,
2386290071Sbapt		const char *key, ...)
2387290071Sbapt{
2388290071Sbapt	va_list ap;
2389290071Sbapt	const ucl_object_t *ret = NULL;
2390290071Sbapt	const char *nk = NULL;
2391290071Sbapt
2392290071Sbapt	if (obj == NULL || key == NULL) {
2393290071Sbapt		return NULL;
2394290071Sbapt	}
2395290071Sbapt
2396298166Sbapt	ret = ucl_object_lookup_len (obj, key, strlen (key));
2397290071Sbapt
2398290071Sbapt	if (ret == NULL) {
2399290071Sbapt		va_start (ap, key);
2400290071Sbapt
2401290071Sbapt		while (ret == NULL) {
2402290071Sbapt			nk = va_arg (ap, const char *);
2403290071Sbapt
2404290071Sbapt			if (nk == NULL) {
2405290071Sbapt				break;
2406290071Sbapt			}
2407290071Sbapt			else {
2408298166Sbapt				ret = ucl_object_lookup_len (obj, nk, strlen (nk));
2409290071Sbapt			}
2410290071Sbapt		}
2411290071Sbapt
2412290071Sbapt		va_end (ap);
2413290071Sbapt	}
2414290071Sbapt
2415290071Sbapt	return ret;
2416290071Sbapt}
2417290071Sbapt
2418290071Sbaptconst ucl_object_t*
2419298166Sbaptucl_object_iterate (const ucl_object_t *obj, ucl_object_iter_t *iter, bool expand_values)
2420262395Sbapt{
2421279549Sbapt	const ucl_object_t *elt = NULL;
2422262395Sbapt
2423263648Sbapt	if (obj == NULL || iter == NULL) {
2424263648Sbapt		return NULL;
2425263648Sbapt	}
2426263648Sbapt
2427262395Sbapt	if (expand_values) {
2428262395Sbapt		switch (obj->type) {
2429262395Sbapt		case UCL_OBJECT:
2430264789Sbapt			return (const ucl_object_t*)ucl_hash_iterate (obj->value.ov, iter);
2431262395Sbapt			break;
2432279549Sbapt		case UCL_ARRAY: {
2433279549Sbapt			unsigned int idx;
2434279549Sbapt			UCL_ARRAY_GET (vec, obj);
2435279549Sbapt			idx = (unsigned int)(uintptr_t)(*iter);
2436279549Sbapt
2437279549Sbapt			if (vec != NULL) {
2438279549Sbapt				while (idx < kv_size (*vec)) {
2439279549Sbapt					if ((elt = kv_A (*vec, idx)) != NULL) {
2440279549Sbapt						idx ++;
2441279549Sbapt						break;
2442279549Sbapt					}
2443279549Sbapt					idx ++;
2444262395Sbapt				}
2445279549Sbapt				*iter = (void *)(uintptr_t)idx;
2446262395Sbapt			}
2447279549Sbapt
2448262395Sbapt			return elt;
2449279549Sbapt			break;
2450279549Sbapt		}
2451262395Sbapt		default:
2452262395Sbapt			/* Go to linear iteration */
2453262395Sbapt			break;
2454262395Sbapt		}
2455262395Sbapt	}
2456262395Sbapt	/* Treat everything as a linear list */
2457262395Sbapt	elt = *iter;
2458262395Sbapt	if (elt == NULL) {
2459262395Sbapt		elt = obj;
2460262395Sbapt	}
2461262395Sbapt	else if (elt == obj) {
2462262395Sbapt		return NULL;
2463262395Sbapt	}
2464264789Sbapt	*iter = __DECONST (void *, elt->next ? elt->next : obj);
2465262395Sbapt	return elt;
2466262395Sbapt
2467262395Sbapt	/* Not reached */
2468262395Sbapt	return NULL;
2469262395Sbapt}
2470263648Sbapt
2471279549Sbaptconst char safe_iter_magic[4] = {'u', 'i', 't', 'e'};
2472279549Sbaptstruct ucl_object_safe_iter {
2473279549Sbapt	char magic[4]; /* safety check */
2474279549Sbapt	const ucl_object_t *impl_it; /* implicit object iteration */
2475279549Sbapt	ucl_object_iter_t expl_it; /* explicit iteration */
2476279549Sbapt};
2477279549Sbapt
2478279549Sbapt#define UCL_SAFE_ITER(ptr) (struct ucl_object_safe_iter *)(ptr)
2479279549Sbapt#define UCL_SAFE_ITER_CHECK(it) do { \
2480279549Sbapt	assert (it != NULL); \
2481279549Sbapt	assert (memcmp (it->magic, safe_iter_magic, sizeof (it->magic)) == 0); \
2482279549Sbapt } while (0)
2483279549Sbapt
2484279549Sbaptucl_object_iter_t
2485279549Sbaptucl_object_iterate_new (const ucl_object_t *obj)
2486279549Sbapt{
2487279549Sbapt	struct ucl_object_safe_iter *it;
2488279549Sbapt
2489279549Sbapt	it = UCL_ALLOC (sizeof (*it));
2490279549Sbapt	if (it != NULL) {
2491279549Sbapt		memcpy (it->magic, safe_iter_magic, sizeof (it->magic));
2492279549Sbapt		it->expl_it = NULL;
2493279549Sbapt		it->impl_it = obj;
2494279549Sbapt	}
2495279549Sbapt
2496279549Sbapt	return (ucl_object_iter_t)it;
2497279549Sbapt}
2498279549Sbapt
2499279549Sbapt
2500279549Sbaptucl_object_iter_t
2501279549Sbaptucl_object_iterate_reset (ucl_object_iter_t it, const ucl_object_t *obj)
2502279549Sbapt{
2503279549Sbapt	struct ucl_object_safe_iter *rit = UCL_SAFE_ITER (it);
2504279549Sbapt
2505279549Sbapt	UCL_SAFE_ITER_CHECK (rit);
2506279549Sbapt
2507314278Sbapt	if (rit->expl_it != NULL) {
2508314278Sbapt		UCL_FREE (sizeof (*rit->expl_it), rit->expl_it);
2509314278Sbapt	}
2510314278Sbapt
2511279549Sbapt	rit->impl_it = obj;
2512279549Sbapt	rit->expl_it = NULL;
2513279549Sbapt
2514279549Sbapt	return it;
2515279549Sbapt}
2516279549Sbapt
2517279549Sbaptconst ucl_object_t*
2518279549Sbaptucl_object_iterate_safe (ucl_object_iter_t it, bool expand_values)
2519279549Sbapt{
2520314278Sbapt	return ucl_object_iterate_full (it, expand_values ? UCL_ITERATE_BOTH :
2521314278Sbapt			UCL_ITERATE_IMPLICIT);
2522314278Sbapt}
2523314278Sbapt
2524314278Sbaptconst ucl_object_t*
2525314278Sbaptucl_object_iterate_full (ucl_object_iter_t it, enum ucl_iterate_type type)
2526314278Sbapt{
2527279549Sbapt	struct ucl_object_safe_iter *rit = UCL_SAFE_ITER (it);
2528279549Sbapt	const ucl_object_t *ret = NULL;
2529279549Sbapt
2530279549Sbapt	UCL_SAFE_ITER_CHECK (rit);
2531279549Sbapt
2532279549Sbapt	if (rit->impl_it == NULL) {
2533279549Sbapt		return NULL;
2534279549Sbapt	}
2535279549Sbapt
2536279549Sbapt	if (rit->impl_it->type == UCL_OBJECT || rit->impl_it->type == UCL_ARRAY) {
2537298166Sbapt		ret = ucl_object_iterate (rit->impl_it, &rit->expl_it, true);
2538279549Sbapt
2539314278Sbapt		if (ret == NULL && (type & UCL_ITERATE_IMPLICIT)) {
2540279549Sbapt			/* Need to switch to another implicit object in chain */
2541279549Sbapt			rit->impl_it = rit->impl_it->next;
2542279549Sbapt			rit->expl_it = NULL;
2543314278Sbapt
2544314278Sbapt			return ucl_object_iterate_safe (it, type);
2545279549Sbapt		}
2546279549Sbapt	}
2547279549Sbapt	else {
2548279549Sbapt		/* Just iterate over the implicit array */
2549279549Sbapt		ret = rit->impl_it;
2550279549Sbapt		rit->impl_it = rit->impl_it->next;
2551314278Sbapt
2552314278Sbapt		if (type & UCL_ITERATE_EXPLICIT) {
2553279549Sbapt			/* We flatten objects if need to expand values */
2554279549Sbapt			if (ret->type == UCL_OBJECT || ret->type == UCL_ARRAY) {
2555314278Sbapt				return ucl_object_iterate_safe (it, type);
2556279549Sbapt			}
2557279549Sbapt		}
2558279549Sbapt	}
2559279549Sbapt
2560279549Sbapt	return ret;
2561279549Sbapt}
2562279549Sbapt
2563279549Sbaptvoid
2564279549Sbaptucl_object_iterate_free (ucl_object_iter_t it)
2565279549Sbapt{
2566279549Sbapt	struct ucl_object_safe_iter *rit = UCL_SAFE_ITER (it);
2567279549Sbapt
2568279549Sbapt	UCL_SAFE_ITER_CHECK (rit);
2569279549Sbapt
2570314278Sbapt	if (rit->expl_it != NULL) {
2571314278Sbapt		UCL_FREE (sizeof (*rit->expl_it), rit->expl_it);
2572314278Sbapt	}
2573314278Sbapt
2574279549Sbapt	UCL_FREE (sizeof (*rit), it);
2575279549Sbapt}
2576279549Sbapt
2577266636Sbaptconst ucl_object_t *
2578298166Sbaptucl_object_lookup_path (const ucl_object_t *top, const char *path_in) {
2579298166Sbapt	return ucl_object_lookup_path_char (top, path_in, '.');
2580290071Sbapt}
2581290071Sbapt
2582290071Sbapt
2583290071Sbaptconst ucl_object_t *
2584298166Sbaptucl_object_lookup_path_char (const ucl_object_t *top, const char *path_in, const char sep) {
2585266636Sbapt	const ucl_object_t *o = NULL, *found;
2586266636Sbapt	const char *p, *c;
2587266636Sbapt	char *err_str;
2588266636Sbapt	unsigned index;
2589263648Sbapt
2590266636Sbapt	if (path_in == NULL || top == NULL) {
2591266636Sbapt		return NULL;
2592266636Sbapt	}
2593266636Sbapt
2594266636Sbapt	found = NULL;
2595266636Sbapt	p = path_in;
2596266636Sbapt
2597266636Sbapt	/* Skip leading dots */
2598290071Sbapt	while (*p == sep) {
2599266636Sbapt		p ++;
2600266636Sbapt	}
2601266636Sbapt
2602266636Sbapt	c = p;
2603266636Sbapt	while (*p != '\0') {
2604266636Sbapt		p ++;
2605290071Sbapt		if (*p == sep || *p == '\0') {
2606266636Sbapt			if (p > c) {
2607266636Sbapt				switch (top->type) {
2608266636Sbapt				case UCL_ARRAY:
2609266636Sbapt					/* Key should be an int */
2610266636Sbapt					index = strtoul (c, &err_str, 10);
2611290071Sbapt					if (err_str != NULL && (*err_str != sep && *err_str != '\0')) {
2612266636Sbapt						return NULL;
2613266636Sbapt					}
2614266636Sbapt					o = ucl_array_find_index (top, index);
2615266636Sbapt					break;
2616266636Sbapt				default:
2617298166Sbapt					o = ucl_object_lookup_len (top, c, p - c);
2618266636Sbapt					break;
2619266636Sbapt				}
2620266636Sbapt				if (o == NULL) {
2621266636Sbapt					return NULL;
2622266636Sbapt				}
2623266636Sbapt				top = o;
2624266636Sbapt			}
2625266636Sbapt			if (*p != '\0') {
2626266636Sbapt				c = p + 1;
2627266636Sbapt			}
2628266636Sbapt		}
2629266636Sbapt	}
2630266636Sbapt	found = o;
2631266636Sbapt
2632266636Sbapt	return found;
2633266636Sbapt}
2634266636Sbapt
2635266636Sbapt
2636263648Sbaptucl_object_t *
2637263648Sbaptucl_object_new (void)
2638263648Sbapt{
2639275223Sbapt	return ucl_object_typed_new (UCL_NULL);
2640263648Sbapt}
2641263648Sbapt
2642263648Sbaptucl_object_t *
2643266636Sbaptucl_object_typed_new (ucl_type_t type)
2644263648Sbapt{
2645275223Sbapt	return ucl_object_new_full (type, 0);
2646275223Sbapt}
2647275223Sbapt
2648275223Sbaptucl_object_t *
2649275223Sbaptucl_object_new_full (ucl_type_t type, unsigned priority)
2650275223Sbapt{
2651263648Sbapt	ucl_object_t *new;
2652275223Sbapt
2653275223Sbapt	if (type != UCL_USERDATA) {
2654275223Sbapt		new = UCL_ALLOC (sizeof (ucl_object_t));
2655275223Sbapt		if (new != NULL) {
2656275223Sbapt			memset (new, 0, sizeof (ucl_object_t));
2657275223Sbapt			new->ref = 1;
2658275223Sbapt			new->type = (type <= UCL_NULL ? type : UCL_NULL);
2659275223Sbapt			new->next = NULL;
2660275223Sbapt			new->prev = new;
2661275223Sbapt			ucl_object_set_priority (new, priority);
2662279549Sbapt
2663279549Sbapt			if (type == UCL_ARRAY) {
2664279549Sbapt				new->value.av = UCL_ALLOC (sizeof (ucl_array_t));
2665279549Sbapt				if (new->value.av) {
2666279549Sbapt					memset (new->value.av, 0, sizeof (ucl_array_t));
2667279549Sbapt					UCL_ARRAY_GET (vec, new);
2668279549Sbapt
2669279549Sbapt					/* Preallocate some space for arrays */
2670279549Sbapt					kv_resize (ucl_object_t *, *vec, 8);
2671279549Sbapt				}
2672279549Sbapt			}
2673275223Sbapt		}
2674263648Sbapt	}
2675275223Sbapt	else {
2676298166Sbapt		new = ucl_object_new_userdata (NULL, NULL, NULL);
2677275223Sbapt		ucl_object_set_priority (new, priority);
2678275223Sbapt	}
2679275223Sbapt
2680263648Sbapt	return new;
2681263648Sbapt}
2682263648Sbapt
2683275223Sbaptucl_object_t*
2684298166Sbaptucl_object_new_userdata (ucl_userdata_dtor dtor,
2685298166Sbapt		ucl_userdata_emitter emitter,
2686298166Sbapt		void *ptr)
2687275223Sbapt{
2688275223Sbapt	struct ucl_object_userdata *new;
2689275223Sbapt	size_t nsize = sizeof (*new);
2690275223Sbapt
2691275223Sbapt	new = UCL_ALLOC (nsize);
2692275223Sbapt	if (new != NULL) {
2693275223Sbapt		memset (new, 0, nsize);
2694275223Sbapt		new->obj.ref = 1;
2695275223Sbapt		new->obj.type = UCL_USERDATA;
2696275223Sbapt		new->obj.next = NULL;
2697275223Sbapt		new->obj.prev = (ucl_object_t *)new;
2698275223Sbapt		new->dtor = dtor;
2699275223Sbapt		new->emitter = emitter;
2700298166Sbapt		new->obj.value.ud = ptr;
2701275223Sbapt	}
2702275223Sbapt
2703275223Sbapt	return (ucl_object_t *)new;
2704275223Sbapt}
2705275223Sbapt
2706266636Sbaptucl_type_t
2707266636Sbaptucl_object_type (const ucl_object_t *obj)
2708266636Sbapt{
2709290071Sbapt	if (obj == NULL) {
2710290071Sbapt		return UCL_NULL;
2711290071Sbapt	}
2712290071Sbapt
2713266636Sbapt	return obj->type;
2714266636Sbapt}
2715266636Sbapt
2716263648Sbaptucl_object_t*
2717263648Sbaptucl_object_fromstring (const char *str)
2718263648Sbapt{
2719263648Sbapt	return ucl_object_fromstring_common (str, 0, UCL_STRING_ESCAPE);
2720263648Sbapt}
2721263648Sbapt
2722263648Sbaptucl_object_t *
2723263648Sbaptucl_object_fromlstring (const char *str, size_t len)
2724263648Sbapt{
2725263648Sbapt	return ucl_object_fromstring_common (str, len, UCL_STRING_ESCAPE);
2726263648Sbapt}
2727263648Sbapt
2728263648Sbaptucl_object_t *
2729263648Sbaptucl_object_fromint (int64_t iv)
2730263648Sbapt{
2731263648Sbapt	ucl_object_t *obj;
2732263648Sbapt
2733263648Sbapt	obj = ucl_object_new ();
2734263648Sbapt	if (obj != NULL) {
2735263648Sbapt		obj->type = UCL_INT;
2736263648Sbapt		obj->value.iv = iv;
2737263648Sbapt	}
2738263648Sbapt
2739263648Sbapt	return obj;
2740263648Sbapt}
2741263648Sbapt
2742263648Sbaptucl_object_t *
2743263648Sbaptucl_object_fromdouble (double dv)
2744263648Sbapt{
2745263648Sbapt	ucl_object_t *obj;
2746263648Sbapt
2747263648Sbapt	obj = ucl_object_new ();
2748263648Sbapt	if (obj != NULL) {
2749263648Sbapt		obj->type = UCL_FLOAT;
2750263648Sbapt		obj->value.dv = dv;
2751263648Sbapt	}
2752263648Sbapt
2753263648Sbapt	return obj;
2754263648Sbapt}
2755263648Sbapt
2756263648Sbaptucl_object_t*
2757263648Sbaptucl_object_frombool (bool bv)
2758263648Sbapt{
2759263648Sbapt	ucl_object_t *obj;
2760263648Sbapt
2761263648Sbapt	obj = ucl_object_new ();
2762263648Sbapt	if (obj != NULL) {
2763263648Sbapt		obj->type = UCL_BOOLEAN;
2764263648Sbapt		obj->value.iv = bv;
2765263648Sbapt	}
2766263648Sbapt
2767263648Sbapt	return obj;
2768263648Sbapt}
2769263648Sbapt
2770264789Sbaptbool
2771263648Sbaptucl_array_append (ucl_object_t *top, ucl_object_t *elt)
2772263648Sbapt{
2773279549Sbapt	UCL_ARRAY_GET (vec, top);
2774263648Sbapt
2775264789Sbapt	if (elt == NULL || top == NULL) {
2776264789Sbapt		return false;
2777263648Sbapt	}
2778263648Sbapt
2779279549Sbapt	if (vec == NULL) {
2780279549Sbapt		vec = UCL_ALLOC (sizeof (*vec));
2781290071Sbapt
2782290071Sbapt		if (vec == NULL) {
2783290071Sbapt			return false;
2784290071Sbapt		}
2785290071Sbapt
2786279549Sbapt		kv_init (*vec);
2787279549Sbapt		top->value.av = (void *)vec;
2788263648Sbapt	}
2789279549Sbapt
2790279549Sbapt	kv_push (ucl_object_t *, *vec, elt);
2791279549Sbapt
2792264789Sbapt	top->len ++;
2793263648Sbapt
2794264789Sbapt	return true;
2795263648Sbapt}
2796263648Sbapt
2797264789Sbaptbool
2798263648Sbaptucl_array_prepend (ucl_object_t *top, ucl_object_t *elt)
2799263648Sbapt{
2800279549Sbapt	UCL_ARRAY_GET (vec, top);
2801263648Sbapt
2802264789Sbapt	if (elt == NULL || top == NULL) {
2803264789Sbapt		return false;
2804263648Sbapt	}
2805263648Sbapt
2806279549Sbapt	if (vec == NULL) {
2807279549Sbapt		vec = UCL_ALLOC (sizeof (*vec));
2808279549Sbapt		kv_init (*vec);
2809279549Sbapt		top->value.av = (void *)vec;
2810279549Sbapt		kv_push (ucl_object_t *, *vec, elt);
2811263648Sbapt	}
2812263648Sbapt	else {
2813279549Sbapt		/* Slow O(n) algorithm */
2814279549Sbapt		kv_prepend (ucl_object_t *, *vec, elt);
2815263648Sbapt	}
2816279549Sbapt
2817264789Sbapt	top->len ++;
2818263648Sbapt
2819264789Sbapt	return true;
2820263648Sbapt}
2821263648Sbapt
2822275223Sbaptbool
2823275223Sbaptucl_array_merge (ucl_object_t *top, ucl_object_t *elt, bool copy)
2824275223Sbapt{
2825279549Sbapt	unsigned i;
2826290071Sbapt	ucl_object_t *cp = NULL;
2827279549Sbapt	ucl_object_t **obj;
2828275223Sbapt
2829275223Sbapt	if (elt == NULL || top == NULL || top->type != UCL_ARRAY || elt->type != UCL_ARRAY) {
2830275223Sbapt		return false;
2831275223Sbapt	}
2832275223Sbapt
2833290071Sbapt	if (copy) {
2834290071Sbapt		cp = ucl_object_copy (elt);
2835290071Sbapt	}
2836290071Sbapt	else {
2837290071Sbapt		cp = ucl_object_ref (elt);
2838290071Sbapt	}
2839290071Sbapt
2840290071Sbapt	UCL_ARRAY_GET (v1, top);
2841290071Sbapt	UCL_ARRAY_GET (v2, cp);
2842290071Sbapt
2843298166Sbapt	if (v1 && v2) {
2844298166Sbapt		kv_concat (ucl_object_t *, *v1, *v2);
2845279549Sbapt
2846298166Sbapt		for (i = v2->n; i < v1->n; i ++) {
2847298166Sbapt			obj = &kv_A (*v1, i);
2848298166Sbapt			if (*obj == NULL) {
2849298166Sbapt				continue;
2850298166Sbapt			}
2851298166Sbapt			top->len ++;
2852279549Sbapt		}
2853275223Sbapt	}
2854275223Sbapt
2855275223Sbapt	return true;
2856275223Sbapt}
2857275223Sbapt
2858263648Sbaptucl_object_t *
2859263648Sbaptucl_array_delete (ucl_object_t *top, ucl_object_t *elt)
2860263648Sbapt{
2861279549Sbapt	UCL_ARRAY_GET (vec, top);
2862279549Sbapt	ucl_object_t *ret = NULL;
2863279549Sbapt	unsigned i;
2864263648Sbapt
2865290071Sbapt	if (vec == NULL) {
2866290071Sbapt		return NULL;
2867290071Sbapt	}
2868290071Sbapt
2869279549Sbapt	for (i = 0; i < vec->n; i ++) {
2870279549Sbapt		if (kv_A (*vec, i) == elt) {
2871279549Sbapt			kv_del (ucl_object_t *, *vec, i);
2872279549Sbapt			ret = elt;
2873279549Sbapt			top->len --;
2874279549Sbapt			break;
2875263648Sbapt		}
2876263648Sbapt	}
2877263648Sbapt
2878279549Sbapt	return ret;
2879263648Sbapt}
2880263648Sbapt
2881264789Sbaptconst ucl_object_t *
2882264789Sbaptucl_array_head (const ucl_object_t *top)
2883263648Sbapt{
2884279549Sbapt	UCL_ARRAY_GET (vec, top);
2885279549Sbapt
2886290071Sbapt	if (vec == NULL || top == NULL || top->type != UCL_ARRAY ||
2887290071Sbapt			top->value.av == NULL) {
2888263648Sbapt		return NULL;
2889263648Sbapt	}
2890279549Sbapt
2891279549Sbapt	return (vec->n > 0 ? vec->a[0] : NULL);
2892263648Sbapt}
2893263648Sbapt
2894264789Sbaptconst ucl_object_t *
2895264789Sbaptucl_array_tail (const ucl_object_t *top)
2896263648Sbapt{
2897279549Sbapt	UCL_ARRAY_GET (vec, top);
2898279549Sbapt
2899263648Sbapt	if (top == NULL || top->type != UCL_ARRAY || top->value.av == NULL) {
2900263648Sbapt		return NULL;
2901263648Sbapt	}
2902279549Sbapt
2903279549Sbapt	return (vec->n > 0 ? vec->a[vec->n - 1] : NULL);
2904263648Sbapt}
2905263648Sbapt
2906263648Sbaptucl_object_t *
2907263648Sbaptucl_array_pop_last (ucl_object_t *top)
2908263648Sbapt{
2909279549Sbapt	UCL_ARRAY_GET (vec, top);
2910279549Sbapt	ucl_object_t **obj, *ret = NULL;
2911279549Sbapt
2912279549Sbapt	if (vec != NULL && vec->n > 0) {
2913279549Sbapt		obj = &kv_A (*vec, vec->n - 1);
2914279549Sbapt		ret = *obj;
2915279549Sbapt		kv_del (ucl_object_t *, *vec, vec->n - 1);
2916279549Sbapt		top->len --;
2917279549Sbapt	}
2918279549Sbapt
2919279549Sbapt	return ret;
2920263648Sbapt}
2921263648Sbapt
2922263648Sbaptucl_object_t *
2923263648Sbaptucl_array_pop_first (ucl_object_t *top)
2924263648Sbapt{
2925279549Sbapt	UCL_ARRAY_GET (vec, top);
2926279549Sbapt	ucl_object_t **obj, *ret = NULL;
2927279549Sbapt
2928279549Sbapt	if (vec != NULL && vec->n > 0) {
2929279549Sbapt		obj = &kv_A (*vec, 0);
2930279549Sbapt		ret = *obj;
2931279549Sbapt		kv_del (ucl_object_t *, *vec, 0);
2932279549Sbapt		top->len --;
2933279549Sbapt	}
2934279549Sbapt
2935279549Sbapt	return ret;
2936263648Sbapt}
2937263648Sbapt
2938266636Sbaptconst ucl_object_t *
2939266636Sbaptucl_array_find_index (const ucl_object_t *top, unsigned int index)
2940266636Sbapt{
2941279549Sbapt	UCL_ARRAY_GET (vec, top);
2942266636Sbapt
2943279549Sbapt	if (vec != NULL && vec->n > 0 && index < vec->n) {
2944279549Sbapt		return kv_A (*vec, index);
2945266636Sbapt	}
2946266636Sbapt
2947266636Sbapt	return NULL;
2948266636Sbapt}
2949266636Sbapt
2950290071Sbaptunsigned int
2951290071Sbaptucl_array_index_of (ucl_object_t *top, ucl_object_t *elt)
2952290071Sbapt{
2953290071Sbapt	UCL_ARRAY_GET (vec, top);
2954290071Sbapt	unsigned i;
2955290071Sbapt
2956290071Sbapt	if (vec == NULL) {
2957290071Sbapt		return (unsigned int)(-1);
2958290071Sbapt	}
2959290071Sbapt
2960290071Sbapt	for (i = 0; i < vec->n; i ++) {
2961290071Sbapt		if (kv_A (*vec, i) == elt) {
2962290071Sbapt			return i;
2963290071Sbapt		}
2964290071Sbapt	}
2965290071Sbapt
2966290071Sbapt	return (unsigned int)(-1);
2967290071Sbapt}
2968290071Sbapt
2969263648Sbaptucl_object_t *
2970275223Sbaptucl_array_replace_index (ucl_object_t *top, ucl_object_t *elt,
2971275223Sbapt	unsigned int index)
2972275223Sbapt{
2973279549Sbapt	UCL_ARRAY_GET (vec, top);
2974279549Sbapt	ucl_object_t *ret = NULL;
2975275223Sbapt
2976279549Sbapt	if (vec != NULL && vec->n > 0 && index < vec->n) {
2977279549Sbapt		ret = kv_A (*vec, index);
2978279549Sbapt		kv_A (*vec, index) = elt;
2979275223Sbapt	}
2980275223Sbapt
2981279549Sbapt	return ret;
2982275223Sbapt}
2983275223Sbapt
2984275223Sbaptucl_object_t *
2985263648Sbaptucl_elt_append (ucl_object_t *head, ucl_object_t *elt)
2986263648Sbapt{
2987263648Sbapt
2988263648Sbapt	if (head == NULL) {
2989263648Sbapt		elt->next = NULL;
2990263648Sbapt		elt->prev = elt;
2991263648Sbapt		head = elt;
2992263648Sbapt	}
2993263648Sbapt	else {
2994263648Sbapt		elt->prev = head->prev;
2995263648Sbapt		head->prev->next = elt;
2996263648Sbapt		head->prev = elt;
2997263648Sbapt		elt->next = NULL;
2998263648Sbapt	}
2999263648Sbapt
3000263648Sbapt	return head;
3001263648Sbapt}
3002263648Sbapt
3003263648Sbaptbool
3004264789Sbaptucl_object_todouble_safe (const ucl_object_t *obj, double *target)
3005263648Sbapt{
3006263648Sbapt	if (obj == NULL || target == NULL) {
3007263648Sbapt		return false;
3008263648Sbapt	}
3009263648Sbapt	switch (obj->type) {
3010263648Sbapt	case UCL_INT:
3011263648Sbapt		*target = obj->value.iv; /* Probaly could cause overflow */
3012263648Sbapt		break;
3013263648Sbapt	case UCL_FLOAT:
3014263648Sbapt	case UCL_TIME:
3015263648Sbapt		*target = obj->value.dv;
3016263648Sbapt		break;
3017263648Sbapt	default:
3018263648Sbapt		return false;
3019263648Sbapt	}
3020263648Sbapt
3021263648Sbapt	return true;
3022263648Sbapt}
3023263648Sbapt
3024263648Sbaptdouble
3025264789Sbaptucl_object_todouble (const ucl_object_t *obj)
3026263648Sbapt{
3027263648Sbapt	double result = 0.;
3028263648Sbapt
3029263648Sbapt	ucl_object_todouble_safe (obj, &result);
3030263648Sbapt	return result;
3031263648Sbapt}
3032263648Sbapt
3033263648Sbaptbool
3034264789Sbaptucl_object_toint_safe (const ucl_object_t *obj, int64_t *target)
3035263648Sbapt{
3036263648Sbapt	if (obj == NULL || target == NULL) {
3037263648Sbapt		return false;
3038263648Sbapt	}
3039263648Sbapt	switch (obj->type) {
3040263648Sbapt	case UCL_INT:
3041263648Sbapt		*target = obj->value.iv;
3042263648Sbapt		break;
3043263648Sbapt	case UCL_FLOAT:
3044263648Sbapt	case UCL_TIME:
3045263648Sbapt		*target = obj->value.dv; /* Loosing of decimal points */
3046263648Sbapt		break;
3047263648Sbapt	default:
3048263648Sbapt		return false;
3049263648Sbapt	}
3050263648Sbapt
3051263648Sbapt	return true;
3052263648Sbapt}
3053263648Sbapt
3054263648Sbaptint64_t
3055264789Sbaptucl_object_toint (const ucl_object_t *obj)
3056263648Sbapt{
3057263648Sbapt	int64_t result = 0;
3058263648Sbapt
3059263648Sbapt	ucl_object_toint_safe (obj, &result);
3060263648Sbapt	return result;
3061263648Sbapt}
3062263648Sbapt
3063263648Sbaptbool
3064264789Sbaptucl_object_toboolean_safe (const ucl_object_t *obj, bool *target)
3065263648Sbapt{
3066263648Sbapt	if (obj == NULL || target == NULL) {
3067263648Sbapt		return false;
3068263648Sbapt	}
3069263648Sbapt	switch (obj->type) {
3070263648Sbapt	case UCL_BOOLEAN:
3071263648Sbapt		*target = (obj->value.iv == true);
3072263648Sbapt		break;
3073263648Sbapt	default:
3074263648Sbapt		return false;
3075263648Sbapt	}
3076263648Sbapt
3077263648Sbapt	return true;
3078263648Sbapt}
3079263648Sbapt
3080263648Sbaptbool
3081264789Sbaptucl_object_toboolean (const ucl_object_t *obj)
3082263648Sbapt{
3083263648Sbapt	bool result = false;
3084263648Sbapt
3085263648Sbapt	ucl_object_toboolean_safe (obj, &result);
3086263648Sbapt	return result;
3087263648Sbapt}
3088263648Sbapt
3089263648Sbaptbool
3090264789Sbaptucl_object_tostring_safe (const ucl_object_t *obj, const char **target)
3091263648Sbapt{
3092263648Sbapt	if (obj == NULL || target == NULL) {
3093263648Sbapt		return false;
3094263648Sbapt	}
3095263648Sbapt
3096263648Sbapt	switch (obj->type) {
3097263648Sbapt	case UCL_STRING:
3098290071Sbapt		if (!(obj->flags & UCL_OBJECT_BINARY)) {
3099290071Sbapt			*target = ucl_copy_value_trash (obj);
3100290071Sbapt		}
3101263648Sbapt		break;
3102263648Sbapt	default:
3103263648Sbapt		return false;
3104263648Sbapt	}
3105263648Sbapt
3106263648Sbapt	return true;
3107263648Sbapt}
3108263648Sbapt
3109263648Sbaptconst char *
3110264789Sbaptucl_object_tostring (const ucl_object_t *obj)
3111263648Sbapt{
3112263648Sbapt	const char *result = NULL;
3113263648Sbapt
3114263648Sbapt	ucl_object_tostring_safe (obj, &result);
3115263648Sbapt	return result;
3116263648Sbapt}
3117263648Sbapt
3118263648Sbaptconst char *
3119264789Sbaptucl_object_tostring_forced (const ucl_object_t *obj)
3120263648Sbapt{
3121290071Sbapt	/* TODO: For binary strings we might encode string here */
3122290071Sbapt	if (!(obj->flags & UCL_OBJECT_BINARY)) {
3123290071Sbapt		return ucl_copy_value_trash (obj);
3124290071Sbapt	}
3125290071Sbapt
3126290071Sbapt	return NULL;
3127263648Sbapt}
3128263648Sbapt
3129263648Sbaptbool
3130264789Sbaptucl_object_tolstring_safe (const ucl_object_t *obj, const char **target, size_t *tlen)
3131263648Sbapt{
3132263648Sbapt	if (obj == NULL || target == NULL) {
3133263648Sbapt		return false;
3134263648Sbapt	}
3135263648Sbapt	switch (obj->type) {
3136263648Sbapt	case UCL_STRING:
3137263648Sbapt		*target = obj->value.sv;
3138263648Sbapt		if (tlen != NULL) {
3139263648Sbapt			*tlen = obj->len;
3140263648Sbapt		}
3141263648Sbapt		break;
3142263648Sbapt	default:
3143263648Sbapt		return false;
3144263648Sbapt	}
3145263648Sbapt
3146263648Sbapt	return true;
3147263648Sbapt}
3148263648Sbapt
3149263648Sbaptconst char *
3150264789Sbaptucl_object_tolstring (const ucl_object_t *obj, size_t *tlen)
3151263648Sbapt{
3152263648Sbapt	const char *result = NULL;
3153263648Sbapt
3154263648Sbapt	ucl_object_tolstring_safe (obj, &result, tlen);
3155263648Sbapt	return result;
3156263648Sbapt}
3157263648Sbapt
3158263648Sbaptconst char *
3159264789Sbaptucl_object_key (const ucl_object_t *obj)
3160263648Sbapt{
3161263648Sbapt	return ucl_copy_key_trash (obj);
3162263648Sbapt}
3163263648Sbapt
3164263648Sbaptconst char *
3165264789Sbaptucl_object_keyl (const ucl_object_t *obj, size_t *len)
3166263648Sbapt{
3167263648Sbapt	if (len == NULL || obj == NULL) {
3168263648Sbapt		return NULL;
3169263648Sbapt	}
3170263648Sbapt	*len = obj->keylen;
3171263648Sbapt	return obj->key;
3172263648Sbapt}
3173263648Sbapt
3174263648Sbaptucl_object_t *
3175264789Sbaptucl_object_ref (const ucl_object_t *obj)
3176263648Sbapt{
3177264789Sbapt	ucl_object_t *res = NULL;
3178264789Sbapt
3179263648Sbapt	if (obj != NULL) {
3180275223Sbapt		if (obj->flags & UCL_OBJECT_EPHEMERAL) {
3181275223Sbapt			/*
3182275223Sbapt			 * Use deep copy for ephemeral objects, note that its refcount
3183275223Sbapt			 * is NOT increased, since ephemeral objects does not need refcount
3184275223Sbapt			 * at all
3185275223Sbapt			 */
3186275223Sbapt			res = ucl_object_copy (obj);
3187275223Sbapt		}
3188275223Sbapt		else {
3189275223Sbapt			res = __DECONST (ucl_object_t *, obj);
3190264789Sbapt#ifdef HAVE_ATOMIC_BUILTINS
3191275223Sbapt			(void)__sync_add_and_fetch (&res->ref, 1);
3192264789Sbapt#else
3193275223Sbapt			res->ref ++;
3194264789Sbapt#endif
3195275223Sbapt		}
3196263648Sbapt	}
3197264789Sbapt	return res;
3198263648Sbapt}
3199263648Sbapt
3200275223Sbaptstatic ucl_object_t *
3201275223Sbaptucl_object_copy_internal (const ucl_object_t *other, bool allow_array)
3202275223Sbapt{
3203275223Sbapt
3204275223Sbapt	ucl_object_t *new;
3205275223Sbapt	ucl_object_iter_t it = NULL;
3206275223Sbapt	const ucl_object_t *cur;
3207275223Sbapt
3208275223Sbapt	new = malloc (sizeof (*new));
3209275223Sbapt
3210275223Sbapt	if (new != NULL) {
3211275223Sbapt		memcpy (new, other, sizeof (*new));
3212275223Sbapt		if (other->flags & UCL_OBJECT_EPHEMERAL) {
3213275223Sbapt			/* Copied object is always non ephemeral */
3214275223Sbapt			new->flags &= ~UCL_OBJECT_EPHEMERAL;
3215275223Sbapt		}
3216275223Sbapt		new->ref = 1;
3217275223Sbapt		/* Unlink from others */
3218275223Sbapt		new->next = NULL;
3219275223Sbapt		new->prev = new;
3220275223Sbapt
3221275223Sbapt		/* deep copy of values stored */
3222275223Sbapt		if (other->trash_stack[UCL_TRASH_KEY] != NULL) {
3223275223Sbapt			new->trash_stack[UCL_TRASH_KEY] =
3224275223Sbapt					strdup (other->trash_stack[UCL_TRASH_KEY]);
3225275223Sbapt			if (other->key == (const char *)other->trash_stack[UCL_TRASH_KEY]) {
3226275223Sbapt				new->key = new->trash_stack[UCL_TRASH_KEY];
3227275223Sbapt			}
3228275223Sbapt		}
3229275223Sbapt		if (other->trash_stack[UCL_TRASH_VALUE] != NULL) {
3230275223Sbapt			new->trash_stack[UCL_TRASH_VALUE] =
3231275223Sbapt					strdup (other->trash_stack[UCL_TRASH_VALUE]);
3232275223Sbapt			if (new->type == UCL_STRING) {
3233275223Sbapt				new->value.sv = new->trash_stack[UCL_TRASH_VALUE];
3234275223Sbapt			}
3235275223Sbapt		}
3236275223Sbapt
3237275223Sbapt		if (other->type == UCL_ARRAY || other->type == UCL_OBJECT) {
3238275223Sbapt			/* reset old value */
3239275223Sbapt			memset (&new->value, 0, sizeof (new->value));
3240275223Sbapt
3241298166Sbapt			while ((cur = ucl_object_iterate (other, &it, true)) != NULL) {
3242275223Sbapt				if (other->type == UCL_ARRAY) {
3243275223Sbapt					ucl_array_append (new, ucl_object_copy_internal (cur, false));
3244275223Sbapt				}
3245275223Sbapt				else {
3246275223Sbapt					ucl_object_t *cp = ucl_object_copy_internal (cur, true);
3247275223Sbapt					if (cp != NULL) {
3248275223Sbapt						ucl_object_insert_key (new, cp, cp->key, cp->keylen,
3249275223Sbapt								false);
3250275223Sbapt					}
3251275223Sbapt				}
3252275223Sbapt			}
3253275223Sbapt		}
3254275223Sbapt		else if (allow_array && other->next != NULL) {
3255275223Sbapt			LL_FOREACH (other->next, cur) {
3256275223Sbapt				ucl_object_t *cp = ucl_object_copy_internal (cur, false);
3257275223Sbapt				if (cp != NULL) {
3258275223Sbapt					DL_APPEND (new, cp);
3259275223Sbapt				}
3260275223Sbapt			}
3261275223Sbapt		}
3262275223Sbapt	}
3263275223Sbapt
3264275223Sbapt	return new;
3265275223Sbapt}
3266275223Sbapt
3267275223Sbaptucl_object_t *
3268275223Sbaptucl_object_copy (const ucl_object_t *other)
3269275223Sbapt{
3270275223Sbapt	return ucl_object_copy_internal (other, true);
3271275223Sbapt}
3272275223Sbapt
3273263648Sbaptvoid
3274263648Sbaptucl_object_unref (ucl_object_t *obj)
3275263648Sbapt{
3276264789Sbapt	if (obj != NULL) {
3277264789Sbapt#ifdef HAVE_ATOMIC_BUILTINS
3278264789Sbapt		unsigned int rc = __sync_sub_and_fetch (&obj->ref, 1);
3279264789Sbapt		if (rc == 0) {
3280264789Sbapt#else
3281264789Sbapt		if (--obj->ref == 0) {
3282264789Sbapt#endif
3283264789Sbapt			ucl_object_free_internal (obj, true, ucl_object_dtor_unref);
3284264789Sbapt		}
3285263648Sbapt	}
3286263648Sbapt}
3287263648Sbapt
3288263648Sbaptint
3289264789Sbaptucl_object_compare (const ucl_object_t *o1, const ucl_object_t *o2)
3290263648Sbapt{
3291264789Sbapt	const ucl_object_t *it1, *it2;
3292263648Sbapt	ucl_object_iter_t iter = NULL;
3293263648Sbapt	int ret = 0;
3294263648Sbapt
3295263648Sbapt	if (o1->type != o2->type) {
3296263648Sbapt		return (o1->type) - (o2->type);
3297263648Sbapt	}
3298263648Sbapt
3299263648Sbapt	switch (o1->type) {
3300263648Sbapt	case UCL_STRING:
3301279549Sbapt		if (o1->len == o2->len && o1->len > 0) {
3302263648Sbapt			ret = strcmp (ucl_object_tostring(o1), ucl_object_tostring(o2));
3303263648Sbapt		}
3304263648Sbapt		else {
3305263648Sbapt			ret = o1->len - o2->len;
3306263648Sbapt		}
3307263648Sbapt		break;
3308263648Sbapt	case UCL_FLOAT:
3309263648Sbapt	case UCL_INT:
3310263648Sbapt	case UCL_TIME:
3311263648Sbapt		ret = ucl_object_todouble (o1) - ucl_object_todouble (o2);
3312263648Sbapt		break;
3313263648Sbapt	case UCL_BOOLEAN:
3314263648Sbapt		ret = ucl_object_toboolean (o1) - ucl_object_toboolean (o2);
3315263648Sbapt		break;
3316263648Sbapt	case UCL_ARRAY:
3317279549Sbapt		if (o1->len == o2->len && o1->len > 0) {
3318279549Sbapt			UCL_ARRAY_GET (vec1, o1);
3319279549Sbapt			UCL_ARRAY_GET (vec2, o2);
3320279549Sbapt			unsigned i;
3321279549Sbapt
3322263648Sbapt			/* Compare all elements in both arrays */
3323279549Sbapt			for (i = 0; i < vec1->n; i ++) {
3324279549Sbapt				it1 = kv_A (*vec1, i);
3325279549Sbapt				it2 = kv_A (*vec2, i);
3326279549Sbapt
3327279549Sbapt				if (it1 == NULL && it2 != NULL) {
3328279549Sbapt					return -1;
3329263648Sbapt				}
3330279549Sbapt				else if (it2 == NULL && it1 != NULL) {
3331279549Sbapt					return 1;
3332279549Sbapt				}
3333279549Sbapt				else if (it1 != NULL && it2 != NULL) {
3334279549Sbapt					ret = ucl_object_compare (it1, it2);
3335279549Sbapt					if (ret != 0) {
3336279549Sbapt						break;
3337279549Sbapt					}
3338279549Sbapt				}
3339263648Sbapt			}
3340263648Sbapt		}
3341263648Sbapt		else {
3342263648Sbapt			ret = o1->len - o2->len;
3343263648Sbapt		}
3344263648Sbapt		break;
3345263648Sbapt	case UCL_OBJECT:
3346279549Sbapt		if (o1->len == o2->len && o1->len > 0) {
3347298166Sbapt			while ((it1 = ucl_object_iterate (o1, &iter, true)) != NULL) {
3348298166Sbapt				it2 = ucl_object_lookup (o2, ucl_object_key (it1));
3349263648Sbapt				if (it2 == NULL) {
3350263648Sbapt					ret = 1;
3351263648Sbapt					break;
3352263648Sbapt				}
3353263648Sbapt				ret = ucl_object_compare (it1, it2);
3354263648Sbapt				if (ret != 0) {
3355263648Sbapt					break;
3356263648Sbapt				}
3357263648Sbapt			}
3358263648Sbapt		}
3359263648Sbapt		else {
3360263648Sbapt			ret = o1->len - o2->len;
3361263648Sbapt		}
3362263648Sbapt		break;
3363263648Sbapt	default:
3364263648Sbapt		ret = 0;
3365263648Sbapt		break;
3366263648Sbapt	}
3367263648Sbapt
3368263648Sbapt	return ret;
3369263648Sbapt}
3370263648Sbapt
3371298166Sbaptint
3372298166Sbaptucl_object_compare_qsort (const ucl_object_t **o1,
3373298166Sbapt		const ucl_object_t **o2)
3374298166Sbapt{
3375298166Sbapt	return ucl_object_compare (*o1, *o2);
3376298166Sbapt}
3377298166Sbapt
3378263648Sbaptvoid
3379263648Sbaptucl_object_array_sort (ucl_object_t *ar,
3380290071Sbapt		int (*cmp)(const ucl_object_t **o1, const ucl_object_t **o2))
3381263648Sbapt{
3382279549Sbapt	UCL_ARRAY_GET (vec, ar);
3383279549Sbapt
3384263648Sbapt	if (cmp == NULL || ar == NULL || ar->type != UCL_ARRAY) {
3385263648Sbapt		return;
3386263648Sbapt	}
3387263648Sbapt
3388279549Sbapt	qsort (vec->a, vec->n, sizeof (ucl_object_t *),
3389279549Sbapt			(int (*)(const void *, const void *))cmp);
3390263648Sbapt}
3391275223Sbapt
3392275223Sbapt#define PRIOBITS 4
3393275223Sbapt
3394275223Sbaptunsigned int
3395275223Sbaptucl_object_get_priority (const ucl_object_t *obj)
3396275223Sbapt{
3397275223Sbapt	if (obj == NULL) {
3398275223Sbapt		return 0;
3399275223Sbapt	}
3400275223Sbapt
3401275223Sbapt	return (obj->flags >> ((sizeof (obj->flags) * NBBY) - PRIOBITS));
3402275223Sbapt}
3403275223Sbapt
3404275223Sbaptvoid
3405275223Sbaptucl_object_set_priority (ucl_object_t *obj,
3406275223Sbapt		unsigned int priority)
3407275223Sbapt{
3408275223Sbapt	if (obj != NULL) {
3409275223Sbapt		priority &= (0x1 << PRIOBITS) - 1;
3410290071Sbapt		priority <<= ((sizeof (obj->flags) * NBBY) - PRIOBITS);
3411290071Sbapt		priority |= obj->flags & ((1 << ((sizeof (obj->flags) * NBBY) -
3412290071Sbapt				PRIOBITS)) - 1);
3413290071Sbapt		obj->flags = priority;
3414275223Sbapt	}
3415275223Sbapt}
3416298166Sbapt
3417298166Sbaptbool
3418298166Sbaptucl_object_string_to_type (const char *input, ucl_type_t *res)
3419298166Sbapt{
3420298166Sbapt	if (strcasecmp (input, "object") == 0) {
3421298166Sbapt		*res = UCL_OBJECT;
3422298166Sbapt	}
3423298166Sbapt	else if (strcasecmp (input, "array") == 0) {
3424298166Sbapt		*res = UCL_ARRAY;
3425298166Sbapt	}
3426298166Sbapt	else if (strcasecmp (input, "integer") == 0) {
3427298166Sbapt		*res = UCL_INT;
3428298166Sbapt	}
3429298166Sbapt	else if (strcasecmp (input, "number") == 0) {
3430298166Sbapt		*res = UCL_FLOAT;
3431298166Sbapt	}
3432298166Sbapt	else if (strcasecmp (input, "string") == 0) {
3433298166Sbapt		*res = UCL_STRING;
3434298166Sbapt	}
3435298166Sbapt	else if (strcasecmp (input, "boolean") == 0) {
3436298166Sbapt		*res = UCL_BOOLEAN;
3437298166Sbapt	}
3438298166Sbapt	else if (strcasecmp (input, "null") == 0) {
3439298166Sbapt		*res = UCL_NULL;
3440298166Sbapt	}
3441298166Sbapt	else if (strcasecmp (input, "userdata") == 0) {
3442298166Sbapt		*res = UCL_USERDATA;
3443298166Sbapt	}
3444298166Sbapt	else {
3445298166Sbapt		return false;
3446298166Sbapt	}
3447298166Sbapt
3448298166Sbapt	return true;
3449298166Sbapt}
3450298166Sbapt
3451298166Sbaptconst char *
3452298166Sbaptucl_object_type_to_string (ucl_type_t type)
3453298166Sbapt{
3454298166Sbapt	const char *res = "unknown";
3455298166Sbapt
3456298166Sbapt	switch (type) {
3457298166Sbapt	case UCL_OBJECT:
3458298166Sbapt		res = "object";
3459298166Sbapt		break;
3460298166Sbapt	case UCL_ARRAY:
3461298166Sbapt		res = "array";
3462298166Sbapt		break;
3463298166Sbapt	case UCL_INT:
3464298166Sbapt		res = "integer";
3465298166Sbapt		break;
3466298166Sbapt	case UCL_FLOAT:
3467298166Sbapt	case UCL_TIME:
3468298166Sbapt		res = "number";
3469298166Sbapt		break;
3470298166Sbapt	case UCL_STRING:
3471298166Sbapt		res = "string";
3472298166Sbapt		break;
3473298166Sbapt	case UCL_BOOLEAN:
3474298166Sbapt		res = "boolean";
3475298166Sbapt		break;
3476298166Sbapt	case UCL_USERDATA:
3477298166Sbapt		res = "userdata";
3478298166Sbapt		break;
3479298166Sbapt	case UCL_NULL:
3480298166Sbapt		res = "null";
3481298166Sbapt		break;
3482298166Sbapt	}
3483298166Sbapt
3484298166Sbapt	return res;
3485298166Sbapt}
3486298166Sbapt
3487298166Sbaptconst ucl_object_t *
3488298166Sbaptucl_parser_get_comments (struct ucl_parser *parser)
3489298166Sbapt{
3490298166Sbapt	if (parser && parser->comments) {
3491298166Sbapt		return parser->comments;
3492298166Sbapt	}
3493298166Sbapt
3494298166Sbapt	return NULL;
3495298166Sbapt}
3496298166Sbapt
3497298166Sbaptconst ucl_object_t *
3498298166Sbaptucl_comments_find (const ucl_object_t *comments,
3499298166Sbapt		const ucl_object_t *srch)
3500298166Sbapt{
3501298166Sbapt	if (comments && srch) {
3502298166Sbapt		return ucl_object_lookup_len (comments, (const char *)&srch,
3503298166Sbapt				sizeof (void *));
3504298166Sbapt	}
3505298166Sbapt
3506298166Sbapt	return NULL;
3507298166Sbapt}
3508298166Sbapt
3509298166Sbaptbool
3510298166Sbaptucl_comments_move (ucl_object_t *comments,
3511298166Sbapt		const ucl_object_t *from, const ucl_object_t *to)
3512298166Sbapt{
3513298166Sbapt	const ucl_object_t *found;
3514298166Sbapt	ucl_object_t *obj;
3515298166Sbapt
3516298166Sbapt	if (comments && from && to) {
3517298166Sbapt		found = ucl_object_lookup_len (comments,
3518298166Sbapt				(const char *)&from, sizeof (void *));
3519298166Sbapt
3520298166Sbapt		if (found) {
3521298166Sbapt			/* Replace key */
3522298166Sbapt			obj = ucl_object_ref (found);
3523298166Sbapt			ucl_object_delete_keyl (comments, (const char *)&from,
3524298166Sbapt					sizeof (void *));
3525298166Sbapt			ucl_object_insert_key (comments, obj, (const char *)&to,
3526298166Sbapt					sizeof (void *), true);
3527298166Sbapt
3528298166Sbapt			return true;
3529298166Sbapt		}
3530298166Sbapt	}
3531298166Sbapt
3532298166Sbapt	return false;
3533298166Sbapt}
3534298166Sbapt
3535298166Sbaptvoid
3536298166Sbaptucl_comments_add (ucl_object_t *comments, const ucl_object_t *obj,
3537298166Sbapt		const char *comment)
3538298166Sbapt{
3539298166Sbapt	if (comments && obj && comment) {
3540298166Sbapt		ucl_object_insert_key (comments, ucl_object_fromstring (comment),
3541298166Sbapt				(const char *)&obj, sizeof (void *), true);
3542298166Sbapt	}
3543298166Sbapt}
3544