]> git.ipfire.org Git - thirdparty/freeswitch.git/blame - src/switch_xml.c
[Core] scan-build: fix false-positive memory leak in switch_xml_set_attr_d and switch...
[thirdparty/freeswitch.git] / src / switch_xml.c
CommitLineData
a2fcb419 1/*
59241895 2 * FreeSWITCH Modular Media Switching Software Library / Soft-Switch Application
6e7d5d08 3 * Copyright (C) 2005-2014, Anthony Minessale II <anthm@freeswitch.org>
59241895
MJ
4 *
5 * Version: MPL 1.1
6 *
7 * The contents of this file are subject to the Mozilla Public License Version
8 * 1.1 (the "License"); you may not use this file except in compliance with
9 * the License. You may obtain a copy of the License at
10 * http://www.mozilla.org/MPL/
11 *
12 * Software distributed under the License is distributed on an "AS IS" basis,
13 * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
14 * for the specific language governing rights and limitations under the
15 * License.
16 *
17 * The Original Code is FreeSWITCH Modular Media Switching Software Library / Soft-Switch Application
18 *
19 * The Initial Developer of the Original Code is
ae220d33 20 * Anthony Minessale II <anthm@freeswitch.org>
59241895
MJ
21 * Portions created by the Initial Developer are Copyright (C)
22 * the Initial Developer. All Rights Reserved.
23 *
24 * Contributor(s):
a2fcb419 25 *
ae220d33 26 * Anthony Minessale II <anthm@freeswitch.org>
59241895 27 * Simon Capper <skyjunky@sbcglobal.net>
4137b360 28 * Marc Olivier Chouinard <mochouinard@moctel.com>
a2fcb419 29 * Raymond Chandler <intralanman@freeswitch.org>
59241895
MJ
30 *
31 * switch_xml.c -- XML PARSER
32 *
33 * Derived from ezxml http://ezxml.sourceforge.net
34 * Original Copyright
35 *
36 * Copyright 2004, 2006 Aaron Voisine <aaron@voisine.org>
37 *
38 * Permission is hereby granted, free of charge, to any person obtaining
39 * a copy of this software and associated documentation files (the
40 * "Software"), to deal in the Software without restriction, including
41 * without limitation the rights to use, copy, modify, merge, publish,
42 * distribute, sublicense, and/or sell copies of the Software, and to
43 * permit persons to whom the Software is furnished to do so, subject to
44 * the following conditions:
45 *
46 * The above copyright notice and this permission notice shall be included
47 * in all copies or substantial portions of the Software.
48 *
49 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
50 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
51 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
52 * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
53 * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
54 * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
55 * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
56 */
57
58#include <switch.h>
0629f95c 59#include <switch_stun.h>
59241895 60#ifndef WIN32
dae2cb4a 61#include <sys/wait.h>
59241895
MJ
62#include <switch_private.h>
63#include <glob.h>
64#else /* we're on windoze :( */
65/* glob functions at end of this file */
66#include <apr_file_io.h>
67
68typedef struct {
886e1ddb
AM
69 size_t gl_pathc; /* Count of total paths so far. */
70 size_t gl_matchc; /* Count of paths matching pattern. */
71 size_t gl_offs; /* Reserved at beginning of gl_pathv. */
72 int gl_flags; /* Copy of flags parameter to glob. */
73 char **gl_pathv; /* List of paths matching pattern. */
59241895 74 /* Copy of errfunc parameter to glob. */
886e1ddb 75 int (*gl_errfunc) (const char *, int);
59241895
MJ
76} glob_t;
77
78/* Believed to have been introduced in 1003.2-1992 */
de13f431
BW
79#define GLOB_APPEND 0x0001 /* Append to output from previous call. */
80#define GLOB_DOOFFS 0x0002 /* Use gl_offs. */
81#define GLOB_ERR 0x0004 /* Return on error. */
82#define GLOB_MARK 0x0008 /* Append / to matching directories. */
59241895 83#define GLOB_NOCHECK 0x0010 /* Return pattern itself if nothing matches. */
de13f431 84#define GLOB_NOSORT 0x0020 /* Don't sort. */
59241895
MJ
85
86/* Error values returned by glob(3) */
87#define GLOB_NOSPACE (-1) /* Malloc call failed. */
88#define GLOB_ABORTED (-2) /* Unignored error. */
89#define GLOB_NOMATCH (-3) /* No match and GLOB_NOCHECK was not set. */
de13f431 90#define GLOB_NOSYS (-4) /* Obsolete: source comptability only. */
59241895
MJ
91
92#define GLOB_ALTDIRFUNC 0x0040 /* Use alternately specified directory funcs. */
93#define GLOB_MAGCHAR 0x0100 /* Pattern had globbing characters. */
94#define GLOB_NOMAGIC 0x0200 /* GLOB_NOCHECK without magic chars (csh). */
de13f431
BW
95#define GLOB_QUOTE 0x0400 /* Quote special chars with \. */
96#define GLOB_LIMIT 0x1000 /* limit number of returned paths */
59241895 97
886e1ddb 98int glob(const char *, int, int (*)(const char *, int), glob_t *);
de13f431 99void globfree(glob_t *);
59241895 100
59241895
MJ
101#endif
102
de13f431 103#define SWITCH_XML_WS "\t\r\n " /* whitespace */
886e1ddb 104#define SWITCH_XML_ERRL 128 /* maximum error string length */
59241895 105
f30e40a8
KR
106static void preprocess_exec_set(char *keyval)
107{
108 char *key = keyval;
0ac27178 109 char *val = strchr(keyval, '=');
f30e40a8
KR
110
111 if (val) {
112 char *ve = val++;
113 while (*val && *val == ' ') {
114 val++;
115 }
116 *ve-- = '\0';
117 while (*ve && *ve == ' ') {
118 *ve-- = '\0';
119 }
120 }
121
122 if (key && val) {
123 switch_stream_handle_t exec_result = { 0 };
124 SWITCH_STANDARD_STREAM(exec_result);
97f42d42 125 if (switch_stream_system(val, &exec_result) == 0) {
f30e40a8
KR
126 if (!zstr(exec_result.data)) {
127 char *tmp = (char *) exec_result.data;
128 tmp = &tmp[strlen(tmp)-1];
129 while (tmp >= (char *) exec_result.data && ( tmp[0] == ' ' || tmp[0] == '\n') ) {
130 tmp[0] = '\0'; /* remove trailing spaces and newlines */
131 tmp--;
132 }
133 switch_core_set_variable(key, exec_result.data);
134 }
135 } else {
136 switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Error while executing command: %s\n", val);
137 }
138 switch_safe_free(exec_result.data);
139 }
140}
141
0629f95c
AV
142static void preprocess_stun_set(char *keyval)
143{
144 char *key = keyval;
0ac27178 145 char *val = strchr(keyval, '=');
0629f95c
AV
146
147 if (val) {
148 char *ve = val++;
149 while (*val && *val == ' ') {
150 val++;
151 }
152 *ve-- = '\0';
153 while (*ve && *ve == ' ') {
154 *ve-- = '\0';
155 }
156 }
157
158 if (key && val) {
159 char *external_ip = NULL;
160 switch_memory_pool_t *pool;
161
162 switch_core_new_memory_pool(&pool);
163
164 if (switch_stun_ip_lookup(&external_ip, val, pool) == SWITCH_STATUS_SUCCESS) {
165 if (!zstr(external_ip)) {
166 char *tmp = external_ip;
167 tmp = &tmp[strlen(tmp) - 1];
168 while (tmp >= external_ip && (tmp[0] == ' ' || tmp[0] == '\n')) {
169 tmp[0] = '\0'; /* remove trailing spaces and newlines */
170 tmp--;
171 }
172 switch_core_set_variable(key, external_ip);
173 }
174 } else {
175 switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "stun-set failed.\n");
176 }
177
178 switch_core_destroy_memory_pool(&pool);
179 }
180}
181
4719d047
SD
182static void preprocess_env_set(char *keyval)
183{
184 char *key = keyval;
0ac27178 185 char *val = strchr(keyval, '=');
4719d047
SD
186
187 if (key && val) {
188 *val++ = '\0';
189
190 if (*val++ == '$') {
191 char *data = getenv(val);
192
193 if (data) {
194 switch_core_set_variable(key, data);
195 }
196 }
197 }
198}
199
c5204c21 200static int preprocess(const char *cwd, const char *file, FILE *write_fd, int rlevel);
59241895
MJ
201
202typedef struct switch_xml_root *switch_xml_root_t;
de13f431
BW
203struct switch_xml_root { /* additional data for the root tag */
204 struct switch_xml xml; /* is a super-struct built on top of switch_xml struct */
205 switch_xml_t cur; /* current xml tree insertion point */
206 char *m; /* original xml string */
34bd0e5e 207 switch_size_t len; /* length of allocated memory */
bc46c9a0 208 uint8_t dynamic; /* Free the original string when calling switch_xml_free */
de13f431
BW
209 char *u; /* UTF-8 conversion of string if original was UTF-16 */
210 char *s; /* start of work area */
211 char *e; /* end of work area */
212 char **ent; /* general entities (ampersand sequences) */
213 char ***attr; /* default attributes */
214 char ***pi; /* processing instructions */
215 short standalone; /* non-zero if <?xml standalone="yes"?> */
216 char err[SWITCH_XML_ERRL]; /* error string */
59241895
MJ
217};
218
de13f431 219char *SWITCH_XML_NIL[] = { NULL }; /* empty, null terminated array of strings */
59241895
MJ
220
221struct switch_xml_binding {
222 switch_xml_search_function_t function;
223 switch_xml_section_t sections;
224 void *user_data;
225 struct switch_xml_binding *next;
226};
227
228
229static switch_xml_binding_t *BINDINGS = NULL;
230static switch_xml_t MAIN_XML_ROOT = NULL;
c5831538 231static switch_memory_pool_t *XML_MEMORY_POOL = NULL;
4714ed43 232
c5831538 233static switch_thread_rwlock_t *B_RWLOCK = NULL;
4714ed43 234static switch_mutex_t *XML_LOCK = NULL;
2582bbcb 235static switch_mutex_t *CACHE_MUTEX = NULL;
4714ed43 236static switch_mutex_t *REFLOCK = NULL;
3ed59f1d 237static switch_mutex_t *FILE_LOCK = NULL;
4714ed43 238
3aaa6209 239SWITCH_DECLARE_NONSTD(switch_xml_t) __switch_xml_open_root(uint8_t reload, const char **err, void *user_data);
07a71592
AM
240
241static switch_xml_open_root_function_t XML_OPEN_ROOT_FUNCTION = (switch_xml_open_root_function_t)__switch_xml_open_root;
242static void *XML_OPEN_ROOT_FUNCTION_USER_DATA = NULL;
243
2582bbcb 244static switch_hash_t *CACHE_HASH = NULL;
a2fcb419 245static switch_hash_t *CACHE_EXPIRES_HASH = NULL;
59241895
MJ
246
247struct xml_section_t {
248 const char *name;
de13f431 249 /* switch_xml_section_t section; */
59241895
MJ
250 uint32_t section;
251};
252
253static struct xml_section_t SECTIONS[] = {
254 {"result", SWITCH_XML_SECTION_RESULT},
255 {"config", SWITCH_XML_SECTION_CONFIG},
256 {"directory", SWITCH_XML_SECTION_DIRECTORY},
257 {"dialplan", SWITCH_XML_SECTION_DIALPLAN},
5b8a1337 258 {"languages", SWITCH_XML_SECTION_LANGUAGES},
7333d46d 259 {"chatplan", SWITCH_XML_SECTION_CHATPLAN},
4dc7b3b2 260 {"channels", SWITCH_XML_SECTION_CHANNELS},
59241895
MJ
261 {NULL, 0}
262};
263
264SWITCH_DECLARE(switch_xml_section_t) switch_xml_parse_section_string(const char *str)
265{
266 size_t x;
267 char buf[1024] = "";
de13f431 268 /*switch_xml_section_t sections = SWITCH_XML_SECTION_RESULT; */
59241895 269 uint32_t sections = SWITCH_XML_SECTION_RESULT;
886e1ddb 270
59241895
MJ
271 if (str) {
272 for (x = 0; x < strlen(str); x++) {
273 buf[x] = (char) tolower((int) str[x]);
274 }
275 for (x = 0;; x++) {
276 if (!SECTIONS[x].name) {
277 break;
278 }
279 if (strstr(buf, SECTIONS[x].name)) {
280 sections |= SECTIONS[x].section;
281 }
282 }
283 }
284 return (switch_xml_section_t) sections;
285}
286
287SWITCH_DECLARE(switch_status_t) switch_xml_unbind_search_function(switch_xml_binding_t **binding)
288{
289 switch_xml_binding_t *ptr, *last = NULL;
290 switch_status_t status = SWITCH_STATUS_FALSE;
291
8ec9b8f7
AM
292
293 switch_thread_rwlock_wrlock(B_RWLOCK);
59241895
MJ
294 for (ptr = BINDINGS; ptr; ptr = ptr->next) {
295 if (ptr == *binding) {
296 if (last) {
297 last->next = (*binding)->next;
298 } else {
299 BINDINGS = (*binding)->next;
300 }
301 status = SWITCH_STATUS_SUCCESS;
302 break;
303 }
304 last = ptr;
305 }
8ec9b8f7 306 switch_thread_rwlock_unlock(B_RWLOCK);
59241895
MJ
307
308 return status;
309}
310
311SWITCH_DECLARE(switch_status_t) switch_xml_unbind_search_function_ptr(switch_xml_search_function_t function)
312{
313 switch_xml_binding_t *ptr, *last = NULL;
314 switch_status_t status = SWITCH_STATUS_FALSE;
315
8ec9b8f7 316 switch_thread_rwlock_wrlock(B_RWLOCK);
59241895
MJ
317 for (ptr = BINDINGS; ptr; ptr = ptr->next) {
318 if (ptr->function == function) {
30a13ca0
AM
319 status = SWITCH_STATUS_SUCCESS;
320
59241895
MJ
321 if (last) {
322 last->next = ptr->next;
323 } else {
324 BINDINGS = ptr->next;
30a13ca0
AM
325 last = NULL;
326 continue;
59241895 327 }
59241895
MJ
328 }
329 last = ptr;
330 }
8ec9b8f7 331 switch_thread_rwlock_unlock(B_RWLOCK);
59241895
MJ
332
333 return status;
334}
335
fc6a7ced
AM
336SWITCH_DECLARE(void) switch_xml_set_binding_sections(switch_xml_binding_t *binding, switch_xml_section_t sections)
337{
338 switch_assert(binding);
339 binding->sections = sections;
340}
341
342SWITCH_DECLARE(void) switch_xml_set_binding_user_data(switch_xml_binding_t *binding, void *user_data)
343{
344 switch_assert(binding);
345 binding->user_data = user_data;
346}
347
34931616
AM
348SWITCH_DECLARE(switch_xml_section_t) switch_xml_get_binding_sections(switch_xml_binding_t *binding)
349{
350 return binding->sections;
351}
352
353SWITCH_DECLARE(void *) switch_xml_get_binding_user_data(switch_xml_binding_t *binding)
354{
355 return binding->user_data;
356}
357
de13f431 358SWITCH_DECLARE(switch_status_t) switch_xml_bind_search_function_ret(switch_xml_search_function_t function,
886e1ddb 359 switch_xml_section_t sections, void *user_data, switch_xml_binding_t **ret_binding)
59241895
MJ
360{
361 switch_xml_binding_t *binding = NULL, *ptr = NULL;
362 assert(function != NULL);
363
364 if (!(binding = (switch_xml_binding_t *) switch_core_alloc(XML_MEMORY_POOL, sizeof(*binding)))) {
365 return SWITCH_STATUS_MEMERR;
366 }
367
368 binding->function = function;
369 binding->sections = sections;
370 binding->user_data = user_data;
371
8ec9b8f7 372 switch_thread_rwlock_wrlock(B_RWLOCK);
59241895
MJ
373 for (ptr = BINDINGS; ptr && ptr->next; ptr = ptr->next);
374
375 if (ptr) {
376 ptr->next = binding;
377 } else {
378 BINDINGS = binding;
379 }
446d7285 380
ff0c6deb
AM
381 if (ret_binding) {
382 *ret_binding = binding;
446d7285
AM
383 }
384
8ec9b8f7 385 switch_thread_rwlock_unlock(B_RWLOCK);
59241895
MJ
386
387 return SWITCH_STATUS_SUCCESS;
388}
389
390SWITCH_DECLARE(switch_xml_t) switch_xml_find_child(switch_xml_t node, const char *childname, const char *attrname, const char *value)
391{
392 switch_xml_t p = NULL;
393
394 if (!(childname && attrname && value)) {
395 return node;
396 }
397
398 for (p = switch_xml_child(node, childname); p; p = p->next) {
399 const char *aname = switch_xml_attr(p, attrname);
0ac27178 400 if (aname && !strcasecmp(aname, value)) {
59241895
MJ
401 break;
402 }
403 }
404
405 return p;
406}
407
886e1ddb 408SWITCH_DECLARE(switch_xml_t) switch_xml_find_child_multi(switch_xml_t node, const char *childname,...)
ed100f44
AM
409{
410 switch_xml_t p = NULL;
886e1ddb
AM
411 const char *names[256] = { 0 };
412 const char *vals[256] = { 0 };
ed100f44
AM
413 int x, i = 0;
414 va_list ap;
376b42c3 415 const char *attrname, *value = NULL;
ed100f44
AM
416
417 va_start(ap, childname);
886e1ddb
AM
418
419 while (i < 255) {
ed100f44
AM
420 if ((attrname = va_arg(ap, const char *))) {
421 value = va_arg(ap, const char *);
422 }
423 if (attrname && value) {
424 names[i] = attrname;
425 vals[i] = value;
426 } else {
427 break;
428 }
429 i++;
430 }
431
432 va_end(ap);
433
434 if (!(childname && i)) {
435 return node;
436 }
886e1ddb 437
ed100f44
AM
438 for (p = switch_xml_child(node, childname); p; p = p->next) {
439 for (x = 0; x < i; x++) {
440 if (names[x] && vals[x]) {
441 const char *aname = switch_xml_attr(p, names[x]);
442
443 if (aname) {
444 if (*vals[x] == '!') {
445 const char *sval = vals[x] + 1;
0ac27178 446 if (strcasecmp(aname, sval)) {
ed100f44
AM
447 goto done;
448 }
449 } else {
450 if (!strcasecmp(aname, vals[x])) {
451 goto done;
452 }
453 }
454 }
455 }
456 }
457 }
458
886e1ddb 459 done:
ed100f44
AM
460
461 return p;
462}
463
de13f431 464/* returns the first child tag with the given name or NULL if not found */
59241895
MJ
465SWITCH_DECLARE(switch_xml_t) switch_xml_child(switch_xml_t xml, const char *name)
466{
467 xml = (xml) ? xml->child : NULL;
468 while (xml && strcmp(name, xml->name))
469 xml = xml->sibling;
470 return xml;
471}
472
de13f431 473/* returns the Nth tag with the same name in the same subsection or NULL if not found */
59241895
MJ
474switch_xml_t switch_xml_idx(switch_xml_t xml, int idx)
475{
476 for (; xml && idx; idx--)
477 xml = xml->next;
478 return xml;
479}
480
de13f431 481/* returns the value of the requested tag attribute or "" if not found */
59241895
MJ
482SWITCH_DECLARE(const char *) switch_xml_attr_soft(switch_xml_t xml, const char *attr)
483{
484 const char *ret = switch_xml_attr(xml, attr);
485
486 return ret ? ret : "";
487}
488
de13f431 489/* returns the value of the requested tag attribute or NULL if not found */
59241895
MJ
490SWITCH_DECLARE(const char *) switch_xml_attr(switch_xml_t xml, const char *attr)
491{
492 int i = 0, j = 1;
493 switch_xml_root_t root = (switch_xml_root_t) xml;
494
495 if (!xml || !xml->attr)
496 return NULL;
383ff711 497 while (xml->attr[i] && attr && strcmp(attr, xml->attr[i]))
59241895
MJ
498 i += 2;
499 if (xml->attr[i])
de13f431 500 return xml->attr[i + 1]; /* found attribute */
59241895
MJ
501
502 while (root->xml.parent)
de13f431 503 root = (switch_xml_root_t) root->xml.parent; /* root tag */
62ce8538 504
41557506
MJ
505 if (!root->attr) {
506 return NULL;
507 }
a2fcb419 508
383ff711 509 for (i = 0; root->attr[i] && xml->name && strcmp(xml->name, root->attr[i][0]); i++);
59241895 510 if (!root->attr[i])
de13f431 511 return NULL; /* no matching default attributes */
383ff711 512 while (root->attr[i][j] && attr && strcmp(attr, root->attr[i][j]))
59241895 513 j += 3;
de13f431 514 return (root->attr[i][j]) ? root->attr[i][j + 1] : NULL; /* found default */
59241895
MJ
515}
516
de13f431 517/* same as switch_xml_get but takes an already initialized va_list */
59241895
MJ
518static switch_xml_t switch_xml_vget(switch_xml_t xml, va_list ap)
519{
520 char *name = va_arg(ap, char *);
521 int idx = -1;
522
523 if (name && *name) {
524 idx = va_arg(ap, int);
525 xml = switch_xml_child(xml, name);
526 }
527 return (idx < 0) ? xml : switch_xml_vget(switch_xml_idx(xml, idx), ap);
528}
529
de13f431
BW
530/* Traverses the xml tree to retrieve a specific subtag. Takes a variable
531 length list of tag names and indexes. The argument list must be terminated
a2fcb419 532 by either an index of -1 or an empty string tag name. Example:
de13f431
BW
533 title = switch_xml_get(library, "shelf", 0, "book", 2, "title", -1);
534 This retrieves the title of the 3rd book on the 1st shelf of library.
535 Returns NULL if not found. */
59241895
MJ
536SWITCH_DECLARE(switch_xml_t) switch_xml_get(switch_xml_t xml,...)
537{
538 va_list ap;
539 switch_xml_t r;
540
541 va_start(ap, xml);
542 r = switch_xml_vget(xml, ap);
543 va_end(ap);
544 return r;
545}
546
de13f431 547/* returns a null terminated array of processing instructions for the given target */
59241895
MJ
548SWITCH_DECLARE(const char **) switch_xml_pi(switch_xml_t xml, const char *target)
549{
550 switch_xml_root_t root = (switch_xml_root_t) xml;
551 int i = 0;
552
553 if (!root)
554 return (const char **) SWITCH_XML_NIL;
555 while (root->xml.parent)
de13f431 556 root = (switch_xml_root_t) root->xml.parent; /* root tag */
41557506
MJ
557 if (!root || !root->pi) {
558 return (const char **) SWITCH_XML_NIL;
559 }
59241895 560 while (root->pi[i] && strcmp(target, root->pi[i][0]))
de13f431 561 i++; /* find target */
59241895
MJ
562 return (const char **) ((root->pi[i]) ? root->pi[i] + 1 : SWITCH_XML_NIL);
563}
564
de13f431 565/* set an error string and return root */
59241895
MJ
566static switch_xml_t switch_xml_err(switch_xml_root_t root, char *s, const char *err, ...)
567{
568 va_list ap;
569 int line = 1;
570 char *t, fmt[SWITCH_XML_ERRL];
571
41557506
MJ
572 if (!root || !root->s) {
573 return NULL;
574 }
575
59241895
MJ
576 for (t = root->s; t && t < s; t++)
577 if (*t == '\n')
578 line++;
579 switch_snprintf(fmt, SWITCH_XML_ERRL, "[error near line %d]: %s", line, err);
580
581 va_start(ap, err);
582 vsnprintf(root->err, SWITCH_XML_ERRL, fmt, ap);
583 va_end(ap);
584
585 return &root->xml;
586}
587
de13f431
BW
588/* Recursively decodes entity and character references and normalizes new lines
589 ent is a null terminated array of alternating entity names and values. set t
590 to '&' for general entity decoding, '%' for parameter entity decoding, 'c'
591 for cdata sections, ' ' for attribute normalization, or '*' for non-cdata
592 attribute normalization. Returns s, or if the decoded string is longer than
593 s, returns a malloced string that must be freed. */
59241895
MJ
594static char *switch_xml_decode(char *s, char **ent, char t)
595{
596 char *e, *r = s, *m = s;
48d6a5f6 597 unsigned long b, c, d, l;
59241895 598
886e1ddb 599 for (; *s; s++) { /* normalize line endings */
59241895
MJ
600 while (*s == '\r') {
601 *(s++) = '\n';
602 if (*s == '\n')
603 memmove(s, (s + 1), strlen(s));
604 }
605 }
606
607 for (s = r;;) {
e92fd635 608 while (*s && *s != '&' && (*s != '%' || t != '%') && !isspace((unsigned char) (*s)))
59241895
MJ
609 s++;
610
611 if (!*s)
612 break;
de13f431 613 else if (t != 'c' && !strncmp(s, "&#", 2)) { /* character reference */
48d6a5f6
PW
614 char *code = s + 2;
615 int base = 10;
616 if (*code == 'x') {
617 code++;
618 base = 16;
619 }
620 if (!isxdigit((int)*code)) { /* "&# 1;" and "&#-1;" are invalid */
621 s++;
622 continue;
623 }
624 c = strtoul(code, &e, base);
59241895
MJ
625 if (!c || *e != ';') {
626 s++;
627 continue;
886e1ddb
AM
628 }
629 /* not a character ref */
59241895 630 if (c < 0x80)
de13f431 631 *(s++) = (char) c; /* US-ASCII subset */
48d6a5f6
PW
632 else if (c > 0x7FFFFFFF) { /* out of UTF-8 range */
633 s++;
634 continue;
635 } else { /* multi-byte UTF-8 sequence */
59241895 636 for (b = 0, d = c; d; d /= 2)
886e1ddb 637 b++; /* number of bits in c */
de13f431 638 b = (b - 2) / 5; /* number of bytes in payload */
48d6a5f6 639 assert(b < 7); /* because c <= 0x7FFFFFFF */
de13f431 640 *(s++) = (char) ((0xFF << (7 - b)) | (c >> (6 * b))); /* head */
59241895 641 while (b)
de13f431 642 *(s++) = (char) (0x80 | ((c >> (6 * --b)) & 0x3F)); /* payload */
59241895
MJ
643 }
644
645 memmove(s, strchr(s, ';') + 1, strlen(strchr(s, ';')));
de13f431
BW
646 } else if ((*s == '&' && (t == '&' || t == ' ' || t == '*')) || (*s == '%' && t == '%')) { /* entity reference */
647 for (b = 0; ent[b] && strncmp(s + 1, ent[b], strlen(ent[b])); b += 2); /* find entity in entity list */
59241895 648
de13f431 649 if (ent[b++]) { /* found a match */
48d6a5f6
PW
650 if ((c = (unsigned long) strlen(ent[b])) - 1 > (e = strchr(s, ';')) - s) {
651 l = (d = (unsigned long) (s - r)) + c + (unsigned long) strlen(e); /* new length */
59241895
MJ
652 if (l) {
653 if (r == m) {
350a739d
AM
654 char *tmp = (char *) switch_must_malloc(l);
655 r = strcpy(tmp, r);
59241895 656 } else {
350a739d 657 r = (char *) switch_must_realloc(r, l);
59241895
MJ
658 }
659 }
de13f431 660 e = strchr((s = r + d), ';'); /* fix up pointers */
59241895
MJ
661 }
662
de13f431
BW
663 memmove(s + c, e + 1, strlen(e)); /* shift rest of string */
664 strncpy(s, ent[b], c); /* copy in replacement text */
59241895 665 } else
de13f431 666 s++; /* not a known entity */
59241895
MJ
667 } else if ((t == ' ' || t == '*') && isspace((int) (*s)))
668 *(s++) = ' ';
669 else
de13f431 670 s++; /* no decoding needed */
59241895
MJ
671 }
672
de13f431 673 if (t == '*') { /* normalize spaces for non-cdata attributes */
59241895 674 for (s = r; *s; s++) {
48d6a5f6 675 if ((l = (unsigned long) strspn(s, " ")))
59241895
MJ
676 memmove(s, s + l, strlen(s + l) + 1);
677 while (*s && *s != ' ')
678 s++;
679 }
680 if (--s >= r && *s == ' ')
de13f431 681 *s = '\0'; /* trim any trailing space */
59241895
MJ
682 }
683 return r;
684}
685
de13f431 686/* called when parser finds start of new tag */
59241895
MJ
687static void switch_xml_open_tag(switch_xml_root_t root, char *name, char **attr)
688{
41557506
MJ
689 switch_xml_t xml;
690
691 if (!root || !root->cur) {
692 return;
693 }
694
695 xml = root->cur;
59241895
MJ
696
697 if (xml->name)
698 xml = switch_xml_add_child(xml, name, strlen(xml->txt));
699 else
de13f431 700 xml->name = name; /* first open tag */
59241895
MJ
701
702 xml->attr = attr;
de13f431 703 root->cur = xml; /* update tag insertion point */
59241895
MJ
704}
705
de13f431 706/* called when parser finds character content between open and closing tag */
59241895
MJ
707static void switch_xml_char_content(switch_xml_root_t root, char *s, switch_size_t len, char t)
708{
41557506 709 switch_xml_t xml;
59241895
MJ
710 char *m = s;
711 switch_size_t l;
712
41557506
MJ
713 if (!root || !root->cur) {
714 return;
715 }
716
717 xml = root->cur;
718
59241895 719 if (!xml || !xml->name || !len)
de13f431 720 return; /* sanity check */
59241895 721
de13f431 722 s[len] = '\0'; /* null terminate text (calling functions anticipate this) */
59241895
MJ
723 len = strlen(s = switch_xml_decode(s, root->ent, t)) + 1;
724
725 if (!*(xml->txt))
de13f431
BW
726 xml->txt = s; /* initial character content */
727 else { /* allocate our own memory and make a copy */
886e1ddb 728 if ((xml->flags & SWITCH_XML_TXTM)) { /* allocate some space */
350a739d 729 xml->txt = (char *) switch_must_realloc(xml->txt, (l = strlen(xml->txt)) + len);
59241895 730 } else {
350a739d
AM
731 char *tmp = (char *) switch_must_malloc((l = strlen(xml->txt)) + len);
732
733 xml->txt = strcpy(tmp, xml->txt);
59241895 734 }
de13f431 735 strcpy(xml->txt + l, s); /* add new char content */
59241895 736 if (s != m)
de13f431 737 free(s); /* free s if it was malloced by switch_xml_decode() */
59241895
MJ
738 }
739
740 if (xml->txt != m)
741 switch_xml_set_flag(xml, SWITCH_XML_TXTM);
742}
743
de13f431 744/* called when parser finds closing tag */
59241895
MJ
745static switch_xml_t switch_xml_close_tag(switch_xml_root_t root, char *name, char *s)
746{
41557506 747 if (!root || !root->cur || !root->cur->name || strcmp(name, root->cur->name))
59241895
MJ
748 return switch_xml_err(root, s, "unexpected closing tag </%s>", name);
749
750 root->cur = root->cur->parent;
751 return NULL;
752}
753
de13f431
BW
754/* checks for circular entity references, returns non-zero if no circular
755 references are found, zero otherwise */
59241895
MJ
756static int switch_xml_ent_ok(char *name, char *s, char **ent)
757{
758 int i;
759
760 for (;; s++) {
761 while (*s && *s != '&')
de13f431 762 s++; /* find next entity reference */
59241895
MJ
763 if (!*s)
764 return 1;
765 if (!strncmp(s + 1, name, strlen(name)))
de13f431 766 return 0; /* circular ref. */
59241895
MJ
767 for (i = 0; ent[i] && strncmp(ent[i], s + 1, strlen(ent[i])); i += 2);
768 if (ent[i] && !switch_xml_ent_ok(name, ent[i + 1], ent))
769 return 0;
770 }
771}
772
de13f431 773/* called when the parser finds a processing instruction */
59241895
MJ
774static void switch_xml_proc_inst(switch_xml_root_t root, char *s, switch_size_t len)
775{
776 int i = 0, j = 1;
777 char *target = s;
778 char **sstmp;
779 char *stmp;
780
de13f431 781 s[len] = '\0'; /* null terminate instruction */
59241895 782 if (*(s += strcspn(s, SWITCH_XML_WS))) {
de13f431
BW
783 *s = '\0'; /* null terminate target */
784 s += strspn(s + 1, SWITCH_XML_WS) + 1; /* skip whitespace after target */
59241895
MJ
785 }
786
886e1ddb
AM
787 if (!root)
788 return;
59241895 789
de13f431 790 if (!strcmp(target, "xml")) { /* <?xml ... ?> */
59241895
MJ
791 if ((s = strstr(s, "standalone")) && !strncmp(s + strspn(s + 10, SWITCH_XML_WS "='\"") + 10, "yes", 3))
792 root->standalone = 1;
793 return;
794 }
795
41557506 796 if (!root->pi || !root->pi[0]) {
350a739d 797 root->pi = (char ***) switch_must_malloc(sizeof(char **));
886e1ddb 798 *(root->pi) = NULL; /* first pi */
59241895
MJ
799 }
800
801 while (root->pi[i] && strcmp(target, root->pi[i][0]))
de13f431
BW
802 i++; /* find target */
803 if (!root->pi[i]) { /* new target */
350a739d
AM
804 char ***ssstmp = (char ***) switch_must_realloc(root->pi, sizeof(char **) * (i + 2));
805
886e1ddb
AM
806 root->pi = ssstmp;
807 if (!root->pi)
808 return;
350a739d 809 root->pi[i] = (char **) switch_must_malloc(sizeof(char *) * 3);
59241895 810 root->pi[i][0] = target;
de13f431 811 root->pi[i][1] = (char *) (root->pi[i + 1] = NULL); /* terminate pi list */
350a739d 812 root->pi[i][2] = switch_must_strdup(""); /* empty document position list */
59241895
MJ
813 }
814
815 while (root->pi[i][j])
de13f431 816 j++; /* find end of instruction list for this target */
350a739d 817 sstmp = (char **) switch_must_realloc(root->pi[i], sizeof(char *) * (j + 3));
59241895 818 root->pi[i] = sstmp;
350a739d 819 stmp = (char *) switch_must_realloc(root->pi[i][j + 1], j + 1);
886e1ddb 820 root->pi[i][j + 2] = stmp;
59241895 821 strcpy(root->pi[i][j + 2] + j - 1, (root->xml.name) ? ">" : "<");
de13f431
BW
822 root->pi[i][j + 1] = NULL; /* null terminate pi list for this target */
823 root->pi[i][j] = s; /* set instruction */
59241895
MJ
824}
825
de13f431 826/* called when the parser finds an internal doctype subset */
59241895
MJ
827static short switch_xml_internal_dtd(switch_xml_root_t root, char *s, switch_size_t len)
828{
829 char q, *c, *t, *n = NULL, *v, **ent, **pe;
830 int i, j;
831 char **sstmp;
832
350a739d 833 pe = (char **) memcpy(switch_must_malloc(sizeof(SWITCH_XML_NIL)), SWITCH_XML_NIL, sizeof(SWITCH_XML_NIL));
886e1ddb 834
59241895
MJ
835 for (s[len] = '\0'; s;) {
836 while (*s && *s != '<' && *s != '%')
de13f431 837 s++; /* find next declaration */
59241895
MJ
838
839 if (!*s)
840 break;
886e1ddb 841 else if (!strncmp(s, "<!ENTITY", 8)) { /* parse entity definitions */
b59c28bd
AV
842 int use_pe;
843
de13f431 844 c = s += strspn(s + 8, SWITCH_XML_WS) + 8; /* skip white space separator */
886e1ddb 845 n = s + strspn(s, SWITCH_XML_WS "%"); /* find name */
de13f431 846 *(s = n + strcspn(n, SWITCH_XML_WS)) = ';'; /* append ; to name */
59241895 847
de13f431 848 v = s + strspn(s + 1, SWITCH_XML_WS) + 1; /* find value */
886e1ddb 849 if ((q = *(v++)) != '"' && q != '\'') { /* skip externals */
59241895
MJ
850 s = strchr(s, '>');
851 continue;
852 }
853
b59c28bd
AV
854 use_pe = (*c == '%');
855 for (i = 0, ent = (use_pe) ? pe : root->ent; ent[i]; i++);
350a739d 856 sstmp = (char **) switch_must_realloc(ent, (i + 3) * sizeof(char *)); /* space for next ent */
59241895 857 ent = sstmp;
b59c28bd 858 if (use_pe)
59241895
MJ
859 pe = ent;
860 else
861 root->ent = ent;
862
de13f431 863 *(++s) = '\0'; /* null terminate name */
59241895 864 if ((s = strchr(v, q)))
de13f431
BW
865 *(s++) = '\0'; /* null terminate value */
866 ent[i + 1] = switch_xml_decode(v, pe, '%'); /* set value */
867 ent[i + 2] = NULL; /* null terminate entity list */
868 if (!switch_xml_ent_ok(n, ent[i + 1], ent)) { /* circular reference */
59241895
MJ
869 if (ent[i + 1] != v)
870 free(ent[i + 1]);
871 switch_xml_err(root, v, "circular entity declaration &%s", n);
872 break;
873 } else
de13f431
BW
874 ent[i] = n; /* set entity name */
875 } else if (!strncmp(s, "<!ATTLIST", 9)) { /* parse default attributes */
876 t = s + strspn(s + 9, SWITCH_XML_WS) + 9; /* skip whitespace separator */
59241895
MJ
877 if (!*t) {
878 switch_xml_err(root, t, "unclosed <!ATTLIST");
879 break;
880 }
881 if (*(s = t + strcspn(t, SWITCH_XML_WS ">")) == '>')
882 continue;
883 else
de13f431 884 *s = '\0'; /* null terminate tag name */
e30c62f8 885 for (i = 0; root->attr[i] && n && strcmp(n, root->attr[i][0]); i++);
59241895 886
9300e0ad
AM
887 //while (*(n = ++s + strspn(s, SWITCH_XML_WS)) && *n != '>') {
888 // gcc 4.4 you are a creep
886e1ddb 889 for (;;) {
9300e0ad
AM
890 s++;
891 if (!(*(n = s + strspn(s, SWITCH_XML_WS)) && *n != '>')) {
892 break;
893 }
59241895 894 if (*(s = n + strcspn(n, SWITCH_XML_WS)))
de13f431 895 *s = '\0'; /* attr name */
59241895
MJ
896 else {
897 switch_xml_err(root, t, "malformed <!ATTLIST");
898 break;
899 }
900
de13f431 901 s += strspn(s + 1, SWITCH_XML_WS) + 1; /* find next token */
886e1ddb 902 c = (strncmp(s, "CDATA", 5)) ? (char *) "*" : (char *) " "; /* is it cdata? */
59241895
MJ
903 if (!strncmp(s, "NOTATION", 8))
904 s += strspn(s + 8, SWITCH_XML_WS) + 8;
905 s = (*s == '(') ? strchr(s, ')') : s + strcspn(s, SWITCH_XML_WS);
906 if (!s) {
907 switch_xml_err(root, t, "malformed <!ATTLIST");
908 break;
909 }
910
de13f431 911 s += strspn(s, SWITCH_XML_WS ")"); /* skip white space separator */
59241895
MJ
912 if (!strncmp(s, "#FIXED", 6))
913 s += strspn(s + 6, SWITCH_XML_WS) + 6;
de13f431 914 if (*s == '#') { /* no default value */
59241895
MJ
915 s += strcspn(s, SWITCH_XML_WS ">") - 1;
916 if (*c == ' ')
de13f431 917 continue; /* cdata is default, nothing to do */
59241895 918 v = NULL;
de13f431 919 } else if ((*s == '"' || *s == '\'') && /* default value */
59241895
MJ
920 (s = strchr(v = s + 1, *s)))
921 *s = '\0';
922 else {
923 switch_xml_err(root, t, "malformed <!ATTLIST");
924 break;
925 }
926
de13f431 927 if (!root->attr[i]) { /* new tag name */
350a739d
AM
928 root->attr = (!i) ? (char ***) switch_must_malloc(2 * sizeof(char **))
929 : (char ***) switch_must_realloc(root->attr, (i + 2) * sizeof(char **));
930 root->attr[i] = (char **) switch_must_malloc(2 * sizeof(char *));
de13f431 931 root->attr[i][0] = t; /* set tag name */
59241895
MJ
932 root->attr[i][1] = (char *) (root->attr[i + 1] = NULL);
933 }
934
de13f431 935 for (j = 1; root->attr[i][j]; j += 3); /* find end of list */
350a739d 936 sstmp = (char **) switch_must_realloc(root->attr[i], (j + 4) * sizeof(char *));
59241895
MJ
937
938 root->attr[i] = sstmp;
de13f431 939 root->attr[i][j + 3] = NULL; /* null terminate list */
886e1ddb 940 root->attr[i][j + 2] = c; /* is it cdata? */
de13f431 941 root->attr[i][j + 1] = (v) ? switch_xml_decode(v, root->ent, *c) : NULL;
886e1ddb 942 root->attr[i][j] = n; /* attribute name */
59241895
MJ
943 }
944 } else if (!strncmp(s, "<!--", 4))
886e1ddb
AM
945 s = strstr(s + 4, "-->"); /* comments */
946 else if (!strncmp(s, "<?", 2)) { /* processing instructions */
59241895
MJ
947 if ((s = strstr(c = s + 2, "?>")))
948 switch_xml_proc_inst(root, c, s++ - c);
949 } else if (*s == '<')
886e1ddb 950 s = strchr(s, '>'); /* skip other declarations */
59241895
MJ
951 else if (*(s++) == '%' && !root->standalone)
952 break;
953 }
954
955 free(pe);
956 return !*root->err;
957}
958
de13f431
BW
959/* Converts a UTF-16 string to UTF-8. Returns a new string that must be freed
960 or NULL if no conversion was needed. */
59241895
MJ
961static char *switch_xml_str2utf8(char **s, switch_size_t *len)
962{
963 char *u;
964 switch_size_t l = 0, sl, max = *len;
965 long c, d;
966 int b, be = (**s == '\xFE') ? 1 : (**s == '\xFF') ? 0 : -1;
967
968 if (be == -1)
de13f431 969 return NULL; /* not UTF-16 */
59241895 970
350a739d 971 u = (char *) switch_must_malloc(max);
59241895 972 for (sl = 2; sl < *len - 1; sl += 2) {
de13f431 973 c = (be) ? (((*s)[sl] & 0xFF) << 8) | ((*s)[sl + 1] & 0xFF) /* UTF-16BE */
886e1ddb 974 : (((*s)[sl + 1] & 0xFF) << 8) | ((*s)[sl] & 0xFF); /* UTF-16LE */
de13f431 975 if (c >= 0xD800 && c <= 0xDFFF && (sl += 2) < *len - 1) { /* high-half */
59241895
MJ
976 d = (be) ? (((*s)[sl] & 0xFF) << 8) | ((*s)[sl + 1] & 0xFF)
977 : (((*s)[sl + 1] & 0xFF) << 8) | ((*s)[sl] & 0xFF);
978 c = (((c & 0x3FF) << 10) | (d & 0x3FF)) + 0x10000;
979 }
980
981 while (l + 6 > max) {
982 char *tmp;
350a739d 983 tmp = (char *) switch_must_realloc(u, max += SWITCH_XML_BUFSIZE);
59241895
MJ
984 u = tmp;
985 }
986 if (c < 0x80)
de13f431
BW
987 u[l++] = (char) c; /* US-ASCII subset */
988 else { /* multi-byte UTF-8 sequence */
59241895 989 for (b = 0, d = c; d; d /= 2)
de13f431
BW
990 b++; /* bits in c */
991 b = (b - 2) / 5; /* bytes in payload */
992 u[l++] = (char) ((0xFF << (7 - b)) | (c >> (6 * b))); /* head */
59241895 993 while (b)
de13f431 994 u[l++] = (char) (0x80 | ((c >> (6 * --b)) & 0x3F)); /* payload */
59241895
MJ
995 }
996 }
350a739d 997 return *s = (char *) switch_must_realloc(u, *len = l);
59241895
MJ
998}
999
de13f431 1000/* frees a tag attribute list */
59241895
MJ
1001static void switch_xml_free_attr(char **attr)
1002{
e42ebbb3 1003 int i, c = 0;
59241895
MJ
1004 char *m;
1005
1006 if (!attr || attr == SWITCH_XML_NIL)
de13f431 1007 return; /* nothing to free */
e42ebbb3
AV
1008 while (attr[c])
1009 c += 2; /* find end of attribute list */
1010 m = attr[c + 1]; /* list of which names and values are malloced */
1011 for (i = c / 2 - 1; i >= 0 ; i--) {
59241895
MJ
1012 if (m[i] & SWITCH_XML_NAMEM)
1013 free(attr[i * 2]);
1014 if (m[i] & SWITCH_XML_TXTM)
1015 free(attr[(i * 2) + 1]);
1016 }
1017 free(m);
1018 free(attr);
1019}
1020
886e1ddb 1021SWITCH_DECLARE(switch_xml_t) switch_xml_parse_str_dynamic(char *s, switch_bool_t dup)
3b168bcb
MR
1022{
1023 switch_xml_root_t root;
5802cb94 1024 char *data;
886e1ddb 1025
5802cb94 1026 switch_assert(s);
350a739d 1027 data = dup ? switch_must_strdup(s) : s;
886e1ddb 1028
3b168bcb 1029 if ((root = (switch_xml_root_t) switch_xml_parse_str(data, strlen(data)))) {
886e1ddb 1030 root->dynamic = 1; /* Make sure we free the memory is switch_xml_free() */
3b168bcb
MR
1031 return &root->xml;
1032 } else {
5802cb94
MR
1033 if (dup) {
1034 free(data);
1035 }
3b168bcb
MR
1036 return NULL;
1037 }
1038}
886e1ddb 1039
6b6c83a7 1040/* parse the given xml string and return a switch_xml structure */
59241895
MJ
1041SWITCH_DECLARE(switch_xml_t) switch_xml_parse_str(char *s, switch_size_t len)
1042{
1043 switch_xml_root_t root = (switch_xml_root_t) switch_xml_new(NULL);
de13f431 1044 char q, e, *d, **attr, **a = NULL; /* initialize a to avoid compile warning */
59241895
MJ
1045 int l, i, j;
1046
1047 root->m = s;
1048 if (!len)
1049 return switch_xml_err(root, s, "root tag missing");
de13f431
BW
1050 root->u = switch_xml_str2utf8(&s, &len); /* convert utf-16 to utf-8 */
1051 root->e = (root->s = s) + len; /* record start and end of work area */
59241895 1052
de13f431
BW
1053 e = s[len - 1]; /* save end char */
1054 s[len - 1] = '\0'; /* turn end char into null terminator */
59241895
MJ
1055
1056 while (*s && *s != '<')
de13f431 1057 s++; /* find first tag */
59241895
MJ
1058 if (!*s)
1059 return switch_xml_err(root, s, "root tag missing");
1060
1061 for (;;) {
1062 attr = (char **) SWITCH_XML_NIL;
1063 d = ++s;
1064
886e1ddb 1065 if (isalpha((int) (*s)) || *s == '_' || *s == ':' || (int8_t) * s < '\0') { /* new tag */
59241895
MJ
1066 if (!root->cur)
1067 return switch_xml_err(root, d, "markup outside of root element");
1068
1069 s += strcspn(s, SWITCH_XML_WS "/>");
1070 while (isspace((int) (*s)))
886e1ddb 1071 *(s++) = '\0'; /* null terminate tag name */
59241895 1072
de13f431 1073 if (*s && *s != '/' && *s != '>') /* find tag in default attr list */
59241895
MJ
1074 for (i = 0; (a = root->attr[i]) && strcmp(a[0], d); i++);
1075
de13f431 1076 for (l = 0; *s && *s != '/' && *s != '>'; l += 2) { /* new attrib */
350a739d
AM
1077 attr = (l) ? (char **) switch_must_realloc(attr, (l + 4) * sizeof(char *))
1078 : (char **) switch_must_malloc(4 * sizeof(char *)); /* allocate space */
1079 attr[l + 3] = (l) ? (char *) switch_must_realloc(attr[l + 1], (l / 2) + 2)
1080 : (char *) switch_must_malloc(2); /* mem for list of maloced vals */
886e1ddb
AM
1081 strcpy(attr[l + 3] + (l / 2), " "); /* value is not malloced */
1082 attr[l + 2] = NULL; /* null terminate list */
1083 attr[l + 1] = (char *) ""; /* temporary attribute value */
1084 attr[l] = s; /* set attribute name */
59241895
MJ
1085
1086 s += strcspn(s, SWITCH_XML_WS "=/>");
1087 if (*s == '=' || isspace((int) (*s))) {
de13f431 1088 *(s++) = '\0'; /* null terminate tag attribute name */
59241895 1089 q = *(s += strspn(s, SWITCH_XML_WS "="));
de13f431 1090 if (q == '"' || q == '\'') { /* attribute value */
59241895
MJ
1091 attr[l + 1] = ++s;
1092 while (*s && *s != q)
1093 s++;
1094 if (*s)
de13f431 1095 *(s++) = '\0'; /* null terminate attribute val */
59241895
MJ
1096 else {
1097 switch_xml_free_attr(attr);
1098 return switch_xml_err(root, d, "missing %c", q);
1099 }
1100
1101 for (j = 1; a && a[j] && strcmp(a[j], attr[l]); j += 3);
1102 attr[l + 1] = switch_xml_decode(attr[l + 1], root->ent, (a && a[j]) ? *a[j + 2] : ' ');
1103 if (attr[l + 1] < d || attr[l + 1] > s)
de13f431 1104 attr[l + 3][l / 2] = SWITCH_XML_TXTM; /* value malloced */
59241895
MJ
1105 }
1106 }
1107 while (isspace((int) (*s)))
1108 s++;
1109 }
1110
de13f431 1111 if (*s == '/') { /* self closing tag */
59241895
MJ
1112 *(s++) = '\0';
1113 if ((*s && *s != '>') || (!*s && e != '>')) {
1114 if (l)
1115 switch_xml_free_attr(attr);
1116 return switch_xml_err(root, d, "missing >");
1117 }
1118 switch_xml_open_tag(root, d, attr);
1119 switch_xml_close_tag(root, d, s);
de13f431
BW
1120 } else if ((q = *s) == '>' || (!*s && e == '>')) { /* open tag */
1121 *s = '\0'; /* temporarily null terminate tag name */
59241895
MJ
1122 switch_xml_open_tag(root, d, attr);
1123 *s = q;
1124 } else {
1125 if (l)
1126 switch_xml_free_attr(attr);
1127 return switch_xml_err(root, d, "missing >");
1128 }
de13f431 1129 } else if (*s == '/') { /* close tag */
59241895
MJ
1130 s += strcspn(d = s + 1, SWITCH_XML_WS ">") + 1;
1131 if (!(q = *s) && e != '>')
1132 return switch_xml_err(root, d, "missing >");
de13f431 1133 *s = '\0'; /* temporarily null terminate tag name */
59241895
MJ
1134 if (switch_xml_close_tag(root, d, s))
1135 return &root->xml;
1136 if (isspace((int) (*s = q)))
1137 s += strspn(s, SWITCH_XML_WS);
de13f431 1138 } else if (!strncmp(s, "!--", 3)) { /* xml comment */
59241895
MJ
1139 if (!(s = strstr(s + 3, "--")) || (*(s += 2) != '>' && *s) || (!*s && e != '>'))
1140 return switch_xml_err(root, d, "unclosed <!--");
de13f431 1141 } else if (!strncmp(s, "![CDATA[", 8)) { /* cdata */
917d850b
SD
1142 if ((s = strstr(s, "]]>"))) {
1143 if (root && root->cur) {
1144 root->cur->flags |= SWITCH_XML_CDATA;
1145 }
59241895 1146 switch_xml_char_content(root, d + 8, (s += 2) - d - 10, 'c');
917d850b 1147 } else {
59241895 1148 return switch_xml_err(root, d, "unclosed <![CDATA[");
917d850b 1149 }
de13f431 1150 } else if (!strncmp(s, "!DOCTYPE", 8)) { /* dtd */
59241895
MJ
1151 for (l = 0; *s && ((!l && *s != '>') || (l && (*s != ']' || *(s + strspn(s + 1, SWITCH_XML_WS) + 1) != '>'))); l = (*s == '[') ? 1 : l)
1152 s += strcspn(s + 1, "[]>") + 1;
1153 if (!*s && e != '>')
1154 return switch_xml_err(root, d, "unclosed <!DOCTYPE");
1155 d = (l) ? strchr(d, '[') + 1 : d;
1156 if (l && !switch_xml_internal_dtd(root, d, s++ - d))
1157 return &root->xml;
de13f431 1158 } else if (*s == '?') { /* <?...?> processing instructions */
59241895
MJ
1159 do {
1160 s = strchr(s, '?');
1161 } while (s && *(++s) && *s != '>');
1162 if (!s || (!*s && e != '>'))
1163 return switch_xml_err(root, d, "unclosed <?");
1164 else
1165 switch_xml_proc_inst(root, d + 1, s - d - 2);
1166 } else
1167 return switch_xml_err(root, d, "unexpected <");
1168
1169 if (!s || !*s)
1170 break;
1171 *s = '\0';
1172 d = ++s;
de13f431 1173 if (*s && *s != '<') { /* tag character content */
59241895
MJ
1174 while (*s && *s != '<')
1175 s++;
1176 if (*s)
1177 switch_xml_char_content(root, d, s - d, '&');
1178 else
1179 break;
1180 } else if (!*s)
1181 break;
1182 }
1183
1184 if (!root->cur)
1185 return &root->xml;
1186 else if (!root->cur->name)
1187 return switch_xml_err(root, d, "root tag missing");
1188 else
1189 return switch_xml_err(root, d, "unclosed tag <%s>", root->cur->name);
1190}
1191
de13f431
BW
1192/* Wrapper for switch_xml_parse_str() that accepts a file stream. Reads the entire
1193 stream into memory and then parses it. For xml files, use switch_xml_parse_file()
1194 or switch_xml_parse_fd() */
59241895
MJ
1195SWITCH_DECLARE(switch_xml_t) switch_xml_parse_fp(FILE * fp)
1196{
1197 switch_xml_root_t root;
1198 switch_size_t l, len = 0;
1199 char *s;
1200
350a739d 1201 s = (char *) switch_must_malloc(SWITCH_XML_BUFSIZE);
df1ab07c 1202
59241895
MJ
1203 do {
1204 len += (l = fread((s + len), 1, SWITCH_XML_BUFSIZE, fp));
1205 if (l == SWITCH_XML_BUFSIZE) {
350a739d 1206 s = (char *) switch_must_realloc(s, len + SWITCH_XML_BUFSIZE);
59241895
MJ
1207 }
1208 } while (s && l == SWITCH_XML_BUFSIZE);
1209
1210 if (!s)
1211 return NULL;
1212 root = (switch_xml_root_t) switch_xml_parse_str(s, len);
de13f431 1213 root->dynamic = 1; /* so we know to free s in switch_xml_free() */
59241895
MJ
1214 return &root->xml;
1215}
1216
de13f431
BW
1217/* A wrapper for switch_xml_parse_str() that accepts a file descriptor. First
1218 attempts to mem map the file. Failing that, reads the file into memory.
1219 Returns NULL on failure. */
59241895
MJ
1220SWITCH_DECLARE(switch_xml_t) switch_xml_parse_fd(int fd)
1221{
1222 switch_xml_root_t root;
1223 struct stat st;
9cf864ba 1224 switch_ssize_t l;
59241895
MJ
1225 void *m;
1226
1227 if (fd < 0)
1228 return NULL;
1229 fstat(fd, &st);
1230
8f4e6392
AM
1231 if (!st.st_size) {
1232 return NULL;
1233 }
1234
350a739d
AM
1235 m = switch_must_malloc(st.st_size);
1236
9cf864ba
TC
1237 if (!(0<(l = read(fd, m, st.st_size)))
1238 || !(root = (switch_xml_root_t) switch_xml_parse_str((char *) m, l))) {
34bd0e5e
MOC
1239 free(m);
1240 return NULL;
59241895 1241 }
34bd0e5e
MOC
1242 root->dynamic = 1; /* so we know to free s in switch_xml_free() */
1243
59241895
MJ
1244 return &root->xml;
1245}
1246
531e0f2d 1247static char *expand_vars(char *buf, char *ebuf, switch_size_t elen, switch_size_t *newlen, const char **err)
59241895
MJ
1248{
1249 char *var, *val;
1250 char *rp = buf;
1251 char *wp = ebuf;
1252 char *ep = ebuf + elen - 1;
1253
1254 if (!(var = strstr(rp, "$${"))) {
1255 *newlen = strlen(buf);
1256 return buf;
1257 }
1258
1259 while (*rp && wp < ep) {
1260
1261 if (*rp == '$' && *(rp + 1) == '$' && *(rp + 2) == '{') {
3718cbc9 1262 char *e = switch_find_end_paren(rp + 2, '{', '}');
59241895
MJ
1263
1264 if (e) {
1265 rp += 3;
1266 var = rp;
1267 *e++ = '\0';
1268 rp = e;
4ae8282e 1269 if ((val = switch_core_get_variable_dup(var))) {
59241895
MJ
1270 char *p;
1271 for (p = val; p && *p && wp <= ep; p++) {
1272 *wp++ = *p;
1273 }
4ae8282e 1274 free(val);
59241895 1275 }
3718cbc9 1276 continue;
531e0f2d
AM
1277 } else if (err) {
1278 *err = "unterminated ${var}";
59241895
MJ
1279 }
1280 }
1281
1282 *wp++ = *rp++;
1283 }
d8e7897f
MJ
1284
1285 if (wp == ep) {
1286 return NULL;
1287 }
1288
59241895
MJ
1289 *wp++ = '\0';
1290 *newlen = strlen(ebuf);
1291
1292 return ebuf;
1293}
1294
c5204c21 1295static FILE *preprocess_exec(const char *cwd, const char *command, FILE *write_fd, int rlevel)
64a0bfc5
AM
1296{
1297#ifdef WIN32
16289ce9
JL
1298 FILE *fp = NULL;
1299 char buffer[1024];
64a0bfc5 1300
16289ce9
JL
1301 if (!command || !strlen(command)) goto end;
1302
1303 if ((fp = _popen(command, "r"))) {
1304 while (fgets(buffer, sizeof(buffer), fp) != NULL) {
1305 if (fwrite(buffer, 1, strlen(buffer), write_fd) <= 0) {
1306 break;
1307 }
1308 }
a2fcb419 1309
16289ce9
JL
1310 if(feof(fp)) {
1311 _pclose(fp);
1312 } else {
1313 switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Exec failed to read the pipe of [%s] to the end\n", command);
1314 }
1315 } else {
1316 switch_snprintf(buffer, sizeof(buffer), "<!-- exec can not execute [%s] -->", command);
1317 fwrite( buffer, 1, strlen(buffer), write_fd);
1318 }
64a0bfc5
AM
1319#else
1320 int fds[2], pid = 0;
1321
1322 if (pipe(fds)) {
1323 goto end;
886e1ddb 1324 } else { /* good to go */
52eff945 1325 pid = switch_fork();
64a0bfc5 1326
886e1ddb 1327 if (pid < 0) { /* ok maybe not */
64a0bfc5
AM
1328 close(fds[0]);
1329 close(fds[1]);
1330 goto end;
886e1ddb 1331 } else if (pid) { /* parent */
64a0bfc5
AM
1332 char buf[1024] = "";
1333 int bytes;
1334 close(fds[1]);
1335 while ((bytes = read(fds[0], buf, sizeof(buf))) > 0) {
c5204c21 1336 if (fwrite(buf, 1, bytes, write_fd) <= 0) {
64a0bfc5
AM
1337 break;
1338 }
1339 }
1340 close(fds[0]);
dae2cb4a 1341 waitpid(pid, NULL, 0);
886e1ddb 1342 } else { /* child */
0f6a2bf8 1343 switch_close_extra_files(fds, 2);
64a0bfc5
AM
1344 close(fds[0]);
1345 dup2(fds[1], STDOUT_FILENO);
70ecd353 1346 switch_system(command, SWITCH_TRUE);
64a0bfc5
AM
1347 close(fds[1]);
1348 exit(0);
1349 }
1350 }
1351#endif
886e1ddb 1352 end:
64a0bfc5
AM
1353
1354 return write_fd;
886e1ddb 1355
64a0bfc5
AM
1356}
1357
2f48c631 1358static FILE *preprocess_glob(const char *cwd, const char *pattern, FILE *write_fd, int rlevel)
59241895
MJ
1359{
1360 char *full_path = NULL;
1361 char *dir_path = NULL, *e = NULL;
886e1ddb 1362 glob_t glob_data;
59241895 1363 size_t n;
a80c67e3 1364 int glob_return;
59241895
MJ
1365
1366 if (!switch_is_file_path(pattern)) {
1367 full_path = switch_mprintf("%s%s%s", cwd, SWITCH_PATH_SEPARATOR, pattern);
1368 pattern = full_path;
1369 }
886e1ddb 1370
a80c67e3
KR
1371 glob_return = glob(pattern, GLOB_ERR, NULL, &glob_data);
1372 if (glob_return == GLOB_NOSPACE || glob_return == GLOB_ABORTED) {
2f48c631 1373 switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Error including %s\n", pattern);
59241895 1374 goto end;
a80c67e3
KR
1375 } else if (glob_return == GLOB_NOMATCH) {
1376 switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_INFO, "No files to include at %s\n", pattern);
1377 goto end;
59241895
MJ
1378 }
1379
1380 for (n = 0; n < glob_data.gl_pathc; ++n) {
350a739d
AM
1381 dir_path = switch_must_strdup(glob_data.gl_pathv[n]);
1382
59241895
MJ
1383 if ((e = strrchr(dir_path, *SWITCH_PATH_SEPARATOR))) {
1384 *e = '\0';
1385 }
1386 if (preprocess(dir_path, glob_data.gl_pathv[n], write_fd, rlevel) < 0) {
59241895 1387 if (rlevel > 100) {
2d6161e8 1388 switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Error including %s (Maximum recursion limit reached)\n", pattern);
59241895 1389 }
59241895 1390 }
7ffcb0e6 1391 free(dir_path);
59241895 1392 }
886e1ddb 1393 globfree(&glob_data);
59241895 1394
a80c67e3 1395 end:
59241895
MJ
1396
1397 switch_safe_free(full_path);
1398
1399 return write_fd;
1400}
1401
c5204c21 1402static int preprocess(const char *cwd, const char *file, FILE *write_fd, int rlevel)
59241895 1403{
c5204c21 1404 FILE *read_fd = NULL;
59241895 1405 switch_size_t cur = 0, ml = 0;
c5204c21 1406 char *q, *cmd, *buf = NULL, *ebuf = NULL;
59241895 1407 char *tcmd, *targ;
531e0f2d 1408 int line = 0;
c5204c21 1409 switch_size_t len = 0, eblen = 0;
886e1ddb 1410
c5204c21
AM
1411 if (rlevel > 100) {
1412 return -1;
59241895
MJ
1413 }
1414
c5204c21
AM
1415 if (!(read_fd = fopen(file, "r"))) {
1416 const char *reason = strerror(errno);
959e672a 1417 switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Couldn't open %s (%s)\n", file, reason);
59241895
MJ
1418 return -1;
1419 }
1420
c5204c21 1421 setvbuf(read_fd, (char *) NULL, _IOFBF, 65536);
a2fcb419 1422
c5204c21 1423 for(;;) {
59241895 1424 char *arg, *e;
531e0f2d 1425 const char *err = NULL;
c5204c21
AM
1426 char *bp;
1427
1428 switch_safe_free(ebuf);
1429
1430 if ((cur = switch_fp_read_dline(read_fd, &buf, &len)) <= 0) {
1431 break;
1432 }
1433
d8e7897f 1434 eblen = len * 2;
350a739d 1435 ebuf = switch_must_malloc(eblen);
c5204c21 1436 memset(ebuf, 0, eblen);
a2fcb419 1437
d8e7897f
MJ
1438 while (!(bp = expand_vars(buf, ebuf, eblen, &cur, &err))) {
1439 eblen *= 2;
350a739d 1440 ebuf = switch_must_realloc(ebuf, eblen);
d8e7897f
MJ
1441 memset(ebuf, 0, eblen);
1442 }
1443
531e0f2d 1444 line++;
886e1ddb 1445
4577ec87
AM
1446 if (err) {
1447 switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Error [%s] in file %s line %d\n", err, file, line);
531e0f2d 1448 }
59241895
MJ
1449
1450 /* we ignore <include> or </include> for the sake of validators as well as <?xml version="1.0"?> type stuff */
1451 if (strstr(buf, "<include>") || strstr(buf, "</include>") || strstr(buf, "<?")) {
1452 continue;
1453 }
1454
1455 if (ml) {
1456 if ((e = strstr(buf, "-->"))) {
1457 ml = 0;
1458 bp = e + 3;
1459 cur = strlen(bp);
1460 } else {
1461 continue;
1462 }
1463 }
1464
886e1ddb
AM
1465 if ((tcmd = (char *) switch_stristr("X-pre-process", bp))) {
1466 if (*(tcmd - 1) != '<') {
59241895
MJ
1467 continue;
1468 }
1469 if ((e = strstr(tcmd, "/>"))) {
0ac27178 1470 e += 2;
59241895 1471 *e = '\0';
c5204c21 1472 if (fwrite(e, 1, (unsigned) strlen(e), write_fd) != (int) strlen(e)) {
59241895
MJ
1473 switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Short write!\n");
1474 }
1475 }
886e1ddb
AM
1476
1477 if (!(tcmd = (char *) switch_stristr("cmd", tcmd))) {
59241895
MJ
1478 continue;
1479 }
1480
886e1ddb 1481 if (!(tcmd = (char *) switch_stristr("=", tcmd))) {
59241895
MJ
1482 continue;
1483 }
1484
886e1ddb 1485 if (!(tcmd = (char *) switch_stristr("\"", tcmd))) {
59241895
MJ
1486 continue;
1487 }
886e1ddb 1488
59241895
MJ
1489 tcmd++;
1490
886e1ddb 1491
59241895
MJ
1492 if ((e = strchr(tcmd, '"'))) {
1493 *e++ = '\0';
1494 }
1495
886e1ddb 1496 if (!(targ = (char *) switch_stristr("data", e))) {
59241895
MJ
1497 continue;
1498 }
1499
886e1ddb 1500 if (!(targ = (char *) switch_stristr("=", targ))) {
59241895
MJ
1501 continue;
1502 }
1503
886e1ddb 1504 if (!(targ = (char *) switch_stristr("\"", targ))) {
59241895
MJ
1505 continue;
1506 }
1507
1508 targ++;
1509
1510 if ((e = strchr(targ, '"'))) {
1511 *e++ = '\0';
1512 }
886e1ddb 1513
59241895 1514 if (!strcasecmp(tcmd, "set")) {
886e1ddb 1515 char *name = (char *) targ;
59241895 1516 char *val = strchr(name, '=');
886e1ddb 1517
59241895
MJ
1518 if (val) {
1519 char *ve = val++;
1520 while (*val && *val == ' ') {
886e1ddb 1521 val++;
59241895
MJ
1522 }
1523 *ve-- = '\0';
1524 while (*ve && *ve == ' ') {
1525 *ve-- = '\0';
1526 }
1527 }
886e1ddb 1528
0ac27178 1529 if (val) {
59241895
MJ
1530 switch_core_set_variable(name, val);
1531 }
886e1ddb 1532
f30e40a8
KR
1533 } else if (!strcasecmp(tcmd, "exec-set")) {
1534 preprocess_exec_set(targ);
0629f95c
AV
1535 } else if (!strcasecmp(tcmd, "stun-set")) {
1536 preprocess_stun_set(targ);
4719d047
SD
1537 } else if (!strcasecmp(tcmd, "env-set")) {
1538 preprocess_env_set(targ);
59241895 1539 } else if (!strcasecmp(tcmd, "include")) {
2f48c631 1540 preprocess_glob(cwd, targ, write_fd, rlevel + 1);
64a0bfc5
AM
1541 } else if (!strcasecmp(tcmd, "exec")) {
1542 preprocess_exec(cwd, targ, write_fd, rlevel + 1);
59241895
MJ
1543 }
1544
1545 continue;
1546 }
886e1ddb 1547
59241895 1548 if ((cmd = strstr(bp, "<!--#"))) {
b39232c7 1549 if (fwrite(bp, 1, (unsigned) (cmd - bp), write_fd) != (unsigned) (cmd - bp)) {
59241895
MJ
1550 switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Short write!\n");
1551 }
1552 if ((e = strstr(cmd, "-->"))) {
1553 *e = '\0';
1554 e += 3;
c5204c21 1555 if (fwrite(e, 1, (unsigned) strlen(e), write_fd) != (int) strlen(e)) {
59241895
MJ
1556 switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Short write!\n");
1557 }
1558 } else {
1559 ml++;
1560 }
1561
1562 cmd += 5;
1563 if ((e = strchr(cmd, '\r')) || (e = strchr(cmd, '\n'))) {
1564 *e = '\0';
1565 }
1566
1567 if ((arg = strchr(cmd, ' '))) {
1568 *arg++ = '\0';
1569 if ((q = strchr(arg, '"'))) {
1570 char *qq = q + 1;
1571
1572 if ((qq = strchr(qq, '"'))) {
1573 *qq = '\0';
1574 arg = q + 1;
1575 }
1576 }
1577
1578 if (!strcasecmp(cmd, "set")) {
1579 char *name = arg;
1580 char *val = strchr(name, '=');
1581
1582 if (val) {
1583 char *ve = val++;
1584 while (*val && *val == ' ') {
1585 val++;
1586 }
1587 *ve-- = '\0';
1588 while (*ve && *ve == ' ') {
1589 *ve-- = '\0';
1590 }
1591 }
1592
0ac27178 1593 if (val) {
59241895
MJ
1594 switch_core_set_variable(name, val);
1595 }
1596
f30e40a8
KR
1597 } else if (!strcasecmp(cmd, "exec-set")) {
1598 preprocess_exec_set(arg);
0629f95c
AV
1599 } else if (!strcasecmp(cmd, "stun-set")) {
1600 preprocess_stun_set(arg);
59241895 1601 } else if (!strcasecmp(cmd, "include")) {
2f48c631 1602 preprocess_glob(cwd, arg, write_fd, rlevel + 1);
64a0bfc5
AM
1603 } else if (!strcasecmp(cmd, "exec")) {
1604 preprocess_exec(cwd, arg, write_fd, rlevel + 1);
59241895
MJ
1605 }
1606 }
1607
1608 continue;
1609 }
1610
c5204c21 1611 if (fwrite(bp, 1, (unsigned) cur, write_fd) != (int) cur) {
59241895
MJ
1612 switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Short write!\n");
1613 }
c5204c21 1614
59241895
MJ
1615 }
1616
c5204c21
AM
1617 switch_safe_free(buf);
1618 switch_safe_free(ebuf);
1619
1620 fclose(read_fd);
1621
1622 return 0;
59241895
MJ
1623}
1624
1625SWITCH_DECLARE(switch_xml_t) switch_xml_parse_file_simple(const char *file)
1626{
1627 int fd = -1;
1628 struct stat st;
9cf864ba 1629 switch_ssize_t l;
59241895
MJ
1630 void *m;
1631 switch_xml_root_t root;
1632
1633 if ((fd = open(file, O_RDONLY, 0)) > -1) {
1634 fstat(fd, &st);
9da34921 1635 if (!st.st_size) goto error;
350a739d
AM
1636 m = switch_must_malloc(st.st_size);
1637
9cf864ba 1638 if (!(0<(l = read(fd, m, st.st_size)))) goto error;
9da34921 1639 if (!(root = (switch_xml_root_t) switch_xml_parse_str((char *) m, l))) goto error;
59241895
MJ
1640 root->dynamic = 1;
1641 close(fd);
1642 return &root->xml;
1643 }
9da34921
AM
1644
1645 error:
1646
1647 switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Error Parsing File [%s]\n", file);
886e1ddb 1648
59241895
MJ
1649 return NULL;
1650}
1651
1652SWITCH_DECLARE(switch_xml_t) switch_xml_parse_file(const char *file)
1653{
c5204c21
AM
1654 int fd = -1;
1655 FILE *write_fd = NULL;
59241895
MJ
1656 switch_xml_t xml = NULL;
1657 char *new_file = NULL;
f087248c 1658 char *new_file_tmp = NULL;
da7f9715 1659 const char *abs, *absw;
59241895 1660
886e1ddb
AM
1661 abs = strrchr(file, '/');
1662 absw = strrchr(file, '\\');
da7f9715
JL
1663 if (abs || absw) {
1664 abs > absw ? abs++ : (abs = ++absw);
59241895
MJ
1665 } else {
1666 abs = file;
1667 }
a2fcb419 1668
3ed59f1d 1669 switch_mutex_lock(FILE_LOCK);
886e1ddb 1670
59241895 1671 if (!(new_file = switch_mprintf("%s%s%s.fsxml", SWITCH_GLOBAL_dirs.log_dir, SWITCH_PATH_SEPARATOR, abs))) {
3ed59f1d 1672 goto done;
59241895
MJ
1673 }
1674
f087248c
BW
1675 if (!(new_file_tmp = switch_mprintf("%s%s%s.fsxml.tmp", SWITCH_GLOBAL_dirs.log_dir, SWITCH_PATH_SEPARATOR, abs))) {
1676 goto done;
1677 }
1678
1679 if ((write_fd = fopen(new_file_tmp, "w+")) == NULL) {
59241895
MJ
1680 goto done;
1681 }
1682
c5204c21
AM
1683 setvbuf(write_fd, (char *) NULL, _IOFBF, 65536);
1684
59241895 1685 if (preprocess(SWITCH_GLOBAL_dirs.conf_dir, file, write_fd, 0) > -1) {
c5204c21
AM
1686 fclose(write_fd);
1687 write_fd = NULL;
69cc7014
JL
1688 unlink (new_file);
1689
f087248c
BW
1690 if ( rename(new_file_tmp,new_file) ) {
1691 goto done;
1692 }
59241895
MJ
1693 if ((fd = open(new_file, O_RDONLY, 0)) > -1) {
1694 if ((xml = switch_xml_parse_fd(fd))) {
1780e228 1695 if (strcmp(abs, SWITCH_GLOBAL_filenames.conf_name)) {
bd41ecc3
AM
1696 xml->free_path = new_file;
1697 new_file = NULL;
1698 }
59241895
MJ
1699 }
1700 close(fd);
1701 fd = -1;
1702 }
1703 }
1704
1705 done:
3ed59f1d
AM
1706
1707 switch_mutex_unlock(FILE_LOCK);
1708
c5204c21
AM
1709 if (write_fd) {
1710 fclose(write_fd);
1711 write_fd = NULL;
59241895 1712 }
3ed59f1d 1713
59241895
MJ
1714 if (fd > -1) {
1715 close(fd);
1716 }
3ed59f1d 1717
f087248c 1718 switch_safe_free(new_file_tmp);
59241895 1719 switch_safe_free(new_file);
3ed59f1d 1720
59241895
MJ
1721 return xml;
1722}
1723
1724SWITCH_DECLARE(switch_status_t) switch_xml_locate(const char *section,
1725 const char *tag_name,
886e1ddb
AM
1726 const char *key_name,
1727 const char *key_value,
1728 switch_xml_t *root, switch_xml_t *node, switch_event_t *params, switch_bool_t clone)
59241895
MJ
1729{
1730 switch_xml_t conf = NULL;
1731 switch_xml_t tag = NULL;
1732 switch_xml_t xml = NULL;
1733 switch_xml_binding_t *binding;
1734 uint8_t loops = 0;
9918f705 1735 switch_xml_section_t sections = BINDINGS ? switch_xml_parse_section_string(section) : 0;
59241895 1736
8ec9b8f7 1737 switch_thread_rwlock_rdlock(B_RWLOCK);
59241895
MJ
1738
1739 for (binding = BINDINGS; binding; binding = binding->next) {
59241895
MJ
1740 if (binding->sections && !(sections & binding->sections)) {
1741 continue;
1742 }
1743
1744 if ((xml = binding->function(section, tag_name, key_name, key_value, params, binding->user_data))) {
1745 const char *err = NULL;
1746
1747 err = switch_xml_error(xml);
df7637f6 1748 if (zstr(err)) {
59241895
MJ
1749 if ((conf = switch_xml_find_child(xml, "section", "name", "result"))) {
1750 switch_xml_t p;
1751 const char *aname;
1752
1753 if ((p = switch_xml_child(conf, "result"))) {
1754 aname = switch_xml_attr(p, "status");
1755 if (aname && !strcasecmp(aname, "not found")) {
1756 switch_xml_free(xml);
1757 xml = NULL;
1758 continue;
1759 }
1760 }
1761 }
1762 break;
1763 } else {
1764 switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Error[%s]\n", err);
1765 switch_xml_free(xml);
1766 xml = NULL;
1767 }
1768 }
1769 }
8ec9b8f7 1770 switch_thread_rwlock_unlock(B_RWLOCK);
59241895
MJ
1771
1772 for (;;) {
1773 if (!xml) {
1774 if (!(xml = switch_xml_root())) {
1775 *node = NULL;
1776 *root = NULL;
1777 return SWITCH_STATUS_FALSE;
1778 }
1779 }
1780
1781 if ((conf = switch_xml_find_child(xml, "section", "name", section)) && (tag = switch_xml_find_child(conf, tag_name, key_name, key_value))) {
93ec3d68 1782 if (clone) {
3b168bcb 1783 char *x = switch_xml_toxml(tag, SWITCH_FALSE);
93ec3d68 1784 switch_assert(x);
886e1ddb 1785 *node = *root = switch_xml_parse_str_dynamic(x, SWITCH_FALSE); /* x will be free()'d in switch_xml_free() */
93ec3d68
MJ
1786 switch_xml_free(xml);
1787 } else {
1788 *node = tag;
1789 *root = xml;
1790 }
59241895
MJ
1791 return SWITCH_STATUS_SUCCESS;
1792 } else {
1793 switch_xml_free(xml);
1794 xml = NULL;
1795 *node = NULL;
1796 *root = NULL;
1797 if (loops++ > 1) {
1798 break;
1799 }
1800 }
1801 }
1802
1803 return SWITCH_STATUS_FALSE;
1804}
1805
886e1ddb 1806SWITCH_DECLARE(switch_status_t) switch_xml_locate_domain(const char *domain_name, switch_event_t *params, switch_xml_t *root, switch_xml_t *domain)
59241895
MJ
1807{
1808 switch_event_t *my_params = NULL;
1809 switch_status_t status;
1810 *domain = NULL;
1811
1812 if (!params) {
003847dd 1813 switch_event_create(&my_params, SWITCH_EVENT_REQUEST_PARAMS);
59241895
MJ
1814 switch_assert(my_params);
1815 switch_event_add_header_string(my_params, SWITCH_STACK_BOTTOM, "domain", domain_name);
1816 params = my_params;
1817 }
1818
93ec3d68 1819 status = switch_xml_locate("directory", "domain", "name", domain_name, root, domain, params, SWITCH_FALSE);
59241895
MJ
1820 if (my_params) {
1821 switch_event_destroy(&my_params);
1822 }
1823 return status;
1824}
1825
ed100f44 1826SWITCH_DECLARE(switch_status_t) switch_xml_locate_group(const char *group_name,
886e1ddb
AM
1827 const char *domain_name,
1828 switch_xml_t *root, switch_xml_t *domain, switch_xml_t *group, switch_event_t *params)
ed100f44
AM
1829{
1830 switch_status_t status = SWITCH_STATUS_FALSE;
1831 switch_event_t *my_params = NULL;
1832 switch_xml_t groups = NULL;
1833
1834 *root = NULL;
1835 *group = NULL;
1836 *domain = NULL;
1837
1838 if (!params) {
1839 switch_event_create(&my_params, SWITCH_EVENT_REQUEST_PARAMS);
1840 switch_assert(my_params);
1841 params = my_params;
1842 }
1843
1844 if (group_name) {
1845 switch_event_add_header_string(params, SWITCH_STACK_BOTTOM, "group_name", group_name);
1846 }
1847
1848 if (domain_name) {
1849 switch_event_add_header_string(params, SWITCH_STACK_BOTTOM, "domain", domain_name);
1850 }
1851
1852 if ((status = switch_xml_locate_domain(domain_name, params, root, domain)) != SWITCH_STATUS_SUCCESS) {
1853 goto end;
1854 }
886e1ddb 1855
ed100f44
AM
1856 status = SWITCH_STATUS_FALSE;
1857
1858 if ((groups = switch_xml_child(*domain, "groups"))) {
1859 if ((*group = switch_xml_find_child(groups, "group", "name", group_name))) {
1860 status = SWITCH_STATUS_SUCCESS;
1861 }
1862 }
1863
886e1ddb 1864 end:
ed100f44
AM
1865
1866 if (my_params) {
1867 switch_event_destroy(&my_params);
1868 }
1869
1870 return status;
1871}
1872
de13f431
BW
1873static switch_status_t find_user_in_tag(switch_xml_t tag, const char *ip, const char *user_name,
1874 const char *key, switch_event_t *params, switch_xml_t *user)
ed100f44
AM
1875{
1876 const char *type = "!pointer";
1877 const char *val;
1878
1879 if (params && (val = switch_event_get_header(params, "user_type"))) {
1880 if (!strcasecmp(val, "any")) {
1881 type = NULL;
1882 } else {
1883 type = val;
1884 }
1885 }
1886
1887 if (ip) {
1888 if ((*user = switch_xml_find_child_multi(tag, "user", "ip", ip, "type", type, NULL))) {
1889 return SWITCH_STATUS_SUCCESS;
1890 }
886e1ddb 1891 }
ed100f44
AM
1892
1893 if (user_name) {
d18fa24a
MJ
1894 if (!strcasecmp(key, "id")) {
1895 if ((*user = switch_xml_find_child_multi(tag, "user", key, user_name, "number-alias", user_name, "type", type, NULL))) {
1896 return SWITCH_STATUS_SUCCESS;
1897 }
1898 } else {
1899 if ((*user = switch_xml_find_child_multi(tag, "user", key, user_name, "type", type, NULL))) {
ed100f44
AM
1900 return SWITCH_STATUS_SUCCESS;
1901 }
ed100f44
AM
1902 }
1903 }
886e1ddb 1904
ed100f44 1905 return SWITCH_STATUS_FALSE;
886e1ddb 1906
ed100f44
AM
1907}
1908
886e1ddb 1909SWITCH_DECLARE(switch_status_t) switch_xml_locate_user_in_domain(const char *user_name, switch_xml_t domain, switch_xml_t *user, switch_xml_t *ingroup)
bb974720
AM
1910{
1911 switch_xml_t group = NULL, groups = NULL, users = NULL;
1912 switch_status_t status = SWITCH_STATUS_FALSE;
886e1ddb 1913
bb974720
AM
1914 if ((groups = switch_xml_child(domain, "groups"))) {
1915 for (group = switch_xml_child(groups, "group"); group; group = group->next) {
1916 if ((users = switch_xml_child(group, "users"))) {
1917 if ((status = find_user_in_tag(users, NULL, user_name, "id", NULL, user)) == SWITCH_STATUS_SUCCESS) {
1918 if (ingroup) {
1919 *ingroup = group;
1920 }
1921 break;
1922 }
1923 }
1924 }
1064bb04
AM
1925 } else {
1926 if ((users = switch_xml_child(domain, "users"))) {
1927 status = find_user_in_tag(users, NULL, user_name, "id", NULL, user);
1928 } else {
1929 status = find_user_in_tag(domain, NULL, user_name, "id", NULL, user);
1930 }
bb974720
AM
1931 }
1932
1933 return status;
1934}
ed100f44 1935
c65da59d
AM
1936
1937SWITCH_DECLARE(switch_xml_t) switch_xml_dup(switch_xml_t xml)
1938{
1939 char *x = switch_xml_toxml(xml, SWITCH_FALSE);
a2fcb419 1940 return switch_xml_parse_str_dynamic(x, SWITCH_FALSE);
c65da59d
AM
1941}
1942
1943
a2fcb419 1944static void do_merge(switch_xml_t in, switch_xml_t src, const char *container, const char *tag_name)
c65da59d
AM
1945{
1946 switch_xml_t itag, tag, param, iparam, iitag;
1947
1948 if (!(itag = switch_xml_child(in, container))) {
1949 itag = switch_xml_add_child_d(in, container, 0);
1950 }
1951
1952 if ((tag = switch_xml_child(src, container))) {
1953 for (param = switch_xml_child(tag, tag_name); param; param = param->next) {
1954 const char *var = switch_xml_attr(param, "name");
1955 const char *val = switch_xml_attr(param, "value");
a2fcb419 1956
0147d4db 1957 switch_bool_t add_child = SWITCH_TRUE;
c65da59d
AM
1958
1959 for (iparam = switch_xml_child(itag, tag_name); iparam; iparam = iparam->next) {
1960 const char *ivar = switch_xml_attr(iparam, "name");
a2fcb419 1961
c65da59d 1962 if (var && ivar && !strcasecmp(var, ivar)) {
0147d4db 1963 add_child = SWITCH_FALSE;
c65da59d
AM
1964 break;
1965 }
1966 }
a2fcb419 1967
0147d4db 1968 if (add_child) {
c65da59d 1969 iitag = switch_xml_add_child_d(itag, tag_name, 0);
ea5db72a
BW
1970 switch_xml_set_attr_d(iitag, "name", var);
1971 switch_xml_set_attr_d(iitag, "value", val);
c65da59d
AM
1972 }
1973 }
1974 }
a2fcb419 1975
c65da59d
AM
1976}
1977
1978
1979SWITCH_DECLARE(void) switch_xml_merge_user(switch_xml_t user, switch_xml_t domain, switch_xml_t group)
1980{
f08c3309 1981 const char *domain_name = switch_xml_attr(domain, "name");
c65da59d
AM
1982
1983 do_merge(user, group, "params", "param");
1984 do_merge(user, group, "variables", "variable");
a6bffd38 1985 do_merge(user, group, "profile-variables", "variable");
c65da59d
AM
1986 do_merge(user, domain, "params", "param");
1987 do_merge(user, domain, "variables", "variable");
a6bffd38 1988 do_merge(user, domain, "profile-variables", "variable");
f08c3309
AM
1989
1990 if (!zstr(domain_name)) {
1991 switch_xml_set_attr_d(user, "domain-name", domain_name);
1992 }
c65da59d
AM
1993}
1994
2582bbcb
AM
1995SWITCH_DECLARE(uint32_t) switch_xml_clear_user_cache(const char *key, const char *user_name, const char *domain_name)
1996{
7151d6ac 1997 switch_hash_index_t *hi = NULL;
2582bbcb
AM
1998 void *val;
1999 const void *var;
2000 char mega_key[1024];
2001 int r = 0;
2002 switch_xml_t lookup;
15b8dfa8 2003 char *expires_val = NULL;
2582bbcb
AM
2004
2005 switch_mutex_lock(CACHE_MUTEX);
2006
2007 if (key && user_name && domain_name) {
2008 switch_snprintf(mega_key, sizeof(mega_key), "%s%s%s", key, user_name, domain_name);
2009
2010 if ((lookup = switch_core_hash_find(CACHE_HASH, mega_key))) {
2011 switch_core_hash_delete(CACHE_HASH, mega_key);
15b8dfa8 2012 if ((expires_val = switch_core_hash_find(CACHE_EXPIRES_HASH, mega_key))) {
a2fcb419 2013 switch_core_hash_delete(CACHE_EXPIRES_HASH, mega_key);
15b8dfa8
AM
2014 free(expires_val);
2015 expires_val = NULL;
a2fcb419 2016 }
2582bbcb
AM
2017 switch_xml_free(lookup);
2018 r++;
2019 }
a2fcb419 2020
2582bbcb 2021 } else {
a2fcb419 2022
7151d6ac 2023 while ((hi = switch_core_hash_first_iter( CACHE_HASH, hi))) {
804ef770 2024 switch_core_hash_this(hi, &var, NULL, &val);
2582bbcb
AM
2025 switch_xml_free(val);
2026 switch_core_hash_delete(CACHE_HASH, var);
2027 r++;
2582bbcb 2028 }
a2fcb419 2029
7151d6ac 2030 while ((hi = switch_core_hash_first_iter( CACHE_EXPIRES_HASH, hi))) {
804ef770 2031 switch_core_hash_this(hi, &var, NULL, &val);
a2fcb419
RC
2032 switch_safe_free(val);
2033 switch_core_hash_delete(CACHE_EXPIRES_HASH, var);
2034 }
7151d6ac
AM
2035
2036 switch_safe_free(hi);
2582bbcb
AM
2037 }
2038
2039 switch_mutex_unlock(CACHE_MUTEX);
a2fcb419 2040
2582bbcb 2041 return r;
a2fcb419 2042
2582bbcb
AM
2043}
2044
2045static switch_status_t switch_xml_locate_user_cache(const char *key, const char *user_name, const char *domain_name, switch_xml_t *user)
2046{
2047 char mega_key[1024];
2582bbcb 2048 switch_status_t status = SWITCH_STATUS_FALSE;
a2fcb419 2049 switch_xml_t lookup;
2582bbcb
AM
2050
2051 switch_snprintf(mega_key, sizeof(mega_key), "%s%s%s", key, user_name, domain_name);
2052
2053 switch_mutex_lock(CACHE_MUTEX);
2054 if ((lookup = switch_core_hash_find(CACHE_HASH, mega_key))) {
a2fcb419
RC
2055 char *expires_lookup = NULL;
2056
2057 if ((expires_lookup = switch_core_hash_find(CACHE_EXPIRES_HASH, mega_key))) {
2058 switch_time_t time_expires = 0;
2059 switch_time_t time_now = 0;
2060
2061 time_now = switch_micro_time_now();
2062 time_expires = atol(expires_lookup);
ab7ae9f7 2063 switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "Cache Info\nTime Now:\t%ld\nExpires:\t%ld\n", (long)time_now, (long)time_expires);
a2fcb419
RC
2064 if (time_expires < time_now) {
2065 switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "Cache expired for %s@%s, doing fresh lookup\n", user_name, domain_name);
2066 } else {
2067 *user = switch_xml_dup(lookup);
2068 status = SWITCH_STATUS_SUCCESS;
2069 }
2070 } else {
2071 *user = switch_xml_dup(lookup);
2072 status = SWITCH_STATUS_SUCCESS;
2073 }
2582bbcb
AM
2074 }
2075 switch_mutex_unlock(CACHE_MUTEX);
2076
2077 return status;
2078}
2079
a2fcb419 2080static void switch_xml_user_cache(const char *key, const char *user_name, const char *domain_name, switch_xml_t user, switch_time_t expires)
2582bbcb
AM
2081{
2082 char mega_key[1024];
2083 switch_xml_t lookup;
a2fcb419 2084 char *expires_lookup;
2582bbcb
AM
2085
2086 switch_snprintf(mega_key, sizeof(mega_key), "%s%s%s", key, user_name, domain_name);
a2fcb419 2087
2582bbcb
AM
2088 switch_mutex_lock(CACHE_MUTEX);
2089 if ((lookup = switch_core_hash_find(CACHE_HASH, mega_key))) {
2090 switch_core_hash_delete(CACHE_HASH, mega_key);
2091 switch_xml_free(lookup);
2092 }
a2fcb419
RC
2093 if ((expires_lookup = switch_core_hash_find(CACHE_EXPIRES_HASH, mega_key))) {
2094 switch_core_hash_delete(CACHE_EXPIRES_HASH, mega_key);
2095 switch_safe_free(expires_lookup);
2096 }
2097 if (expires) {
781180ff
AV
2098 char *expires_val = (char *)switch_core_hash_insert_alloc(CACHE_EXPIRES_HASH, mega_key, 22);
2099 if (!snprintf(expires_val, 22, "%ld", (long)expires)) {
2100 switch_core_hash_delete(CACHE_EXPIRES_HASH, mega_key);
bdbefdcc 2101 switch_safe_free(expires_val);
a2fcb419
RC
2102 }
2103 }
2582bbcb
AM
2104 switch_core_hash_insert(CACHE_HASH, mega_key, switch_xml_dup(user));
2105 switch_mutex_unlock(CACHE_MUTEX);
2106}
2107
c65da59d
AM
2108SWITCH_DECLARE(switch_status_t) switch_xml_locate_user_merged(const char *key, const char *user_name, const char *domain_name,
2109 const char *ip, switch_xml_t *user, switch_event_t *params)
2110{
2111 switch_xml_t xml, domain, group, x_user, x_user_dup;
2112 switch_status_t status = SWITCH_STATUS_FALSE;
726b6076
AM
2113 char *kdup = NULL;
2114 char *keys[10] = {0};
2115 int i, nkeys;
c65da59d 2116
726b6076 2117 if (strchr(key, ':')) {
350a739d 2118 kdup = switch_must_strdup(key);
726b6076
AM
2119 nkeys = switch_split(kdup, ':', keys);
2120 } else {
2121 keys[0] = (char *)key;
2122 nkeys = 1;
2123 }
a2fcb419 2124
726b6076
AM
2125 for(i = 0; i < nkeys; i++) {
2126 if ((status = switch_xml_locate_user_cache(keys[i], user_name, domain_name, &x_user)) == SWITCH_STATUS_SUCCESS) {
2127 *user = x_user;
2128 break;
2129 } else if ((status = switch_xml_locate_user(keys[i], user_name, domain_name, ip, &xml, &domain, &x_user, &group, params)) == SWITCH_STATUS_SUCCESS) {
2130 const char *cacheable = NULL;
2131
2132 x_user_dup = switch_xml_dup(x_user);
2133 switch_xml_merge_user(x_user_dup, domain, group);
2134
2135 cacheable = switch_xml_attr(x_user_dup, "cacheable");
87c5c64c 2136 if (!zstr(cacheable)) {
726b6076
AM
2137 switch_time_t expires = 0;
2138 switch_time_t time_now = 0;
2139
2140 if (switch_is_number(cacheable)) {
2141 int cache_ms = atol(cacheable);
df1ab07c 2142 switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "caching lookup for user %s@%s for %d milliseconds\n",
726b6076
AM
2143 user_name, domain_name, cache_ms);
2144 time_now = switch_micro_time_now();
2145 expires = time_now + (cache_ms * 1000);
2146 } else {
2147 switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "caching lookup for user %s@%s indefinitely\n", user_name, domain_name);
2148 }
2149 switch_xml_user_cache(keys[i], user_name, domain_name, x_user_dup, expires);
a2fcb419 2150 }
726b6076
AM
2151 *user = x_user_dup;
2152 switch_xml_free(xml);
2153 break;
2582bbcb 2154 }
c65da59d
AM
2155 }
2156
726b6076
AM
2157 switch_safe_free(kdup);
2158
c65da59d
AM
2159 return status;
2160
2161}
2162
59241895
MJ
2163SWITCH_DECLARE(switch_status_t) switch_xml_locate_user(const char *key,
2164 const char *user_name,
886e1ddb
AM
2165 const char *domain_name,
2166 const char *ip,
59241895 2167 switch_xml_t *root,
886e1ddb 2168 switch_xml_t *domain, switch_xml_t *user, switch_xml_t *ingroup, switch_event_t *params)
59241895 2169{
5e5847f3 2170 switch_status_t status = SWITCH_STATUS_FALSE;
73279f01 2171 switch_event_t *my_params = NULL;
ed100f44 2172 switch_xml_t group = NULL, groups = NULL, users = NULL;
886e1ddb 2173
59241895
MJ
2174 *root = NULL;
2175 *user = NULL;
2176 *domain = NULL;
2177
772f9570
AM
2178 if (ingroup) {
2179 *ingroup = NULL;
2180 }
2181
5e5847f3 2182 if (!params) {
003847dd 2183 switch_event_create(&my_params, SWITCH_EVENT_REQUEST_PARAMS);
5e5847f3
AM
2184 switch_assert(my_params);
2185 params = my_params;
2186 }
59241895 2187
5e5847f3 2188 switch_event_add_header_string(params, SWITCH_STACK_BOTTOM, "key", key);
59241895 2189
5e5847f3
AM
2190 if (user_name) {
2191 switch_event_add_header_string(params, SWITCH_STACK_BOTTOM, "user", user_name);
2192 }
59241895 2193
5e5847f3
AM
2194 if (domain_name) {
2195 switch_event_add_header_string(params, SWITCH_STACK_BOTTOM, "domain", domain_name);
59241895 2196 }
59241895 2197
5e5847f3
AM
2198 if (ip) {
2199 switch_event_add_header_string(params, SWITCH_STACK_BOTTOM, "ip", ip);
2200 }
886e1ddb 2201
59241895 2202 if ((status = switch_xml_locate_domain(domain_name, params, root, domain)) != SWITCH_STATUS_SUCCESS) {
5e5847f3 2203 goto end;
59241895 2204 }
886e1ddb 2205
a2a748dd
AM
2206 status = SWITCH_STATUS_FALSE;
2207
ed100f44
AM
2208 if ((groups = switch_xml_child(*domain, "groups"))) {
2209 for (group = switch_xml_child(groups, "group"); group; group = group->next) {
2210 if ((users = switch_xml_child(group, "users"))) {
2211 if ((status = find_user_in_tag(users, ip, user_name, key, params, user)) == SWITCH_STATUS_SUCCESS) {
2212 if (ingroup) {
2213 *ingroup = group;
2214 }
2215 break;
2216 }
59241895
MJ
2217 }
2218 }
ed100f44 2219 }
59241895 2220
ed100f44 2221 if (status != SWITCH_STATUS_SUCCESS) {
1064bb04
AM
2222 if ((users = switch_xml_child(*domain, "users"))) {
2223 status = find_user_in_tag(users, ip, user_name, key, params, user);
2224 } else {
2225 status = find_user_in_tag(*domain, ip, user_name, key, params, user);
2226 }
59241895 2227 }
886e1ddb
AM
2228
2229 end:
5e5847f3
AM
2230
2231 if (my_params) {
2232 switch_event_destroy(&my_params);
2233 }
2234
e5f6e42e
AM
2235 if (status != SWITCH_STATUS_SUCCESS && root && *root) {
2236 switch_xml_free(*root);
2237 *root = NULL;
2238 *domain = NULL;
2239 }
2240
5e5847f3 2241 return status;
59241895
MJ
2242}
2243
2244SWITCH_DECLARE(switch_xml_t) switch_xml_root(void)
2245{
4714ed43 2246 switch_xml_t xml;
471bd6df 2247
4714ed43
AM
2248 switch_mutex_lock(REFLOCK);
2249 xml = MAIN_XML_ROOT;
2250 xml->refs++;
2251 switch_mutex_unlock(REFLOCK);
a2fcb419 2252
4714ed43 2253 return xml;
59241895
MJ
2254}
2255
7e9f64ee
AM
2256struct destroy_xml {
2257 switch_xml_t xml;
2258 switch_memory_pool_t *pool;
2259};
2260
2261static void *SWITCH_THREAD_FUNC destroy_thread(switch_thread_t *thread, void *obj)
2262{
2263 struct destroy_xml *dx = (struct destroy_xml *) obj;
2264 switch_memory_pool_t *pool = dx->pool;
2265 switch_xml_free(dx->xml);
2266 switch_core_destroy_memory_pool(&pool);
2267 return NULL;
2268}
2269
2270SWITCH_DECLARE(void) switch_xml_free_in_thread(switch_xml_t xml, int stacksize)
2271{
2272 switch_thread_t *thread;
886e1ddb 2273 switch_threadattr_t *thd_attr;
7e9f64ee
AM
2274 switch_memory_pool_t *pool = NULL;
2275 struct destroy_xml *dx;
2276
2277 switch_core_new_memory_pool(&pool);
2278
2279 switch_threadattr_create(&thd_attr, pool);
886e1ddb 2280 switch_threadattr_detach_set(thd_attr, 1);
de13f431 2281 /* TBD figure out how much space we need by looking at the xml_t when stacksize == 0 */
886e1ddb 2282 switch_threadattr_stacksize_set(thd_attr, stacksize);
7e9f64ee
AM
2283
2284 dx = switch_core_alloc(pool, sizeof(*dx));
2285 dx->pool = pool;
2286 dx->xml = xml;
2287
2288 switch_thread_create(&thread, thd_attr, destroy_thread, dx, pool);
7e9f64ee
AM
2289}
2290
59241895
MJ
2291static char not_so_threadsafe_error_buffer[256] = "";
2292
07a71592
AM
2293SWITCH_DECLARE(switch_status_t) switch_xml_set_root(switch_xml_t new_main)
2294{
2295 switch_xml_t old_root = NULL;
a2fcb419 2296
07a71592
AM
2297 switch_mutex_lock(REFLOCK);
2298
2299 old_root = MAIN_XML_ROOT;
2300 MAIN_XML_ROOT = new_main;
2301 switch_set_flag(MAIN_XML_ROOT, SWITCH_XML_ROOT);
2302 MAIN_XML_ROOT->refs++;
a2fcb419 2303
07a71592
AM
2304 if (old_root) {
2305 if (old_root->refs) {
2306 old_root->refs--;
2307 }
2308
2309 if (!old_root->refs) {
2310 switch_xml_free(old_root);
2311 }
2312 }
2313
2314 switch_mutex_unlock(REFLOCK);
2315
2316 return SWITCH_STATUS_SUCCESS;
2317}
2318
2319SWITCH_DECLARE(switch_status_t) switch_xml_set_open_root_function(switch_xml_open_root_function_t func, void *user_data)
2320{
2321 if (XML_LOCK) {
2322 switch_mutex_lock(XML_LOCK);
2323 }
a2fcb419 2324
07a71592
AM
2325 XML_OPEN_ROOT_FUNCTION = func;
2326 XML_OPEN_ROOT_FUNCTION_USER_DATA = user_data;
2327
2328 if (XML_LOCK) {
2329 switch_mutex_unlock(XML_LOCK);
2330 }
2331 return SWITCH_STATUS_SUCCESS;
2332}
2333
a2fcb419 2334SWITCH_DECLARE(switch_xml_t) switch_xml_open_root(uint8_t reload, const char **err)
07a71592
AM
2335{
2336 switch_xml_t root = NULL;
32437d04 2337 switch_event_t *event;
07a71592
AM
2338
2339 switch_mutex_lock(XML_LOCK);
2340
2341 if (XML_OPEN_ROOT_FUNCTION) {
2342 root = XML_OPEN_ROOT_FUNCTION(reload, err, XML_OPEN_ROOT_FUNCTION_USER_DATA);
2343 }
2344 switch_mutex_unlock(XML_LOCK);
2345
32437d04
AM
2346
2347 if (root) {
2348 if (switch_event_create(&event, SWITCH_EVENT_RELOADXML) == SWITCH_STATUS_SUCCESS) {
2349 if (switch_event_fire(&event) != SWITCH_STATUS_SUCCESS) {
2350 switch_event_destroy(&event);
2351 }
2352 }
2353 }
2354
07a71592
AM
2355 return root;
2356}
2357
3aaa6209 2358SWITCH_DECLARE_NONSTD(switch_xml_t) __switch_xml_open_root(uint8_t reload, const char **err, void *user_data)
59241895
MJ
2359{
2360 char path_buf[1024];
1ba98b02 2361 uint8_t errcnt = 0;
4714ed43 2362 switch_xml_t new_main, r = NULL;
59241895 2363
4714ed43
AM
2364 if (MAIN_XML_ROOT) {
2365 if (!reload) {
2366 r = switch_xml_root();
2367 goto done;
2368 }
59241895
MJ
2369 }
2370
bf607b0d 2371 switch_snprintf(path_buf, sizeof(path_buf), "%s%s%s", SWITCH_GLOBAL_dirs.conf_dir, SWITCH_PATH_SEPARATOR, SWITCH_GLOBAL_filenames.conf_name);
59241895
MJ
2372 if ((new_main = switch_xml_parse_file(path_buf))) {
2373 *err = switch_xml_error(new_main);
2374 switch_copy_string(not_so_threadsafe_error_buffer, *err, sizeof(not_so_threadsafe_error_buffer));
2375 *err = not_so_threadsafe_error_buffer;
df7637f6 2376 if (!zstr(*err)) {
59241895
MJ
2377 switch_xml_free(new_main);
2378 new_main = NULL;
2379 errcnt++;
2380 } else {
59241895 2381 *err = "Success";
07a71592 2382 switch_xml_set_root(new_main);
471bd6df 2383
59241895
MJ
2384 }
2385 } else {
2386 *err = "Cannot Open log directory or XML Root!";
2387 errcnt++;
2388 }
2389
59241895 2390 if (errcnt == 0) {
333019eb 2391 r = switch_xml_root();
59241895
MJ
2392 }
2393
07a71592 2394 done:
4714ed43 2395
333019eb 2396 return r;
59241895
MJ
2397}
2398
42c9df72
AM
2399SWITCH_DECLARE(switch_status_t) switch_xml_reload(const char **err)
2400{
2401 switch_xml_t xml_root;
a2fcb419 2402
42c9df72
AM
2403 if ((xml_root = switch_xml_open_root(1, err))) {
2404 switch_xml_free(xml_root);
2405 return SWITCH_STATUS_SUCCESS;
2406 }
2407
2408 return SWITCH_STATUS_GENERR;
2409}
2410
59241895
MJ
2411SWITCH_DECLARE(switch_status_t) switch_xml_init(switch_memory_pool_t *pool, const char **err)
2412{
2413 switch_xml_t xml;
2414 XML_MEMORY_POOL = pool;
2415 *err = "Success";
2416
2582bbcb 2417 switch_mutex_init(&CACHE_MUTEX, SWITCH_MUTEX_NESTED, XML_MEMORY_POOL);
4714ed43
AM
2418 switch_mutex_init(&XML_LOCK, SWITCH_MUTEX_NESTED, XML_MEMORY_POOL);
2419 switch_mutex_init(&REFLOCK, SWITCH_MUTEX_NESTED, XML_MEMORY_POOL);
3ed59f1d 2420 switch_mutex_init(&FILE_LOCK, SWITCH_MUTEX_NESTED, XML_MEMORY_POOL);
804ef770
AM
2421 switch_core_hash_init(&CACHE_HASH);
2422 switch_core_hash_init(&CACHE_EXPIRES_HASH);
4714ed43 2423
8ec9b8f7 2424 switch_thread_rwlock_create(&B_RWLOCK, XML_MEMORY_POOL);
59241895
MJ
2425
2426 assert(pool != NULL);
2427
2428 if ((xml = switch_xml_open_root(FALSE, err))) {
2429 switch_xml_free(xml);
2430 return SWITCH_STATUS_SUCCESS;
2431 } else {
2432 return SWITCH_STATUS_FALSE;
2433 }
2434}
2435
2436SWITCH_DECLARE(switch_status_t) switch_xml_destroy(void)
2437{
333019eb 2438 switch_status_t status = SWITCH_STATUS_FALSE;
3ed59f1d 2439
2582bbcb 2440
4714ed43 2441 switch_mutex_lock(XML_LOCK);
3ed59f1d 2442 switch_mutex_lock(REFLOCK);
886e1ddb 2443
59241895
MJ
2444 if (MAIN_XML_ROOT) {
2445 switch_xml_t xml = MAIN_XML_ROOT;
2446 MAIN_XML_ROOT = NULL;
2447 switch_xml_free(xml);
333019eb 2448 status = SWITCH_STATUS_SUCCESS;
59241895
MJ
2449 }
2450
4714ed43 2451 switch_mutex_unlock(XML_LOCK);
3ed59f1d 2452 switch_mutex_unlock(REFLOCK);
333019eb 2453
2582bbcb
AM
2454 switch_xml_clear_user_cache(NULL, NULL, NULL);
2455
2456 switch_core_hash_destroy(&CACHE_HASH);
718d2341 2457 switch_core_hash_destroy(&CACHE_EXPIRES_HASH);
2582bbcb 2458
333019eb 2459 return status;
59241895
MJ
2460}
2461
2462SWITCH_DECLARE(switch_xml_t) switch_xml_open_cfg(const char *file_path, switch_xml_t *node, switch_event_t *params)
2463{
2464 switch_xml_t xml = NULL, cfg = NULL;
2465
2466 *node = NULL;
2467
2468 assert(MAIN_XML_ROOT != NULL);
2469
93ec3d68 2470 if (switch_xml_locate("configuration", "configuration", "name", file_path, &xml, &cfg, params, SWITCH_FALSE) == SWITCH_STATUS_SUCCESS) {
59241895
MJ
2471 *node = cfg;
2472 }
2473
2474 return xml;
2475
2476}
2477
de13f431
BW
2478/* Encodes ampersand sequences appending the results to *dst, reallocating *dst
2479 if length exceeds max. a is non-zero for attribute encoding. Returns *dst */
79079942 2480static char *switch_xml_ampencode(const char *s, switch_size_t len, char **dst, switch_size_t *dlen, switch_size_t *max, short a, switch_bool_t use_utf8_encoding)
59241895
MJ
2481{
2482 const char *e = NULL;
2483 int immune = 0;
4cd616cc
MOC
2484 int expecting_x_utf_8_char = 0;
2485 int unicode_char = 0x000000;
59241895 2486
886e1ddb
AM
2487 if (!(s && *s))
2488 return *dst;
59241895
MJ
2489
2490 if (len) {
2491 e = s + len;
2492 }
2493
2494 while (s != e) {
2495 while (*dlen + 10 > *max) {
350a739d 2496 *dst = (char *) switch_must_realloc(*dst, *max += SWITCH_XML_BUFSIZE);
59241895
MJ
2497 }
2498
2499 if (immune) {
2500 if (*s == '\0') {
2501 return *dst;
2502 }
2503 (*dst)[(*dlen)++] = *s;
886e1ddb 2504 } else
59241895 2505 switch (*s) {
886e1ddb
AM
2506 case '\0':
2507 return *dst;
2508 case '&':
2509 *dlen += sprintf(*dst + *dlen, "&amp;");
2510 break;
2511 case '<':
2512 if (*(s + 1) == '!') {
2513 (*dst)[(*dlen)++] = *s;
2514 immune++;
2515 break;
2516 }
2517 *dlen += sprintf(*dst + *dlen, "&lt;");
2518 break;
2519 case '>':
2520 *dlen += sprintf(*dst + *dlen, "&gt;");
59241895 2521 break;
886e1ddb
AM
2522 case '"':
2523 *dlen += sprintf(*dst + *dlen, (a) ? "&quot;" : "\"");
2524 break;
2525 case '\n':
2526 *dlen += sprintf(*dst + *dlen, (a) ? "&#xA;" : "\n");
2527 break;
2528 case '\t':
2529 *dlen += sprintf(*dst + *dlen, (a) ? "&#x9;" : "\t");
2530 break;
2531 case '\r':
2532 *dlen += sprintf(*dst + *dlen, "&#xD;");
2533 break;
2534 default:
79079942 2535 if (use_utf8_encoding && expecting_x_utf_8_char == 0 && ((*s >> 8) & 0x01)) {
4cd616cc
MOC
2536 int num = 1;
2537 for (;num<4;num++) {
2538 if (! ((*s >> (7-num)) & 0x01)) {
2539 break;
2540 }
2541 }
2542 switch (num) {
2543 case 2:
2544 unicode_char = *s & 0x1f;
2545 break;
2546 case 3:
2547 unicode_char = *s & 0x0f;
2548 break;
2549 case 4:
2550 unicode_char = *s & 0x07;
2551 break;
2552 default:
2553 switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_WARNING, "Invalid UTF-8 Initial charactere, skip it\n");
2554 /* ERROR HERE */
2555 break;
2556 }
2557 expecting_x_utf_8_char = num - 1;
2558
79079942 2559 } else if (use_utf8_encoding && expecting_x_utf_8_char > 0) {
4cd616cc
MOC
2560 if (((*s >> 6) & 0x03) == 0x2) {
2561
2562 unicode_char = unicode_char << 6;
2563 unicode_char = unicode_char | (*s & 0x3f);
2564 } else {
2565 switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_WARNING, "Invalid UTF-8 character to ampersand, skip it\n");
2566 expecting_x_utf_8_char = 0;
2567 break;
2568 }
2569 expecting_x_utf_8_char--;
2570 if (expecting_x_utf_8_char == 0) {
2571 *dlen += sprintf(*dst + *dlen, "&#x%X;", unicode_char);
2572 }
2573 } else {
2574 (*dst)[(*dlen)++] = *s;
2575 }
59241895 2576 }
59241895
MJ
2577 s++;
2578 }
2579 return *dst;
2580}
2581
2582#define XML_INDENT " "
de13f431
BW
2583/* Recursively converts each tag to xml appending it to *s. Reallocates *s if
2584 its length exceeds max. start is the location of the previous tag in the
2585 parent tag's character content. Returns *s. */
79079942 2586static char *switch_xml_toxml_r(switch_xml_t xml, char **s, switch_size_t *len, switch_size_t *max, switch_size_t start, char ***attr, uint32_t *count, int isroot, switch_bool_t use_utf8_encoding)
59241895
MJ
2587{
2588 int i, j;
9fa14d52
BW
2589 char *txt;
2590 switch_size_t off;
2591 uint32_t lcount;
287fd668 2592 uint32_t loops = 0;
9fa14d52 2593
886e1ddb 2594 tailrecurse:
9fa14d52 2595 off = 0;
287fd668
AM
2596 txt = "";
2597
2598 if (loops++) {
2599 isroot = 0;
2600 }
2601
2602 if (!isroot && xml->parent) {
2603 txt = (char *) xml->parent->txt;
2604 }
59241895 2605
de13f431 2606 /* parent character content up to this tag */
79079942 2607 *s = switch_xml_ampencode(txt + start, xml->off - start, s, len, max, 0, use_utf8_encoding);
59241895 2608
de13f431 2609 while (*len + strlen(xml->name) + 5 + (strlen(XML_INDENT) * (*count)) + 1 > *max) { /* reallocate s */
350a739d 2610 *s = (char *) switch_must_realloc(*s, *max += SWITCH_XML_BUFSIZE);
59241895
MJ
2611 }
2612
53ab0e2a 2613 if (*len && *(*s + (*len) - 1) == '>') {
de13f431 2614 *len += sprintf(*s + *len, "\n"); /* indent */
59241895
MJ
2615 }
2616 for (lcount = 0; lcount < *count; lcount++) {
de13f431 2617 *len += sprintf(*s + *len, "%s", XML_INDENT); /* indent */
59241895
MJ
2618 }
2619
de13f431
BW
2620 *len += sprintf(*s + *len, "<%s", xml->name); /* open tag */
2621 for (i = 0; xml->attr[i]; i += 2) { /* tag attributes */
59241895
MJ
2622 if (switch_xml_attr(xml, xml->attr[i]) != xml->attr[i + 1])
2623 continue;
de13f431 2624 while (*len + strlen(xml->attr[i]) + 7 + (strlen(XML_INDENT) * (*count)) > *max) { /* reallocate s */
350a739d 2625 *s = (char *) switch_must_realloc(*s, *max += SWITCH_XML_BUFSIZE);
59241895
MJ
2626 }
2627
2628 *len += sprintf(*s + *len, " %s=\"", xml->attr[i]);
79079942 2629 switch_xml_ampencode(xml->attr[i + 1], 0, s, len, max, 1, use_utf8_encoding);
59241895
MJ
2630 *len += sprintf(*s + *len, "\"");
2631 }
2632
2633 for (i = 0; attr[i] && strcmp(attr[i][0], xml->name); i++);
de13f431 2634 for (j = 1; attr[i] && attr[i][j]; j += 3) { /* default attributes */
59241895 2635 if (!attr[i][j + 1] || switch_xml_attr(xml, attr[i][j]) != attr[i][j + 1])
de13f431
BW
2636 continue; /* skip duplicates and non-values */
2637 while (*len + strlen(attr[i][j]) + 8 + (strlen(XML_INDENT) * (*count)) > *max) { /* reallocate s */
350a739d 2638 *s = (char *) switch_must_realloc(*s, *max += SWITCH_XML_BUFSIZE);
59241895
MJ
2639 }
2640
2641 *len += sprintf(*s + *len, " %s=\"", attr[i][j]);
79079942 2642 switch_xml_ampencode(attr[i][j + 1], 0, s, len, max, 1, use_utf8_encoding);
59241895
MJ
2643 *len += sprintf(*s + *len, "\"");
2644 }
2645
2646 *len += sprintf(*s + *len, (xml->child || xml->txt) ? ">" : "/>\n");
2647
2648 if (xml->child) {
2649 (*count)++;
79079942 2650 *s = switch_xml_toxml_r(xml->child, s, len, max, 0, attr, count, 0, use_utf8_encoding);
59241895
MJ
2651
2652 } else {
79079942 2653 *s = switch_xml_ampencode(xml->txt, 0, s, len, max, 0, use_utf8_encoding); /* data */
59241895
MJ
2654 }
2655
de13f431 2656 while (*len + strlen(xml->name) + 5 + (strlen(XML_INDENT) * (*count)) > *max) { /* reallocate s */
350a739d 2657 *s = (char *) switch_must_realloc(*s, *max += SWITCH_XML_BUFSIZE);
886e1ddb 2658 }
59241895
MJ
2659
2660 if (xml->child || xml->txt) {
2661 if (*(*s + (*len) - 1) == '\n') {
2662 for (lcount = 0; lcount < *count; lcount++) {
de13f431 2663 *len += sprintf(*s + *len, "%s", XML_INDENT); /* indent */
59241895
MJ
2664 }
2665 }
f4e55fb1 2666 *len += sprintf(*s + (*len), "</%s>\n", xml->name); /* close tag */
59241895
MJ
2667 }
2668
2669 while (txt[off] && off < xml->off)
de13f431 2670 off++; /* make sure off is within bounds */
59241895 2671
287fd668 2672 if (!isroot && xml->ordered) {
9fa14d52
BW
2673 xml = xml->ordered;
2674 start = off;
2675 goto tailrecurse;
2676/*
79079942 2677 return switch_xml_toxml_r(xml->ordered, s, len, max, off, attr, count, use_utf8_encoding);
9fa14d52 2678*/
59241895
MJ
2679 } else {
2680 if (*count > 0)
2681 (*count)--;
79079942 2682 return switch_xml_ampencode(txt + off, 0, s, len, max, 0, use_utf8_encoding);
59241895
MJ
2683 }
2684}
2685
79079942 2686SWITCH_DECLARE(char *) switch_xml_toxml_nolock_ex(switch_xml_t xml, switch_bool_t prn_header, switch_bool_t use_utf8_encoding)
277c1141 2687{
350a739d
AM
2688 char *s = (char *) switch_must_malloc(SWITCH_XML_BUFSIZE);
2689
79079942 2690 return switch_xml_toxml_buf_ex(xml, s, SWITCH_XML_BUFSIZE, 0, prn_header, use_utf8_encoding);
277c1141 2691}
2692
79079942 2693SWITCH_DECLARE(char *) switch_xml_toxml_ex(switch_xml_t xml, switch_bool_t prn_header, switch_bool_t use_utf8_encoding)
59241895 2694{
4a520847 2695 char *r, *s;
277c1141 2696
350a739d 2697 s = (char *) switch_must_malloc(SWITCH_XML_BUFSIZE);
277c1141 2698
79079942 2699 r = switch_xml_toxml_buf_ex(xml, s, SWITCH_XML_BUFSIZE, 0, prn_header, use_utf8_encoding);
287fd668 2700
4a520847 2701 return r;
59241895
MJ
2702}
2703
79079942 2704SWITCH_DECLARE(char *) switch_xml_tohtml_ex(switch_xml_t xml, switch_bool_t prn_header, switch_bool_t use_utf8_encoding)
6b6c83a7
JL
2705{
2706 char *r, *s, *h;
2707 switch_size_t rlen = 0;
2708 switch_size_t len = SWITCH_XML_BUFSIZE;
350a739d
AM
2709
2710 s = (char *) switch_must_malloc(SWITCH_XML_BUFSIZE);
2711 h = (char *) switch_must_malloc(SWITCH_XML_BUFSIZE);
2712
79079942
SD
2713 r = switch_xml_toxml_buf_ex(xml, s, SWITCH_XML_BUFSIZE, 0, prn_header, use_utf8_encoding);
2714 h = switch_xml_ampencode(r, 0, &h, &rlen, &len, 1, use_utf8_encoding);
6b6c83a7 2715 switch_safe_free(r);
6b6c83a7
JL
2716 return h;
2717}
2718
2719/* converts a switch_xml structure back to xml, returning a string of xml data that
de13f431 2720 must be freed */
79079942 2721SWITCH_DECLARE(char *) switch_xml_toxml_buf_ex(switch_xml_t xml, char *buf, switch_size_t buflen, switch_size_t offset, switch_bool_t prn_header, switch_bool_t use_utf8_encoding)
59241895 2722{
287fd668 2723 switch_xml_t p = (xml) ? xml->parent : NULL;
59241895
MJ
2724 switch_xml_root_t root = (switch_xml_root_t) xml;
2725 switch_size_t len = 0, max = buflen;
350a739d 2726 char *s, *t, *n;
59241895
MJ
2727 int i, j, k;
2728 uint32_t count = 0;
886e1ddb 2729
59241895
MJ
2730 s = buf;
2731 assert(s != NULL);
2732 memset(s, 0, max);
2733 len += offset;
2734 if (prn_header) {
2735 len += sprintf(s + len, "<?xml version=\"1.0\"?>\n");
2736 }
886e1ddb 2737
59241895 2738 if (!xml || !xml->name) {
350a739d 2739 return (char *) switch_must_realloc(s, len + 1);
59241895
MJ
2740 }
2741
2742 while (root->xml.parent) {
de13f431 2743 root = (switch_xml_root_t) root->xml.parent; /* root tag */
59241895
MJ
2744 }
2745
de13f431 2746 for (i = 0; !p && root->pi[i]; i++) { /* pre-root processing instructions */
59241895
MJ
2747 for (k = 2; root->pi[i][k - 1]; k++);
2748 for (j = 1; (n = root->pi[i][j]); j++) {
2749 if (root->pi[i][k][j - 1] == '>') {
de13f431 2750 continue; /* not pre-root */
59241895
MJ
2751 }
2752 while (len + strlen(t = root->pi[i][0]) + strlen(n) + 7 > max) {
350a739d 2753 s = (char *) switch_must_realloc(s, max += SWITCH_XML_BUFSIZE);
59241895
MJ
2754 }
2755 len += sprintf(s + len, "<?%s%s%s?>", t, *n ? " " : "", n);
2756 }
2757 }
2758
79079942 2759 s = switch_xml_toxml_r(xml, &s, &len, &max, 0, root->attr, &count, 1, use_utf8_encoding);
59241895 2760
de13f431 2761 for (i = 0; !p && root->pi[i]; i++) { /* post-root processing instructions */
59241895
MJ
2762 for (k = 2; root->pi[i][k - 1]; k++);
2763 for (j = 1; (n = root->pi[i][j]); j++) {
2764 if (root->pi[i][k][j - 1] == '<') {
de13f431 2765 continue; /* not post-root */
59241895
MJ
2766 }
2767 while (len + strlen(t = root->pi[i][0]) + strlen(n) + 7 > max) {
350a739d 2768 s = (char *) switch_must_realloc(s, max += SWITCH_XML_BUFSIZE);
59241895
MJ
2769 }
2770 len += sprintf(s + len, "\n<?%s%s%s?>", t, *n ? " " : "", n);
2771 }
2772 }
2773
350a739d 2774 return (char *) switch_must_realloc(s, len + 1);
59241895
MJ
2775}
2776
de13f431 2777/* free the memory allocated for the switch_xml structure */
59241895
MJ
2778SWITCH_DECLARE(void) switch_xml_free(switch_xml_t xml)
2779{
9fa14d52 2780 switch_xml_root_t root;
59241895
MJ
2781 int i, j;
2782 char **a, *s;
9fa14d52 2783 switch_xml_t orig_xml;
4714ed43 2784 int refs = 0;
59241895 2785
4714ed43 2786 tailrecurse:
886e1ddb 2787 root = (switch_xml_root_t) xml;
f6f7f31c 2788 if (!xml) {
59241895 2789 return;
59241895
MJ
2790 }
2791
471bd6df 2792 if (switch_test_flag(xml, SWITCH_XML_ROOT)) {
4714ed43 2793 switch_mutex_lock(REFLOCK);
471bd6df 2794
4714ed43
AM
2795 if (xml->refs) {
2796 xml->refs--;
2797 refs = xml->refs;
471bd6df 2798 }
4714ed43 2799 switch_mutex_unlock(REFLOCK);
471bd6df 2800 }
471bd6df 2801
4714ed43 2802 if (refs) {
59241895
MJ
2803 return;
2804 }
2805
2806 if (xml->free_path) {
bd41ecc3
AM
2807 if (unlink(xml->free_path) != 0) {
2808 switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_WARNING, "Failed to delete file [%s]\n", xml->free_path);
59241895
MJ
2809 }
2810 switch_safe_free(xml->free_path);
2811 }
2812
2813 switch_xml_free(xml->child);
886e1ddb 2814 /*switch_xml_free(xml->ordered); */
59241895 2815
de13f431 2816 if (!xml->parent) { /* free root tag allocations */
383ff711 2817#if (_MSC_VER >= 1400) // VC8+
886e1ddb 2818 __analysis_assume(sizeof(root->ent) > 44); /* tail recursion confuses code analysis */
383ff711 2819#endif
de13f431 2820 for (i = 10; root->ent[i]; i += 2) /* 0 - 9 are default entities (<>&"') */
59241895
MJ
2821 if ((s = root->ent[i + 1]) < root->s || s > root->e)
2822 free(s);
de13f431 2823 free(root->ent); /* free list of general entities */
59241895
MJ
2824
2825 for (i = 0; (a = root->attr[i]); i++) {
de13f431 2826 for (j = 1; a[j++]; j += 2) /* free malloced attribute values */
59241895
MJ
2827 if (a[j] && (a[j] < root->s || a[j] > root->e))
2828 free(a[j]);
2829 free(a);
2830 }
2831 if (root->attr[0])
de13f431 2832 free(root->attr); /* free default attribute list */
59241895
MJ
2833
2834 for (i = 0; root->pi[i]; i++) {
2835 for (j = 1; root->pi[i][j]; j++);
2836 free(root->pi[i][j + 1]);
2837 free(root->pi[i]);
2838 }
2839 if (root->pi[0])
de13f431 2840 free(root->pi); /* free processing instructions */
59241895
MJ
2841
2842 if (root->dynamic == 1)
de13f431 2843 free(root->m); /* malloced xml data */
59241895 2844 if (root->u)
de13f431 2845 free(root->u); /* utf8 conversion */
59241895
MJ
2846 }
2847
de13f431 2848 switch_xml_free_attr(xml->attr); /* tag attributes */
59241895 2849 if ((xml->flags & SWITCH_XML_TXTM))
de13f431 2850 free(xml->txt); /* character content */
59241895 2851 if ((xml->flags & SWITCH_XML_NAMEM))
de13f431 2852 free(xml->name); /* tag name */
9fa14d52
BW
2853 if (xml->ordered) {
2854 orig_xml = xml;
2855 xml = xml->ordered;
2856 free(orig_xml);
2857 goto tailrecurse;
2858 }
59241895
MJ
2859 free(xml);
2860}
2861
de13f431 2862/* return parser error message or empty string if none */
59241895
MJ
2863SWITCH_DECLARE(const char *) switch_xml_error(switch_xml_t xml)
2864{
2865 while (xml && xml->parent)
de13f431 2866 xml = xml->parent; /* find root tag */
59241895
MJ
2867 return (xml) ? ((switch_xml_root_t) xml)->err : "";
2868}
2869
de13f431 2870/* returns a new empty switch_xml structure with the given root tag name */
59241895
MJ
2871SWITCH_DECLARE(switch_xml_t) switch_xml_new(const char *name)
2872{
2873 static const char *ent[] = { "lt;", "&#60;", "gt;", "&#62;", "quot;", "&#34;",
2874 "apos;", "&#39;", "amp;", "&#38;", NULL
2875 };
350a739d
AM
2876 switch_xml_root_t root = (switch_xml_root_t) switch_must_malloc(sizeof(struct switch_xml_root));
2877
bbb8adf2 2878 memset(root, '\0', sizeof(struct switch_xml_root));
59241895
MJ
2879 root->xml.name = (char *) name;
2880 root->cur = &root->xml;
886e1ddb 2881 strcpy(root->err, root->xml.txt = (char *) "");
350a739d 2882 root->ent = (char **) memcpy(switch_must_malloc(sizeof(ent)), ent, sizeof(ent));
59241895
MJ
2883 root->attr = root->pi = (char ***) (root->xml.attr = SWITCH_XML_NIL);
2884 return &root->xml;
2885}
2886
6b6c83a7 2887/* inserts an existing tag into a switch_xml structure */
59241895
MJ
2888SWITCH_DECLARE(switch_xml_t) switch_xml_insert(switch_xml_t xml, switch_xml_t dest, switch_size_t off)
2889{
2890 switch_xml_t cur, prev, head;
2891
2892 xml->next = xml->sibling = xml->ordered = NULL;
2893 xml->off = off;
2894 xml->parent = dest;
2895
de13f431
BW
2896 if ((head = dest->child)) { /* already have sub tags */
2897 if (head->off <= off) { /* not first subtag */
59241895
MJ
2898 for (cur = head; cur->ordered && cur->ordered->off <= off; cur = cur->ordered);
2899 xml->ordered = cur->ordered;
2900 cur->ordered = xml;
de13f431 2901 } else { /* first subtag */
59241895
MJ
2902 xml->ordered = head;
2903 dest->child = xml;
2904 }
2905
de13f431
BW
2906 for (cur = head, prev = NULL; cur && strcmp(cur->name, xml->name); prev = cur, cur = cur->sibling); /* find tag type */
2907 if (cur && cur->off <= off) { /* not first of type */
59241895
MJ
2908 while (cur->next && cur->next->off <= off)
2909 cur = cur->next;
2910 xml->next = cur->next;
2911 cur->next = xml;
de13f431 2912 } else { /* first tag of this type */
59241895 2913 if (prev && cur)
de13f431
BW
2914 prev->sibling = cur->sibling; /* remove old first */
2915 xml->next = cur; /* old first tag is now next */
2916 for (cur = head, prev = NULL; cur && cur->off <= off; prev = cur, cur = cur->sibling); /* new sibling insert point */
59241895
MJ
2917 xml->sibling = cur;
2918 if (prev)
2919 prev->sibling = xml;
2920 }
2921 } else
de13f431 2922 dest->child = xml; /* only sub tag */
59241895
MJ
2923
2924 return xml;
2925}
2926
de13f431
BW
2927/* Adds a child tag. off is the offset of the child tag relative to the start
2928 of the parent tag's character content. Returns the child tag */
59241895
MJ
2929SWITCH_DECLARE(switch_xml_t) switch_xml_add_child(switch_xml_t xml, const char *name, switch_size_t off)
2930{
2931 switch_xml_t child;
2932
886e1ddb
AM
2933 if (!xml)
2934 return NULL;
350a739d
AM
2935 child = (switch_xml_t) switch_must_malloc(sizeof(struct switch_xml));
2936
bbb8adf2 2937 memset(child, '\0', sizeof(struct switch_xml));
59241895
MJ
2938 child->name = (char *) name;
2939 child->attr = SWITCH_XML_NIL;
2940 child->off = off;
2941 child->parent = xml;
886e1ddb 2942 child->txt = (char *) "";
59241895
MJ
2943
2944 return switch_xml_insert(child, xml, off);
2945}
2946
c776680c
CR
2947/* Adds a child tag. off is the offset of the child tag relative to the start
2948 of the parent tag's character content. Returns the child tag */
2949SWITCH_DECLARE(switch_xml_t) switch_xml_add_child_d(switch_xml_t xml, const char *name, switch_size_t off)
2950{
2951 if (!xml) return NULL;
2952 return switch_xml_set_flag(switch_xml_add_child(xml, strdup(name), off), SWITCH_XML_NAMEM);
2953}
2954
de13f431 2955/* sets the character content for the given tag and returns the tag */
59241895
MJ
2956SWITCH_DECLARE(switch_xml_t) switch_xml_set_txt(switch_xml_t xml, const char *txt)
2957{
2958 if (!xml)
2959 return NULL;
2960 if (xml->flags & SWITCH_XML_TXTM)
de13f431 2961 free(xml->txt); /* existing txt was malloced */
59241895
MJ
2962 xml->flags &= ~SWITCH_XML_TXTM;
2963 xml->txt = (char *) txt;
2964 return xml;
2965}
2966
c776680c
CR
2967/* sets the character content for the given tag and returns the tag */
2968SWITCH_DECLARE(switch_xml_t) switch_xml_set_txt_d(switch_xml_t xml, const char *txt)
2969{
2970 if (!xml) return NULL;
2971 return switch_xml_set_flag(switch_xml_set_txt(xml, strdup(txt)), SWITCH_XML_TXTM);
2972}
2973
de13f431
BW
2974/* Sets the given tag attribute or adds a new attribute if not found. A value
2975 of NULL will remove the specified attribute. Returns the tag given */
59241895
MJ
2976SWITCH_DECLARE(switch_xml_t) switch_xml_set_attr(switch_xml_t xml, const char *name, const char *value)
2977{
af5281e9 2978 int l = 0, c;
59241895
MJ
2979
2980 if (!xml)
2981 return NULL;
2982 while (xml->attr[l] && strcmp(xml->attr[l], name))
2983 l += 2;
de13f431 2984 if (!xml->attr[l]) { /* not found, add as new attribute */
59241895 2985 if (!value)
af5281e9 2986 return xml; /* nothing to do */
de13f431 2987 if (xml->attr == SWITCH_XML_NIL) { /* first attribute */
350a739d 2988 xml->attr = (char **) switch_must_malloc(4 * sizeof(char *));
53cd0690 2989 xml->attr[l + 1] = switch_must_strdup(""); /* empty list of malloced names/vals */
59241895 2990 } else {
350a739d 2991 xml->attr = (char **) switch_must_realloc(xml->attr, (l + 4) * sizeof(char *));
59241895
MJ
2992 }
2993
de13f431 2994 xml->attr[l] = (char *) name; /* set attribute name */
af5281e9 2995 xml->attr[l + 2] = NULL; /* null terminate attribute list */
350a739d 2996 xml->attr[l + 3] = (char *) switch_must_realloc(xml->attr[l + 1], (c = (int) strlen(xml->attr[l + 1])) + 2);
af5281e9 2997 strcpy(xml->attr[l + 3] + c, " "); /* set name/value as not malloced */
59241895 2998 if (xml->flags & SWITCH_XML_DUP)
af5281e9 2999 xml->attr[l + 3][c] = SWITCH_XML_NAMEM;
95fb8c77
AV
3000 c = l + 2; /* end of attribute list */
3001 } else {
3002 for (c = l; xml->attr[c]; c += 2); /* find end of attribute list */
3003
3004 if (xml->flags & SWITCH_XML_DUP)
3005 free((char*)name); /* name was strduped */
3006 if (xml->attr[c + 1][l / 2] & SWITCH_XML_TXTM)
3007 free(xml->attr[l + 1]); /* old val */
3008 }
59241895 3009
59241895 3010 if (xml->flags & SWITCH_XML_DUP)
af5281e9 3011 xml->attr[c + 1][l / 2] |= SWITCH_XML_TXTM;
59241895 3012 else
af5281e9 3013 xml->attr[c + 1][l / 2] &= ~SWITCH_XML_TXTM;
59241895 3014
af5281e9
AM
3015 if (value)
3016 xml->attr[l + 1] = (char *) value; /* set attribute value */
3017 else { /* remove attribute */
af5281e9
AM
3018 if (xml->attr[c + 1][l / 2] & SWITCH_XML_NAMEM)
3019 free(xml->attr[l]);
95fb8c77
AV
3020 c -= 2;
3021 if (c > 0) {
3022 memmove(xml->attr + l, xml->attr + l + 2, (c - l + 2) * sizeof(char*));
3023 xml->attr = (char**)switch_must_realloc(xml->attr, (c + 2) * sizeof(char*));
3024 memmove(xml->attr[c + 1] + (l / 2), xml->attr[c + 1] + (l / 2) + 1, (c / 2) - (l / 2)); /* fix list of which name/vals are malloced */
3025 xml->attr[c + 1][c / 2] = '\0';
3026 } else {
3027 /* last attribute removed, reset attribute list */
3028 free(xml->attr[3]);
3029 free(xml->attr);
3030 xml->attr = SWITCH_XML_NIL;
3031 }
af5281e9
AM
3032 }
3033 xml->flags &= ~SWITCH_XML_DUP; /* clear strdup() flag */
59241895
MJ
3034
3035 return xml;
3036}
3037
c776680c
CR
3038/* Sets the given tag attribute or adds a new attribute if not found. A value
3039 of NULL will remove the specified attribute. Returns the tag given */
3040SWITCH_DECLARE(switch_xml_t) switch_xml_set_attr_d(switch_xml_t xml, const char *name, const char *value)
3041{
3042 if (!xml) return NULL;
c35a3bb4 3043 return switch_xml_set_attr(switch_xml_set_flag(xml, SWITCH_XML_DUP), switch_must_strdup(name), switch_must_strdup(switch_str_nil(value)));
c776680c
CR
3044}
3045
3046/* Sets the given tag attribute or adds a new attribute if not found. A value
3047 of NULL will remove the specified attribute. Returns the tag given */
3048SWITCH_DECLARE(switch_xml_t) switch_xml_set_attr_d_buf(switch_xml_t xml, const char *name, const char *value)
3049{
3050 if (!xml) return NULL;
c35a3bb4 3051 return switch_xml_set_attr(switch_xml_set_flag(xml, SWITCH_XML_DUP), switch_must_strdup(name), switch_must_strdup(value));
c776680c
CR
3052}
3053
de13f431 3054/* sets a flag for the given tag and returns the tag */
59241895
MJ
3055SWITCH_DECLARE(switch_xml_t) switch_xml_set_flag(switch_xml_t xml, switch_xml_flag_t flag)
3056{
3057 if (xml)
3058 xml->flags |= flag;
3059 return xml;
3060}
3061
de13f431 3062/* removes a tag along with its subtags without freeing its memory */
59241895
MJ
3063SWITCH_DECLARE(switch_xml_t) switch_xml_cut(switch_xml_t xml)
3064{
3065 switch_xml_t cur;
3066
3067 if (!xml)
de13f431 3068 return NULL; /* nothing to do */
59241895 3069 if (xml->next)
de13f431 3070 xml->next->sibling = xml->sibling; /* patch sibling list */
59241895 3071
de13f431
BW
3072 if (xml->parent) { /* not root tag */
3073 cur = xml->parent->child; /* find head of subtag list */
59241895 3074 if (cur == xml)
de13f431
BW
3075 xml->parent->child = xml->ordered; /* first subtag */
3076 else { /* not first subtag */
59241895
MJ
3077 while (cur->ordered != xml)
3078 cur = cur->ordered;
de13f431 3079 cur->ordered = cur->ordered->ordered; /* patch ordered list */
59241895 3080
de13f431
BW
3081 cur = xml->parent->child; /* go back to head of subtag list */
3082 if (strcmp(cur->name, xml->name)) { /* not in first sibling list */
59241895
MJ
3083 while (strcmp(cur->sibling->name, xml->name))
3084 cur = cur->sibling;
de13f431 3085 if (cur->sibling == xml) { /* first of a sibling list */
59241895
MJ
3086 cur->sibling = (xml->next) ? xml->next : cur->sibling->sibling;
3087 } else
de13f431 3088 cur = cur->sibling; /* not first of a sibling list */
59241895
MJ
3089 }
3090
3091 while (cur->next && cur->next != xml)
3092 cur = cur->next;
3093 if (cur->next)
de13f431 3094 cur->next = cur->next->next; /* patch next list */
59241895
MJ
3095 }
3096 }
de13f431 3097 xml->ordered = xml->sibling = xml->next = NULL; /* prevent switch_xml_free() from clobbering ordered list */
59241895
MJ
3098 return xml;
3099}
3100
a2fcb419 3101SWITCH_DECLARE(int) switch_xml_std_datetime_check(switch_xml_t xcond, int *offset, const char *tzname)
65a75664 3102{
09a734bb 3103
c9fcce08 3104 const char *xdt = switch_xml_attr(xcond, "date-time");
09a734bb
MJ
3105 const char *xyear = switch_xml_attr(xcond, "year");
3106 const char *xyday = switch_xml_attr(xcond, "yday");
3107 const char *xmon = switch_xml_attr(xcond, "mon");
3108 const char *xmday = switch_xml_attr(xcond, "mday");
3109 const char *xweek = switch_xml_attr(xcond, "week");
3110 const char *xmweek = switch_xml_attr(xcond, "mweek");
3111 const char *xwday = switch_xml_attr(xcond, "wday");
3112 const char *xhour = switch_xml_attr(xcond, "hour");
3113 const char *xminute = switch_xml_attr(xcond, "minute");
3114 const char *xminday = switch_xml_attr(xcond, "minute-of-day");
4ab8fa13 3115 const char *xtod = switch_xml_attr(xcond, "time-of-day");
65a75664 3116 const char *tzoff = switch_xml_attr(xcond, "tz-offset");
01dde19c 3117 const char *isdst = switch_xml_attr(xcond, "dst");
09a734bb 3118
01dde19c
AM
3119 int loffset = -1000;
3120 int eoffset = -1000;
3121 int dst = -1000;
09a734bb
MJ
3122 switch_time_t ts = switch_micro_time_now();
3123 int time_match = -1;
01dde19c
AM
3124 switch_time_exp_t tm, tm2;
3125
3126 if (!zstr(isdst)) {
3127 dst = switch_true(isdst);
3128 }
09a734bb 3129
65a75664
AM
3130 if (!zstr(tzoff) && switch_is_number(tzoff)) {
3131 loffset = atoi(tzoff);
65a75664
AM
3132 }
3133
01dde19c 3134 switch_time_exp_lt(&tm2, ts);
65a75664
AM
3135
3136 if (offset) {
01dde19c 3137 eoffset = *offset;
6d7e2799 3138 switch_time_exp_tz(&tm, ts, *offset * 3600);
a4a44fb1
AM
3139 } else if (!zstr(tzname)) {
3140 switch_time_exp_tz_name(tzname, &tm, ts);
65a75664 3141 } else {
01dde19c
AM
3142 tm = tm2;
3143 }
3144
3145 if (eoffset == -1000) {
3146 eoffset = tm.tm_gmtoff / 3600;
3147 }
3148
3149 if (loffset == -1000) {
3150 loffset = eoffset;
3151 }
3152
3153
3154 if (time_match && tzoff) {
3155 time_match = loffset == eoffset;
3156 switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG9,
3157 "XML DateTime Check: TZOFFSET[%d] == %d (%s)\n", eoffset, loffset, time_match ? "PASS" : "FAIL");
3158
3159 }
3160
3161 if (time_match && dst > -1) {
3162 time_match = (tm2.tm_isdst > 0 && dst > 0);
3163 switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG9,
a2fcb419 3164 "XML DateTime Check: DST[%s] == %s (%s)\n",
01dde19c
AM
3165 tm2.tm_isdst > 0 ? "true" : "false", dst > 0 ? "true" : "false", time_match ? "PASS" : "FAIL");
3166
65a75664 3167 }
09a734bb 3168
c9fcce08
MOC
3169 if (time_match && xdt) {
3170 char tmpdate[80];
3171 switch_size_t retsize;
3172 switch_strftime(tmpdate, &retsize, sizeof(tmpdate), "%Y-%m-%d %H:%M:%S", &tm);
1b13e159 3173 time_match = switch_fulldate_cmp(xdt, &ts);
c9fcce08
MOC
3174 switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG,
3175 "XML DateTime Check: date time[%s] =~ %s (%s)\n", tmpdate, xdt, time_match ? "PASS" : "FAIL");
3176 }
3177
09a734bb
MJ
3178 if (time_match && xyear) {
3179 int test = tm.tm_year + 1900;
3180 time_match = switch_number_cmp(xyear, test);
3181 switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG9,
3182 "XML DateTime Check: year[%d] =~ %s (%s)\n", test, xyear, time_match ? "PASS" : "FAIL");
3183 }
3184
3185 if (time_match && xyday) {
3186 int test = tm.tm_yday + 1;
3187 time_match = switch_number_cmp(xyday, test);
3188 switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG9,
3189 "XML DateTime Check: day of year[%d] =~ %s (%s)\n", test, xyday, time_match ? "PASS" : "FAIL");
3190 }
3191
3192 if (time_match && xmon) {
3193 int test = tm.tm_mon + 1;
3194 time_match = switch_number_cmp(xmon, test);
3195 switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG9,
3196 "XML DateTime Check: month[%d] =~ %s (%s)\n", test, xmon, time_match ? "PASS" : "FAIL");
3197 }
3198
3199 if (time_match && xmday) {
3200 int test = tm.tm_mday;
3201 time_match = switch_number_cmp(xmday, test);
3202 switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG9,
3203 "XML DateTime Check: day of month[%d] =~ %s (%s)\n", test, xmday, time_match ? "PASS" : "FAIL");
3204 }
3205
09a734bb
MJ
3206 if (time_match && xweek) {
3207 int test = (int) (tm.tm_yday / 7 + 1);
3208 time_match = switch_number_cmp(xweek, test);
3209 switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG9,
3210 "XML DateTime Check: week of year[%d] =~ %s (%s)\n", test, xweek, time_match ? "PASS" : "FAIL");
3211 }
3212
3213 if (time_match && xmweek) {
3214 /* calculate the day of the week of the first of the month (0-6) */
3215 int firstdow = (int) (7 - (tm.tm_mday - (tm.tm_wday + 1)) % 7) % 7;
3216 /* calculate the week of the month (1-6)*/
3217 int test = (int) ceil((tm.tm_mday + firstdow) / 7.0);
3218 time_match = switch_number_cmp(xmweek, test);
3219 switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG9,
3220 "XML DateTime: week of month[%d] =~ %s (%s)\n", test, xmweek, time_match ? "PASS" : "FAIL");
3221 }
3222
3223 if (time_match && xwday) {
3224 int test = tm.tm_wday + 1;
59ec8ced 3225 time_match = switch_dow_cmp(xwday, test);
09a734bb 3226 switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG9,
59ec8ced 3227 "XML DateTime Check: day of week[%s] =~ %s (%s)\n", switch_dow_int2str(test), xwday, time_match ? "PASS" : "FAIL");
09a734bb
MJ
3228 }
3229 if (time_match && xhour) {
3230 int test = tm.tm_hour;
3231 time_match = switch_number_cmp(xhour, test);
3232 switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG9,
3233 "XML DateTime Check: hour[%d] =~ %s (%s)\n", test, xhour, time_match ? "PASS" : "FAIL");
3234 }
3235
3236 if (time_match && xminute) {
3237 int test = tm.tm_min;
3238 time_match = switch_number_cmp(xminute, test);
3239 switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG9,
3240 "XML DateTime Check: minute[%d] =~ %s (%s)\n", test, xminute, time_match ? "PASS" : "FAIL");
3241 }
3242
3243 if (time_match && xminday) {
3244 int test = (tm.tm_hour * 60) + (tm.tm_min + 1);
3245 time_match = switch_number_cmp(xminday, test);
3246 switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG9,
3247 "XML DateTime Check: minute of day[%d] =~ %s (%s)\n", test, xminday, time_match ? "PASS" : "FAIL");
3248 }
3249
4ab8fa13
MOC
3250 if (time_match && xtod) {
3251 int test = (tm.tm_hour * 60 * 60) + (tm.tm_min * 60) + tm.tm_sec;
3252 char tmpdate[10];
d09e6c60 3253 switch_snprintf(tmpdate, 10, "%d:%d:%d", tm.tm_hour, tm.tm_min, tm.tm_sec);
4ab8fa13
MOC
3254 time_match = switch_tod_cmp(xtod, test);
3255 switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG9,
3256 "XML DateTime Check: time of day[%s] =~ %s (%s)\n", tmpdate, xtod, time_match ? "PASS" : "FAIL");
3257 }
3258
09a734bb
MJ
3259 return time_match;
3260}
3261
9d9b44e5 3262SWITCH_DECLARE(switch_status_t) switch_xml_locate_language_ex(switch_xml_t *root, switch_xml_t *node, switch_event_t *params, switch_xml_t *language, switch_xml_t *phrases, switch_xml_t *macros, const char *str_language) {
4137b360
MOC
3263 switch_status_t status = SWITCH_STATUS_FALSE;
3264
3265 if (switch_xml_locate("languages", NULL, NULL, NULL, root, node, params, SWITCH_TRUE) != SWITCH_STATUS_SUCCESS) {
3266 switch_xml_t sub_macros;
3267
3268 if (switch_xml_locate("phrases", NULL, NULL, NULL, root, node, params, SWITCH_TRUE) != SWITCH_STATUS_SUCCESS) {
3269 switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Open of languages and phrases failed.\n");
3270 goto done;
3271 }
3272 if (!(sub_macros = switch_xml_child(*node, "macros"))) {
3273 switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Can't find macros tag.\n");
3274 switch_xml_free(*root);
3275 *root = NULL;
3276 *node = NULL;
3277 goto done;
3278 }
3279 if (!(*language = switch_xml_find_child(sub_macros, "language", "name", str_language))) {
3280 switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Can't find language %s.\n", str_language);
3281 switch_xml_free(*root);
3282 *root = NULL;
3283 *node = NULL;
3284 goto done;
3285 }
3286 *macros = *language;
3287 } else {
3288 if (!(*language = switch_xml_find_child(*node, "language", "name", str_language))) {
3289 switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Can't find language %s.\n", str_language);
3290 switch_xml_free(*root);
3291 *root = NULL;
3292 goto done;
3293 }
3294 if (!(*phrases = switch_xml_child(*language, "phrases"))) {
3295 switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Can't find phrases tag.\n");
3296 switch_xml_free(*root);
3297 *root = NULL;
3298 *node = NULL;
3299 *language = NULL;
3300 goto done;
3301 }
3302
3303 if (!(*macros = switch_xml_child(*phrases, "macros"))) {
3304 switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Can't find macros tag.\n");
3305 switch_xml_free(*root);
3306 *root = NULL;
3307 *node = NULL;
3308 *language = NULL;
3309 *phrases = NULL;
3310 goto done;
3311 }
3312 }
3313 status = SWITCH_STATUS_SUCCESS;
3314
3315done:
3316 return status;
3317}
09a734bb 3318
9d9b44e5 3319SWITCH_DECLARE(switch_status_t) switch_xml_locate_language(switch_xml_t *root, switch_xml_t *node, switch_event_t *params, switch_xml_t *language, switch_xml_t *phrases, switch_xml_t *macros, const char *str_language) {
3320 switch_status_t status;
3321
3322 if ((status = switch_xml_locate_language_ex(root, node, params, language, phrases, macros, str_language)) != SWITCH_STATUS_SUCCESS) {
1c63aceb 3323 char *str_language_dup = strdup(str_language);
9d9b44e5 3324 char *secondary;
0ac27178 3325 switch_assert(str_language_dup);
1c63aceb 3326 if ((secondary = strchr(str_language_dup, '-'))) {
9d9b44e5 3327 *secondary++ = '\0';
1c63aceb
MJ
3328 switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_WARNING,
3329 "language %s not found. trying %s by removing %s\n", str_language, str_language_dup, secondary);
9d9b44e5 3330 switch_event_add_header_string(params, SWITCH_STACK_BOTTOM, "lang", str_language_dup);
3331 status = switch_xml_locate_language_ex(root, node, params, language, phrases, macros, str_language_dup);
3332 }
3333 switch_safe_free(str_language_dup);
3334 }
3335
3336 return status;
3337}
3338
59241895 3339#ifdef WIN32
a2fcb419
RC
3340/*
3341 * globbing functions for windows, part of libc on unix, this code was cut and paste from
59241895
MJ
3342 * freebsd lib and distilled a bit to work with windows
3343 */
3344
3345/*
3346 * Copyright (c) 1989, 1993
3347 * The Regents of the University of California. All rights reserved.
3348 *
3349 * This code is derived from software contributed to Berkeley by
3350 * Guido van Rossum.
3351 *
3352 * Redistribution and use in source and binary forms, with or without
3353 * modification, are permitted provided that the following conditions
3354 * are met:
3355 * 1. Redistributions of source code must retain the above copyright
3356 * notice, this list of conditions and the following disclaimer.
3357 * 2. Redistributions in binary form must reproduce the above copyright
3358 * notice, this list of conditions and the following disclaimer in the
3359 * documentation and/or other materials provided with the distribution.
3360 * 4. Neither the name of the University nor the names of its contributors
3361 * may be used to endorse or promote products derived from this software
3362 * without specific prior written permission.
3363 *
3364 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
3365 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
3366 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
3367 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
3368 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
3369 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
3370 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
3371 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
3372 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
3373 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
3374 * SUCH DAMAGE.
3375 */
3376
3377#define DOLLAR '$'
3378#define DOT '.'
3379#define EOS '\0'
3380#define LBRACKET '['
3381#define NOT '!'
3382#define QUESTION '?'
3383#define RANGE '-'
3384#define RBRACKET ']'
3385#define SEP '/'
e22f4233 3386#define WIN_SEP '/'
59241895
MJ
3387#define STAR '*'
3388#define TILDE '~'
3389#define UNDERSCORE '_'
3390#define LBRACE '{'
3391#define RBRACE '}'
3392#define SLASH '/'
3393#define COMMA ','
3394
3395#define M_QUOTE (char)0x80
3396#define M_PROTECT (char)0x40
3397#define M_MASK (char)0xff
3398#define M_ASCII (char)0x7f
3399
3400#define CHAR(c) ((char)((c)&M_ASCII))
3401#define META(c) ((char)((c)|M_QUOTE))
3402#define M_ALL META('*')
3403#define M_END META(']')
3404#define M_NOT META('!')
3405#define M_ONE META('?')
3406#define M_RNG META('-')
3407#define M_SET META('[')
3408#define ismeta(c) (((c)&M_QUOTE) != 0)
3409
3410#ifndef MAXPATHLEN
3411#define MAXPATHLEN 256
3412#endif
3413
886e1ddb
AM
3414static int compare(const void *, const void *);
3415static int glob0(const char *, glob_t *, size_t *);
3416static int glob1(char *, glob_t *, size_t *);
3417static int glob2(char *, char *, char *, char *, glob_t *, size_t *);
3418static int glob3(char *, char *, char *, char *, char *, glob_t *, size_t *);
3419static int globextend(const char *, glob_t *, size_t *);
3420static int match(char *, char *, char *);
59241895
MJ
3421
3422#pragma warning(push)
3423#pragma warning(disable:4310)
3424
886e1ddb 3425int glob(const char *pattern, int flags, int (*errfunc) (const char *, int), glob_t *pglob)
59241895
MJ
3426{
3427 const unsigned char *patnext;
5d4b5c3d 3428 size_t limit;
59241895
MJ
3429 char c;
3430 char *bufnext, *bufend, patbuf[MAXPATHLEN];
886e1ddb 3431
59241895
MJ
3432 patnext = (unsigned char *) pattern;
3433 if (!(flags & GLOB_APPEND)) {
3434 pglob->gl_pathc = 0;
3435 pglob->gl_pathv = NULL;
3436 if (!(flags & GLOB_DOOFFS))
3437 pglob->gl_offs = 0;
3438 }
3439 if (flags & GLOB_LIMIT) {
3440 limit = pglob->gl_matchc;
3441 if (limit == 0)
3442 limit = 9999999;
3443 } else
3444 limit = 0;
3445 pglob->gl_flags = flags & ~GLOB_MAGCHAR;
3446 pglob->gl_errfunc = errfunc;
3447 pglob->gl_matchc = 0;
886e1ddb 3448
59241895
MJ
3449 bufnext = patbuf;
3450 bufend = bufnext + MAXPATHLEN - 1;
3451 while (bufnext < bufend && (c = *patnext++) != EOS)
3452 *bufnext++ = c;
3453 *bufnext = EOS;
886e1ddb 3454
59241895
MJ
3455 return glob0(patbuf, pglob, &limit);
3456}
3457
3458/*
3459 * The main glob() routine: compiles the pattern (optionally processing
3460 * quotes), calls glob1() to do the real pattern matching, and finally
3461 * sorts the list (unless unsorted operation is requested). Returns 0
3462 * if things went well, nonzero if errors occurred.
3463 */
5d4b5c3d 3464static int glob0(const char *pattern, glob_t *pglob, size_t *limit)
59241895
MJ
3465{
3466 const char *qpatnext;
3467 int c, err;
5d4b5c3d 3468 size_t oldpathc;
59241895 3469 char *bufnext, patbuf[MAXPATHLEN];
886e1ddb 3470
59241895
MJ
3471 qpatnext = pattern;
3472 oldpathc = pglob->gl_pathc;
3473 bufnext = patbuf;
886e1ddb 3474
59241895
MJ
3475 /* We don't need to check for buffer overflow any more. */
3476 while ((c = *qpatnext++) != EOS) {
3477 switch (c) {
886e1ddb
AM
3478 case SEP:
3479 *bufnext++ = WIN_SEP;
3480 break;
3481 case LBRACKET:
3482 c = *qpatnext;
3483 if (c == NOT)
3484 ++qpatnext;
3485 if (*qpatnext == EOS || strchr((char *) qpatnext + 1, RBRACKET) == NULL) {
3486 *bufnext++ = LBRACKET;
59241895 3487 if (c == NOT)
886e1ddb 3488 --qpatnext;
59241895 3489 break;
886e1ddb
AM
3490 }
3491 *bufnext++ = M_SET;
3492 if (c == NOT)
3493 *bufnext++ = M_NOT;
3494 c = *qpatnext++;
3495 do {
59241895 3496 *bufnext++ = CHAR(c);
886e1ddb
AM
3497 if (*qpatnext == RANGE && (c = qpatnext[1]) != RBRACKET) {
3498 *bufnext++ = M_RNG;
3499 *bufnext++ = CHAR(c);
3500 qpatnext += 2;
3501 }
3502 } while ((c = *qpatnext++) != RBRACKET);
3503 pglob->gl_flags |= GLOB_MAGCHAR;
3504 *bufnext++ = M_END;
3505 break;
3506 case QUESTION:
3507 pglob->gl_flags |= GLOB_MAGCHAR;
3508 *bufnext++ = M_ONE;
3509 break;
3510 case STAR:
3511 pglob->gl_flags |= GLOB_MAGCHAR;
3512 /* collapse adjacent stars to one,
3513 * to avoid exponential behavior
3514 */
3515 if (bufnext == patbuf || bufnext[-1] != M_ALL)
3516 *bufnext++ = M_ALL;
3517 break;
3518 default:
3519 *bufnext++ = CHAR(c);
3520 break;
59241895
MJ
3521 }
3522 }
3523 *bufnext = EOS;
886e1ddb 3524
59241895 3525 if ((err = glob1(patbuf, pglob, limit)) != 0)
886e1ddb
AM
3526 return (err);
3527
59241895
MJ
3528 /*
3529 * If there was no match we are going to append the pattern
3530 * if GLOB_NOCHECK was specified or if GLOB_NOMAGIC was specified
3531 * and the pattern did not contain any magic characters
3532 * GLOB_NOMAGIC is there just for compatibility with csh.
3533 */
3534 if (pglob->gl_pathc == oldpathc) {
886e1ddb
AM
3535 if (((pglob->gl_flags & GLOB_NOCHECK) || ((pglob->gl_flags & GLOB_NOMAGIC) && !(pglob->gl_flags & GLOB_MAGCHAR))))
3536 return (globextend(pattern, pglob, limit));
59241895 3537 else
886e1ddb 3538 return (GLOB_NOMATCH);
59241895
MJ
3539 }
3540 if (!(pglob->gl_flags & GLOB_NOSORT))
886e1ddb
AM
3541 qsort(pglob->gl_pathv + pglob->gl_offs + oldpathc, pglob->gl_pathc - oldpathc, sizeof(char *), compare);
3542 return (0);
59241895
MJ
3543}
3544
3545static int compare(const void *p, const void *q)
3546{
886e1ddb 3547 return (strcmp(*(char **) p, *(char **) q));
59241895
MJ
3548}
3549
5d4b5c3d 3550static int glob1(char *pattern, glob_t *pglob, size_t *limit)
59241895
MJ
3551{
3552 char pathbuf[MAXPATHLEN];
886e1ddb 3553
59241895
MJ
3554 /* A null pathname is invalid -- POSIX 1003.1 sect. 2.4. */
3555 if (*pattern == EOS)
886e1ddb
AM
3556 return (0);
3557 return (glob2(pathbuf, pathbuf, pathbuf + MAXPATHLEN - 1, pattern, pglob, limit));
59241895
MJ
3558}
3559
3560/*
3561 * The functions glob2 and glob3 are mutually recursive; there is one level
3562 * of recursion for each segment in the pattern that contains one or more
3563 * meta characters.
3564 */
5d4b5c3d 3565static int glob2(char *pathbuf, char *pathend, char *pathend_last, char *pattern, glob_t *pglob, size_t *limit)
59241895
MJ
3566{
3567 struct stat sb;
3568 char *p, *q;
3569 int anymeta;
886e1ddb 3570
59241895
MJ
3571 /*
3572 * Loop over pattern segments until end of pattern or until
3573 * segment with meta character found.
3574 */
3575 for (anymeta = 0;;) {
886e1ddb 3576 if (*pattern == EOS) { /* End of pattern? */
59241895
MJ
3577 *pathend = EOS;
3578 if (stat(pathbuf, &sb))
886e1ddb
AM
3579 return (0);
3580
3581 if (((pglob->gl_flags & GLOB_MARK) && pathend[-1] != SEP && pathend[-1] != WIN_SEP) && (_S_IFDIR & sb.st_mode)) {
59241895
MJ
3582 if (pathend + 1 > pathend_last)
3583 return (GLOB_ABORTED);
3584 *pathend++ = WIN_SEP;
3585 *pathend = EOS;
3586 }
3587 ++pglob->gl_matchc;
886e1ddb 3588 return (globextend(pathbuf, pglob, limit));
59241895 3589 }
886e1ddb 3590
59241895
MJ
3591 /* Find end of next segment, copy tentatively to pathend. */
3592 q = pathend;
3593 p = pattern;
3594 while (*p != EOS && *p != SEP && *p != WIN_SEP) {
3595 if (ismeta(*p))
3596 anymeta = 1;
3597 if (q + 1 > pathend_last)
3598 return (GLOB_ABORTED);
3599 *q++ = *p++;
3600 }
886e1ddb
AM
3601
3602 if (!anymeta) { /* No expansion, do next segment. */
59241895
MJ
3603 pathend = q;
3604 pattern = p;
3605 while (*pattern == SEP || *pattern == WIN_SEP) {
3606 if (pathend + 1 > pathend_last)
3607 return (GLOB_ABORTED);
3608 *pathend++ = *pattern++;
3609 }
886e1ddb
AM
3610 } else /* Need expansion, recurse. */
3611 return (glob3(pathbuf, pathend, pathend_last, pattern, p, pglob, limit));
59241895
MJ
3612 }
3613 /* NOTREACHED */
3614}
3615
5d4b5c3d 3616static int glob3(char *pathbuf, char *pathend, char *pathend_last, char *pattern, char *restpattern, glob_t *pglob, size_t *limit)
59241895
MJ
3617{
3618 int err;
886e1ddb
AM
3619 apr_dir_t *dirp;
3620 apr_pool_t *pool;
3621
59241895 3622 apr_pool_create(&pool, NULL);
886e1ddb 3623
59241895
MJ
3624 if (pathend > pathend_last)
3625 return (GLOB_ABORTED);
3626 *pathend = EOS;
3627 errno = 0;
886e1ddb
AM
3628
3629 if (apr_dir_open(&dirp, pathbuf, pool) != APR_SUCCESS) {
59241895
MJ
3630 /* TODO: don't call for ENOENT or ENOTDIR? */
3631 apr_pool_destroy(pool);
3632 if (pglob->gl_errfunc) {
886e1ddb 3633 if (pglob->gl_errfunc(pathbuf, errno) || pglob->gl_flags & GLOB_ERR)
59241895
MJ
3634 return (GLOB_ABORTED);
3635 }
886e1ddb 3636 return (0);
59241895 3637 }
886e1ddb 3638
59241895 3639 err = 0;
886e1ddb 3640
59241895 3641 /* Search directory for matching names. */
886e1ddb 3642 while (dirp) {
59241895
MJ
3643 apr_finfo_t dp;
3644 unsigned char *sc;
3645 char *dc;
886e1ddb 3646
d0688264 3647 if (apr_dir_read(&dp, APR_FINFO_NAME, dirp) != APR_SUCCESS)
59241895 3648 break;
d0688264 3649 if (!(dp.valid & APR_FINFO_NAME) || !(dp.name) || !strlen(dp.name))
59241895 3650 break;
886e1ddb 3651
59241895
MJ
3652 /* Initial DOT must be matched literally. */
3653 if (dp.name[0] == DOT && *pattern != DOT)
3654 continue;
3655 dc = pathend;
3656 sc = (unsigned char *) dp.name;
886e1ddb 3657
59241895 3658 while (dc < pathend_last && (*dc++ = *sc++) != EOS);
886e1ddb 3659
59241895
MJ
3660 if (!match(pathend, pattern, restpattern)) {
3661 *pathend = EOS;
3662 continue;
3663 }
886e1ddb 3664 err = glob2(pathbuf, --dc, pathend_last, restpattern, pglob, limit);
59241895
MJ
3665 if (err)
3666 break;
3667 }
886e1ddb
AM
3668
3669 if (dirp)
3670 apr_dir_close(dirp);
59241895 3671 apr_pool_destroy(pool);
886e1ddb 3672 return (err);
59241895
MJ
3673}
3674
3675
3676/*
ff3f04f1 3677 * Extend the gl_pathv member of a glob_t structure to accommodate a new item,
59241895
MJ
3678 * add the new item, and update gl_pathc.
3679 *
3680 * This assumes the BSD realloc, which only copies the block when its size
3681 * crosses a power-of-two boundary; for v7 realloc, this would cause quadratic
3682 * behavior.
3683 *
3684 * Return 0 if new item added, error code if memory couldn't be allocated.
3685 *
3686 * Invariant of the glob_t structure:
3687 * Either gl_pathc is zero and gl_pathv is NULL; or gl_pathc > 0 and
3688 * gl_pathv points to (gl_offs + gl_pathc + 1) items.
3689 */
5d4b5c3d 3690static int globextend(const char *path, glob_t *pglob, size_t *limit)
59241895
MJ
3691{
3692 char **pathv;
886e1ddb 3693 char *copy;
5d4b5c3d
RJ
3694 size_t i;
3695 size_t newsize, len;
59241895 3696 const char *p;
886e1ddb 3697
1bbf3a82 3698 if (*limit && pglob->gl_pathc > *limit) {
59241895
MJ
3699 errno = 0;
3700 return (GLOB_NOSPACE);
3701 }
886e1ddb 3702
59241895 3703 newsize = sizeof(*pathv) * (2 + pglob->gl_pathc + pglob->gl_offs);
350a739d 3704 pathv = pglob->gl_pathv ? switch_must_realloc((char *) pglob->gl_pathv, newsize) : switch_must_malloc(newsize);
886e1ddb 3705
59241895
MJ
3706 if (pglob->gl_pathv == NULL && pglob->gl_offs > 0) {
3707 /* first time around -- clear initial gl_offs items */
3708 pathv += pglob->gl_offs;
886e1ddb 3709 for (i = pglob->gl_offs; i-- > 0;)
59241895
MJ
3710 *--pathv = NULL;
3711 }
3712 pglob->gl_pathv = pathv;
886e1ddb 3713
59241895
MJ
3714 for (p = path; *p++;)
3715 continue;
886e1ddb 3716 len = (size_t) (p - path);
350a739d
AM
3717 copy = switch_must_malloc(len);
3718 memcpy(copy, path, len);
3719 pathv[pglob->gl_offs + pglob->gl_pathc++] = copy;
59241895 3720 pathv[pglob->gl_offs + pglob->gl_pathc] = NULL;
886e1ddb 3721 return (copy == NULL ? GLOB_NOSPACE : 0);
59241895
MJ
3722}
3723
3724/*
3725 * pattern matching function for filenames. Each occurrence of the *
3726 * pattern causes a recursion level.
3727 */
3728static int match(char *name, char *pat, char *patend)
3729{
3730 int ok, negate_range;
3731 char c, k;
3732 char s1[6];
886e1ddb 3733
59241895
MJ
3734 while (pat < patend) {
3735 c = *pat++;
3736 switch (c & M_MASK) {
886e1ddb
AM
3737 case M_ALL:
3738 if (pat == patend)
3739 return (1);
3740 do
3741 if (match(name, pat, patend))
3742 return (1);
3743 while (*name++ != EOS);
3744 return (0);
3745 case M_ONE:
3746 if (*name++ == EOS)
3747 return (0);
3748 break;
3749 case M_SET:
3750 ok = 0;
3751 if ((k = *name++) == EOS)
3752 return (0);
3753 if ((negate_range = ((*pat & M_MASK) == M_NOT)) != EOS)
3754 ++pat;
3755 while (((c = *pat++) & M_MASK) != M_END)
3756 if ((*pat & M_MASK) == M_RNG) {
3757 memset(s1, 0, sizeof(s1));
3758 s1[0] = c;
3759 s1[2] = k;
3760 s1[4] = pat[1];
3761 if (strcoll(&s1[0], &s1[2]) <= 0 && strcoll(&s1[2], &s1[4]) <= 0)
59241895 3762 ok = 1;
886e1ddb
AM
3763 pat += 2;
3764 } else if (c == k)
3765 ok = 1;
3766 if (ok == negate_range)
3767 return (0);
3768 break;
3769 default:
3770 if (*name++ != c)
3771 return (0);
3772 break;
59241895
MJ
3773 }
3774 }
886e1ddb 3775 return (*name == EOS);
59241895
MJ
3776}
3777
3778/* Free allocated data belonging to a glob_t structure. */
3779void globfree(glob_t *pglob)
3780{
5d4b5c3d 3781 size_t i;
59241895 3782 char **pp;
886e1ddb 3783
59241895
MJ
3784 if (pglob->gl_pathv != NULL) {
3785 pp = pglob->gl_pathv + pglob->gl_offs;
3786 for (i = pglob->gl_pathc; i--; ++pp)
3787 if (*pp)
3788 free(*pp);
3789 free(pglob->gl_pathv);
3790 pglob->gl_pathv = NULL;
3791 }
3792}
886e1ddb 3793
59241895
MJ
3794#pragma warning(pop)
3795#endif
3796
3797/* For Emacs:
3798 * Local Variables:
3799 * mode:c
3800 * indent-tabs-mode:t
3801 * tab-width:4
3802 * c-basic-offset:4
3803 * End:
3804 * For VIM:
32adc789 3805 * vim:set softtabstop=4 shiftwidth=4 tabstop=4 noet:
59241895 3806 */