xref: /freebsd/contrib/libucl/src/ucl_util.c (revision fed1ca4b719c56c930f2259d80663cd34be812bb)
1 /* Copyright (c) 2013, Vsevolod Stakhov
2  * Copyright (c) 2015 Allan Jude <allanjude@freebsd.org>
3  * All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions are met:
7  *       * Redistributions of source code must retain the above copyright
8  *         notice, this list of conditions and the following disclaimer.
9  *       * Redistributions in binary form must reproduce the above copyright
10  *         notice, this list of conditions and the following disclaimer in the
11  *         documentation and/or other materials provided with the distribution.
12  *
13  * THIS SOFTWARE IS PROVIDED ''AS IS'' AND ANY
14  * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
15  * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
16  * DISCLAIMED. IN NO EVENT SHALL AUTHOR BE LIABLE FOR ANY
17  * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
18  * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
19  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
20  * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
21  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
22  * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
23  */
24 
25 #include "ucl.h"
26 #include "ucl_internal.h"
27 #include "ucl_chartable.h"
28 #include "kvec.h"
29 #include <stdarg.h>
30 #include <stdio.h> /* for snprintf */
31 
32 #ifndef _WIN32
33 #include <glob.h>
34 #endif
35 
36 #ifdef HAVE_LIBGEN_H
37 #include <libgen.h> /* For dirname */
38 #endif
39 
40 typedef kvec_t(ucl_object_t *) ucl_array_t;
41 
42 #define UCL_ARRAY_GET(ar, obj) ucl_array_t *ar = \
43 	(ucl_array_t *)((obj) != NULL ? (obj)->value.av : NULL)
44 
45 #ifdef HAVE_OPENSSL
46 #include <openssl/err.h>
47 #include <openssl/sha.h>
48 #include <openssl/rsa.h>
49 #include <openssl/ssl.h>
50 #include <openssl/evp.h>
51 #endif
52 
53 #ifdef CURL_FOUND
54 /* Seems to be broken */
55 #define CURL_DISABLE_TYPECHECK 1
56 #include <curl/curl.h>
57 #endif
58 #ifdef HAVE_FETCH_H
59 #include <fetch.h>
60 #endif
61 
62 #ifdef _WIN32
63 #include <windows.h>
64 
65 #ifndef PROT_READ
66 #define PROT_READ       1
67 #endif
68 #ifndef PROT_WRITE
69 #define PROT_WRITE      2
70 #endif
71 #ifndef PROT_READWRITE
72 #define PROT_READWRITE  3
73 #endif
74 #ifndef MAP_SHARED
75 #define MAP_SHARED      1
76 #endif
77 #ifndef MAP_PRIVATE
78 #define MAP_PRIVATE     2
79 #endif
80 #ifndef MAP_FAILED
81 #define MAP_FAILED      ((void *) -1)
82 #endif
83 
84 #ifdef _WIN32
85 #include <limits.h>
86 #define NBBY CHAR_BIT
87 #endif
88 
89 static void *ucl_mmap(char *addr, size_t length, int prot, int access, int fd, off_t offset)
90 {
91 	void *map = NULL;
92 	HANDLE handle = INVALID_HANDLE_VALUE;
93 
94 	switch (prot) {
95 	default:
96 	case PROT_READ:
97 		{
98 			handle = CreateFileMapping((HANDLE) _get_osfhandle(fd), 0, PAGE_READONLY, 0, length, 0);
99 			if (!handle) break;
100 			map = (void *) MapViewOfFile(handle, FILE_MAP_READ, 0, 0, length);
101 			CloseHandle(handle);
102 			break;
103 		}
104 	case PROT_WRITE:
105 		{
106 			handle = CreateFileMapping((HANDLE) _get_osfhandle(fd), 0, PAGE_READWRITE, 0, length, 0);
107 			if (!handle) break;
108 			map = (void *) MapViewOfFile(handle, FILE_MAP_WRITE, 0, 0, length);
109 			CloseHandle(handle);
110 			break;
111 		}
112 	case PROT_READWRITE:
113 		{
114 			handle = CreateFileMapping((HANDLE) _get_osfhandle(fd), 0, PAGE_READWRITE, 0, length, 0);
115 			if (!handle) break;
116 			map = (void *) MapViewOfFile(handle, FILE_MAP_ALL_ACCESS, 0, 0, length);
117 			CloseHandle(handle);
118 			break;
119 		}
120 	}
121 	if (map == (void *) NULL) {
122 		return (void *) MAP_FAILED;
123 	}
124 	return (void *) ((char *) map + offset);
125 }
126 
127 static int ucl_munmap(void *map,size_t length)
128 {
129 	if (!UnmapViewOfFile(map)) {
130 		return(-1);
131 	}
132 	return(0);
133 }
134 
135 static char* ucl_realpath(const char *path, char *resolved_path) {
136     char *p;
137     char tmp[MAX_PATH + 1];
138     strncpy(tmp, path, sizeof(tmp)-1);
139     p = tmp;
140     while(*p) {
141         if (*p == '/') *p = '\\';
142         p++;
143     }
144     return _fullpath(resolved_path, tmp, MAX_PATH);
145 }
146 #else
147 #define ucl_mmap mmap
148 #define ucl_munmap munmap
149 #define ucl_realpath realpath
150 #endif
151 
152 typedef void (*ucl_object_dtor) (ucl_object_t *obj);
153 static void ucl_object_free_internal (ucl_object_t *obj, bool allow_rec,
154 		ucl_object_dtor dtor);
155 static void ucl_object_dtor_unref (ucl_object_t *obj);
156 
157 static void
158 ucl_object_dtor_free (ucl_object_t *obj)
159 {
160 	if (obj->trash_stack[UCL_TRASH_KEY] != NULL) {
161 		UCL_FREE (obj->hh.keylen, obj->trash_stack[UCL_TRASH_KEY]);
162 	}
163 	if (obj->trash_stack[UCL_TRASH_VALUE] != NULL) {
164 		UCL_FREE (obj->len, obj->trash_stack[UCL_TRASH_VALUE]);
165 	}
166 	/* Do not free ephemeral objects */
167 	if ((obj->flags & UCL_OBJECT_EPHEMERAL) == 0) {
168 		if (obj->type != UCL_USERDATA) {
169 			UCL_FREE (sizeof (ucl_object_t), obj);
170 		}
171 		else {
172 			struct ucl_object_userdata *ud = (struct ucl_object_userdata *)obj;
173 			if (ud->dtor) {
174 				ud->dtor (obj->value.ud);
175 			}
176 			UCL_FREE (sizeof (*ud), obj);
177 		}
178 	}
179 }
180 
181 /*
182  * This is a helper function that performs exactly the same as
183  * `ucl_object_unref` but it doesn't iterate over elements allowing
184  * to use it for individual elements of arrays and multiple values
185  */
186 static void
187 ucl_object_dtor_unref_single (ucl_object_t *obj)
188 {
189 	if (obj != NULL) {
190 #ifdef HAVE_ATOMIC_BUILTINS
191 		unsigned int rc = __sync_sub_and_fetch (&obj->ref, 1);
192 		if (rc == 0) {
193 #else
194 		if (--obj->ref == 0) {
195 #endif
196 			ucl_object_free_internal (obj, false, ucl_object_dtor_unref);
197 		}
198 	}
199 }
200 
201 static void
202 ucl_object_dtor_unref (ucl_object_t *obj)
203 {
204 	if (obj->ref == 0) {
205 		ucl_object_dtor_free (obj);
206 	}
207 	else {
208 		/* This may cause dtor unref being called one more time */
209 		ucl_object_dtor_unref_single (obj);
210 	}
211 }
212 
213 static void
214 ucl_object_free_internal (ucl_object_t *obj, bool allow_rec, ucl_object_dtor dtor)
215 {
216 	ucl_object_t *tmp, *sub;
217 
218 	while (obj != NULL) {
219 		if (obj->type == UCL_ARRAY) {
220 			UCL_ARRAY_GET (vec, obj);
221 			unsigned int i;
222 
223 			if (vec != NULL) {
224 				for (i = 0; i < vec->n; i ++) {
225 					sub = kv_A (*vec, i);
226 					if (sub != NULL) {
227 						tmp = sub;
228 						while (sub) {
229 							tmp = sub->next;
230 							dtor (sub);
231 							sub = tmp;
232 						}
233 					}
234 				}
235 				kv_destroy (*vec);
236 				UCL_FREE (sizeof (*vec), vec);
237 			}
238 			obj->value.av = NULL;
239 		}
240 		else if (obj->type == UCL_OBJECT) {
241 			if (obj->value.ov != NULL) {
242 				ucl_hash_destroy (obj->value.ov, (ucl_hash_free_func)dtor);
243 			}
244 			obj->value.ov = NULL;
245 		}
246 		tmp = obj->next;
247 		dtor (obj);
248 		obj = tmp;
249 
250 		if (!allow_rec) {
251 			break;
252 		}
253 	}
254 }
255 
256 void
257 ucl_object_free (ucl_object_t *obj)
258 {
259 	ucl_object_free_internal (obj, true, ucl_object_dtor_free);
260 }
261 
262 size_t
263 ucl_unescape_json_string (char *str, size_t len)
264 {
265 	char *t = str, *h = str;
266 	int i, uval;
267 
268 	if (len <= 1) {
269 		return len;
270 	}
271 	/* t is target (tortoise), h is source (hare) */
272 
273 	while (len) {
274 		if (*h == '\\') {
275 			h ++;
276 
277 			if (len == 1) {
278 				/*
279 				 * If \ is last, then do not try to go further
280 				 * Issue: #74
281 				 */
282 				len --;
283 				*t++ = '\\';
284 				continue;
285 			}
286 
287 			switch (*h) {
288 			case 'n':
289 				*t++ = '\n';
290 				break;
291 			case 'r':
292 				*t++ = '\r';
293 				break;
294 			case 'b':
295 				*t++ = '\b';
296 				break;
297 			case 't':
298 				*t++ = '\t';
299 				break;
300 			case 'f':
301 				*t++ = '\f';
302 				break;
303 			case '\\':
304 				*t++ = '\\';
305 				break;
306 			case '"':
307 				*t++ = '"';
308 				break;
309 			case 'u':
310 				/* Unicode escape */
311 				uval = 0;
312 				h ++; /* u character */
313 				len --;
314 
315 				if (len > 3) {
316 					for (i = 0; i < 4; i++) {
317 						uval <<= 4;
318 						if (isdigit (h[i])) {
319 							uval += h[i] - '0';
320 						}
321 						else if (h[i] >= 'a' && h[i] <= 'f') {
322 							uval += h[i] - 'a' + 10;
323 						}
324 						else if (h[i] >= 'A' && h[i] <= 'F') {
325 							uval += h[i] - 'A' + 10;
326 						}
327 						else {
328 							break;
329 						}
330 					}
331 
332 					/* Encode */
333 					if(uval < 0x80) {
334 						t[0] = (char)uval;
335 						t ++;
336 					}
337 					else if(uval < 0x800) {
338 						t[0] = 0xC0 + ((uval & 0x7C0) >> 6);
339 						t[1] = 0x80 + ((uval & 0x03F));
340 						t += 2;
341 					}
342 					else if(uval < 0x10000) {
343 						t[0] = 0xE0 + ((uval & 0xF000) >> 12);
344 						t[1] = 0x80 + ((uval & 0x0FC0) >> 6);
345 						t[2] = 0x80 + ((uval & 0x003F));
346 						t += 3;
347 					}
348 #if 0
349 					/* It's not actually supported now */
350 					else if(uval <= 0x10FFFF) {
351 						t[0] = 0xF0 + ((uval & 0x1C0000) >> 18);
352 						t[1] = 0x80 + ((uval & 0x03F000) >> 12);
353 						t[2] = 0x80 + ((uval & 0x000FC0) >> 6);
354 						t[3] = 0x80 + ((uval & 0x00003F));
355 						t += 4;
356 					}
357 #endif
358 					else {
359 						*t++ = '?';
360 					}
361 
362 					/* Consume 4 characters of source */
363 					h += 4;
364 					len -= 4;
365 
366 					if (len > 0) {
367 						len --; /* for '\' character */
368 					}
369 					continue;
370 				}
371 				else {
372 					*t++ = 'u';
373 				}
374 				break;
375 			default:
376 				*t++ = *h;
377 				break;
378 			}
379 			h ++;
380 			len --;
381 		}
382 		else {
383 			*t++ = *h++;
384 		}
385 
386 		if (len > 0) {
387 			len --;
388 		}
389 	}
390 	*t = '\0';
391 
392 	return (t - str);
393 }
394 
395 char *
396 ucl_copy_key_trash (const ucl_object_t *obj)
397 {
398 	ucl_object_t *deconst;
399 
400 	if (obj == NULL) {
401 		return NULL;
402 	}
403 	if (obj->trash_stack[UCL_TRASH_KEY] == NULL && obj->key != NULL) {
404 		deconst = __DECONST (ucl_object_t *, obj);
405 		deconst->trash_stack[UCL_TRASH_KEY] = malloc (obj->keylen + 1);
406 		if (deconst->trash_stack[UCL_TRASH_KEY] != NULL) {
407 			memcpy (deconst->trash_stack[UCL_TRASH_KEY], obj->key, obj->keylen);
408 			deconst->trash_stack[UCL_TRASH_KEY][obj->keylen] = '\0';
409 		}
410 		deconst->key = obj->trash_stack[UCL_TRASH_KEY];
411 		deconst->flags |= UCL_OBJECT_ALLOCATED_KEY;
412 	}
413 
414 	return obj->trash_stack[UCL_TRASH_KEY];
415 }
416 
417 char *
418 ucl_copy_value_trash (const ucl_object_t *obj)
419 {
420 	ucl_object_t *deconst;
421 
422 	if (obj == NULL) {
423 		return NULL;
424 	}
425 	if (obj->trash_stack[UCL_TRASH_VALUE] == NULL) {
426 		deconst = __DECONST (ucl_object_t *, obj);
427 		if (obj->type == UCL_STRING) {
428 
429 			/* Special case for strings */
430 			if (obj->flags & UCL_OBJECT_BINARY) {
431 				deconst->trash_stack[UCL_TRASH_VALUE] = malloc (obj->len);
432 				if (deconst->trash_stack[UCL_TRASH_VALUE] != NULL) {
433 					memcpy (deconst->trash_stack[UCL_TRASH_VALUE],
434 							obj->value.sv,
435 							obj->len);
436 					deconst->value.sv = obj->trash_stack[UCL_TRASH_VALUE];
437 				}
438 			}
439 			else {
440 				deconst->trash_stack[UCL_TRASH_VALUE] = malloc (obj->len + 1);
441 				if (deconst->trash_stack[UCL_TRASH_VALUE] != NULL) {
442 					memcpy (deconst->trash_stack[UCL_TRASH_VALUE],
443 							obj->value.sv,
444 							obj->len);
445 					deconst->trash_stack[UCL_TRASH_VALUE][obj->len] = '\0';
446 					deconst->value.sv = obj->trash_stack[UCL_TRASH_VALUE];
447 				}
448 			}
449 		}
450 		else {
451 			/* Just emit value in json notation */
452 			deconst->trash_stack[UCL_TRASH_VALUE] = ucl_object_emit_single_json (obj);
453 			deconst->len = strlen (obj->trash_stack[UCL_TRASH_VALUE]);
454 		}
455 		deconst->flags |= UCL_OBJECT_ALLOCATED_VALUE;
456 	}
457 
458 	return obj->trash_stack[UCL_TRASH_VALUE];
459 }
460 
461 ucl_object_t*
462 ucl_parser_get_object (struct ucl_parser *parser)
463 {
464 	if (parser->state != UCL_STATE_ERROR && parser->top_obj != NULL) {
465 		return ucl_object_ref (parser->top_obj);
466 	}
467 
468 	return NULL;
469 }
470 
471 void
472 ucl_parser_free (struct ucl_parser *parser)
473 {
474 	struct ucl_stack *stack, *stmp;
475 	struct ucl_macro *macro, *mtmp;
476 	struct ucl_chunk *chunk, *ctmp;
477 	struct ucl_pubkey *key, *ktmp;
478 	struct ucl_variable *var, *vtmp;
479 	ucl_object_t *tr, *trtmp;
480 
481 	if (parser == NULL) {
482 		return;
483 	}
484 
485 	if (parser->top_obj != NULL) {
486 		ucl_object_unref (parser->top_obj);
487 	}
488 
489 	if (parser->includepaths != NULL) {
490 		ucl_object_unref (parser->includepaths);
491 	}
492 
493 	LL_FOREACH_SAFE (parser->stack, stack, stmp) {
494 		free (stack);
495 	}
496 	HASH_ITER (hh, parser->macroes, macro, mtmp) {
497 		free (macro->name);
498 		HASH_DEL (parser->macroes, macro);
499 		UCL_FREE (sizeof (struct ucl_macro), macro);
500 	}
501 	LL_FOREACH_SAFE (parser->chunks, chunk, ctmp) {
502 		UCL_FREE (sizeof (struct ucl_chunk), chunk);
503 	}
504 	LL_FOREACH_SAFE (parser->keys, key, ktmp) {
505 		UCL_FREE (sizeof (struct ucl_pubkey), key);
506 	}
507 	LL_FOREACH_SAFE (parser->variables, var, vtmp) {
508 		free (var->value);
509 		free (var->var);
510 		UCL_FREE (sizeof (struct ucl_variable), var);
511 	}
512 	LL_FOREACH_SAFE (parser->trash_objs, tr, trtmp) {
513 		ucl_object_free_internal (tr, false, ucl_object_dtor_free);
514 	}
515 
516 	if (parser->err != NULL) {
517 		utstring_free (parser->err);
518 	}
519 
520 	if (parser->cur_file) {
521 		free (parser->cur_file);
522 	}
523 
524 	if (parser->comments) {
525 		ucl_object_unref (parser->comments);
526 	}
527 
528 	UCL_FREE (sizeof (struct ucl_parser), parser);
529 }
530 
531 const char *
532 ucl_parser_get_error(struct ucl_parser *parser)
533 {
534 	if (parser == NULL) {
535 		return NULL;
536 	}
537 
538 	if (parser->err == NULL) {
539 		return NULL;
540 	}
541 
542 	return utstring_body (parser->err);
543 }
544 
545 int
546 ucl_parser_get_error_code(struct ucl_parser *parser)
547 {
548 	if (parser == NULL) {
549 		return 0;
550 	}
551 
552 	return parser->err_code;
553 }
554 
555 unsigned
556 ucl_parser_get_column(struct ucl_parser *parser)
557 {
558 	if (parser == NULL || parser->chunks == NULL) {
559 		return 0;
560 	}
561 
562 	return parser->chunks->column;
563 }
564 
565 unsigned
566 ucl_parser_get_linenum(struct ucl_parser *parser)
567 {
568 	if (parser == NULL || parser->chunks == NULL) {
569 		return 0;
570 	}
571 
572 	return parser->chunks->line;
573 }
574 
575 void
576 ucl_parser_clear_error(struct ucl_parser *parser)
577 {
578 	if (parser != NULL && parser->err != NULL) {
579 		utstring_free(parser->err);
580 		parser->err = NULL;
581 		parser->err_code = 0;
582 	}
583 }
584 
585 bool
586 ucl_pubkey_add (struct ucl_parser *parser, const unsigned char *key, size_t len)
587 {
588 #ifndef HAVE_OPENSSL
589 	ucl_create_err (&parser->err, "cannot check signatures without openssl");
590 	return false;
591 #else
592 # if (OPENSSL_VERSION_NUMBER < 0x10000000L)
593 	ucl_create_err (&parser->err, "cannot check signatures, openssl version is unsupported");
594 	return EXIT_FAILURE;
595 # else
596 	struct ucl_pubkey *nkey;
597 	BIO *mem;
598 
599 	mem = BIO_new_mem_buf ((void *)key, len);
600 	nkey = UCL_ALLOC (sizeof (struct ucl_pubkey));
601 	if (nkey == NULL) {
602 		ucl_create_err (&parser->err, "cannot allocate memory for key");
603 		return false;
604 	}
605 	nkey->key = PEM_read_bio_PUBKEY (mem, &nkey->key, NULL, NULL);
606 	BIO_free (mem);
607 	if (nkey->key == NULL) {
608 		UCL_FREE (sizeof (struct ucl_pubkey), nkey);
609 		ucl_create_err (&parser->err, "%s",
610 				ERR_error_string (ERR_get_error (), NULL));
611 		return false;
612 	}
613 	LL_PREPEND (parser->keys, nkey);
614 # endif
615 #endif
616 	return true;
617 }
618 
619 #ifdef CURL_FOUND
620 struct ucl_curl_cbdata {
621 	unsigned char *buf;
622 	size_t buflen;
623 };
624 
625 static size_t
626 ucl_curl_write_callback (void* contents, size_t size, size_t nmemb, void* ud)
627 {
628 	struct ucl_curl_cbdata *cbdata = ud;
629 	size_t realsize = size * nmemb;
630 
631 	cbdata->buf = realloc (cbdata->buf, cbdata->buflen + realsize + 1);
632 	if (cbdata->buf == NULL) {
633 		return 0;
634 	}
635 
636 	memcpy (&(cbdata->buf[cbdata->buflen]), contents, realsize);
637 	cbdata->buflen += realsize;
638 	cbdata->buf[cbdata->buflen] = 0;
639 
640 	return realsize;
641 }
642 #endif
643 
644 /**
645  * Fetch a url and save results to the memory buffer
646  * @param url url to fetch
647  * @param len length of url
648  * @param buf target buffer
649  * @param buflen target length
650  * @return
651  */
652 bool
653 ucl_fetch_url (const unsigned char *url, unsigned char **buf, size_t *buflen,
654 		UT_string **err, bool must_exist)
655 {
656 
657 #ifdef HAVE_FETCH_H
658 	struct url *fetch_url;
659 	struct url_stat us;
660 	FILE *in;
661 
662 	fetch_url = fetchParseURL (url);
663 	if (fetch_url == NULL) {
664 		ucl_create_err (err, "invalid URL %s: %s",
665 				url, strerror (errno));
666 		return false;
667 	}
668 	if ((in = fetchXGet (fetch_url, &us, "")) == NULL) {
669 		if (!must_exist) {
670 			ucl_create_err (err, "cannot fetch URL %s: %s",
671 				url, strerror (errno));
672 		}
673 		fetchFreeURL (fetch_url);
674 		return false;
675 	}
676 
677 	*buflen = us.size;
678 	*buf = malloc (*buflen);
679 	if (*buf == NULL) {
680 		ucl_create_err (err, "cannot allocate buffer for URL %s: %s",
681 				url, strerror (errno));
682 		fclose (in);
683 		fetchFreeURL (fetch_url);
684 		return false;
685 	}
686 
687 	if (fread (*buf, *buflen, 1, in) != 1) {
688 		ucl_create_err (err, "cannot read URL %s: %s",
689 				url, strerror (errno));
690 		fclose (in);
691 		fetchFreeURL (fetch_url);
692 		return false;
693 	}
694 
695 	fetchFreeURL (fetch_url);
696 	return true;
697 #elif defined(CURL_FOUND)
698 	CURL *curl;
699 	int r;
700 	struct ucl_curl_cbdata cbdata;
701 
702 	curl = curl_easy_init ();
703 	if (curl == NULL) {
704 		ucl_create_err (err, "CURL interface is broken");
705 		return false;
706 	}
707 	if ((r = curl_easy_setopt (curl, CURLOPT_URL, url)) != CURLE_OK) {
708 		ucl_create_err (err, "invalid URL %s: %s",
709 				url, curl_easy_strerror (r));
710 		curl_easy_cleanup (curl);
711 		return false;
712 	}
713 	curl_easy_setopt (curl, CURLOPT_WRITEFUNCTION, ucl_curl_write_callback);
714 	cbdata.buf = NULL;
715 	cbdata.buflen = 0;
716 	curl_easy_setopt (curl, CURLOPT_WRITEDATA, &cbdata);
717 
718 	if ((r = curl_easy_perform (curl)) != CURLE_OK) {
719 		if (!must_exist) {
720 			ucl_create_err (err, "error fetching URL %s: %s",
721 				url, curl_easy_strerror (r));
722 		}
723 		curl_easy_cleanup (curl);
724 		if (cbdata.buf) {
725 			free (cbdata.buf);
726 		}
727 		return false;
728 	}
729 	*buf = cbdata.buf;
730 	*buflen = cbdata.buflen;
731 
732 	return true;
733 #else
734 	ucl_create_err (err, "URL support is disabled");
735 	return false;
736 #endif
737 }
738 
739 /**
740  * Fetch a file and save results to the memory buffer
741  * @param filename filename to fetch
742  * @param len length of filename
743  * @param buf target buffer
744  * @param buflen target length
745  * @return
746  */
747 bool
748 ucl_fetch_file (const unsigned char *filename, unsigned char **buf, size_t *buflen,
749 		UT_string **err, bool must_exist)
750 {
751 	int fd;
752 	struct stat st;
753 
754 	if (stat (filename, &st) == -1 || !S_ISREG (st.st_mode)) {
755 		if (must_exist) {
756 			ucl_create_err (err, "cannot stat file %s: %s",
757 					filename, strerror (errno));
758 		}
759 		return false;
760 	}
761 	if (st.st_size == 0) {
762 		/* Do not map empty files */
763 		*buf = NULL;
764 		*buflen = 0;
765 	}
766 	else {
767 		if ((fd = open (filename, O_RDONLY)) == -1) {
768 			ucl_create_err (err, "cannot open file %s: %s",
769 					filename, strerror (errno));
770 			return false;
771 		}
772 		if ((*buf = ucl_mmap (NULL, st.st_size, PROT_READ, MAP_SHARED, fd, 0)) == MAP_FAILED) {
773 			close (fd);
774 			ucl_create_err (err, "cannot mmap file %s: %s",
775 					filename, strerror (errno));
776 			*buf = NULL;
777 
778 			return false;
779 		}
780 		*buflen = st.st_size;
781 		close (fd);
782 	}
783 
784 	return true;
785 }
786 
787 
788 #if (defined(HAVE_OPENSSL) && OPENSSL_VERSION_NUMBER >= 0x10000000L)
789 static inline bool
790 ucl_sig_check (const unsigned char *data, size_t datalen,
791 		const unsigned char *sig, size_t siglen, struct ucl_parser *parser)
792 {
793 	struct ucl_pubkey *key;
794 	char dig[EVP_MAX_MD_SIZE];
795 	unsigned int diglen;
796 	EVP_PKEY_CTX *key_ctx;
797 	EVP_MD_CTX *sign_ctx = NULL;
798 
799 	sign_ctx = EVP_MD_CTX_create ();
800 
801 	LL_FOREACH (parser->keys, key) {
802 		key_ctx = EVP_PKEY_CTX_new (key->key, NULL);
803 		if (key_ctx != NULL) {
804 			if (EVP_PKEY_verify_init (key_ctx) <= 0) {
805 				EVP_PKEY_CTX_free (key_ctx);
806 				continue;
807 			}
808 			if (EVP_PKEY_CTX_set_rsa_padding (key_ctx, RSA_PKCS1_PADDING) <= 0) {
809 				EVP_PKEY_CTX_free (key_ctx);
810 				continue;
811 			}
812 			if (EVP_PKEY_CTX_set_signature_md (key_ctx, EVP_sha256 ()) <= 0) {
813 				EVP_PKEY_CTX_free (key_ctx);
814 				continue;
815 			}
816 			EVP_DigestInit (sign_ctx, EVP_sha256 ());
817 			EVP_DigestUpdate (sign_ctx, data, datalen);
818 			EVP_DigestFinal (sign_ctx, dig, &diglen);
819 
820 			if (EVP_PKEY_verify (key_ctx, sig, siglen, dig, diglen) == 1) {
821 				EVP_MD_CTX_destroy (sign_ctx);
822 				EVP_PKEY_CTX_free (key_ctx);
823 				return true;
824 			}
825 
826 			EVP_PKEY_CTX_free (key_ctx);
827 		}
828 	}
829 
830 	EVP_MD_CTX_destroy (sign_ctx);
831 
832 	return false;
833 }
834 #endif
835 
836 struct ucl_include_params {
837 	bool check_signature;
838 	bool must_exist;
839 	bool use_glob;
840 	bool use_prefix;
841 	bool soft_fail;
842 	bool allow_glob;
843 	unsigned priority;
844 	enum ucl_duplicate_strategy strat;
845 	enum ucl_parse_type parse_type;
846 	const char *prefix;
847 	const char *target;
848 };
849 
850 /**
851  * Include an url to configuration
852  * @param data
853  * @param len
854  * @param parser
855  * @param err
856  * @return
857  */
858 static bool
859 ucl_include_url (const unsigned char *data, size_t len,
860 		struct ucl_parser *parser,
861 		struct ucl_include_params *params)
862 {
863 
864 	bool res;
865 	unsigned char *buf = NULL;
866 	size_t buflen = 0;
867 	struct ucl_chunk *chunk;
868 	char urlbuf[PATH_MAX];
869 	int prev_state;
870 
871 	snprintf (urlbuf, sizeof (urlbuf), "%.*s", (int)len, data);
872 
873 	if (!ucl_fetch_url (urlbuf, &buf, &buflen, &parser->err, params->must_exist)) {
874 		return !params->must_exist;
875 	}
876 
877 	if (params->check_signature) {
878 #if (defined(HAVE_OPENSSL) && OPENSSL_VERSION_NUMBER >= 0x10000000L)
879 		unsigned char *sigbuf = NULL;
880 		size_t siglen = 0;
881 		/* We need to check signature first */
882 		snprintf (urlbuf, sizeof (urlbuf), "%.*s.sig", (int)len, data);
883 		if (!ucl_fetch_url (urlbuf, &sigbuf, &siglen, &parser->err, true)) {
884 			return false;
885 		}
886 		if (!ucl_sig_check (buf, buflen, sigbuf, siglen, parser)) {
887 			ucl_create_err (&parser->err, "cannot verify url %s: %s",
888 							urlbuf,
889 							ERR_error_string (ERR_get_error (), NULL));
890 			if (siglen > 0) {
891 				ucl_munmap (sigbuf, siglen);
892 			}
893 			return false;
894 		}
895 		if (siglen > 0) {
896 			ucl_munmap (sigbuf, siglen);
897 		}
898 #endif
899 	}
900 
901 	prev_state = parser->state;
902 	parser->state = UCL_STATE_INIT;
903 
904 	res = ucl_parser_add_chunk_full (parser, buf, buflen, params->priority,
905 			params->strat, params->parse_type);
906 	if (res == true) {
907 		/* Remove chunk from the stack */
908 		chunk = parser->chunks;
909 		if (chunk != NULL) {
910 			parser->chunks = chunk->next;
911 			UCL_FREE (sizeof (struct ucl_chunk), chunk);
912 		}
913 	}
914 
915 	parser->state = prev_state;
916 	free (buf);
917 
918 	return res;
919 }
920 
921 /**
922  * Include a single file to the parser
923  * @param data
924  * @param len
925  * @param parser
926  * @param check_signature
927  * @param must_exist
928  * @param allow_glob
929  * @param priority
930  * @return
931  */
932 static bool
933 ucl_include_file_single (const unsigned char *data, size_t len,
934 		struct ucl_parser *parser, struct ucl_include_params *params)
935 {
936 	bool res;
937 	struct ucl_chunk *chunk;
938 	unsigned char *buf = NULL;
939 	char *old_curfile, *ext;
940 	size_t buflen = 0;
941 	char filebuf[PATH_MAX], realbuf[PATH_MAX];
942 	int prev_state;
943 	struct ucl_variable *cur_var, *tmp_var, *old_curdir = NULL,
944 			*old_filename = NULL;
945 	ucl_object_t *nest_obj = NULL, *old_obj = NULL, *new_obj = NULL;
946 	ucl_hash_t *container = NULL;
947 	struct ucl_stack *st = NULL;
948 
949 	snprintf (filebuf, sizeof (filebuf), "%.*s", (int)len, data);
950 	if (ucl_realpath (filebuf, realbuf) == NULL) {
951 		if (params->soft_fail) {
952 			return false;
953 		}
954 		if (!params->must_exist) {
955 			return true;
956 		}
957 		ucl_create_err (&parser->err, "cannot open file %s: %s",
958 									filebuf,
959 									strerror (errno));
960 		return false;
961 	}
962 
963 	if (parser->cur_file && strcmp (realbuf, parser->cur_file) == 0) {
964 		/* We are likely including the file itself */
965 		if (params->soft_fail) {
966 			return false;
967 		}
968 
969 		ucl_create_err (&parser->err, "trying to include the file %s from itself",
970 				realbuf);
971 		return false;
972 	}
973 
974 	if (!ucl_fetch_file (realbuf, &buf, &buflen, &parser->err, params->must_exist)) {
975 		if (params->soft_fail) {
976 			return false;
977 		}
978 		return (!params->must_exist || false);
979 	}
980 
981 	if (params->check_signature) {
982 #if (defined(HAVE_OPENSSL) && OPENSSL_VERSION_NUMBER >= 0x10000000L)
983 		unsigned char *sigbuf = NULL;
984 		size_t siglen = 0;
985 		/* We need to check signature first */
986 		snprintf (filebuf, sizeof (filebuf), "%s.sig", realbuf);
987 		if (!ucl_fetch_file (filebuf, &sigbuf, &siglen, &parser->err, true)) {
988 			return false;
989 		}
990 		if (!ucl_sig_check (buf, buflen, sigbuf, siglen, parser)) {
991 			ucl_create_err (&parser->err, "cannot verify file %s: %s",
992 							filebuf,
993 							ERR_error_string (ERR_get_error (), NULL));
994 			if (sigbuf) {
995 				ucl_munmap (sigbuf, siglen);
996 			}
997 			return false;
998 		}
999 		if (sigbuf) {
1000 			ucl_munmap (sigbuf, siglen);
1001 		}
1002 #endif
1003 	}
1004 
1005 	old_curfile = parser->cur_file;
1006 	parser->cur_file = strdup (realbuf);
1007 
1008 	/* Store old file vars */
1009 	DL_FOREACH_SAFE (parser->variables, cur_var, tmp_var) {
1010 		if (strcmp (cur_var->var, "CURDIR") == 0) {
1011 			old_curdir = cur_var;
1012 			DL_DELETE (parser->variables, cur_var);
1013 		}
1014 		else if (strcmp (cur_var->var, "FILENAME") == 0) {
1015 			old_filename = cur_var;
1016 			DL_DELETE (parser->variables, cur_var);
1017 		}
1018 	}
1019 
1020 	ucl_parser_set_filevars (parser, realbuf, false);
1021 
1022 	prev_state = parser->state;
1023 	parser->state = UCL_STATE_INIT;
1024 
1025 	if (params->use_prefix && params->prefix == NULL) {
1026 		/* Auto generate a key name based on the included filename */
1027 		params->prefix = basename (realbuf);
1028 		ext = strrchr (params->prefix, '.');
1029 		if (ext != NULL && (strcmp (ext, ".conf") == 0 || strcmp (ext, ".ucl") == 0)) {
1030 			/* Strip off .conf or .ucl */
1031 			*ext = '\0';
1032 		}
1033 	}
1034 	if (params->prefix != NULL) {
1035 		/* This is a prefixed include */
1036 		container = parser->stack->obj->value.ov;
1037 
1038 		old_obj = __DECONST (ucl_object_t *, ucl_hash_search (container,
1039 				params->prefix, strlen (params->prefix)));
1040 
1041 		if (strcasecmp (params->target, "array") == 0 && old_obj == NULL) {
1042 			/* Create an array with key: prefix */
1043 			old_obj = ucl_object_new_full (UCL_ARRAY, params->priority);
1044 			old_obj->key = params->prefix;
1045 			old_obj->keylen = strlen (params->prefix);
1046 			ucl_copy_key_trash(old_obj);
1047 			old_obj->prev = old_obj;
1048 			old_obj->next = NULL;
1049 
1050 			container = ucl_hash_insert_object (container, old_obj,
1051 					parser->flags & UCL_PARSER_KEY_LOWERCASE);
1052 			parser->stack->obj->len ++;
1053 
1054 			nest_obj = ucl_object_new_full (UCL_OBJECT, params->priority);
1055 			nest_obj->prev = nest_obj;
1056 			nest_obj->next = NULL;
1057 
1058 			ucl_array_append (old_obj, nest_obj);
1059 		}
1060 		else if (old_obj == NULL) {
1061 			/* Create an object with key: prefix */
1062 			nest_obj = ucl_object_new_full (UCL_OBJECT, params->priority);
1063 
1064 			if (nest_obj == NULL) {
1065 				ucl_create_err (&parser->err, "cannot allocate memory for an object");
1066 				if (buf) {
1067 					ucl_munmap (buf, buflen);
1068 				}
1069 
1070 				return false;
1071 			}
1072 
1073 			nest_obj->key = params->prefix;
1074 			nest_obj->keylen = strlen (params->prefix);
1075 			ucl_copy_key_trash(nest_obj);
1076 			nest_obj->prev = nest_obj;
1077 			nest_obj->next = NULL;
1078 
1079 			container = ucl_hash_insert_object (container, nest_obj,
1080 					parser->flags & UCL_PARSER_KEY_LOWERCASE);
1081 			parser->stack->obj->len ++;
1082 		}
1083 		else if (strcasecmp (params->target, "array") == 0 ||
1084 				ucl_object_type(old_obj) == UCL_ARRAY) {
1085 			if (ucl_object_type(old_obj) == UCL_ARRAY) {
1086 				/* Append to the existing array */
1087 				nest_obj = ucl_object_new_full (UCL_OBJECT, params->priority);
1088 				if (nest_obj == NULL) {
1089 					ucl_create_err (&parser->err, "cannot allocate memory for an object");
1090 					if (buf) {
1091 						ucl_munmap (buf, buflen);
1092 					}
1093 
1094 					return false;
1095 				}
1096 				nest_obj->prev = nest_obj;
1097 				nest_obj->next = NULL;
1098 
1099 				ucl_array_append (old_obj, nest_obj);
1100 			}
1101 			else {
1102 				/* Convert the object to an array */
1103 				new_obj = ucl_object_typed_new (UCL_ARRAY);
1104 				if (new_obj == NULL) {
1105 					ucl_create_err (&parser->err, "cannot allocate memory for an object");
1106 					if (buf) {
1107 						ucl_munmap (buf, buflen);
1108 					}
1109 
1110 					return false;
1111 				}
1112 				new_obj->key = old_obj->key;
1113 				new_obj->keylen = old_obj->keylen;
1114 				new_obj->flags |= UCL_OBJECT_MULTIVALUE;
1115 				new_obj->prev = new_obj;
1116 				new_obj->next = NULL;
1117 
1118 				nest_obj = ucl_object_new_full (UCL_OBJECT, params->priority);
1119 				if (nest_obj == NULL) {
1120 					ucl_create_err (&parser->err, "cannot allocate memory for an object");
1121 					if (buf) {
1122 						ucl_munmap (buf, buflen);
1123 					}
1124 
1125 					return false;
1126 				}
1127 				nest_obj->prev = nest_obj;
1128 				nest_obj->next = NULL;
1129 
1130 				ucl_array_append (new_obj, old_obj);
1131 				ucl_array_append (new_obj, nest_obj);
1132 				ucl_hash_replace (container, old_obj, new_obj);
1133 			}
1134 		}
1135 		else {
1136 			if (ucl_object_type (old_obj) == UCL_OBJECT) {
1137 				/* Append to existing Object*/
1138 				nest_obj = old_obj;
1139 			}
1140 			else {
1141 				/* The key is not an object */
1142 				ucl_create_err (&parser->err,
1143 						"Conflicting type for key: %s",
1144 						params->prefix);
1145 				if (buf) {
1146 					ucl_munmap (buf, buflen);
1147 				}
1148 
1149 				return false;
1150 			}
1151 		}
1152 
1153 		 /* Put all of the content of the include inside that object */
1154 		parser->stack->obj->value.ov = container;
1155 
1156 		st = UCL_ALLOC (sizeof (struct ucl_stack));
1157 		if (st == NULL) {
1158 			ucl_create_err (&parser->err, "cannot allocate memory for an object");
1159 			ucl_object_unref (nest_obj);
1160 
1161 			if (buf) {
1162 				ucl_munmap (buf, buflen);
1163 			}
1164 
1165 			return false;
1166 		}
1167 		st->obj = nest_obj;
1168 		st->level = parser->stack->level;
1169 		LL_PREPEND (parser->stack, st);
1170 		parser->cur_obj = nest_obj;
1171 	}
1172 
1173 	res = ucl_parser_add_chunk_full (parser, buf, buflen, params->priority,
1174 			params->strat, params->parse_type);
1175 	if (!res && !params->must_exist) {
1176 		/* Free error */
1177 		utstring_free (parser->err);
1178 		parser->err = NULL;
1179 		parser->state = UCL_STATE_AFTER_VALUE;
1180 	}
1181 
1182 	/* Stop nesting the include, take 1 level off the stack */
1183 	if (params->prefix != NULL && nest_obj != NULL) {
1184 		parser->stack = st->next;
1185 		UCL_FREE (sizeof (struct ucl_stack), st);
1186 	}
1187 
1188 	/* Remove chunk from the stack */
1189 	chunk = parser->chunks;
1190 	if (chunk != NULL) {
1191 		parser->chunks = chunk->next;
1192 		UCL_FREE (sizeof (struct ucl_chunk), chunk);
1193 		parser->recursion --;
1194 	}
1195 
1196 	/* Restore old file vars */
1197 	if (parser->cur_file) {
1198 		free (parser->cur_file);
1199 	}
1200 
1201 	parser->cur_file = old_curfile;
1202 	DL_FOREACH_SAFE (parser->variables, cur_var, tmp_var) {
1203 		if (strcmp (cur_var->var, "CURDIR") == 0 && old_curdir) {
1204 			DL_DELETE (parser->variables, cur_var);
1205 			free (cur_var->var);
1206 			free (cur_var->value);
1207 			UCL_FREE (sizeof (struct ucl_variable), cur_var);
1208 		}
1209 		else if (strcmp (cur_var->var, "FILENAME") == 0 && old_filename) {
1210 			DL_DELETE (parser->variables, cur_var);
1211 			free (cur_var->var);
1212 			free (cur_var->value);
1213 			UCL_FREE (sizeof (struct ucl_variable), cur_var);
1214 		}
1215 	}
1216 	if (old_filename) {
1217 		DL_APPEND (parser->variables, old_filename);
1218 	}
1219 	if (old_curdir) {
1220 		DL_APPEND (parser->variables, old_curdir);
1221 	}
1222 
1223 	parser->state = prev_state;
1224 
1225 	if (buflen > 0) {
1226 		ucl_munmap (buf, buflen);
1227 	}
1228 
1229 	return res;
1230 }
1231 
1232 /**
1233  * Include a file to configuration
1234  * @param data
1235  * @param len
1236  * @param parser
1237  * @param err
1238  * @return
1239  */
1240 static bool
1241 ucl_include_file (const unsigned char *data, size_t len,
1242 		struct ucl_parser *parser, struct ucl_include_params *params)
1243 {
1244 	const unsigned char *p = data, *end = data + len;
1245 	bool need_glob = false;
1246 	int cnt = 0;
1247 	char glob_pattern[PATH_MAX];
1248 	size_t i;
1249 
1250 #ifndef _WIN32
1251 	if (!params->allow_glob) {
1252 		return ucl_include_file_single (data, len, parser, params);
1253 	}
1254 	else {
1255 		/* Check for special symbols in a filename */
1256 		while (p != end) {
1257 			if (*p == '*' || *p == '?') {
1258 				need_glob = true;
1259 				break;
1260 			}
1261 			p ++;
1262 		}
1263 		if (need_glob) {
1264 			glob_t globbuf;
1265 			memset (&globbuf, 0, sizeof (globbuf));
1266 			ucl_strlcpy (glob_pattern, (const char *)data,
1267 				(len + 1 < sizeof (glob_pattern) ? len + 1 : sizeof (glob_pattern)));
1268 			if (glob (glob_pattern, 0, NULL, &globbuf) != 0) {
1269 				return (!params->must_exist || false);
1270 			}
1271 			for (i = 0; i < globbuf.gl_pathc; i ++) {
1272 				if (!ucl_include_file_single ((unsigned char *)globbuf.gl_pathv[i],
1273 						strlen (globbuf.gl_pathv[i]), parser, params)) {
1274 					if (params->soft_fail) {
1275 						continue;
1276 					}
1277 					globfree (&globbuf);
1278 					return false;
1279 				}
1280 				cnt ++;
1281 			}
1282 			globfree (&globbuf);
1283 
1284 			if (cnt == 0 && params->must_exist) {
1285 				ucl_create_err (&parser->err, "cannot match any files for pattern %s",
1286 					glob_pattern);
1287 				return false;
1288 			}
1289 		}
1290 		else {
1291 			return ucl_include_file_single (data, len, parser, params);
1292 		}
1293 	}
1294 #else
1295 	/* Win32 compilers do not support globbing. Therefore, for Win32,
1296 	   treat allow_glob/need_glob as a NOOP and just return */
1297 	return ucl_include_file_single (data, len, parser, params);
1298 #endif
1299 
1300 	return true;
1301 }
1302 
1303 /**
1304  * Common function to handle .*include* macros
1305  * @param data
1306  * @param len
1307  * @param args
1308  * @param parser
1309  * @param default_try
1310  * @param default_sign
1311  * @return
1312  */
1313 static bool
1314 ucl_include_common (const unsigned char *data, size_t len,
1315 		const ucl_object_t *args, struct ucl_parser *parser,
1316 		bool default_try,
1317 		bool default_sign)
1318 {
1319 	bool allow_url = false, search = false;
1320 	const char *duplicate;
1321 	const ucl_object_t *param;
1322 	ucl_object_iter_t it = NULL, ip = NULL;
1323 	char ipath[PATH_MAX];
1324 	struct ucl_include_params params;
1325 
1326 	/* Default values */
1327 	params.soft_fail = default_try;
1328 	params.allow_glob = false;
1329 	params.check_signature = default_sign;
1330 	params.use_prefix = false;
1331 	params.target = "object";
1332 	params.prefix = NULL;
1333 	params.priority = 0;
1334 	params.parse_type = UCL_PARSE_UCL;
1335 	params.strat = UCL_DUPLICATE_APPEND;
1336 	params.must_exist = !default_try;
1337 
1338 	/* Process arguments */
1339 	if (args != NULL && args->type == UCL_OBJECT) {
1340 		while ((param = ucl_object_iterate (args, &it, true)) != NULL) {
1341 			if (param->type == UCL_BOOLEAN) {
1342 				if (strncmp (param->key, "try", param->keylen) == 0) {
1343 					params.must_exist = !ucl_object_toboolean (param);
1344 				}
1345 				else if (strncmp (param->key, "sign", param->keylen) == 0) {
1346 					params.check_signature = ucl_object_toboolean (param);
1347 				}
1348 				else if (strncmp (param->key, "glob", param->keylen) == 0) {
1349 					params.allow_glob = ucl_object_toboolean (param);
1350 				}
1351 				else if (strncmp (param->key, "url", param->keylen) == 0) {
1352 					allow_url = ucl_object_toboolean (param);
1353 				}
1354 				else if (strncmp (param->key, "prefix", param->keylen) == 0) {
1355 					params.use_prefix = ucl_object_toboolean (param);
1356 				}
1357 			}
1358 			else if (param->type == UCL_STRING) {
1359 				if (strncmp (param->key, "key", param->keylen) == 0) {
1360 					params.prefix = ucl_object_tostring (param);
1361 				}
1362 				else if (strncmp (param->key, "target", param->keylen) == 0) {
1363 					params.target = ucl_object_tostring (param);
1364 				}
1365 				else if (strncmp (param->key, "duplicate", param->keylen) == 0) {
1366 					duplicate = ucl_object_tostring (param);
1367 
1368 					if (strcmp (duplicate, "append") == 0) {
1369 						params.strat = UCL_DUPLICATE_APPEND;
1370 					}
1371 					else if (strcmp (duplicate, "merge") == 0) {
1372 						params.strat = UCL_DUPLICATE_MERGE;
1373 					}
1374 					else if (strcmp (duplicate, "rewrite") == 0) {
1375 						params.strat = UCL_DUPLICATE_REWRITE;
1376 					}
1377 					else if (strcmp (duplicate, "error") == 0) {
1378 						params.strat = UCL_DUPLICATE_ERROR;
1379 					}
1380 				}
1381 			}
1382 			else if (param->type == UCL_ARRAY) {
1383 				if (strncmp (param->key, "path", param->keylen) == 0) {
1384 					ucl_set_include_path (parser, __DECONST(ucl_object_t *, param));
1385 				}
1386 			}
1387 			else if (param->type == UCL_INT) {
1388 				if (strncmp (param->key, "priority", param->keylen) == 0) {
1389 					params.priority = ucl_object_toint (param);
1390 				}
1391 			}
1392 		}
1393 	}
1394 
1395 	if (parser->includepaths == NULL) {
1396 		if (allow_url && ucl_strnstr (data, "://", len) != NULL) {
1397 			/* Globbing is not used for URL's */
1398 			return ucl_include_url (data, len, parser, &params);
1399 		}
1400 		else if (data != NULL) {
1401 			/* Try to load a file */
1402 			return ucl_include_file (data, len, parser, &params);
1403 		}
1404 	}
1405 	else {
1406 		if (allow_url && ucl_strnstr (data, "://", len) != NULL) {
1407 			/* Globbing is not used for URL's */
1408 			return ucl_include_url (data, len, parser, &params);
1409 		}
1410 
1411 		ip = ucl_object_iterate_new (parser->includepaths);
1412 		while ((param = ucl_object_iterate_safe (ip, true)) != NULL) {
1413 			if (ucl_object_type(param) == UCL_STRING) {
1414 				snprintf (ipath, sizeof (ipath), "%s/%.*s", ucl_object_tostring(param),
1415 						(int)len, data);
1416 				if ((search = ucl_include_file (ipath, strlen (ipath),
1417 						parser, &params))) {
1418 					if (!params.allow_glob) {
1419 						break;
1420 					}
1421 				}
1422 			}
1423 		}
1424 		ucl_object_iterate_free (ip);
1425 		if (search == true) {
1426 			return true;
1427 		}
1428 		else {
1429 			ucl_create_err (&parser->err,
1430 					"cannot find file: %.*s in search path",
1431 					(int)len, data);
1432 			return false;
1433 		}
1434 	}
1435 
1436 	return false;
1437 }
1438 
1439 /**
1440  * Handle include macro
1441  * @param data include data
1442  * @param len length of data
1443  * @param args UCL object representing arguments to the macro
1444  * @param ud user data
1445  * @return
1446  */
1447 bool
1448 ucl_include_handler (const unsigned char *data, size_t len,
1449 		const ucl_object_t *args, void* ud)
1450 {
1451 	struct ucl_parser *parser = ud;
1452 
1453 	return ucl_include_common (data, len, args, parser, false, false);
1454 }
1455 
1456 /**
1457  * Handle includes macro
1458  * @param data include data
1459  * @param len length of data
1460  * @param args UCL object representing arguments to the macro
1461  * @param ud user data
1462  * @return
1463  */
1464 bool
1465 ucl_includes_handler (const unsigned char *data, size_t len,
1466 		const ucl_object_t *args, void* ud)
1467 {
1468 	struct ucl_parser *parser = ud;
1469 
1470 	return ucl_include_common (data, len, args, parser, false, true);
1471 }
1472 
1473 /**
1474  * Handle tryinclude macro
1475  * @param data include data
1476  * @param len length of data
1477  * @param args UCL object representing arguments to the macro
1478  * @param ud user data
1479  * @return
1480  */
1481 bool
1482 ucl_try_include_handler (const unsigned char *data, size_t len,
1483 		const ucl_object_t *args, void* ud)
1484 {
1485 	struct ucl_parser *parser = ud;
1486 
1487 	return ucl_include_common (data, len, args, parser, true, false);
1488 }
1489 
1490 /**
1491  * Handle priority macro
1492  * @param data include data
1493  * @param len length of data
1494  * @param args UCL object representing arguments to the macro
1495  * @param ud user data
1496  * @return
1497  */
1498 bool
1499 ucl_priority_handler (const unsigned char *data, size_t len,
1500 		const ucl_object_t *args, void* ud)
1501 {
1502 	struct ucl_parser *parser = ud;
1503 	unsigned priority = 255;
1504 	const ucl_object_t *param;
1505 	bool found = false;
1506 	char *value = NULL, *leftover = NULL;
1507 	ucl_object_iter_t it = NULL;
1508 
1509 	if (parser == NULL) {
1510 		return false;
1511 	}
1512 
1513 	/* Process arguments */
1514 	if (args != NULL && args->type == UCL_OBJECT) {
1515 		while ((param = ucl_object_iterate (args, &it, true)) != NULL) {
1516 			if (param->type == UCL_INT) {
1517 				if (strncmp (param->key, "priority", param->keylen) == 0) {
1518 					priority = ucl_object_toint (param);
1519 					found = true;
1520 				}
1521 			}
1522 		}
1523 	}
1524 
1525 	if (len > 0) {
1526 		value = malloc(len + 1);
1527 		ucl_strlcpy(value, (const char *)data, len + 1);
1528 		priority = strtol(value, &leftover, 10);
1529 		if (*leftover != '\0') {
1530 			ucl_create_err (&parser->err, "Invalid priority value in macro: %s",
1531 				value);
1532 			free(value);
1533 			return false;
1534 		}
1535 		free(value);
1536 		found = true;
1537 	}
1538 
1539 	if (found == true) {
1540 		parser->chunks->priority = priority;
1541 		return true;
1542 	}
1543 
1544 	ucl_create_err (&parser->err, "Unable to parse priority macro");
1545 	return false;
1546 }
1547 
1548 /**
1549  * Handle load macro
1550  * @param data include data
1551  * @param len length of data
1552  * @param args UCL object representing arguments to the macro
1553  * @param ud user data
1554  * @return
1555  */
1556 bool
1557 ucl_load_handler (const unsigned char *data, size_t len,
1558 		const ucl_object_t *args, void* ud)
1559 {
1560 	struct ucl_parser *parser = ud;
1561 	const ucl_object_t *param;
1562 	ucl_object_t *obj, *old_obj;
1563 	ucl_object_iter_t it = NULL;
1564 	bool try_load, multiline, test;
1565 	const char *target, *prefix;
1566 	char *load_file, *tmp;
1567 	unsigned char *buf;
1568 	size_t buflen;
1569 	unsigned priority;
1570 	int64_t iv;
1571 	ucl_object_t *container = NULL;
1572 	enum ucl_string_flags flags;
1573 
1574 	/* Default values */
1575 	try_load = false;
1576 	multiline = false;
1577 	test = false;
1578 	target = "string";
1579 	prefix = NULL;
1580 	load_file = NULL;
1581 	buf = NULL;
1582 	buflen = 0;
1583 	priority = 0;
1584 	obj = NULL;
1585 	old_obj = NULL;
1586 	flags = 0;
1587 
1588 	if (parser == NULL) {
1589 		return false;
1590 	}
1591 
1592 	/* Process arguments */
1593 	if (args != NULL && args->type == UCL_OBJECT) {
1594 		while ((param = ucl_object_iterate (args, &it, true)) != NULL) {
1595 			if (param->type == UCL_BOOLEAN) {
1596 				if (strncmp (param->key, "try", param->keylen) == 0) {
1597 					try_load = ucl_object_toboolean (param);
1598 				}
1599 				else if (strncmp (param->key, "multiline", param->keylen) == 0) {
1600 					multiline = ucl_object_toboolean (param);
1601 				}
1602 				else if (strncmp (param->key, "escape", param->keylen) == 0) {
1603 					test = ucl_object_toboolean (param);
1604 					if (test) {
1605 						flags |= UCL_STRING_ESCAPE;
1606 					}
1607 				}
1608 				else if (strncmp (param->key, "trim", param->keylen) == 0) {
1609 					test = ucl_object_toboolean (param);
1610 					if (test) {
1611 						flags |= UCL_STRING_TRIM;
1612 					}
1613 				}
1614 			}
1615 			else if (param->type == UCL_STRING) {
1616 				if (strncmp (param->key, "key", param->keylen) == 0) {
1617 					prefix = ucl_object_tostring (param);
1618 				}
1619 				else if (strncmp (param->key, "target", param->keylen) == 0) {
1620 					target = ucl_object_tostring (param);
1621 				}
1622 			}
1623 			else if (param->type == UCL_INT) {
1624 				if (strncmp (param->key, "priority", param->keylen) == 0) {
1625 					priority = ucl_object_toint (param);
1626 				}
1627 			}
1628 		}
1629 	}
1630 
1631 	if (prefix == NULL || strlen (prefix) == 0) {
1632 		ucl_create_err (&parser->err, "No Key specified in load macro");
1633 		return false;
1634 	}
1635 
1636 	if (len > 0) {
1637 		load_file = malloc (len + 1);
1638 		if (!load_file) {
1639 			ucl_create_err (&parser->err, "cannot allocate memory for suffix");
1640 
1641 			return false;
1642 		}
1643 
1644 		snprintf (load_file, len + 1, "%.*s", (int)len, data);
1645 
1646 		if (!ucl_fetch_file (load_file, &buf, &buflen, &parser->err,
1647 				!try_load)) {
1648 			free (load_file);
1649 
1650 			return (try_load || false);
1651 		}
1652 
1653 		free (load_file);
1654 		container = parser->stack->obj;
1655 		old_obj = __DECONST (ucl_object_t *, ucl_object_lookup (container,
1656 				prefix));
1657 
1658 		if (old_obj != NULL) {
1659 			ucl_create_err (&parser->err, "Key %s already exists", prefix);
1660 			if (buf) {
1661 				ucl_munmap (buf, buflen);
1662 			}
1663 
1664 			return false;
1665 		}
1666 
1667 		if (strcasecmp (target, "string") == 0) {
1668 			obj = ucl_object_fromstring_common (buf, buflen, flags);
1669 			ucl_copy_value_trash (obj);
1670 			if (multiline) {
1671 				obj->flags |= UCL_OBJECT_MULTILINE;
1672 			}
1673 		}
1674 		else if (strcasecmp (target, "int") == 0) {
1675 			tmp = malloc (buflen + 1);
1676 
1677 			if (tmp == NULL) {
1678 				ucl_create_err (&parser->err, "Memory allocation failed");
1679 				if (buf) {
1680 					ucl_munmap (buf, buflen);
1681 				}
1682 
1683 				return false;
1684 			}
1685 
1686 			snprintf (tmp, buflen + 1, "%.*s", (int)buflen, buf);
1687 			iv = strtoll (tmp, NULL, 10);
1688 			obj = ucl_object_fromint (iv);
1689 			free (tmp);
1690 		}
1691 
1692 		if (buf) {
1693 			ucl_munmap (buf, buflen);
1694 		}
1695 
1696 		if (obj != NULL) {
1697 			obj->key = prefix;
1698 			obj->keylen = strlen (prefix);
1699 			ucl_copy_key_trash (obj);
1700 			obj->prev = obj;
1701 			obj->next = NULL;
1702 			ucl_object_set_priority (obj, priority);
1703 			ucl_object_insert_key (container, obj, obj->key, obj->keylen, false);
1704 		}
1705 
1706 		return true;
1707 	}
1708 
1709 	ucl_create_err (&parser->err, "Unable to parse load macro");
1710 	return false;
1711 }
1712 
1713 bool
1714 ucl_inherit_handler (const unsigned char *data, size_t len,
1715 		const ucl_object_t *args, const ucl_object_t *ctx, void* ud)
1716 {
1717 	const ucl_object_t *parent, *cur;
1718 	ucl_object_t *target, *copy;
1719 	ucl_object_iter_t it = NULL;
1720 	bool replace = false;
1721 	struct ucl_parser *parser = ud;
1722 
1723 	parent = ucl_object_lookup_len (ctx, data, len);
1724 
1725 	/* Some sanity checks */
1726 	if (parent == NULL || ucl_object_type (parent) != UCL_OBJECT) {
1727 		ucl_create_err (&parser->err, "Unable to find inherited object %*.s",
1728 				(int)len, data);
1729 		return false;
1730 	}
1731 
1732 	if (parser->stack == NULL || parser->stack->obj == NULL ||
1733 			ucl_object_type (parser->stack->obj) != UCL_OBJECT) {
1734 		ucl_create_err (&parser->err, "Invalid inherit context");
1735 		return false;
1736 	}
1737 
1738 	target = parser->stack->obj;
1739 
1740 	if (args && (cur = ucl_object_lookup (args, "replace")) != NULL) {
1741 		replace = ucl_object_toboolean (cur);
1742 	}
1743 
1744 	while ((cur = ucl_object_iterate (parent, &it, true))) {
1745 		/* We do not replace existing keys */
1746 		if (!replace && ucl_object_lookup_len (target, cur->key, cur->keylen)) {
1747 			continue;
1748 		}
1749 
1750 		copy = ucl_object_copy (cur);
1751 
1752 		if (!replace) {
1753 			copy->flags |= UCL_OBJECT_INHERITED;
1754 		}
1755 
1756 		ucl_object_insert_key (target, copy, copy->key,
1757 				copy->keylen, false);
1758 	}
1759 
1760 	return true;
1761 }
1762 
1763 bool
1764 ucl_parser_set_filevars (struct ucl_parser *parser, const char *filename, bool need_expand)
1765 {
1766 	char realbuf[PATH_MAX], *curdir;
1767 
1768 	if (filename != NULL) {
1769 		if (need_expand) {
1770 			if (ucl_realpath (filename, realbuf) == NULL) {
1771 				return false;
1772 			}
1773 		}
1774 		else {
1775 			ucl_strlcpy (realbuf, filename, sizeof (realbuf));
1776 		}
1777 
1778 		/* Define variables */
1779 		ucl_parser_register_variable (parser, "FILENAME", realbuf);
1780 		curdir = dirname (realbuf);
1781 		ucl_parser_register_variable (parser, "CURDIR", curdir);
1782 	}
1783 	else {
1784 		/* Set everything from the current dir */
1785 		curdir = getcwd (realbuf, sizeof (realbuf));
1786 		ucl_parser_register_variable (parser, "FILENAME", "undef");
1787 		ucl_parser_register_variable (parser, "CURDIR", curdir);
1788 	}
1789 
1790 	return true;
1791 }
1792 
1793 bool
1794 ucl_parser_add_file_priority (struct ucl_parser *parser, const char *filename,
1795 		unsigned priority)
1796 {
1797 	unsigned char *buf;
1798 	size_t len;
1799 	bool ret;
1800 	char realbuf[PATH_MAX];
1801 
1802 	if (ucl_realpath (filename, realbuf) == NULL) {
1803 		ucl_create_err (&parser->err, "cannot open file %s: %s",
1804 				filename,
1805 				strerror (errno));
1806 		return false;
1807 	}
1808 
1809 	if (!ucl_fetch_file (realbuf, &buf, &len, &parser->err, true)) {
1810 		return false;
1811 	}
1812 
1813 	if (parser->cur_file) {
1814 		free (parser->cur_file);
1815 	}
1816 	parser->cur_file = strdup (realbuf);
1817 	ucl_parser_set_filevars (parser, realbuf, false);
1818 	ret = ucl_parser_add_chunk_priority (parser, buf, len, priority);
1819 
1820 	if (len > 0) {
1821 		ucl_munmap (buf, len);
1822 	}
1823 
1824 	return ret;
1825 }
1826 
1827 bool
1828 ucl_parser_add_file (struct ucl_parser *parser, const char *filename)
1829 {
1830 	if (parser == NULL) {
1831 		return false;
1832 	}
1833 
1834 	return ucl_parser_add_file_priority(parser, filename,
1835 			parser->default_priority);
1836 }
1837 
1838 bool
1839 ucl_parser_add_fd_priority (struct ucl_parser *parser, int fd,
1840 		unsigned priority)
1841 {
1842 	unsigned char *buf;
1843 	size_t len;
1844 	bool ret;
1845 	struct stat st;
1846 
1847 	if (fstat (fd, &st) == -1) {
1848 		ucl_create_err (&parser->err, "cannot stat fd %d: %s",
1849 			fd, strerror (errno));
1850 		return false;
1851 	}
1852 	if ((buf = ucl_mmap (NULL, st.st_size, PROT_READ, MAP_SHARED, fd, 0)) == MAP_FAILED) {
1853 		ucl_create_err (&parser->err, "cannot mmap fd %d: %s",
1854 			fd, strerror (errno));
1855 		return false;
1856 	}
1857 
1858 	if (parser->cur_file) {
1859 		free (parser->cur_file);
1860 	}
1861 	parser->cur_file = NULL;
1862 	len = st.st_size;
1863 	ret = ucl_parser_add_chunk_priority (parser, buf, len, priority);
1864 
1865 	if (len > 0) {
1866 		ucl_munmap (buf, len);
1867 	}
1868 
1869 	return ret;
1870 }
1871 
1872 bool
1873 ucl_parser_add_fd (struct ucl_parser *parser, int fd)
1874 {
1875 	if (parser == NULL) {
1876 		return false;
1877 	}
1878 
1879 	return ucl_parser_add_fd_priority(parser, fd, parser->default_priority);
1880 }
1881 
1882 size_t
1883 ucl_strlcpy (char *dst, const char *src, size_t siz)
1884 {
1885 	char *d = dst;
1886 	const char *s = src;
1887 	size_t n = siz;
1888 
1889 	/* Copy as many bytes as will fit */
1890 	if (n != 0) {
1891 		while (--n != 0) {
1892 			if ((*d++ = *s++) == '\0') {
1893 				break;
1894 			}
1895 		}
1896 	}
1897 
1898 	if (n == 0 && siz != 0) {
1899 		*d = '\0';
1900 	}
1901 
1902 	return (s - src - 1);    /* count does not include NUL */
1903 }
1904 
1905 size_t
1906 ucl_strlcpy_unsafe (char *dst, const char *src, size_t siz)
1907 {
1908 	memcpy (dst, src, siz - 1);
1909 	dst[siz - 1] = '\0';
1910 
1911 	return siz - 1;
1912 }
1913 
1914 size_t
1915 ucl_strlcpy_tolower (char *dst, const char *src, size_t siz)
1916 {
1917 	char *d = dst;
1918 	const char *s = src;
1919 	size_t n = siz;
1920 
1921 	/* Copy as many bytes as will fit */
1922 	if (n != 0) {
1923 		while (--n != 0) {
1924 			if ((*d++ = tolower (*s++)) == '\0') {
1925 				break;
1926 			}
1927 		}
1928 	}
1929 
1930 	if (n == 0 && siz != 0) {
1931 		*d = '\0';
1932 	}
1933 
1934 	return (s - src);    /* count does not include NUL */
1935 }
1936 
1937 /*
1938  * Find the first occurrence of find in s
1939  */
1940 char *
1941 ucl_strnstr (const char *s, const char *find, int len)
1942 {
1943 	char c, sc;
1944 	int mlen;
1945 
1946 	if ((c = *find++) != 0) {
1947 		mlen = strlen (find);
1948 		do {
1949 			do {
1950 				if ((sc = *s++) == 0 || len-- == 0)
1951 					return (NULL);
1952 			} while (sc != c);
1953 		} while (strncmp (s, find, mlen) != 0);
1954 		s--;
1955 	}
1956 	return ((char *)s);
1957 }
1958 
1959 /*
1960  * Find the first occurrence of find in s, ignore case.
1961  */
1962 char *
1963 ucl_strncasestr (const char *s, const char *find, int len)
1964 {
1965 	char c, sc;
1966 	int mlen;
1967 
1968 	if ((c = *find++) != 0) {
1969 		c = tolower (c);
1970 		mlen = strlen (find);
1971 		do {
1972 			do {
1973 				if ((sc = *s++) == 0 || len-- == 0)
1974 					return (NULL);
1975 			} while (tolower (sc) != c);
1976 		} while (strncasecmp (s, find, mlen) != 0);
1977 		s--;
1978 	}
1979 	return ((char *)s);
1980 }
1981 
1982 ucl_object_t *
1983 ucl_object_fromstring_common (const char *str, size_t len, enum ucl_string_flags flags)
1984 {
1985 	ucl_object_t *obj;
1986 	const char *start, *end, *p, *pos;
1987 	char *dst, *d;
1988 	size_t escaped_len;
1989 
1990 	if (str == NULL) {
1991 		return NULL;
1992 	}
1993 
1994 	obj = ucl_object_new ();
1995 	if (obj) {
1996 		if (len == 0) {
1997 			len = strlen (str);
1998 		}
1999 		if (flags & UCL_STRING_TRIM) {
2000 			/* Skip leading spaces */
2001 			for (start = str; (size_t)(start - str) < len; start ++) {
2002 				if (!ucl_test_character (*start, UCL_CHARACTER_WHITESPACE_UNSAFE)) {
2003 					break;
2004 				}
2005 			}
2006 			/* Skip trailing spaces */
2007 			for (end = str + len - 1; end > start; end --) {
2008 				if (!ucl_test_character (*end, UCL_CHARACTER_WHITESPACE_UNSAFE)) {
2009 					break;
2010 				}
2011 			}
2012 			end ++;
2013 		}
2014 		else {
2015 			start = str;
2016 			end = str + len;
2017 		}
2018 
2019 		obj->type = UCL_STRING;
2020 		if (flags & UCL_STRING_ESCAPE) {
2021 			for (p = start, escaped_len = 0; p < end; p ++, escaped_len ++) {
2022 				if (ucl_test_character (*p, UCL_CHARACTER_JSON_UNSAFE)) {
2023 					escaped_len ++;
2024 				}
2025 			}
2026 			dst = malloc (escaped_len + 1);
2027 			if (dst != NULL) {
2028 				for (p = start, d = dst; p < end; p ++, d ++) {
2029 					if (ucl_test_character (*p, UCL_CHARACTER_JSON_UNSAFE)) {
2030 						switch (*p) {
2031 						case '\n':
2032 							*d++ = '\\';
2033 							*d = 'n';
2034 							break;
2035 						case '\r':
2036 							*d++ = '\\';
2037 							*d = 'r';
2038 							break;
2039 						case '\b':
2040 							*d++ = '\\';
2041 							*d = 'b';
2042 							break;
2043 						case '\t':
2044 							*d++ = '\\';
2045 							*d = 't';
2046 							break;
2047 						case '\f':
2048 							*d++ = '\\';
2049 							*d = 'f';
2050 							break;
2051 						case '\\':
2052 							*d++ = '\\';
2053 							*d = '\\';
2054 							break;
2055 						case '"':
2056 							*d++ = '\\';
2057 							*d = '"';
2058 							break;
2059 						}
2060 					}
2061 					else {
2062 						*d = *p;
2063 					}
2064 				}
2065 				*d = '\0';
2066 				obj->value.sv = dst;
2067 				obj->trash_stack[UCL_TRASH_VALUE] = dst;
2068 				obj->len = escaped_len;
2069 			}
2070 		}
2071 		else {
2072 			dst = malloc (end - start + 1);
2073 			if (dst != NULL) {
2074 				ucl_strlcpy_unsafe (dst, start, end - start + 1);
2075 				obj->value.sv = dst;
2076 				obj->trash_stack[UCL_TRASH_VALUE] = dst;
2077 				obj->len = end - start;
2078 			}
2079 		}
2080 		if ((flags & UCL_STRING_PARSE) && dst != NULL) {
2081 			/* Parse what we have */
2082 			if (flags & UCL_STRING_PARSE_BOOLEAN) {
2083 				if (!ucl_maybe_parse_boolean (obj, dst, obj->len) && (flags & UCL_STRING_PARSE_NUMBER)) {
2084 					ucl_maybe_parse_number (obj, dst, dst + obj->len, &pos,
2085 							flags & UCL_STRING_PARSE_DOUBLE,
2086 							flags & UCL_STRING_PARSE_BYTES,
2087 							flags & UCL_STRING_PARSE_TIME);
2088 				}
2089 			}
2090 			else {
2091 				ucl_maybe_parse_number (obj, dst, dst + obj->len, &pos,
2092 						flags & UCL_STRING_PARSE_DOUBLE,
2093 						flags & UCL_STRING_PARSE_BYTES,
2094 						flags & UCL_STRING_PARSE_TIME);
2095 			}
2096 		}
2097 	}
2098 
2099 	return obj;
2100 }
2101 
2102 static bool
2103 ucl_object_insert_key_common (ucl_object_t *top, ucl_object_t *elt,
2104 		const char *key, size_t keylen, bool copy_key, bool merge, bool replace)
2105 {
2106 	ucl_object_t *found, *tmp;
2107 	const ucl_object_t *cur;
2108 	ucl_object_iter_t it = NULL;
2109 	const char *p;
2110 	int ret = true;
2111 
2112 	if (elt == NULL || key == NULL) {
2113 		return false;
2114 	}
2115 
2116 	if (top == NULL) {
2117 		return false;
2118 	}
2119 
2120 	if (top->type != UCL_OBJECT) {
2121 		/* It is possible to convert NULL type to an object */
2122 		if (top->type == UCL_NULL) {
2123 			top->type = UCL_OBJECT;
2124 		}
2125 		else {
2126 			/* Refuse converting of other object types */
2127 			return false;
2128 		}
2129 	}
2130 
2131 	if (top->value.ov == NULL) {
2132 		top->value.ov = ucl_hash_create (false);
2133 	}
2134 
2135 	if (keylen == 0) {
2136 		keylen = strlen (key);
2137 	}
2138 
2139 	for (p = key; p < key + keylen; p ++) {
2140 		if (ucl_test_character (*p, UCL_CHARACTER_UCL_UNSAFE)) {
2141 			elt->flags |= UCL_OBJECT_NEED_KEY_ESCAPE;
2142 			break;
2143 		}
2144 	}
2145 
2146 	/* workaround for some use cases */
2147 	if (elt->trash_stack[UCL_TRASH_KEY] != NULL &&
2148 			key != (const char *)elt->trash_stack[UCL_TRASH_KEY]) {
2149 		/* Remove copied key */
2150 		free (elt->trash_stack[UCL_TRASH_KEY]);
2151 		elt->trash_stack[UCL_TRASH_KEY] = NULL;
2152 		elt->flags &= ~UCL_OBJECT_ALLOCATED_KEY;
2153 	}
2154 
2155 	elt->key = key;
2156 	elt->keylen = keylen;
2157 
2158 	if (copy_key) {
2159 		ucl_copy_key_trash (elt);
2160 	}
2161 
2162 	found = __DECONST (ucl_object_t *, ucl_hash_search_obj (top->value.ov, elt));
2163 
2164 	if (found == NULL) {
2165 		top->value.ov = ucl_hash_insert_object (top->value.ov, elt, false);
2166 		top->len ++;
2167 		if (replace) {
2168 			ret = false;
2169 		}
2170 	}
2171 	else {
2172 		if (replace) {
2173 			ucl_hash_replace (top->value.ov, found, elt);
2174 			ucl_object_unref (found);
2175 		}
2176 		else if (merge) {
2177 			if (found->type != UCL_OBJECT && elt->type == UCL_OBJECT) {
2178 				/* Insert old elt to new one */
2179 				ucl_object_insert_key_common (elt, found, found->key,
2180 						found->keylen, copy_key, false, false);
2181 				ucl_hash_delete (top->value.ov, found);
2182 				top->value.ov = ucl_hash_insert_object (top->value.ov, elt, false);
2183 			}
2184 			else if (found->type == UCL_OBJECT && elt->type != UCL_OBJECT) {
2185 				/* Insert new to old */
2186 				ucl_object_insert_key_common (found, elt, elt->key,
2187 						elt->keylen, copy_key, false, false);
2188 			}
2189 			else if (found->type == UCL_OBJECT && elt->type == UCL_OBJECT) {
2190 				/* Mix two hashes */
2191 				while ((cur = ucl_object_iterate (elt, &it, true)) != NULL) {
2192 					tmp = ucl_object_ref (cur);
2193 					ucl_object_insert_key_common (found, tmp, cur->key,
2194 							cur->keylen, copy_key, false, false);
2195 				}
2196 				ucl_object_unref (elt);
2197 			}
2198 			else {
2199 				/* Just make a list of scalars */
2200 				DL_APPEND (found, elt);
2201 			}
2202 		}
2203 		else {
2204 			DL_APPEND (found, elt);
2205 		}
2206 	}
2207 
2208 	return ret;
2209 }
2210 
2211 bool
2212 ucl_object_delete_keyl (ucl_object_t *top, const char *key, size_t keylen)
2213 {
2214 	ucl_object_t *found;
2215 
2216 	if (top == NULL || key == NULL) {
2217 		return false;
2218 	}
2219 
2220 	found = __DECONST (ucl_object_t *, ucl_object_lookup_len (top, key, keylen));
2221 
2222 	if (found == NULL) {
2223 		return false;
2224 	}
2225 
2226 	ucl_hash_delete (top->value.ov, found);
2227 	ucl_object_unref (found);
2228 	top->len --;
2229 
2230 	return true;
2231 }
2232 
2233 bool
2234 ucl_object_delete_key (ucl_object_t *top, const char *key)
2235 {
2236 	return ucl_object_delete_keyl (top, key, strlen (key));
2237 }
2238 
2239 ucl_object_t*
2240 ucl_object_pop_keyl (ucl_object_t *top, const char *key, size_t keylen)
2241 {
2242 	const ucl_object_t *found;
2243 
2244 	if (top == NULL || key == NULL) {
2245 		return false;
2246 	}
2247 	found = ucl_object_lookup_len (top, key, keylen);
2248 
2249 	if (found == NULL) {
2250 		return NULL;
2251 	}
2252 	ucl_hash_delete (top->value.ov, found);
2253 	top->len --;
2254 
2255 	return __DECONST (ucl_object_t *, found);
2256 }
2257 
2258 ucl_object_t*
2259 ucl_object_pop_key (ucl_object_t *top, const char *key)
2260 {
2261 	return ucl_object_pop_keyl (top, key, strlen (key));
2262 }
2263 
2264 bool
2265 ucl_object_insert_key (ucl_object_t *top, ucl_object_t *elt,
2266 		const char *key, size_t keylen, bool copy_key)
2267 {
2268 	return ucl_object_insert_key_common (top, elt, key, keylen, copy_key, false, false);
2269 }
2270 
2271 bool
2272 ucl_object_insert_key_merged (ucl_object_t *top, ucl_object_t *elt,
2273 		const char *key, size_t keylen, bool copy_key)
2274 {
2275 	return ucl_object_insert_key_common (top, elt, key, keylen, copy_key, true, false);
2276 }
2277 
2278 bool
2279 ucl_object_replace_key (ucl_object_t *top, ucl_object_t *elt,
2280 		const char *key, size_t keylen, bool copy_key)
2281 {
2282 	return ucl_object_insert_key_common (top, elt, key, keylen, copy_key, false, true);
2283 }
2284 
2285 bool
2286 ucl_object_merge (ucl_object_t *top, ucl_object_t *elt, bool copy)
2287 {
2288 	ucl_object_t *cur = NULL, *cp = NULL, *found = NULL;
2289 	ucl_object_iter_t iter = NULL;
2290 
2291 	if (top == NULL || top->type != UCL_OBJECT || elt == NULL || elt->type != UCL_OBJECT) {
2292 		return false;
2293 	}
2294 
2295 	/* Mix two hashes */
2296 	while ((cur = (ucl_object_t*)ucl_hash_iterate (elt->value.ov, &iter))) {
2297 		if (copy) {
2298 			cp = ucl_object_copy (cur);
2299 		}
2300 		else {
2301 			cp = ucl_object_ref (cur);
2302 		}
2303 		found = __DECONST(ucl_object_t *, ucl_hash_search (top->value.ov, cp->key, cp->keylen));
2304 		if (found == NULL) {
2305 			/* The key does not exist */
2306 			top->value.ov = ucl_hash_insert_object (top->value.ov, cp, false);
2307 			top->len ++;
2308 		}
2309 		else {
2310 			/* The key already exists, replace it */
2311 			ucl_hash_replace (top->value.ov, found, cp);
2312 			ucl_object_unref (found);
2313 		}
2314 	}
2315 
2316 	return true;
2317 }
2318 
2319 const ucl_object_t *
2320 ucl_object_lookup_len (const ucl_object_t *obj, const char *key, size_t klen)
2321 {
2322 	const ucl_object_t *ret;
2323 	ucl_object_t srch;
2324 
2325 	if (obj == NULL || obj->type != UCL_OBJECT || key == NULL) {
2326 		return NULL;
2327 	}
2328 
2329 	srch.key = key;
2330 	srch.keylen = klen;
2331 	ret = ucl_hash_search_obj (obj->value.ov, &srch);
2332 
2333 	return ret;
2334 }
2335 
2336 const ucl_object_t *
2337 ucl_object_lookup (const ucl_object_t *obj, const char *key)
2338 {
2339 	if (key == NULL) {
2340 		return NULL;
2341 	}
2342 
2343 	return ucl_object_lookup_len (obj, key, strlen (key));
2344 }
2345 
2346 const ucl_object_t*
2347 ucl_object_lookup_any (const ucl_object_t *obj,
2348 		const char *key, ...)
2349 {
2350 	va_list ap;
2351 	const ucl_object_t *ret = NULL;
2352 	const char *nk = NULL;
2353 
2354 	if (obj == NULL || key == NULL) {
2355 		return NULL;
2356 	}
2357 
2358 	ret = ucl_object_lookup_len (obj, key, strlen (key));
2359 
2360 	if (ret == NULL) {
2361 		va_start (ap, key);
2362 
2363 		while (ret == NULL) {
2364 			nk = va_arg (ap, const char *);
2365 
2366 			if (nk == NULL) {
2367 				break;
2368 			}
2369 			else {
2370 				ret = ucl_object_lookup_len (obj, nk, strlen (nk));
2371 			}
2372 		}
2373 
2374 		va_end (ap);
2375 	}
2376 
2377 	return ret;
2378 }
2379 
2380 const ucl_object_t*
2381 ucl_object_iterate (const ucl_object_t *obj, ucl_object_iter_t *iter, bool expand_values)
2382 {
2383 	const ucl_object_t *elt = NULL;
2384 
2385 	if (obj == NULL || iter == NULL) {
2386 		return NULL;
2387 	}
2388 
2389 	if (expand_values) {
2390 		switch (obj->type) {
2391 		case UCL_OBJECT:
2392 			return (const ucl_object_t*)ucl_hash_iterate (obj->value.ov, iter);
2393 			break;
2394 		case UCL_ARRAY: {
2395 			unsigned int idx;
2396 			UCL_ARRAY_GET (vec, obj);
2397 			idx = (unsigned int)(uintptr_t)(*iter);
2398 
2399 			if (vec != NULL) {
2400 				while (idx < kv_size (*vec)) {
2401 					if ((elt = kv_A (*vec, idx)) != NULL) {
2402 						idx ++;
2403 						break;
2404 					}
2405 					idx ++;
2406 				}
2407 				*iter = (void *)(uintptr_t)idx;
2408 			}
2409 
2410 			return elt;
2411 			break;
2412 		}
2413 		default:
2414 			/* Go to linear iteration */
2415 			break;
2416 		}
2417 	}
2418 	/* Treat everything as a linear list */
2419 	elt = *iter;
2420 	if (elt == NULL) {
2421 		elt = obj;
2422 	}
2423 	else if (elt == obj) {
2424 		return NULL;
2425 	}
2426 	*iter = __DECONST (void *, elt->next ? elt->next : obj);
2427 	return elt;
2428 
2429 	/* Not reached */
2430 	return NULL;
2431 }
2432 
2433 const char safe_iter_magic[4] = {'u', 'i', 't', 'e'};
2434 struct ucl_object_safe_iter {
2435 	char magic[4]; /* safety check */
2436 	const ucl_object_t *impl_it; /* implicit object iteration */
2437 	ucl_object_iter_t expl_it; /* explicit iteration */
2438 };
2439 
2440 #define UCL_SAFE_ITER(ptr) (struct ucl_object_safe_iter *)(ptr)
2441 #define UCL_SAFE_ITER_CHECK(it) do { \
2442 	assert (it != NULL); \
2443 	assert (memcmp (it->magic, safe_iter_magic, sizeof (it->magic)) == 0); \
2444  } while (0)
2445 
2446 ucl_object_iter_t
2447 ucl_object_iterate_new (const ucl_object_t *obj)
2448 {
2449 	struct ucl_object_safe_iter *it;
2450 
2451 	it = UCL_ALLOC (sizeof (*it));
2452 	if (it != NULL) {
2453 		memcpy (it->magic, safe_iter_magic, sizeof (it->magic));
2454 		it->expl_it = NULL;
2455 		it->impl_it = obj;
2456 	}
2457 
2458 	return (ucl_object_iter_t)it;
2459 }
2460 
2461 
2462 ucl_object_iter_t
2463 ucl_object_iterate_reset (ucl_object_iter_t it, const ucl_object_t *obj)
2464 {
2465 	struct ucl_object_safe_iter *rit = UCL_SAFE_ITER (it);
2466 
2467 	UCL_SAFE_ITER_CHECK (rit);
2468 
2469 	rit->impl_it = obj;
2470 	rit->expl_it = NULL;
2471 
2472 	return it;
2473 }
2474 
2475 const ucl_object_t*
2476 ucl_object_iterate_safe (ucl_object_iter_t it, bool expand_values)
2477 {
2478 	struct ucl_object_safe_iter *rit = UCL_SAFE_ITER (it);
2479 	const ucl_object_t *ret = NULL;
2480 
2481 	UCL_SAFE_ITER_CHECK (rit);
2482 
2483 	if (rit->impl_it == NULL) {
2484 		return NULL;
2485 	}
2486 
2487 	if (rit->impl_it->type == UCL_OBJECT || rit->impl_it->type == UCL_ARRAY) {
2488 		ret = ucl_object_iterate (rit->impl_it, &rit->expl_it, true);
2489 
2490 		if (ret == NULL) {
2491 			/* Need to switch to another implicit object in chain */
2492 			rit->impl_it = rit->impl_it->next;
2493 			rit->expl_it = NULL;
2494 			return ucl_object_iterate_safe (it, expand_values);
2495 		}
2496 	}
2497 	else {
2498 		/* Just iterate over the implicit array */
2499 		ret = rit->impl_it;
2500 		rit->impl_it = rit->impl_it->next;
2501 		if (expand_values) {
2502 			/* We flatten objects if need to expand values */
2503 			if (ret->type == UCL_OBJECT || ret->type == UCL_ARRAY) {
2504 				return ucl_object_iterate_safe (it, expand_values);
2505 			}
2506 		}
2507 	}
2508 
2509 	return ret;
2510 }
2511 
2512 void
2513 ucl_object_iterate_free (ucl_object_iter_t it)
2514 {
2515 	struct ucl_object_safe_iter *rit = UCL_SAFE_ITER (it);
2516 
2517 	UCL_SAFE_ITER_CHECK (rit);
2518 
2519 	UCL_FREE (sizeof (*rit), it);
2520 }
2521 
2522 const ucl_object_t *
2523 ucl_object_lookup_path (const ucl_object_t *top, const char *path_in) {
2524 	return ucl_object_lookup_path_char (top, path_in, '.');
2525 }
2526 
2527 
2528 const ucl_object_t *
2529 ucl_object_lookup_path_char (const ucl_object_t *top, const char *path_in, const char sep) {
2530 	const ucl_object_t *o = NULL, *found;
2531 	const char *p, *c;
2532 	char *err_str;
2533 	unsigned index;
2534 
2535 	if (path_in == NULL || top == NULL) {
2536 		return NULL;
2537 	}
2538 
2539 	found = NULL;
2540 	p = path_in;
2541 
2542 	/* Skip leading dots */
2543 	while (*p == sep) {
2544 		p ++;
2545 	}
2546 
2547 	c = p;
2548 	while (*p != '\0') {
2549 		p ++;
2550 		if (*p == sep || *p == '\0') {
2551 			if (p > c) {
2552 				switch (top->type) {
2553 				case UCL_ARRAY:
2554 					/* Key should be an int */
2555 					index = strtoul (c, &err_str, 10);
2556 					if (err_str != NULL && (*err_str != sep && *err_str != '\0')) {
2557 						return NULL;
2558 					}
2559 					o = ucl_array_find_index (top, index);
2560 					break;
2561 				default:
2562 					o = ucl_object_lookup_len (top, c, p - c);
2563 					break;
2564 				}
2565 				if (o == NULL) {
2566 					return NULL;
2567 				}
2568 				top = o;
2569 			}
2570 			if (*p != '\0') {
2571 				c = p + 1;
2572 			}
2573 		}
2574 	}
2575 	found = o;
2576 
2577 	return found;
2578 }
2579 
2580 
2581 ucl_object_t *
2582 ucl_object_new (void)
2583 {
2584 	return ucl_object_typed_new (UCL_NULL);
2585 }
2586 
2587 ucl_object_t *
2588 ucl_object_typed_new (ucl_type_t type)
2589 {
2590 	return ucl_object_new_full (type, 0);
2591 }
2592 
2593 ucl_object_t *
2594 ucl_object_new_full (ucl_type_t type, unsigned priority)
2595 {
2596 	ucl_object_t *new;
2597 
2598 	if (type != UCL_USERDATA) {
2599 		new = UCL_ALLOC (sizeof (ucl_object_t));
2600 		if (new != NULL) {
2601 			memset (new, 0, sizeof (ucl_object_t));
2602 			new->ref = 1;
2603 			new->type = (type <= UCL_NULL ? type : UCL_NULL);
2604 			new->next = NULL;
2605 			new->prev = new;
2606 			ucl_object_set_priority (new, priority);
2607 
2608 			if (type == UCL_ARRAY) {
2609 				new->value.av = UCL_ALLOC (sizeof (ucl_array_t));
2610 				if (new->value.av) {
2611 					memset (new->value.av, 0, sizeof (ucl_array_t));
2612 					UCL_ARRAY_GET (vec, new);
2613 
2614 					/* Preallocate some space for arrays */
2615 					kv_resize (ucl_object_t *, *vec, 8);
2616 				}
2617 			}
2618 		}
2619 	}
2620 	else {
2621 		new = ucl_object_new_userdata (NULL, NULL, NULL);
2622 		ucl_object_set_priority (new, priority);
2623 	}
2624 
2625 	return new;
2626 }
2627 
2628 ucl_object_t*
2629 ucl_object_new_userdata (ucl_userdata_dtor dtor,
2630 		ucl_userdata_emitter emitter,
2631 		void *ptr)
2632 {
2633 	struct ucl_object_userdata *new;
2634 	size_t nsize = sizeof (*new);
2635 
2636 	new = UCL_ALLOC (nsize);
2637 	if (new != NULL) {
2638 		memset (new, 0, nsize);
2639 		new->obj.ref = 1;
2640 		new->obj.type = UCL_USERDATA;
2641 		new->obj.next = NULL;
2642 		new->obj.prev = (ucl_object_t *)new;
2643 		new->dtor = dtor;
2644 		new->emitter = emitter;
2645 		new->obj.value.ud = ptr;
2646 	}
2647 
2648 	return (ucl_object_t *)new;
2649 }
2650 
2651 ucl_type_t
2652 ucl_object_type (const ucl_object_t *obj)
2653 {
2654 	if (obj == NULL) {
2655 		return UCL_NULL;
2656 	}
2657 
2658 	return obj->type;
2659 }
2660 
2661 ucl_object_t*
2662 ucl_object_fromstring (const char *str)
2663 {
2664 	return ucl_object_fromstring_common (str, 0, UCL_STRING_ESCAPE);
2665 }
2666 
2667 ucl_object_t *
2668 ucl_object_fromlstring (const char *str, size_t len)
2669 {
2670 	return ucl_object_fromstring_common (str, len, UCL_STRING_ESCAPE);
2671 }
2672 
2673 ucl_object_t *
2674 ucl_object_fromint (int64_t iv)
2675 {
2676 	ucl_object_t *obj;
2677 
2678 	obj = ucl_object_new ();
2679 	if (obj != NULL) {
2680 		obj->type = UCL_INT;
2681 		obj->value.iv = iv;
2682 	}
2683 
2684 	return obj;
2685 }
2686 
2687 ucl_object_t *
2688 ucl_object_fromdouble (double dv)
2689 {
2690 	ucl_object_t *obj;
2691 
2692 	obj = ucl_object_new ();
2693 	if (obj != NULL) {
2694 		obj->type = UCL_FLOAT;
2695 		obj->value.dv = dv;
2696 	}
2697 
2698 	return obj;
2699 }
2700 
2701 ucl_object_t*
2702 ucl_object_frombool (bool bv)
2703 {
2704 	ucl_object_t *obj;
2705 
2706 	obj = ucl_object_new ();
2707 	if (obj != NULL) {
2708 		obj->type = UCL_BOOLEAN;
2709 		obj->value.iv = bv;
2710 	}
2711 
2712 	return obj;
2713 }
2714 
2715 bool
2716 ucl_array_append (ucl_object_t *top, ucl_object_t *elt)
2717 {
2718 	UCL_ARRAY_GET (vec, top);
2719 
2720 	if (elt == NULL || top == NULL) {
2721 		return false;
2722 	}
2723 
2724 	if (vec == NULL) {
2725 		vec = UCL_ALLOC (sizeof (*vec));
2726 
2727 		if (vec == NULL) {
2728 			return false;
2729 		}
2730 
2731 		kv_init (*vec);
2732 		top->value.av = (void *)vec;
2733 	}
2734 
2735 	kv_push (ucl_object_t *, *vec, elt);
2736 
2737 	top->len ++;
2738 
2739 	return true;
2740 }
2741 
2742 bool
2743 ucl_array_prepend (ucl_object_t *top, ucl_object_t *elt)
2744 {
2745 	UCL_ARRAY_GET (vec, top);
2746 
2747 	if (elt == NULL || top == NULL) {
2748 		return false;
2749 	}
2750 
2751 	if (vec == NULL) {
2752 		vec = UCL_ALLOC (sizeof (*vec));
2753 		kv_init (*vec);
2754 		top->value.av = (void *)vec;
2755 		kv_push (ucl_object_t *, *vec, elt);
2756 	}
2757 	else {
2758 		/* Slow O(n) algorithm */
2759 		kv_prepend (ucl_object_t *, *vec, elt);
2760 	}
2761 
2762 	top->len ++;
2763 
2764 	return true;
2765 }
2766 
2767 bool
2768 ucl_array_merge (ucl_object_t *top, ucl_object_t *elt, bool copy)
2769 {
2770 	unsigned i;
2771 	ucl_object_t *cp = NULL;
2772 	ucl_object_t **obj;
2773 
2774 	if (elt == NULL || top == NULL || top->type != UCL_ARRAY || elt->type != UCL_ARRAY) {
2775 		return false;
2776 	}
2777 
2778 	if (copy) {
2779 		cp = ucl_object_copy (elt);
2780 	}
2781 	else {
2782 		cp = ucl_object_ref (elt);
2783 	}
2784 
2785 	UCL_ARRAY_GET (v1, top);
2786 	UCL_ARRAY_GET (v2, cp);
2787 
2788 	if (v1 && v2) {
2789 		kv_concat (ucl_object_t *, *v1, *v2);
2790 
2791 		for (i = v2->n; i < v1->n; i ++) {
2792 			obj = &kv_A (*v1, i);
2793 			if (*obj == NULL) {
2794 				continue;
2795 			}
2796 			top->len ++;
2797 		}
2798 	}
2799 
2800 	return true;
2801 }
2802 
2803 ucl_object_t *
2804 ucl_array_delete (ucl_object_t *top, ucl_object_t *elt)
2805 {
2806 	UCL_ARRAY_GET (vec, top);
2807 	ucl_object_t *ret = NULL;
2808 	unsigned i;
2809 
2810 	if (vec == NULL) {
2811 		return NULL;
2812 	}
2813 
2814 	for (i = 0; i < vec->n; i ++) {
2815 		if (kv_A (*vec, i) == elt) {
2816 			kv_del (ucl_object_t *, *vec, i);
2817 			ret = elt;
2818 			top->len --;
2819 			break;
2820 		}
2821 	}
2822 
2823 	return ret;
2824 }
2825 
2826 const ucl_object_t *
2827 ucl_array_head (const ucl_object_t *top)
2828 {
2829 	UCL_ARRAY_GET (vec, top);
2830 
2831 	if (vec == NULL || top == NULL || top->type != UCL_ARRAY ||
2832 			top->value.av == NULL) {
2833 		return NULL;
2834 	}
2835 
2836 	return (vec->n > 0 ? vec->a[0] : NULL);
2837 }
2838 
2839 const ucl_object_t *
2840 ucl_array_tail (const ucl_object_t *top)
2841 {
2842 	UCL_ARRAY_GET (vec, top);
2843 
2844 	if (top == NULL || top->type != UCL_ARRAY || top->value.av == NULL) {
2845 		return NULL;
2846 	}
2847 
2848 	return (vec->n > 0 ? vec->a[vec->n - 1] : NULL);
2849 }
2850 
2851 ucl_object_t *
2852 ucl_array_pop_last (ucl_object_t *top)
2853 {
2854 	UCL_ARRAY_GET (vec, top);
2855 	ucl_object_t **obj, *ret = NULL;
2856 
2857 	if (vec != NULL && vec->n > 0) {
2858 		obj = &kv_A (*vec, vec->n - 1);
2859 		ret = *obj;
2860 		kv_del (ucl_object_t *, *vec, vec->n - 1);
2861 		top->len --;
2862 	}
2863 
2864 	return ret;
2865 }
2866 
2867 ucl_object_t *
2868 ucl_array_pop_first (ucl_object_t *top)
2869 {
2870 	UCL_ARRAY_GET (vec, top);
2871 	ucl_object_t **obj, *ret = NULL;
2872 
2873 	if (vec != NULL && vec->n > 0) {
2874 		obj = &kv_A (*vec, 0);
2875 		ret = *obj;
2876 		kv_del (ucl_object_t *, *vec, 0);
2877 		top->len --;
2878 	}
2879 
2880 	return ret;
2881 }
2882 
2883 const ucl_object_t *
2884 ucl_array_find_index (const ucl_object_t *top, unsigned int index)
2885 {
2886 	UCL_ARRAY_GET (vec, top);
2887 
2888 	if (vec != NULL && vec->n > 0 && index < vec->n) {
2889 		return kv_A (*vec, index);
2890 	}
2891 
2892 	return NULL;
2893 }
2894 
2895 unsigned int
2896 ucl_array_index_of (ucl_object_t *top, ucl_object_t *elt)
2897 {
2898 	UCL_ARRAY_GET (vec, top);
2899 	unsigned i;
2900 
2901 	if (vec == NULL) {
2902 		return (unsigned int)(-1);
2903 	}
2904 
2905 	for (i = 0; i < vec->n; i ++) {
2906 		if (kv_A (*vec, i) == elt) {
2907 			return i;
2908 		}
2909 	}
2910 
2911 	return (unsigned int)(-1);
2912 }
2913 
2914 ucl_object_t *
2915 ucl_array_replace_index (ucl_object_t *top, ucl_object_t *elt,
2916 	unsigned int index)
2917 {
2918 	UCL_ARRAY_GET (vec, top);
2919 	ucl_object_t *ret = NULL;
2920 
2921 	if (vec != NULL && vec->n > 0 && index < vec->n) {
2922 		ret = kv_A (*vec, index);
2923 		kv_A (*vec, index) = elt;
2924 	}
2925 
2926 	return ret;
2927 }
2928 
2929 ucl_object_t *
2930 ucl_elt_append (ucl_object_t *head, ucl_object_t *elt)
2931 {
2932 
2933 	if (head == NULL) {
2934 		elt->next = NULL;
2935 		elt->prev = elt;
2936 		head = elt;
2937 	}
2938 	else {
2939 		elt->prev = head->prev;
2940 		head->prev->next = elt;
2941 		head->prev = elt;
2942 		elt->next = NULL;
2943 	}
2944 
2945 	return head;
2946 }
2947 
2948 bool
2949 ucl_object_todouble_safe (const ucl_object_t *obj, double *target)
2950 {
2951 	if (obj == NULL || target == NULL) {
2952 		return false;
2953 	}
2954 	switch (obj->type) {
2955 	case UCL_INT:
2956 		*target = obj->value.iv; /* Probaly could cause overflow */
2957 		break;
2958 	case UCL_FLOAT:
2959 	case UCL_TIME:
2960 		*target = obj->value.dv;
2961 		break;
2962 	default:
2963 		return false;
2964 	}
2965 
2966 	return true;
2967 }
2968 
2969 double
2970 ucl_object_todouble (const ucl_object_t *obj)
2971 {
2972 	double result = 0.;
2973 
2974 	ucl_object_todouble_safe (obj, &result);
2975 	return result;
2976 }
2977 
2978 bool
2979 ucl_object_toint_safe (const ucl_object_t *obj, int64_t *target)
2980 {
2981 	if (obj == NULL || target == NULL) {
2982 		return false;
2983 	}
2984 	switch (obj->type) {
2985 	case UCL_INT:
2986 		*target = obj->value.iv;
2987 		break;
2988 	case UCL_FLOAT:
2989 	case UCL_TIME:
2990 		*target = obj->value.dv; /* Loosing of decimal points */
2991 		break;
2992 	default:
2993 		return false;
2994 	}
2995 
2996 	return true;
2997 }
2998 
2999 int64_t
3000 ucl_object_toint (const ucl_object_t *obj)
3001 {
3002 	int64_t result = 0;
3003 
3004 	ucl_object_toint_safe (obj, &result);
3005 	return result;
3006 }
3007 
3008 bool
3009 ucl_object_toboolean_safe (const ucl_object_t *obj, bool *target)
3010 {
3011 	if (obj == NULL || target == NULL) {
3012 		return false;
3013 	}
3014 	switch (obj->type) {
3015 	case UCL_BOOLEAN:
3016 		*target = (obj->value.iv == true);
3017 		break;
3018 	default:
3019 		return false;
3020 	}
3021 
3022 	return true;
3023 }
3024 
3025 bool
3026 ucl_object_toboolean (const ucl_object_t *obj)
3027 {
3028 	bool result = false;
3029 
3030 	ucl_object_toboolean_safe (obj, &result);
3031 	return result;
3032 }
3033 
3034 bool
3035 ucl_object_tostring_safe (const ucl_object_t *obj, const char **target)
3036 {
3037 	if (obj == NULL || target == NULL) {
3038 		return false;
3039 	}
3040 
3041 	switch (obj->type) {
3042 	case UCL_STRING:
3043 		if (!(obj->flags & UCL_OBJECT_BINARY)) {
3044 			*target = ucl_copy_value_trash (obj);
3045 		}
3046 		break;
3047 	default:
3048 		return false;
3049 	}
3050 
3051 	return true;
3052 }
3053 
3054 const char *
3055 ucl_object_tostring (const ucl_object_t *obj)
3056 {
3057 	const char *result = NULL;
3058 
3059 	ucl_object_tostring_safe (obj, &result);
3060 	return result;
3061 }
3062 
3063 const char *
3064 ucl_object_tostring_forced (const ucl_object_t *obj)
3065 {
3066 	/* TODO: For binary strings we might encode string here */
3067 	if (!(obj->flags & UCL_OBJECT_BINARY)) {
3068 		return ucl_copy_value_trash (obj);
3069 	}
3070 
3071 	return NULL;
3072 }
3073 
3074 bool
3075 ucl_object_tolstring_safe (const ucl_object_t *obj, const char **target, size_t *tlen)
3076 {
3077 	if (obj == NULL || target == NULL) {
3078 		return false;
3079 	}
3080 	switch (obj->type) {
3081 	case UCL_STRING:
3082 		*target = obj->value.sv;
3083 		if (tlen != NULL) {
3084 			*tlen = obj->len;
3085 		}
3086 		break;
3087 	default:
3088 		return false;
3089 	}
3090 
3091 	return true;
3092 }
3093 
3094 const char *
3095 ucl_object_tolstring (const ucl_object_t *obj, size_t *tlen)
3096 {
3097 	const char *result = NULL;
3098 
3099 	ucl_object_tolstring_safe (obj, &result, tlen);
3100 	return result;
3101 }
3102 
3103 const char *
3104 ucl_object_key (const ucl_object_t *obj)
3105 {
3106 	return ucl_copy_key_trash (obj);
3107 }
3108 
3109 const char *
3110 ucl_object_keyl (const ucl_object_t *obj, size_t *len)
3111 {
3112 	if (len == NULL || obj == NULL) {
3113 		return NULL;
3114 	}
3115 	*len = obj->keylen;
3116 	return obj->key;
3117 }
3118 
3119 ucl_object_t *
3120 ucl_object_ref (const ucl_object_t *obj)
3121 {
3122 	ucl_object_t *res = NULL;
3123 
3124 	if (obj != NULL) {
3125 		if (obj->flags & UCL_OBJECT_EPHEMERAL) {
3126 			/*
3127 			 * Use deep copy for ephemeral objects, note that its refcount
3128 			 * is NOT increased, since ephemeral objects does not need refcount
3129 			 * at all
3130 			 */
3131 			res = ucl_object_copy (obj);
3132 		}
3133 		else {
3134 			res = __DECONST (ucl_object_t *, obj);
3135 #ifdef HAVE_ATOMIC_BUILTINS
3136 			(void)__sync_add_and_fetch (&res->ref, 1);
3137 #else
3138 			res->ref ++;
3139 #endif
3140 		}
3141 	}
3142 	return res;
3143 }
3144 
3145 static ucl_object_t *
3146 ucl_object_copy_internal (const ucl_object_t *other, bool allow_array)
3147 {
3148 
3149 	ucl_object_t *new;
3150 	ucl_object_iter_t it = NULL;
3151 	const ucl_object_t *cur;
3152 
3153 	new = malloc (sizeof (*new));
3154 
3155 	if (new != NULL) {
3156 		memcpy (new, other, sizeof (*new));
3157 		if (other->flags & UCL_OBJECT_EPHEMERAL) {
3158 			/* Copied object is always non ephemeral */
3159 			new->flags &= ~UCL_OBJECT_EPHEMERAL;
3160 		}
3161 		new->ref = 1;
3162 		/* Unlink from others */
3163 		new->next = NULL;
3164 		new->prev = new;
3165 
3166 		/* deep copy of values stored */
3167 		if (other->trash_stack[UCL_TRASH_KEY] != NULL) {
3168 			new->trash_stack[UCL_TRASH_KEY] =
3169 					strdup (other->trash_stack[UCL_TRASH_KEY]);
3170 			if (other->key == (const char *)other->trash_stack[UCL_TRASH_KEY]) {
3171 				new->key = new->trash_stack[UCL_TRASH_KEY];
3172 			}
3173 		}
3174 		if (other->trash_stack[UCL_TRASH_VALUE] != NULL) {
3175 			new->trash_stack[UCL_TRASH_VALUE] =
3176 					strdup (other->trash_stack[UCL_TRASH_VALUE]);
3177 			if (new->type == UCL_STRING) {
3178 				new->value.sv = new->trash_stack[UCL_TRASH_VALUE];
3179 			}
3180 		}
3181 
3182 		if (other->type == UCL_ARRAY || other->type == UCL_OBJECT) {
3183 			/* reset old value */
3184 			memset (&new->value, 0, sizeof (new->value));
3185 
3186 			while ((cur = ucl_object_iterate (other, &it, true)) != NULL) {
3187 				if (other->type == UCL_ARRAY) {
3188 					ucl_array_append (new, ucl_object_copy_internal (cur, false));
3189 				}
3190 				else {
3191 					ucl_object_t *cp = ucl_object_copy_internal (cur, true);
3192 					if (cp != NULL) {
3193 						ucl_object_insert_key (new, cp, cp->key, cp->keylen,
3194 								false);
3195 					}
3196 				}
3197 			}
3198 		}
3199 		else if (allow_array && other->next != NULL) {
3200 			LL_FOREACH (other->next, cur) {
3201 				ucl_object_t *cp = ucl_object_copy_internal (cur, false);
3202 				if (cp != NULL) {
3203 					DL_APPEND (new, cp);
3204 				}
3205 			}
3206 		}
3207 	}
3208 
3209 	return new;
3210 }
3211 
3212 ucl_object_t *
3213 ucl_object_copy (const ucl_object_t *other)
3214 {
3215 	return ucl_object_copy_internal (other, true);
3216 }
3217 
3218 void
3219 ucl_object_unref (ucl_object_t *obj)
3220 {
3221 	if (obj != NULL) {
3222 #ifdef HAVE_ATOMIC_BUILTINS
3223 		unsigned int rc = __sync_sub_and_fetch (&obj->ref, 1);
3224 		if (rc == 0) {
3225 #else
3226 		if (--obj->ref == 0) {
3227 #endif
3228 			ucl_object_free_internal (obj, true, ucl_object_dtor_unref);
3229 		}
3230 	}
3231 }
3232 
3233 int
3234 ucl_object_compare (const ucl_object_t *o1, const ucl_object_t *o2)
3235 {
3236 	const ucl_object_t *it1, *it2;
3237 	ucl_object_iter_t iter = NULL;
3238 	int ret = 0;
3239 
3240 	if (o1->type != o2->type) {
3241 		return (o1->type) - (o2->type);
3242 	}
3243 
3244 	switch (o1->type) {
3245 	case UCL_STRING:
3246 		if (o1->len == o2->len && o1->len > 0) {
3247 			ret = strcmp (ucl_object_tostring(o1), ucl_object_tostring(o2));
3248 		}
3249 		else {
3250 			ret = o1->len - o2->len;
3251 		}
3252 		break;
3253 	case UCL_FLOAT:
3254 	case UCL_INT:
3255 	case UCL_TIME:
3256 		ret = ucl_object_todouble (o1) - ucl_object_todouble (o2);
3257 		break;
3258 	case UCL_BOOLEAN:
3259 		ret = ucl_object_toboolean (o1) - ucl_object_toboolean (o2);
3260 		break;
3261 	case UCL_ARRAY:
3262 		if (o1->len == o2->len && o1->len > 0) {
3263 			UCL_ARRAY_GET (vec1, o1);
3264 			UCL_ARRAY_GET (vec2, o2);
3265 			unsigned i;
3266 
3267 			/* Compare all elements in both arrays */
3268 			for (i = 0; i < vec1->n; i ++) {
3269 				it1 = kv_A (*vec1, i);
3270 				it2 = kv_A (*vec2, i);
3271 
3272 				if (it1 == NULL && it2 != NULL) {
3273 					return -1;
3274 				}
3275 				else if (it2 == NULL && it1 != NULL) {
3276 					return 1;
3277 				}
3278 				else if (it1 != NULL && it2 != NULL) {
3279 					ret = ucl_object_compare (it1, it2);
3280 					if (ret != 0) {
3281 						break;
3282 					}
3283 				}
3284 			}
3285 		}
3286 		else {
3287 			ret = o1->len - o2->len;
3288 		}
3289 		break;
3290 	case UCL_OBJECT:
3291 		if (o1->len == o2->len && o1->len > 0) {
3292 			while ((it1 = ucl_object_iterate (o1, &iter, true)) != NULL) {
3293 				it2 = ucl_object_lookup (o2, ucl_object_key (it1));
3294 				if (it2 == NULL) {
3295 					ret = 1;
3296 					break;
3297 				}
3298 				ret = ucl_object_compare (it1, it2);
3299 				if (ret != 0) {
3300 					break;
3301 				}
3302 			}
3303 		}
3304 		else {
3305 			ret = o1->len - o2->len;
3306 		}
3307 		break;
3308 	default:
3309 		ret = 0;
3310 		break;
3311 	}
3312 
3313 	return ret;
3314 }
3315 
3316 int
3317 ucl_object_compare_qsort (const ucl_object_t **o1,
3318 		const ucl_object_t **o2)
3319 {
3320 	return ucl_object_compare (*o1, *o2);
3321 }
3322 
3323 void
3324 ucl_object_array_sort (ucl_object_t *ar,
3325 		int (*cmp)(const ucl_object_t **o1, const ucl_object_t **o2))
3326 {
3327 	UCL_ARRAY_GET (vec, ar);
3328 
3329 	if (cmp == NULL || ar == NULL || ar->type != UCL_ARRAY) {
3330 		return;
3331 	}
3332 
3333 	qsort (vec->a, vec->n, sizeof (ucl_object_t *),
3334 			(int (*)(const void *, const void *))cmp);
3335 }
3336 
3337 #define PRIOBITS 4
3338 
3339 unsigned int
3340 ucl_object_get_priority (const ucl_object_t *obj)
3341 {
3342 	if (obj == NULL) {
3343 		return 0;
3344 	}
3345 
3346 	return (obj->flags >> ((sizeof (obj->flags) * NBBY) - PRIOBITS));
3347 }
3348 
3349 void
3350 ucl_object_set_priority (ucl_object_t *obj,
3351 		unsigned int priority)
3352 {
3353 	if (obj != NULL) {
3354 		priority &= (0x1 << PRIOBITS) - 1;
3355 		priority <<= ((sizeof (obj->flags) * NBBY) - PRIOBITS);
3356 		priority |= obj->flags & ((1 << ((sizeof (obj->flags) * NBBY) -
3357 				PRIOBITS)) - 1);
3358 		obj->flags = priority;
3359 	}
3360 }
3361 
3362 bool
3363 ucl_object_string_to_type (const char *input, ucl_type_t *res)
3364 {
3365 	if (strcasecmp (input, "object") == 0) {
3366 		*res = UCL_OBJECT;
3367 	}
3368 	else if (strcasecmp (input, "array") == 0) {
3369 		*res = UCL_ARRAY;
3370 	}
3371 	else if (strcasecmp (input, "integer") == 0) {
3372 		*res = UCL_INT;
3373 	}
3374 	else if (strcasecmp (input, "number") == 0) {
3375 		*res = UCL_FLOAT;
3376 	}
3377 	else if (strcasecmp (input, "string") == 0) {
3378 		*res = UCL_STRING;
3379 	}
3380 	else if (strcasecmp (input, "boolean") == 0) {
3381 		*res = UCL_BOOLEAN;
3382 	}
3383 	else if (strcasecmp (input, "null") == 0) {
3384 		*res = UCL_NULL;
3385 	}
3386 	else if (strcasecmp (input, "userdata") == 0) {
3387 		*res = UCL_USERDATA;
3388 	}
3389 	else {
3390 		return false;
3391 	}
3392 
3393 	return true;
3394 }
3395 
3396 const char *
3397 ucl_object_type_to_string (ucl_type_t type)
3398 {
3399 	const char *res = "unknown";
3400 
3401 	switch (type) {
3402 	case UCL_OBJECT:
3403 		res = "object";
3404 		break;
3405 	case UCL_ARRAY:
3406 		res = "array";
3407 		break;
3408 	case UCL_INT:
3409 		res = "integer";
3410 		break;
3411 	case UCL_FLOAT:
3412 	case UCL_TIME:
3413 		res = "number";
3414 		break;
3415 	case UCL_STRING:
3416 		res = "string";
3417 		break;
3418 	case UCL_BOOLEAN:
3419 		res = "boolean";
3420 		break;
3421 	case UCL_USERDATA:
3422 		res = "userdata";
3423 		break;
3424 	case UCL_NULL:
3425 		res = "null";
3426 		break;
3427 	}
3428 
3429 	return res;
3430 }
3431 
3432 const ucl_object_t *
3433 ucl_parser_get_comments (struct ucl_parser *parser)
3434 {
3435 	if (parser && parser->comments) {
3436 		return parser->comments;
3437 	}
3438 
3439 	return NULL;
3440 }
3441 
3442 const ucl_object_t *
3443 ucl_comments_find (const ucl_object_t *comments,
3444 		const ucl_object_t *srch)
3445 {
3446 	if (comments && srch) {
3447 		return ucl_object_lookup_len (comments, (const char *)&srch,
3448 				sizeof (void *));
3449 	}
3450 
3451 	return NULL;
3452 }
3453 
3454 bool
3455 ucl_comments_move (ucl_object_t *comments,
3456 		const ucl_object_t *from, const ucl_object_t *to)
3457 {
3458 	const ucl_object_t *found;
3459 	ucl_object_t *obj;
3460 
3461 	if (comments && from && to) {
3462 		found = ucl_object_lookup_len (comments,
3463 				(const char *)&from, sizeof (void *));
3464 
3465 		if (found) {
3466 			/* Replace key */
3467 			obj = ucl_object_ref (found);
3468 			ucl_object_delete_keyl (comments, (const char *)&from,
3469 					sizeof (void *));
3470 			ucl_object_insert_key (comments, obj, (const char *)&to,
3471 					sizeof (void *), true);
3472 
3473 			return true;
3474 		}
3475 	}
3476 
3477 	return false;
3478 }
3479 
3480 void
3481 ucl_comments_add (ucl_object_t *comments, const ucl_object_t *obj,
3482 		const char *comment)
3483 {
3484 	if (comments && obj && comment) {
3485 		ucl_object_insert_key (comments, ucl_object_fromstring (comment),
3486 				(const char *)&obj, sizeof (void *), true);
3487 	}
3488 }
3489