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