Wed Nov 28 2012 04:18:17

Asterisk developer's documentation


xmldoc.c
Go to the documentation of this file.
00001 /*
00002  * Asterisk -- An open source telephony toolkit.
00003  *
00004  * Copyright (C) 2008, Eliel C. Sardanons (LU1ALY) <eliels@gmail.com>
00005  *
00006  * See http://www.asterisk.org for more information about
00007  * the Asterisk project. Please do not directly contact
00008  * any of the maintainers of this project for assistance;
00009  * the project provides a web site, mailing lists and IRC
00010  * channels for your use.
00011  *
00012  * This program is free software, distributed under the terms of
00013  * the GNU General Public License Version 2. See the LICENSE file
00014  * at the top of the source tree.
00015  */
00016 
00017 /*! \file
00018  *
00019  * \brief XML Documentation API
00020  *
00021  * \author Eliel C. Sardanons (LU1ALY) <eliels@gmail.com>
00022  *
00023  * \extref libxml2 http://www.xmlsoft.org/
00024  */
00025 
00026 /*** MODULEINFO
00027    <support_level>core</support_level>
00028  ***/
00029 
00030 #include "asterisk.h"
00031 
00032 ASTERISK_FILE_VERSION(__FILE__, "$Revision: 371590 $")
00033 
00034 #include "asterisk/_private.h"
00035 #include "asterisk/paths.h"
00036 #include "asterisk/linkedlists.h"
00037 #include "asterisk/strings.h"
00038 #include "asterisk/config.h"
00039 #include "asterisk/term.h"
00040 #include "asterisk/xmldoc.h"
00041 
00042 #ifdef AST_XML_DOCS
00043 
00044 /*! \brief Default documentation language. */
00045 static const char default_documentation_language[] = "en_US";
00046 
00047 /*! \brief Number of columns to print when showing the XML documentation with a
00048  *         'core show application/function *' CLI command. Used in text wrapping.*/
00049 static const int xmldoc_text_columns = 74;
00050 
00051 /*! \brief This is a value that we will use to let the wrapping mechanism move the cursor
00052  *         backward and forward xmldoc_max_diff positions before cutting the middle of a
00053  *         word, trying to find a space or a \n. */
00054 static const int xmldoc_max_diff = 5;
00055 
00056 /*! \brief XML documentation language. */
00057 static char documentation_language[6];
00058 
00059 /*! \brief XML documentation tree */
00060 struct documentation_tree {
00061    char *filename;               /*!< XML document filename. */
00062    struct ast_xml_doc *doc;         /*!< Open document pointer. */
00063    AST_RWLIST_ENTRY(documentation_tree) entry;
00064 };
00065 
00066 static char *xmldoc_get_syntax_cmd(struct ast_xml_node *fixnode, const char *name, int printname);
00067 static int xmldoc_parse_enumlist(struct ast_xml_node *fixnode, const char *tabs, struct ast_str **buffer);
00068 
00069 /*!
00070  * \brief Container of documentation trees
00071  *
00072  * \note A RWLIST is a sufficient container type to use here for now.
00073  *       However, some changes will need to be made to implement ref counting
00074  *       if reload support is added in the future.
00075  */
00076 static AST_RWLIST_HEAD_STATIC(xmldoc_tree, documentation_tree);
00077 
00078 static const struct strcolorized_tags {
00079    const char *init;      /*!< Replace initial tag with this string. */
00080    const char *end;       /*!< Replace end tag with this string. */
00081    const int colorfg;     /*!< Foreground color. */
00082    const char *inittag;   /*!< Initial tag description. */
00083    const char *endtag;    /*!< Ending tag description. */
00084 } colorized_tags[] = {
00085    { "<",  ">",  COLOR_GREEN,  "<replaceable>", "</replaceable>" },
00086    { "\'", "\'", COLOR_BLUE,   "<literal>",     "</literal>" },
00087    { "*",  "*",  COLOR_RED,    "<emphasis>",    "</emphasis>" },
00088    { "\"", "\"", COLOR_YELLOW, "<filename>",    "</filename>" },
00089    { "\"", "\"", COLOR_CYAN,   "<directory>",   "</directory>" },
00090    { "${", "}",  COLOR_GREEN,  "<variable>",    "</variable>" },
00091    { "",   "",   COLOR_BLUE,   "<value>",       "</value>" },
00092    { "",   "",   COLOR_BLUE,   "<enum>",        "</enum>" },
00093    { "\'", "\'", COLOR_GRAY,   "<astcli>",      "</astcli>" },
00094 
00095    /* Special tags */
00096    { "", "", COLOR_YELLOW, "<note>",   "</note>" },
00097    { "", "", COLOR_RED,   "<warning>", "</warning>" }
00098 };
00099 
00100 static const struct strspecial_tags {
00101    const char *tagname;    /*!< Special tag name. */
00102    const char *init;    /*!< Print this at the beginning. */
00103    const char *end;     /*!< Print this at the end. */
00104 } special_tags[] = {
00105    { "note",    "<note>NOTE:</note> ",             "" },
00106    { "warning", "<warning>WARNING!!!:</warning> ", "" }
00107 };
00108 
00109 /*! \internal
00110  *  \brief Calculate the space in bytes used by a format string
00111  *         that will be passed to a sprintf function.
00112  *  \param postbr The format string to use to calculate the length.
00113  *  \retval The postbr length.
00114  */
00115 static int xmldoc_postbrlen(const char *postbr)
00116 {
00117    int postbrreallen = 0, i;
00118    size_t postbrlen;
00119 
00120    if (!postbr) {
00121       return 0;
00122    }
00123    postbrlen = strlen(postbr);
00124    for (i = 0; i < postbrlen; i++) {
00125       if (postbr[i] == '\t') {
00126          postbrreallen += 8 - (postbrreallen % 8);
00127       } else {
00128          postbrreallen++;
00129       }
00130    }
00131    return postbrreallen;
00132 }
00133 
00134 /*! \internal
00135  *  \brief Setup postbr to be used while wrapping the text.
00136  *         Add to postbr array all the spaces and tabs at the beginning of text.
00137  *  \param postbr output array.
00138  *  \param len text array length.
00139  *  \param text Text with format string before the actual string.
00140  */
00141 static void xmldoc_setpostbr(char *postbr, size_t len, const char *text)
00142 {
00143    int c, postbrlen = 0;
00144 
00145    if (!text) {
00146       return;
00147    }
00148 
00149    for (c = 0; c < len; c++) {
00150       if (text[c] == '\t' || text[c] == ' ') {
00151          postbr[postbrlen++] = text[c];
00152       } else {
00153          break;
00154       }
00155    }
00156    postbr[postbrlen] = '\0';
00157 }
00158 
00159 /*! \internal
00160  *  \brief Try to find a space or a break in text starting at currentpost
00161  *         and moving at most maxdiff positions.
00162  *         Helper for xmldoc_string_wrap().
00163  *  \param text Input string where it will search.
00164  *  \param currentpos Current position within text.
00165  *  \param maxdiff Not move more than maxdiff inside text.
00166  *  \retval 1 if a space or break is found inside text while moving.
00167  *  \retval 0 if no space or break is found.
00168  */
00169 static int xmldoc_wait_nextspace(const char *text, int currentpos, int maxdiff)
00170 {
00171    int i, textlen;
00172 
00173    if (!text) {
00174       return 0;
00175    }
00176 
00177    textlen = strlen(text);
00178    for (i = currentpos; i < textlen; i++) {
00179       if (text[i] == ESC) {
00180          /* Move to the end of the escape sequence */
00181          while (i < textlen && text[i] != 'm') {
00182             i++;
00183          }
00184       } else if (text[i] == ' ' || text[i] == '\n') {
00185          /* Found the next space or linefeed */
00186          return 1;
00187       } else if (i - currentpos > maxdiff) {
00188          /* We have looked the max distance and didn't find it */
00189          return 0;
00190       }
00191    }
00192 
00193    /* Reached the end and did not find it */
00194 
00195    return 0;
00196 }
00197 
00198 /*! \internal
00199  *  \brief Helper function for xmldoc_string_wrap().
00200  *    Try to found a space or a break inside text moving backward
00201  *    not more than maxdiff positions.
00202  *  \param text The input string where to search for a space.
00203  *  \param currentpos The current cursor position.
00204  *  \param maxdiff The max number of positions to move within text.
00205  *  \retval 0 If no space is found (Notice that text[currentpos] is not a space or a break)
00206  *  \retval > 0 If a space or a break is found, and the result is the position relative to
00207  *    currentpos.
00208  */
00209 static int xmldoc_foundspace_backward(const char *text, int currentpos, int maxdiff)
00210 {
00211    int i;
00212 
00213    for (i = currentpos; i > 0; i--) {
00214       if (text[i] == ' ' || text[i] == '\n') {
00215          return (currentpos - i);
00216       } else if (text[i] == 'm' && (text[i - 1] >= '0' || text[i - 1] <= '9')) {
00217          /* give up, we found the end of a possible ESC sequence. */
00218          return 0;
00219       } else if (currentpos - i > maxdiff) {
00220          /* give up, we can't move anymore. */
00221          return 0;
00222       }
00223    }
00224 
00225    /* we found the beginning of the text */
00226 
00227    return 0;
00228 }
00229 
00230 /*! \internal
00231  *  \brief Justify a text to a number of columns.
00232  *  \param text Input text to be justified.
00233  *  \param columns Number of columns to preserve in the text.
00234  *  \param maxdiff Try to not cut a word when goinf down.
00235  *  \retval NULL on error.
00236  *  \retval The wrapped text.
00237  */
00238 static char *xmldoc_string_wrap(const char *text, int columns, int maxdiff)
00239 {
00240    struct ast_str *tmp;
00241    char *ret, postbr[160];
00242    int count = 1, i, backspace, needtobreak = 0, colmax, textlen;
00243 
00244    /* sanity check */
00245    if (!text || columns <= 0 || maxdiff < 0) {
00246       ast_log(LOG_WARNING, "Passing wrong arguments while trying to wrap the text\n");
00247       return NULL;
00248    }
00249 
00250    tmp = ast_str_create(strlen(text) * 3);
00251 
00252    if (!tmp) {
00253       return NULL;
00254    }
00255 
00256    /* Check for blanks and tabs and put them in postbr. */
00257    xmldoc_setpostbr(postbr, sizeof(postbr), text);
00258    colmax = columns - xmldoc_postbrlen(postbr);
00259 
00260    textlen = strlen(text);
00261    for (i = 0; i < textlen; i++) {
00262       if (needtobreak || !(count % colmax)) {
00263          if (text[i] == ' ') {
00264             ast_str_append(&tmp, 0, "\n%s", postbr);
00265             needtobreak = 0;
00266             count = 1;
00267          } else if (text[i] != '\n') {
00268             needtobreak = 1;
00269             if (xmldoc_wait_nextspace(text, i, maxdiff)) {
00270                /* wait for the next space */
00271                ast_str_append(&tmp, 0, "%c", text[i]);
00272                continue;
00273             }
00274             /* Try to look backwards */
00275             backspace = xmldoc_foundspace_backward(text, i, maxdiff);
00276             if (backspace) {
00277                needtobreak = 1;
00278                ast_str_truncate(tmp, -backspace);
00279                i -= backspace + 1;
00280                continue;
00281             }
00282             ast_str_append(&tmp, 0, "\n%s", postbr);
00283             needtobreak = 0;
00284             count = 1;
00285          }
00286          /* skip blanks after a \n */
00287          while (text[i] == ' ') {
00288             i++;
00289          }
00290       }
00291       if (text[i] == '\n') {
00292          xmldoc_setpostbr(postbr, sizeof(postbr), &text[i] + 1);
00293          colmax = columns - xmldoc_postbrlen(postbr);
00294          needtobreak = 0;
00295          count = 1;
00296       }
00297       if (text[i] == ESC) {
00298          /* Ignore Escape sequences. */
00299          do {
00300             ast_str_append(&tmp, 0, "%c", text[i]);
00301             i++;
00302          } while (i < textlen && text[i] != 'm');
00303       } else {
00304          count++;
00305       }
00306       ast_str_append(&tmp, 0, "%c", text[i]);
00307    }
00308 
00309    ret = ast_strdup(ast_str_buffer(tmp));
00310    ast_free(tmp);
00311 
00312    return ret;
00313 }
00314 
00315 char *ast_xmldoc_printable(const char *bwinput, int withcolors)
00316 {
00317    struct ast_str *colorized;
00318    char *wrapped = NULL;
00319    int i, c, len, colorsection;
00320    char *tmp;
00321    size_t bwinputlen;
00322    static const int base_fg = COLOR_CYAN;
00323 
00324    if (!bwinput) {
00325       return NULL;
00326    }
00327 
00328    bwinputlen = strlen(bwinput);
00329 
00330    if (!(colorized = ast_str_create(256))) {
00331       return NULL;
00332    }
00333 
00334    if (withcolors) {
00335       ast_term_color_code(&colorized, base_fg, 0);
00336       if (!colorized) {
00337          return NULL;
00338       }
00339    }
00340 
00341    for (i = 0; i < bwinputlen; i++) {
00342       colorsection = 0;
00343       /* Check if we are at the beginning of a tag to be colorized. */
00344       for (c = 0; c < ARRAY_LEN(colorized_tags); c++) {
00345          if (strncasecmp(bwinput + i, colorized_tags[c].inittag, strlen(colorized_tags[c].inittag))) {
00346             continue;
00347          }
00348 
00349          if (!(tmp = strcasestr(bwinput + i + strlen(colorized_tags[c].inittag), colorized_tags[c].endtag))) {
00350             continue;
00351          }
00352 
00353          len = tmp - (bwinput + i + strlen(colorized_tags[c].inittag));
00354 
00355          /* Setup color */
00356          if (withcolors) {
00357             ast_term_color_code(&colorized, colorized_tags[c].colorfg, 0);
00358             if (!colorized) {
00359                return NULL;
00360             }
00361          }
00362 
00363          /* copy initial string replace */
00364          ast_str_append(&colorized, 0, "%s", colorized_tags[c].init);
00365          if (!colorized) {
00366             return NULL;
00367          }
00368          {
00369             char buf[len + 1];
00370             ast_copy_string(buf, bwinput + i + strlen(colorized_tags[c].inittag), sizeof(buf));
00371             ast_str_append(&colorized, 0, "%s", buf);
00372          }
00373          if (!colorized) {
00374             return NULL;
00375          }
00376 
00377          /* copy the ending string replace */
00378          ast_str_append(&colorized, 0, "%s", colorized_tags[c].end);
00379          if (!colorized) {
00380             return NULL;
00381          }
00382 
00383          /* Continue with the last color. */
00384          if (withcolors) {
00385             ast_term_color_code(&colorized, base_fg, 0);
00386             if (!colorized) {
00387                return NULL;
00388             }
00389          }
00390 
00391          i += len + strlen(colorized_tags[c].endtag) + strlen(colorized_tags[c].inittag) - 1;
00392          colorsection = 1;
00393          break;
00394       }
00395 
00396       if (!colorsection) {
00397          ast_str_append(&colorized, 0, "%c", bwinput[i]);
00398          if (!colorized) {
00399             return NULL;
00400          }
00401       }
00402    }
00403 
00404    if (withcolors) {
00405       ast_str_append(&colorized, 0, "%s", term_end());
00406       if (!colorized) {
00407          return NULL;
00408       }
00409    }
00410 
00411    /* Wrap the text, notice that string wrap will avoid cutting an ESC sequence. */
00412    wrapped = xmldoc_string_wrap(ast_str_buffer(colorized), xmldoc_text_columns, xmldoc_max_diff);
00413 
00414    ast_free(colorized);
00415 
00416    return wrapped;
00417 }
00418 
00419 /*! \internal
00420  *  \brief Cleanup spaces and tabs after a \n
00421  *  \param text String to be cleaned up.
00422  *  \param output buffer (not already allocated).
00423  *  \param lastspaces Remove last spaces in the string.
00424  */
00425 static void xmldoc_string_cleanup(const char *text, struct ast_str **output, int lastspaces)
00426 {
00427    int i;
00428    size_t textlen;
00429 
00430    if (!text) {
00431       *output = NULL;
00432       return;
00433    }
00434 
00435    textlen = strlen(text);
00436 
00437    *output = ast_str_create(textlen);
00438    if (!(*output)) {
00439       ast_log(LOG_ERROR, "Problem allocating output buffer\n");
00440       return;
00441    }
00442 
00443    for (i = 0; i < textlen; i++) {
00444       if (text[i] == '\n' || text[i] == '\r') {
00445          /* remove spaces/tabs/\n after a \n. */
00446          while (text[i + 1] == '\t' || text[i + 1] == '\r' || text[i + 1] == '\n') {
00447             i++;
00448          }
00449          ast_str_append(output, 0, " ");
00450          continue;
00451       } else {
00452          ast_str_append(output, 0, "%c", text[i]);
00453       }
00454    }
00455 
00456    /* remove last spaces (we don't want always to remove the trailing spaces). */
00457    if (lastspaces) {
00458       ast_str_trim_blanks(*output);
00459    }
00460 }
00461 
00462 /*! \internal
00463  * \brief Check if the given attribute on the given node matches the given value.
00464  * \param node the node to match
00465  * \param attr the name of the attribute
00466  * \param value the expected value of the attribute
00467  * \retval true if the given attribute contains the given value
00468  * \retval false if the given attribute does not exist or does not contain the given value
00469  */
00470 static int xmldoc_attribute_match(struct ast_xml_node *node, const char *attr, const char *value)
00471 {
00472    const char *attr_value = ast_xml_get_attribute(node, attr);
00473    int match = attr_value && !strcmp(attr_value, value);
00474    ast_xml_free_attr(attr_value);
00475    return match;
00476 }
00477 
00478 /*! \internal
00479  *  \brief Get the application/function node for 'name' application/function with language 'language'
00480  *         and module 'module' if we don't find any, get the first application
00481  *         with 'name' no matter which language or module.
00482  *  \param type 'application', 'function', ...
00483  *  \param name Application or Function name.
00484  *  \param module Module item is in.
00485  *  \param language Try to get this language (if not found try with en_US)
00486  *  \retval NULL on error.
00487  *  \retval A node of type ast_xml_node.
00488  */
00489 static struct ast_xml_node *xmldoc_get_node(const char *type, const char *name, const char *module, const char *language)
00490 {
00491    struct ast_xml_node *node = NULL;
00492    struct ast_xml_node *first_match = NULL;
00493    struct ast_xml_node *lang_match = NULL;
00494    struct documentation_tree *doctree;
00495 
00496    AST_RWLIST_RDLOCK(&xmldoc_tree);
00497    AST_LIST_TRAVERSE(&xmldoc_tree, doctree, entry) {
00498       /* the core xml documents have priority over thirdparty document. */
00499       node = ast_xml_get_root(doctree->doc);
00500       if (!node) {
00501          break;
00502       }
00503 
00504       node = ast_xml_node_get_children(node);
00505       while ((node = ast_xml_find_element(node, type, "name", name))) {
00506          if (!ast_xml_node_get_children(node)) {
00507             /* ignore empty nodes */
00508             node = ast_xml_node_get_next(node);
00509             continue;
00510          }
00511 
00512          if (!first_match) {
00513             first_match = node;
00514          }
00515 
00516          /* Check language */
00517          if (xmldoc_attribute_match(node, "language", language)) {
00518             if (!lang_match) {
00519                lang_match = node;
00520             }
00521 
00522             /* if module is empty we have a match */
00523             if (ast_strlen_zero(module)) {
00524                break;
00525             }
00526 
00527             /* Check module */
00528             if (xmldoc_attribute_match(node, "module", module)) {
00529                break;
00530             }
00531          }
00532 
00533          node = ast_xml_node_get_next(node);
00534       }
00535 
00536       /* if we matched lang and module return this match */
00537       if (node) {
00538          break;
00539       }
00540 
00541       /* we didn't match lang and module, just return the first
00542        * result with a matching language if we have one */
00543       if (lang_match) {
00544          node = lang_match;
00545          break;
00546       }
00547 
00548       /* we didn't match with only the language, just return the
00549        * first match */
00550       if (first_match) {
00551          node = first_match;
00552          break;
00553       }
00554    }
00555    AST_RWLIST_UNLOCK(&xmldoc_tree);
00556 
00557    return node;
00558 }
00559 
00560 /*! \internal
00561  *  \brief Helper function used to build the syntax, it allocates the needed buffer (or reallocates it),
00562  *         and based on the reverse value it makes use of fmt to print the parameter list inside the
00563  *         realloced buffer (syntax).
00564  *  \param reverse We are going backwards while generating the syntax?
00565  *  \param len Current length of 'syntax' buffer.
00566  *  \param syntax Output buffer for the concatenated values.
00567  *  \param fmt A format string that will be used in a sprintf call.
00568  */
00569 static void __attribute__((format(printf, 4, 5))) xmldoc_reverse_helper(int reverse, int *len, char **syntax, const char *fmt, ...)
00570 {
00571    int totlen, tmpfmtlen;
00572    char *tmpfmt, tmp;
00573    va_list ap;
00574 
00575    va_start(ap, fmt);
00576    if (ast_vasprintf(&tmpfmt, fmt, ap) < 0) {
00577       va_end(ap);
00578       return;
00579    }
00580    va_end(ap);
00581 
00582    tmpfmtlen = strlen(tmpfmt);
00583    totlen = *len + tmpfmtlen + 1;
00584 
00585    *syntax = ast_realloc(*syntax, totlen);
00586 
00587    if (!*syntax) {
00588       ast_free(tmpfmt);
00589       return;
00590    }
00591 
00592    if (reverse) {
00593       memmove(*syntax + tmpfmtlen, *syntax, *len);
00594       /* Save this char, it will be overwritten by the \0 of strcpy. */
00595       tmp = (*syntax)[0];
00596       strcpy(*syntax, tmpfmt);
00597       /* Restore the already saved char. */
00598       (*syntax)[tmpfmtlen] = tmp;
00599       (*syntax)[totlen - 1] = '\0';
00600    } else {
00601       strcpy(*syntax + *len, tmpfmt);
00602    }
00603 
00604    *len = totlen - 1;
00605    ast_free(tmpfmt);
00606 }
00607 
00608 /*! \internal
00609  *  \brief Check if the passed node has 'what' tags inside it.
00610  *  \param node Root node to search 'what' elements.
00611  *  \param what node name to search inside node.
00612  *  \retval 1 If a 'what' element is found inside 'node'.
00613  *  \retval 0 If no 'what' is found inside 'node'.
00614  */
00615 static int xmldoc_has_inside(struct ast_xml_node *fixnode, const char *what)
00616 {
00617    struct ast_xml_node *node = fixnode;
00618 
00619    for (node = ast_xml_node_get_children(fixnode); node; node = ast_xml_node_get_next(node)) {
00620       if (!strcasecmp(ast_xml_node_get_name(node), what)) {
00621          return 1;
00622       }
00623    }
00624    return 0;
00625 }
00626 
00627 /*! \internal
00628  *  \brief Check if the passed node has at least one node inside it.
00629  *  \param node Root node to search node elements.
00630  *  \retval 1 If a node element is found inside 'node'.
00631  *  \retval 0 If no node is found inside 'node'.
00632  */
00633 static int xmldoc_has_nodes(struct ast_xml_node *fixnode)
00634 {
00635    struct ast_xml_node *node = fixnode;
00636 
00637    for (node = ast_xml_node_get_children(fixnode); node; node = ast_xml_node_get_next(node)) {
00638       if (strcasecmp(ast_xml_node_get_name(node), "text")) {
00639          return 1;
00640       }
00641    }
00642    return 0;
00643 }
00644 
00645 /*! \internal
00646  *  \brief Check if the passed node has at least one specialtag.
00647  *  \param node Root node to search "specialtags" elements.
00648  *  \retval 1 If a "specialtag" element is found inside 'node'.
00649  *  \retval 0 If no "specialtag" is found inside 'node'.
00650  */
00651 static int xmldoc_has_specialtags(struct ast_xml_node *fixnode)
00652 {
00653    struct ast_xml_node *node = fixnode;
00654    int i;
00655 
00656    for (node = ast_xml_node_get_children(fixnode); node; node = ast_xml_node_get_next(node)) {
00657       for (i = 0; i < ARRAY_LEN(special_tags); i++) {
00658          if (!strcasecmp(ast_xml_node_get_name(node), special_tags[i].tagname)) {
00659             return 1;
00660          }
00661       }
00662    }
00663    return 0;
00664 }
00665 
00666 /*! \internal
00667  *  \brief Build the syntax for a specified starting node.
00668  *  \param rootnode A pointer to the ast_xml root node.
00669  *  \param rootname Name of the application, function, option, etc. to build the syntax.
00670  *  \param childname The name of each parameter node.
00671  *  \param printparenthesis Boolean if we must print parenthesis if not parameters are found in the rootnode.
00672  *  \param printrootname Boolean if we must print the rootname before the syntax and parenthesis at the begining/end.
00673  *  \retval NULL on error.
00674  *  \retval An ast_malloc'ed string with the syntax generated.
00675  */
00676 static char *xmldoc_get_syntax_fun(struct ast_xml_node *rootnode, const char *rootname, const char *childname, int printparenthesis, int printrootname)
00677 {
00678 #define GOTONEXT(__rev, __a) (__rev ? ast_xml_node_get_prev(__a) : ast_xml_node_get_next(__a))
00679 #define ISLAST(__rev, __a)  (__rev == 1 ? (ast_xml_node_get_prev(__a) ? 0 : 1) : (ast_xml_node_get_next(__a) ? 0 : 1))
00680 #define MP(__a) ((multiple ? __a : ""))
00681    struct ast_xml_node *node = NULL, *firstparam = NULL, *lastparam = NULL;
00682    const char *paramtype, *multipletype, *paramnameattr, *attrargsep, *parenthesis, *argname;
00683    int reverse, required, paramcount = 0, openbrackets = 0, len = 0, hasparams=0;
00684    int reqfinode = 0, reqlanode = 0, optmidnode = 0, prnparenthesis, multiple;
00685    char *syntax = NULL, *argsep, *paramname;
00686 
00687    if (ast_strlen_zero(rootname) || ast_strlen_zero(childname)) {
00688       ast_log(LOG_WARNING, "Tried to look in XML tree with faulty rootname or childname while creating a syntax.\n");
00689       return NULL;
00690    }
00691 
00692    if (!rootnode || !ast_xml_node_get_children(rootnode)) {
00693       /* If the rootnode field is not found, at least print name. */
00694       if (ast_asprintf(&syntax, "%s%s", (printrootname ? rootname : ""), (printparenthesis ? "()" : "")) < 0) {
00695          syntax = NULL;
00696       }
00697       return syntax;
00698    }
00699 
00700    /* Get the argument separator from the root node attribute name 'argsep', if not found
00701    defaults to ','. */
00702    attrargsep = ast_xml_get_attribute(rootnode, "argsep");
00703    if (attrargsep) {
00704       argsep = ast_strdupa(attrargsep);
00705       ast_xml_free_attr(attrargsep);
00706    } else {
00707       argsep = ast_strdupa(",");
00708    }
00709 
00710    /* Get order of evaluation. */
00711    for (node = ast_xml_node_get_children(rootnode); node; node = ast_xml_node_get_next(node)) {
00712       if (strcasecmp(ast_xml_node_get_name(node), childname)) {
00713          continue;
00714       }
00715       required = 0;
00716       hasparams = 1;
00717       if ((paramtype = ast_xml_get_attribute(node, "required"))) {
00718          if (ast_true(paramtype)) {
00719             required = 1;
00720          }
00721          ast_xml_free_attr(paramtype);
00722       }
00723 
00724       lastparam = node;
00725       reqlanode = required;
00726 
00727       if (!firstparam) {
00728          /* first parameter node */
00729          firstparam = node;
00730          reqfinode = required;
00731       }
00732    }
00733 
00734    if (!hasparams) {
00735       /* This application, function, option, etc, doesn't have any params. */
00736       if (ast_asprintf(&syntax, "%s%s", (printrootname ? rootname : ""), (printparenthesis ? "()" : "")) < 0) {
00737          syntax = NULL;
00738       }
00739       return syntax;
00740    }
00741 
00742    if (reqfinode && reqlanode) {
00743       /* check midnode */
00744       for (node = ast_xml_node_get_children(rootnode); node; node = ast_xml_node_get_next(node)) {
00745          if (strcasecmp(ast_xml_node_get_name(node), childname)) {
00746             continue;
00747          }
00748          if (node != firstparam && node != lastparam) {
00749             if ((paramtype = ast_xml_get_attribute(node, "required"))) {
00750                if (!ast_true(paramtype)) {
00751                   optmidnode = 1;
00752                   break;
00753                }
00754                ast_xml_free_attr(paramtype);
00755             }
00756          }
00757       }
00758    }
00759 
00760    if ((!reqfinode && reqlanode) || (reqfinode && reqlanode && optmidnode)) {
00761       reverse = 1;
00762       node = lastparam;
00763    } else {
00764       reverse = 0;
00765       node = firstparam;
00766    }
00767 
00768    /* init syntax string. */
00769    if (reverse) {
00770       xmldoc_reverse_helper(reverse, &len, &syntax,
00771          (printrootname ? (printrootname == 2 ? ")]" : ")"): ""));
00772    } else {
00773       xmldoc_reverse_helper(reverse, &len, &syntax, "%s%s", (printrootname ? rootname : ""),
00774          (printrootname ? (printrootname == 2 ? "[(" : "(") : ""));
00775    }
00776 
00777    for (; node; node = GOTONEXT(reverse, node)) {
00778       if (strcasecmp(ast_xml_node_get_name(node), childname)) {
00779          continue;
00780       }
00781 
00782       /* Get the argument name, if it is not the leaf, go inside that parameter. */
00783       if (xmldoc_has_inside(node, "argument")) {
00784          parenthesis = ast_xml_get_attribute(node, "hasparams");
00785          prnparenthesis = 0;
00786          if (parenthesis) {
00787             prnparenthesis = ast_true(parenthesis);
00788             if (!strcasecmp(parenthesis, "optional")) {
00789                prnparenthesis = 2;
00790             }
00791             ast_xml_free_attr(parenthesis);
00792          }
00793          argname = ast_xml_get_attribute(node, "name");
00794          if (argname) {
00795             paramname = xmldoc_get_syntax_fun(node, argname, "argument", prnparenthesis, prnparenthesis);
00796             ast_xml_free_attr(argname);
00797          } else {
00798             /* Malformed XML, print **UNKOWN** */
00799             paramname = ast_strdup("**unknown**");
00800          }
00801       } else {
00802          paramnameattr = ast_xml_get_attribute(node, "name");
00803          if (!paramnameattr) {
00804             ast_log(LOG_WARNING, "Malformed XML %s: no %s name\n", rootname, childname);
00805             if (syntax) {
00806                /* Free already allocated syntax */
00807                ast_free(syntax);
00808             }
00809             /* to give up is ok? */
00810             if (ast_asprintf(&syntax, "%s%s", (printrootname ? rootname : ""), (printparenthesis ? "()" : "")) < 0) {
00811                syntax = NULL;
00812             }
00813             return syntax;
00814          }
00815          paramname = ast_strdup(paramnameattr);
00816          ast_xml_free_attr(paramnameattr);
00817       }
00818 
00819       if (!paramname) {
00820          return NULL;
00821       }
00822 
00823       /* Defaults to 'false'. */
00824       multiple = 0;
00825       if ((multipletype = ast_xml_get_attribute(node, "multiple"))) {
00826          if (ast_true(multipletype)) {
00827             multiple = 1;
00828          }
00829          ast_xml_free_attr(multipletype);
00830       }
00831 
00832       required = 0;  /* Defaults to 'false'. */
00833       if ((paramtype = ast_xml_get_attribute(node, "required"))) {
00834          if (ast_true(paramtype)) {
00835             required = 1;
00836          }
00837          ast_xml_free_attr(paramtype);
00838       }
00839 
00840       /* build syntax core. */
00841 
00842       if (required) {
00843          /* First parameter */
00844          if (!paramcount) {
00845             xmldoc_reverse_helper(reverse, &len, &syntax, "%s%s%s%s", paramname, MP("["), MP(argsep), MP("...]"));
00846          } else {
00847             /* Time to close open brackets. */
00848             while (openbrackets > 0) {
00849                xmldoc_reverse_helper(reverse, &len, &syntax, (reverse ? "[" : "]"));
00850                openbrackets--;
00851             }
00852             if (reverse) {
00853                xmldoc_reverse_helper(reverse, &len, &syntax, "%s%s", paramname, argsep);
00854             } else {
00855                xmldoc_reverse_helper(reverse, &len, &syntax, "%s%s", argsep, paramname);
00856             }
00857             xmldoc_reverse_helper(reverse, &len, &syntax, "%s%s%s", MP("["), MP(argsep), MP("...]"));
00858          }
00859       } else {
00860          /* First parameter */
00861          if (!paramcount) {
00862             xmldoc_reverse_helper(reverse, &len, &syntax, "[%s%s%s%s]", paramname, MP("["), MP(argsep), MP("...]"));
00863          } else {
00864             if (ISLAST(reverse, node)) {
00865                /* This is the last parameter. */
00866                if (reverse) {
00867                   xmldoc_reverse_helper(reverse, &len, &syntax, "[%s%s%s%s]%s", paramname,
00868                            MP("["), MP(argsep), MP("...]"), argsep);
00869                } else {
00870                   xmldoc_reverse_helper(reverse, &len, &syntax, "%s[%s%s%s%s]", argsep, paramname,
00871                            MP("["), MP(argsep), MP("...]"));
00872                }
00873             } else {
00874                if (reverse) {
00875                   xmldoc_reverse_helper(reverse, &len, &syntax, "%s%s%s%s%s]", paramname, argsep,
00876                            MP("["), MP(argsep), MP("...]"));
00877                } else {
00878                   xmldoc_reverse_helper(reverse, &len, &syntax, "[%s%s%s%s%s", argsep, paramname,
00879                            MP("["), MP(argsep), MP("...]"));
00880                }
00881                openbrackets++;
00882             }
00883          }
00884       }
00885       ast_free(paramname);
00886 
00887       paramcount++;
00888    }
00889 
00890    /* Time to close open brackets. */
00891    while (openbrackets > 0) {
00892       xmldoc_reverse_helper(reverse, &len, &syntax, (reverse ? "[" : "]"));
00893       openbrackets--;
00894    }
00895 
00896    /* close syntax string. */
00897    if (reverse) {
00898       xmldoc_reverse_helper(reverse, &len, &syntax, "%s%s", (printrootname ? rootname : ""),
00899          (printrootname ? (printrootname == 2 ? "[(" : "(") : ""));
00900    } else {
00901       xmldoc_reverse_helper(reverse, &len, &syntax, (printrootname ? (printrootname == 2 ? ")]" : ")") : ""));
00902    }
00903 
00904    return syntax;
00905 #undef ISLAST
00906 #undef GOTONEXT
00907 #undef MP
00908 }
00909 
00910 /*! \internal
00911  *  \brief Parse an enumlist inside a <parameter> to generate a COMMAND
00912  *         syntax.
00913  *  \param fixnode A pointer to the <enumlist> node.
00914  *  \retval {<unknown>} on error.
00915  *  \retval A string inside brackets {} with the enum's separated by pipes |.
00916  */
00917 static char *xmldoc_parse_cmd_enumlist(struct ast_xml_node *fixnode)
00918 {
00919    struct ast_xml_node *node = fixnode;
00920    struct ast_str *paramname;
00921    char *enumname, *ret;
00922    int first = 1;
00923 
00924    paramname = ast_str_create(128);
00925    if (!paramname) {
00926       return ast_strdup("{<unkown>}");
00927    }
00928 
00929    ast_str_append(&paramname, 0, "{");
00930 
00931    for (node = ast_xml_node_get_children(node); node; node = ast_xml_node_get_next(node)) {
00932       if (strcasecmp(ast_xml_node_get_name(node), "enum")) {
00933          continue;
00934       }
00935 
00936       enumname = xmldoc_get_syntax_cmd(node, "", 0);
00937       if (!enumname) {
00938          continue;
00939       }
00940       if (!first) {
00941          ast_str_append(&paramname, 0, "|");
00942       }
00943       ast_str_append(&paramname, 0, "%s", enumname);
00944       first = 0;
00945       ast_free(enumname);
00946    }
00947 
00948    ast_str_append(&paramname, 0, "}");
00949 
00950    ret = ast_strdup(ast_str_buffer(paramname));
00951    ast_free(paramname);
00952 
00953    return ret;
00954 }
00955 
00956 /*! \internal
00957  *  \brief Generate a syntax of COMMAND type.
00958  *  \param fixnode The <syntax> node pointer.
00959  *  \param name The name of the 'command'.
00960  *  \param printname Print the name of the command before the paramters?
00961  *  \retval On error, return just 'name'.
00962  *  \retval On success return the generated syntax.
00963  */
00964 static char *xmldoc_get_syntax_cmd(struct ast_xml_node *fixnode, const char *name, int printname)
00965 {
00966    struct ast_str *syntax;
00967    struct ast_xml_node *tmpnode, *node = fixnode;
00968    char *ret, *paramname;
00969    const char *paramtype, *attrname, *literal;
00970    int required, isenum, first = 1, isliteral;
00971 
00972    syntax = ast_str_create(128);
00973    if (!syntax) {
00974       /* at least try to return something... */
00975       return ast_strdup(name);
00976    }
00977 
00978    /* append name to output string. */
00979    if (printname) {
00980       ast_str_append(&syntax, 0, "%s", name);
00981       first = 0;
00982    }
00983 
00984    for (node = ast_xml_node_get_children(node); node; node = ast_xml_node_get_next(node)) {
00985       if (strcasecmp(ast_xml_node_get_name(node), "parameter")) {
00986          continue;
00987       }
00988 
00989       if (xmldoc_has_inside(node, "parameter")) {
00990          /* is this a recursive parameter. */
00991          paramname = xmldoc_get_syntax_cmd(node, "", 0);
00992          isenum = 1;
00993       } else {
00994          for (tmpnode = ast_xml_node_get_children(node); tmpnode; tmpnode = ast_xml_node_get_next(tmpnode)) {
00995             if (!strcasecmp(ast_xml_node_get_name(tmpnode), "enumlist")) {
00996                break;
00997             }
00998          }
00999          if (tmpnode) {
01000             /* parse enumlist (note that this is a special enumlist
01001             that is used to describe a syntax like {<param1>|<param2>|...} */
01002             paramname = xmldoc_parse_cmd_enumlist(tmpnode);
01003             isenum = 1;
01004          } else {
01005             /* this is a simple parameter. */
01006             attrname = ast_xml_get_attribute(node, "name");
01007             if (!attrname) {
01008                /* ignore this bogus parameter and continue. */
01009                continue;
01010             }
01011             paramname = ast_strdup(attrname);
01012             ast_xml_free_attr(attrname);
01013             isenum = 0;
01014          }
01015       }
01016 
01017       /* Is this parameter required? */
01018       required = 0;
01019       paramtype = ast_xml_get_attribute(node, "required");
01020       if (paramtype) {
01021          required = ast_true(paramtype);
01022          ast_xml_free_attr(paramtype);
01023       }
01024 
01025       /* Is this a replaceable value or a fixed parameter value? */
01026       isliteral = 0;
01027       literal = ast_xml_get_attribute(node, "literal");
01028       if (literal) {
01029          isliteral = ast_true(literal);
01030          ast_xml_free_attr(literal);
01031       }
01032 
01033       /* if required="false" print with [...].
01034        * if literal="true" or is enum print without <..>.
01035        * if not first print a space at the beginning.
01036        */
01037       ast_str_append(&syntax, 0, "%s%s%s%s%s%s",
01038             (first ? "" : " "),
01039             (required ? "" : "["),
01040             (isenum || isliteral ? "" : "<"),
01041             paramname,
01042             (isenum || isliteral ? "" : ">"),
01043             (required ? "" : "]"));
01044       first = 0;
01045       ast_free(paramname);
01046    }
01047 
01048    /* return a common string. */
01049    ret = ast_strdup(ast_str_buffer(syntax));
01050    ast_free(syntax);
01051 
01052    return ret;
01053 }
01054 
01055 /*! \internal
01056  *  \brief Generate an AMI action syntax.
01057  *  \param fixnode The manager action node pointer.
01058  *  \param name The name of the manager action.
01059  *  \retval The generated syntax.
01060  *  \retval NULL on error.
01061  */
01062 static char *xmldoc_get_syntax_manager(struct ast_xml_node *fixnode, const char *name)
01063 {
01064    struct ast_str *syntax;
01065    struct ast_xml_node *node = fixnode;
01066    const char *paramtype, *attrname;
01067    int required;
01068    char *ret;
01069 
01070    syntax = ast_str_create(128);
01071    if (!syntax) {
01072       return ast_strdup(name);
01073    }
01074 
01075    ast_str_append(&syntax, 0, "Action: %s", name);
01076 
01077    for (node = ast_xml_node_get_children(node); node; node = ast_xml_node_get_next(node)) {
01078       if (strcasecmp(ast_xml_node_get_name(node), "parameter")) {
01079          continue;
01080       }
01081 
01082       /* Is this parameter required? */
01083       required = 0;
01084       paramtype = ast_xml_get_attribute(node, "required");
01085       if (paramtype) {
01086          required = ast_true(paramtype);
01087          ast_xml_free_attr(paramtype);
01088       }
01089 
01090       attrname = ast_xml_get_attribute(node, "name");
01091       if (!attrname) {
01092          /* ignore this bogus parameter and continue. */
01093          continue;
01094       }
01095 
01096       ast_str_append(&syntax, 0, "\n%s%s:%s <value>",
01097          (required ? "" : "["),
01098          attrname,
01099          (required ? "" : "]"));
01100 
01101       ast_xml_free_attr(attrname);
01102    }
01103 
01104    /* return a common string. */
01105    ret = ast_strdup(ast_str_buffer(syntax));
01106    ast_free(syntax);
01107 
01108    return ret;
01109 }
01110 
01111 /*! \brief Types of syntax that we are able to generate. */
01112 enum syntaxtype {
01113    FUNCTION_SYNTAX,
01114    MANAGER_SYNTAX,
01115    COMMAND_SYNTAX
01116 };
01117 
01118 /*! \brief Mapping between type of node and type of syntax to generate. */
01119 static struct strsyntaxtype {
01120    const char *type;
01121    enum syntaxtype stxtype;
01122 } stxtype[] = {
01123    { "function",     FUNCTION_SYNTAX   },
01124    { "application",  FUNCTION_SYNTAX   },
01125    { "manager",      MANAGER_SYNTAX  },
01126    { "agi",    COMMAND_SYNTAX }
01127 };
01128 
01129 /*! \internal
01130  *  \brief Get syntax type based on type of node.
01131  *  \param type Type of node.
01132  *  \retval The type of syntax to generate based on the type of node.
01133  */
01134 static enum syntaxtype xmldoc_get_syntax_type(const char *type)
01135 {
01136    int i;
01137    for (i=0; i < ARRAY_LEN(stxtype); i++) {
01138       if (!strcasecmp(stxtype[i].type, type)) {
01139          return stxtype[i].stxtype;
01140       }
01141    }
01142 
01143    return FUNCTION_SYNTAX;
01144 }
01145 
01146 char *ast_xmldoc_build_syntax(const char *type, const char *name, const char *module)
01147 {
01148    struct ast_xml_node *node;
01149    char *syntax = NULL;
01150 
01151    node = xmldoc_get_node(type, name, module, documentation_language);
01152    if (!node) {
01153       return NULL;
01154    }
01155 
01156    for (node = ast_xml_node_get_children(node); node; node = ast_xml_node_get_next(node)) {
01157       if (!strcasecmp(ast_xml_node_get_name(node), "syntax")) {
01158          break;
01159       }
01160    }
01161 
01162    if (node) {
01163       switch (xmldoc_get_syntax_type(type)) {
01164       case FUNCTION_SYNTAX:
01165          syntax = xmldoc_get_syntax_fun(node, name, "parameter", 1, 1);
01166          break;
01167       case COMMAND_SYNTAX:
01168          syntax = xmldoc_get_syntax_cmd(node, name, 1);
01169          break;
01170       case MANAGER_SYNTAX:
01171          syntax = xmldoc_get_syntax_manager(node, name);
01172          break;
01173       default:
01174          syntax = xmldoc_get_syntax_fun(node, name, "parameter", 1, 1);
01175       }
01176    }
01177    return syntax;
01178 }
01179 
01180 /*! \internal
01181  *  \brief Parse a <para> element.
01182  *  \param node The <para> element pointer.
01183  *  \param tabs Added this string before the content of the <para> element.
01184  *  \param posttabs Added this string after the content of the <para> element.
01185  *  \param buffer This must be an already allocated ast_str. It will be used
01186  *         to store the result (if already has something it will be appended to the current
01187  *         string).
01188  *  \retval 1 If 'node' is a named 'para'.
01189  *  \retval 2 If data is appended in buffer.
01190  *  \retval 0 on error.
01191  */
01192 static int xmldoc_parse_para(struct ast_xml_node *node, const char *tabs, const char *posttabs, struct ast_str **buffer)
01193 {
01194    const char *tmptext;
01195    struct ast_xml_node *tmp;
01196    int ret = 0;
01197    struct ast_str *tmpstr;
01198 
01199    if (!node || !ast_xml_node_get_children(node)) {
01200       return ret;
01201    }
01202 
01203    if (strcasecmp(ast_xml_node_get_name(node), "para")) {
01204       return ret;
01205    }
01206 
01207    ast_str_append(buffer, 0, "%s", tabs);
01208 
01209    ret = 1;
01210 
01211    for (tmp = ast_xml_node_get_children(node); tmp; tmp = ast_xml_node_get_next(tmp)) {
01212       /* Get the text inside the <para> element and append it to buffer. */
01213       tmptext = ast_xml_get_text(tmp);
01214       if (tmptext) {
01215          /* Strip \n etc. */
01216          xmldoc_string_cleanup(tmptext, &tmpstr, 0);
01217          ast_xml_free_text(tmptext);
01218          if (tmpstr) {
01219             if (strcasecmp(ast_xml_node_get_name(tmp), "text")) {
01220                ast_str_append(buffer, 0, "<%s>%s</%s>", ast_xml_node_get_name(tmp),
01221                      ast_str_buffer(tmpstr), ast_xml_node_get_name(tmp));
01222             } else {
01223                ast_str_append(buffer, 0, "%s", ast_str_buffer(tmpstr));
01224             }
01225             ast_free(tmpstr);
01226             ret = 2;
01227          }
01228       }
01229    }
01230 
01231    ast_str_append(buffer, 0, "%s", posttabs);
01232 
01233    return ret;
01234 }
01235 
01236 /*! \internal
01237  *  \brief Parse special elements defined in 'struct special_tags' special elements must have a <para> element inside them.
01238  *  \param fixnode special tag node pointer.
01239  *  \param tabs put tabs before printing the node content.
01240  *  \param posttabs put posttabs after printing node content.
01241  *  \param buffer Output buffer, the special tags will be appended here.
01242  *  \retval 0 if no special element is parsed.
01243  *  \retval 1 if a special element is parsed (data is appended to buffer).
01244  *  \retval 2 if a special element is parsed and also a <para> element is parsed inside the specialtag.
01245  */
01246 static int xmldoc_parse_specialtags(struct ast_xml_node *fixnode, const char *tabs, const char *posttabs, struct ast_str **buffer)
01247 {
01248    struct ast_xml_node *node = fixnode;
01249    int ret = 0, i, count = 0;
01250 
01251    if (!node || !ast_xml_node_get_children(node)) {
01252       return ret;
01253    }
01254 
01255    for (i = 0; i < ARRAY_LEN(special_tags); i++) {
01256       if (strcasecmp(ast_xml_node_get_name(node), special_tags[i].tagname)) {
01257          continue;
01258       }
01259 
01260       ret = 1;
01261       /* This is a special tag. */
01262 
01263       /* concat data */
01264       if (!ast_strlen_zero(special_tags[i].init)) {
01265          ast_str_append(buffer, 0, "%s%s", tabs, special_tags[i].init);
01266       }
01267 
01268       /* parse <para> elements inside special tags. */
01269       for (node = ast_xml_node_get_children(node); node; node = ast_xml_node_get_next(node)) {
01270          /* first <para> just print it without tabs at the begining. */
01271          if (xmldoc_parse_para(node, (!count ? "" : tabs), posttabs, buffer) == 2) {
01272             ret = 2;
01273          }
01274       }
01275 
01276       if (!ast_strlen_zero(special_tags[i].end)) {
01277          ast_str_append(buffer, 0, "%s%s", special_tags[i].end, posttabs);
01278       }
01279 
01280       break;
01281    }
01282 
01283    return ret;
01284 }
01285 
01286 /*! \internal
01287  *  \brief Parse an <argument> element from the xml documentation.
01288  *  \param fixnode Pointer to the 'argument' xml node.
01289  *  \param insideparameter If we are parsing an <argument> inside a <parameter>.
01290  *  \param paramtabs pre tabs if we are inside a parameter element.
01291  *  \param tabs What to be printed before the argument name.
01292  *  \param buffer Output buffer to put values found inside the <argument> element.
01293  *  \retval 1 If there is content inside the argument.
01294  *  \retval 0 If the argument element is not parsed, or there is no content inside it.
01295  */
01296 static int xmldoc_parse_argument(struct ast_xml_node *fixnode, int insideparameter, const char *paramtabs, const char *tabs, struct ast_str **buffer)
01297 {
01298    struct ast_xml_node *node = fixnode;
01299    const char *argname;
01300    int count = 0, ret = 0;
01301 
01302    if (!node || !ast_xml_node_get_children(node)) {
01303       return ret;
01304    }
01305 
01306    /* Print the argument names */
01307    argname = ast_xml_get_attribute(node, "name");
01308    if (!argname) {
01309       return 0;
01310    }
01311    if (xmldoc_has_inside(node, "para") || xmldoc_has_specialtags(node)) {
01312       ast_str_append(buffer, 0, "%s%s%s", tabs, argname, (insideparameter ? "\n" : ""));
01313       ast_xml_free_attr(argname);
01314    } else {
01315       ast_xml_free_attr(argname);
01316       return 0;
01317    }
01318 
01319    for (node = ast_xml_node_get_children(node); node; node = ast_xml_node_get_next(node)) {
01320       if (xmldoc_parse_para(node, (insideparameter ? paramtabs : (!count ? " - " : tabs)), "\n", buffer) == 2) {
01321          count++;
01322          ret = 1;
01323       } else if (xmldoc_parse_specialtags(node, (insideparameter ? paramtabs : (!count ? " - " : tabs)), "\n", buffer) == 2) {
01324          count++;
01325          ret = 1;
01326       }
01327    }
01328 
01329    return ret;
01330 }
01331 
01332 /*! \internal
01333  *  \brief Parse a <variable> node inside a <variablelist> node.
01334  *  \param node The variable node to parse.
01335  *  \param tabs A string to be appended at the begining of the output that will be stored
01336  *         in buffer.
01337  *  \param buffer This must be an already created ast_str. It will be used
01338  *         to store the result (if already has something it will be appended to the current
01339  *         string).
01340  *  \retval 0 if no data is appended.
01341  *  \retval 1 if data is appended.
01342  */
01343 static int xmldoc_parse_variable(struct ast_xml_node *node, const char *tabs, struct ast_str **buffer)
01344 {
01345    struct ast_xml_node *tmp;
01346    const char *valname;
01347    const char *tmptext;
01348    struct ast_str *cleanstr;
01349    int ret = 0, printedpara=0;
01350 
01351    for (tmp = ast_xml_node_get_children(node); tmp; tmp = ast_xml_node_get_next(tmp)) {
01352       if (xmldoc_parse_para(tmp, (ret ? tabs : ""), "\n", buffer)) {
01353          printedpara = 1;
01354          continue;
01355       } else if (xmldoc_parse_specialtags(tmp, (ret ? tabs : ""), "\n", buffer)) {
01356          printedpara = 1;
01357          continue;
01358       }
01359 
01360       if (strcasecmp(ast_xml_node_get_name(tmp), "value")) {
01361          continue;
01362       }
01363 
01364       /* Parse a <value> tag only. */
01365       if (!printedpara) {
01366          ast_str_append(buffer, 0, "\n");
01367          printedpara = 1;
01368       }
01369       /* Parse each <value name='valuename'>desciption</value> */
01370       valname = ast_xml_get_attribute(tmp, "name");
01371       if (valname) {
01372          ret = 1;
01373          ast_str_append(buffer, 0, "%s<value>%s</value>", tabs, valname);
01374          ast_xml_free_attr(valname);
01375       }
01376       tmptext = ast_xml_get_text(tmp);
01377       /* Check inside this node for any explanation about its meaning. */
01378       if (tmptext) {
01379          /* Cleanup text. */
01380          xmldoc_string_cleanup(tmptext, &cleanstr, 1);
01381          ast_xml_free_text(tmptext);
01382          if (cleanstr && ast_str_strlen(cleanstr) > 0) {
01383             ast_str_append(buffer, 0, ":%s", ast_str_buffer(cleanstr));
01384          }
01385          ast_free(cleanstr);
01386       }
01387       ast_str_append(buffer, 0, "\n");
01388    }
01389 
01390    return ret;
01391 }
01392 
01393 /*! \internal
01394  *  \brief Parse a <variablelist> node and put all the output inside 'buffer'.
01395  *  \param node The variablelist node pointer.
01396  *  \param tabs A string to be appended at the begining of the output that will be stored
01397  *         in buffer.
01398  *  \param buffer This must be an already created ast_str. It will be used
01399  *         to store the result (if already has something it will be appended to the current
01400  *         string).
01401  *  \retval 1 If a <variablelist> element is parsed.
01402  *  \retval 0 On error.
01403  */
01404 static int xmldoc_parse_variablelist(struct ast_xml_node *node, const char *tabs, struct ast_str **buffer)
01405 {
01406    struct ast_xml_node *tmp;
01407    const char *varname;
01408    char *vartabs;
01409    int ret = 0;
01410 
01411    if (!node || !ast_xml_node_get_children(node)) {
01412       return ret;
01413    }
01414 
01415    if (strcasecmp(ast_xml_node_get_name(node), "variablelist")) {
01416       return ret;
01417    }
01418 
01419    /* use this spacing (add 4 spaces) inside a variablelist node. */
01420    if (ast_asprintf(&vartabs, "%s    ", tabs) < 0) {
01421       return ret;
01422    }
01423    for (tmp = ast_xml_node_get_children(node); tmp; tmp = ast_xml_node_get_next(tmp)) {
01424       /* We can have a <para> element inside the variable list */
01425       if ((xmldoc_parse_para(tmp, (ret ? tabs : ""), "\n", buffer))) {
01426          ret = 1;
01427          continue;
01428       } else if ((xmldoc_parse_specialtags(tmp, (ret ? tabs : ""), "\n", buffer))) {
01429          ret = 1;
01430          continue;
01431       }
01432 
01433       if (!strcasecmp(ast_xml_node_get_name(tmp), "variable")) {
01434          /* Store the variable name in buffer. */
01435          varname = ast_xml_get_attribute(tmp, "name");
01436          if (varname) {
01437             ast_str_append(buffer, 0, "%s<variable>%s</variable>: ", tabs, varname);
01438             ast_xml_free_attr(varname);
01439             /* Parse the <variable> possible values. */
01440             xmldoc_parse_variable(tmp, vartabs, buffer);
01441             ret = 1;
01442          }
01443       }
01444    }
01445 
01446    ast_free(vartabs);
01447 
01448    return ret;
01449 }
01450 
01451 char *ast_xmldoc_build_seealso(const char *type, const char *name, const char *module)
01452 {
01453    struct ast_str *outputstr;
01454    char *output;
01455    struct ast_xml_node *node;
01456    const char *typename;
01457    const char *content;
01458    int first = 1;
01459 
01460    if (ast_strlen_zero(type) || ast_strlen_zero(name)) {
01461       return NULL;
01462    }
01463 
01464    /* get the application/function root node. */
01465    node = xmldoc_get_node(type, name, module, documentation_language);
01466    if (!node || !ast_xml_node_get_children(node)) {
01467       return NULL;
01468    }
01469 
01470    /* Find the <see-also> node. */
01471    for (node = ast_xml_node_get_children(node); node; node = ast_xml_node_get_next(node)) {
01472       if (!strcasecmp(ast_xml_node_get_name(node), "see-also")) {
01473          break;
01474       }
01475    }
01476 
01477    if (!node || !ast_xml_node_get_children(node)) {
01478       /* we couldnt find a <see-also> node. */
01479       return NULL;
01480    }
01481 
01482    /* prepare the output string. */
01483    outputstr = ast_str_create(128);
01484    if (!outputstr) {
01485       return NULL;
01486    }
01487 
01488    /* get into the <see-also> node. */
01489    for (node = ast_xml_node_get_children(node); node; node = ast_xml_node_get_next(node)) {
01490       if (strcasecmp(ast_xml_node_get_name(node), "ref")) {
01491          continue;
01492       }
01493 
01494       /* parse the <ref> node. 'type' attribute is required. */
01495       typename = ast_xml_get_attribute(node, "type");
01496       if (!typename) {
01497          continue;
01498       }
01499       content = ast_xml_get_text(node);
01500       if (!content) {
01501          ast_xml_free_attr(typename);
01502          continue;
01503       }
01504       if (!strcasecmp(typename, "application")) {
01505          ast_str_append(&outputstr, 0, "%s%s()",   (first ? "" : ", "), content);
01506       } else if (!strcasecmp(typename, "function")) {
01507          ast_str_append(&outputstr, 0, "%s%s", (first ? "" : ", "), content);
01508       } else if (!strcasecmp(typename, "astcli")) {
01509          ast_str_append(&outputstr, 0, "%s<astcli>%s</astcli>", (first ? "" : ", "), content);
01510       } else {
01511          ast_str_append(&outputstr, 0, "%s%s", (first ? "" : ", "), content);
01512       }
01513       first = 0;
01514       ast_xml_free_text(content);
01515       ast_xml_free_attr(typename);
01516    }
01517 
01518    output = ast_strdup(ast_str_buffer(outputstr));
01519    ast_free(outputstr);
01520 
01521    return output;
01522 }
01523 
01524 /*! \internal
01525  *  \brief Parse a <enum> node.
01526  *  \brief fixnode An ast_xml_node pointer to the <enum> node.
01527  *  \bried buffer The output buffer.
01528  *  \retval 0 if content is not found inside the enum element (data is not appended to buffer).
01529  *  \retval 1 if content is found and data is appended to buffer.
01530  */
01531 static int xmldoc_parse_enum(struct ast_xml_node *fixnode, const char *tabs, struct ast_str **buffer)
01532 {
01533    struct ast_xml_node *node = fixnode;
01534    int ret = 0;
01535    char *optiontabs;
01536 
01537    if (ast_asprintf(&optiontabs, "%s    ", tabs) < 0) {
01538       return ret;
01539    }
01540 
01541    for (node = ast_xml_node_get_children(node); node; node = ast_xml_node_get_next(node)) {
01542       if ((xmldoc_parse_para(node, (ret ? tabs : " - "), "\n", buffer))) {
01543          ret = 1;
01544       } else if ((xmldoc_parse_specialtags(node, (ret ? tabs : " - "), "\n", buffer))) {
01545          ret = 1;
01546       }
01547 
01548       xmldoc_parse_enumlist(node, optiontabs, buffer);
01549    }
01550 
01551    ast_free(optiontabs);
01552 
01553    return ret;
01554 }
01555 
01556 /*! \internal
01557  *  \brief Parse a <enumlist> node.
01558  *  \param fixnode As ast_xml pointer to the <enumlist> node.
01559  *  \param buffer The ast_str output buffer.
01560  *  \retval 0 if no <enumlist> node was parsed.
01561  *  \retval 1 if a <enumlist> node was parsed.
01562  */
01563 static int xmldoc_parse_enumlist(struct ast_xml_node *fixnode, const char *tabs, struct ast_str **buffer)
01564 {
01565    struct ast_xml_node *node = fixnode;
01566    const char *enumname;
01567    int ret = 0;
01568 
01569    for (node = ast_xml_node_get_children(node); node; node = ast_xml_node_get_next(node)) {
01570       if (strcasecmp(ast_xml_node_get_name(node), "enum")) {
01571          continue;
01572       }
01573 
01574       enumname = ast_xml_get_attribute(node, "name");
01575       if (enumname) {
01576          ast_str_append(buffer, 0, "%s<enum>%s</enum>", tabs, enumname);
01577          ast_xml_free_attr(enumname);
01578 
01579          /* parse only enum elements inside a enumlist node. */
01580          if ((xmldoc_parse_enum(node, tabs, buffer))) {
01581             ret = 1;
01582          } else {
01583             ast_str_append(buffer, 0, "\n");
01584          }
01585       }
01586    }
01587    return ret;
01588 }
01589 
01590 /*! \internal
01591  *  \brief Parse an <option> node.
01592  *  \param fixnode An ast_xml pointer to the <option> node.
01593  *  \param tabs A string to be appended at the begining of each line being added to the
01594  *              buffer string.
01595  *  \param buffer The output buffer.
01596  *  \retval 0 if no option node is parsed.
01597  *  \retval 1 if an option node is parsed.
01598  */
01599 static int xmldoc_parse_option(struct ast_xml_node *fixnode, const char *tabs, struct ast_str **buffer)
01600 {
01601    struct ast_xml_node *node;
01602    int ret = 0;
01603    char *optiontabs;
01604 
01605    if (ast_asprintf(&optiontabs, "%s    ", tabs) < 0) {
01606       return ret;
01607    }
01608    for (node = ast_xml_node_get_children(fixnode); node; node = ast_xml_node_get_next(node)) {
01609       if (!strcasecmp(ast_xml_node_get_name(node), "argument")) {
01610          /* if this is the first data appended to buffer, print a \n*/
01611          if (!ret && ast_xml_node_get_children(node)) {
01612             /* print \n */
01613             ast_str_append(buffer, 0, "\n");
01614          }
01615          if (xmldoc_parse_argument(node, 0, NULL, optiontabs, buffer)) {
01616             ret = 1;
01617          }
01618          continue;
01619       }
01620 
01621       if (xmldoc_parse_para(node, (ret ? tabs :  ""), "\n", buffer)) {
01622          ret = 1;
01623       } else if (xmldoc_parse_specialtags(node, (ret ? tabs :  ""), "\n", buffer)) {
01624          ret = 1;
01625       }
01626 
01627       xmldoc_parse_variablelist(node, optiontabs, buffer);
01628 
01629       xmldoc_parse_enumlist(node, optiontabs, buffer);
01630    }
01631    ast_free(optiontabs);
01632 
01633    return ret;
01634 }
01635 
01636 /*! \internal
01637  *  \brief Parse an <optionlist> element from the xml documentation.
01638  *  \param fixnode Pointer to the optionlist xml node.
01639  *  \param tabs A string to be appended at the begining of each line being added to the
01640  *              buffer string.
01641  *  \param buffer Output buffer to put what is inside the optionlist tag.
01642  */
01643 static void xmldoc_parse_optionlist(struct ast_xml_node *fixnode, const char *tabs, struct ast_str **buffer)
01644 {
01645    struct ast_xml_node *node;
01646    const char *optname, *hasparams;
01647    char *optionsyntax;
01648    int optparams;
01649 
01650    for (node = ast_xml_node_get_children(fixnode); node; node = ast_xml_node_get_next(node)) {
01651       /* Start appending every option tag. */
01652       if (strcasecmp(ast_xml_node_get_name(node), "option")) {
01653          continue;
01654       }
01655 
01656       /* Get the option name. */
01657       optname = ast_xml_get_attribute(node, "name");
01658       if (!optname) {
01659          continue;
01660       }
01661 
01662       optparams = 1;
01663       hasparams = ast_xml_get_attribute(node, "hasparams");
01664       if (hasparams && !strcasecmp(hasparams, "optional")) {
01665          optparams = 2;
01666       }
01667 
01668       optionsyntax = xmldoc_get_syntax_fun(node, optname, "argument", 0, optparams);
01669       if (!optionsyntax) {
01670          ast_xml_free_attr(optname);
01671          ast_xml_free_attr(hasparams);
01672          continue;
01673       }
01674 
01675       ast_str_append(buffer, 0, "%s%s: ", tabs, optionsyntax);
01676 
01677       if (!xmldoc_parse_option(node, tabs, buffer)) {
01678          ast_str_append(buffer, 0, "\n");
01679       }
01680       ast_str_append(buffer, 0, "\n");
01681       ast_xml_free_attr(optname);
01682       ast_xml_free_attr(hasparams);
01683       ast_free(optionsyntax);
01684    }
01685 }
01686 
01687 /*! \internal
01688  *  \brief Parse a 'parameter' tag inside a syntax element.
01689  *  \param fixnode A pointer to the 'parameter' xml node.
01690  *  \param tabs A string to be appended at the beginning of each line being printed inside
01691  *              'buffer'.
01692  *  \param buffer String buffer to put values found inside the parameter element.
01693  */
01694 static void xmldoc_parse_parameter(struct ast_xml_node *fixnode, const char *tabs, struct ast_str **buffer)
01695 {
01696    const char *paramname;
01697    struct ast_xml_node *node = fixnode;
01698    int hasarguments, printed = 0;
01699    char *internaltabs;
01700 
01701    if (strcasecmp(ast_xml_node_get_name(node), "parameter")) {
01702       return;
01703    }
01704 
01705    hasarguments = xmldoc_has_inside(node, "argument");
01706    if (!(paramname = ast_xml_get_attribute(node, "name"))) {
01707       /* parameter MUST have an attribute name. */
01708       return;
01709    }
01710 
01711    if (ast_asprintf(&internaltabs, "%s    ", tabs) < 0) {
01712       ast_xml_free_attr(paramname);
01713       return;
01714    }
01715 
01716    if (!hasarguments && xmldoc_has_nodes(node)) {
01717       ast_str_append(buffer, 0, "%s\n", paramname);
01718       ast_xml_free_attr(paramname);
01719       printed = 1;
01720    }
01721 
01722    for (node = ast_xml_node_get_children(node); node; node = ast_xml_node_get_next(node)) {
01723       if (!strcasecmp(ast_xml_node_get_name(node), "optionlist")) {
01724          xmldoc_parse_optionlist(node, internaltabs, buffer);
01725       } else if (!strcasecmp(ast_xml_node_get_name(node), "enumlist")) {
01726          xmldoc_parse_enumlist(node, internaltabs, buffer);
01727       } else if (!strcasecmp(ast_xml_node_get_name(node), "argument")) {
01728          xmldoc_parse_argument(node, 1, internaltabs, (!hasarguments ? "        " : ""), buffer);
01729       } else if (!strcasecmp(ast_xml_node_get_name(node), "para")) {
01730          if (!printed) {
01731             ast_str_append(buffer, 0, "%s\n", paramname);
01732             ast_xml_free_attr(paramname);
01733             printed = 1;
01734          }
01735          if (xmldoc_parse_para(node, internaltabs, "\n", buffer)) {
01736             /* If anything ever goes in below this condition before the continue below,
01737              * we should probably continue immediately. */
01738             continue;
01739          }
01740          continue;
01741       } else if ((xmldoc_parse_specialtags(node, internaltabs, "\n", buffer))) {
01742          continue;
01743       }
01744    }
01745    if (!printed) {
01746       ast_xml_free_attr(paramname);
01747    }
01748    ast_free(internaltabs);
01749 }
01750 
01751 char *ast_xmldoc_build_arguments(const char *type, const char *name, const char *module)
01752 {
01753    struct ast_xml_node *node;
01754    struct ast_str *ret = ast_str_create(128);
01755    char *retstr = NULL;
01756 
01757    if (ast_strlen_zero(type) || ast_strlen_zero(name)) {
01758       ast_free(ret);
01759       return NULL;
01760    }
01761 
01762    node = xmldoc_get_node(type, name, module, documentation_language);
01763 
01764    if (!node || !ast_xml_node_get_children(node)) {
01765       ast_free(ret);
01766       return NULL;
01767    }
01768 
01769    /* Find the syntax field. */
01770    for (node = ast_xml_node_get_children(node); node; node = ast_xml_node_get_next(node)) {
01771       if (!strcasecmp(ast_xml_node_get_name(node), "syntax")) {
01772          break;
01773       }
01774    }
01775 
01776    if (!node || !ast_xml_node_get_children(node)) {
01777       /* We couldn't find the syntax node. */
01778       ast_free(ret);
01779       return NULL;
01780    }
01781 
01782    for (node = ast_xml_node_get_children(node); node; node = ast_xml_node_get_next(node)) {
01783       xmldoc_parse_parameter(node, "", &ret);
01784    }
01785 
01786    if (ast_str_strlen(ret) > 0) {
01787       /* remove last '\n' */
01788       char *buf = ast_str_buffer(ret);
01789       if (buf[ast_str_strlen(ret) - 1] == '\n') {
01790          ast_str_truncate(ret, -1);
01791       }
01792       retstr = ast_strdup(ast_str_buffer(ret));
01793    }
01794    ast_free(ret);
01795 
01796    return retstr;
01797 }
01798 
01799 /*! \internal
01800  *  \brief Return the string within a node formatted with <para> and <variablelist> elements.
01801  *  \param node Parent node where content resides.
01802  *  \param raw If set, return the node's content without further processing.
01803  *  \param raw_wrap Wrap raw text.
01804  *  \retval NULL on error
01805  *  \retval Node content on success.
01806  */
01807 static struct ast_str *xmldoc_get_formatted(struct ast_xml_node *node, int raw_output, int raw_wrap)
01808 {
01809    struct ast_xml_node *tmp;
01810    const char *notcleanret, *tmpstr;
01811    struct ast_str *ret;
01812 
01813    if (raw_output) {
01814       /* xmldoc_string_cleanup will allocate the ret object */
01815       notcleanret = ast_xml_get_text(node);
01816       tmpstr = notcleanret;
01817       xmldoc_string_cleanup(ast_skip_blanks(notcleanret), &ret, 0);
01818       ast_xml_free_text(tmpstr);
01819    } else {
01820       ret = ast_str_create(128);
01821       for (tmp = ast_xml_node_get_children(node); tmp; tmp = ast_xml_node_get_next(tmp)) {
01822          /* if found, parse a <para> element. */
01823          if (xmldoc_parse_para(tmp, "", "\n", &ret)) {
01824             continue;
01825          } else if (xmldoc_parse_specialtags(tmp, "", "\n", &ret)) {
01826             continue;
01827          }
01828          /* if found, parse a <variablelist> element. */
01829          xmldoc_parse_variablelist(tmp, "", &ret);
01830          xmldoc_parse_enumlist(tmp, "    ", &ret);
01831       }
01832       /* remove last '\n' */
01833       /* XXX Don't modify ast_str internals manually */
01834       tmpstr = ast_str_buffer(ret);
01835       if (tmpstr[ast_str_strlen(ret) - 1] == '\n') {
01836          ast_str_truncate(ret, -1);
01837       }
01838    }
01839    return ret;
01840 }
01841 
01842 /*!
01843  *  \brief Get the content of a field (synopsis, description, etc) from an asterisk document tree
01844  *  \param type Type of element (application, function, ...).
01845  *  \param name Name of element (Dial, Echo, Playback, ...).
01846  *  \param var Name of field to return (synopsis, description, etc).
01847  *  \param raw Field only contains text, no other elements inside it.
01848  *  \retval NULL On error.
01849  *  \retval Field text content on success.
01850  */
01851 static char *xmldoc_build_field(const char *type, const char *name, const char *module, const char *var, int raw)
01852 {
01853    struct ast_xml_node *node;
01854    char *ret = NULL;
01855    struct ast_str *formatted;
01856 
01857    if (ast_strlen_zero(type) || ast_strlen_zero(name)) {
01858       ast_log(LOG_ERROR, "Tried to look in XML tree with faulty values.\n");
01859       return ret;
01860    }
01861 
01862    node = xmldoc_get_node(type, name, module, documentation_language);
01863 
01864    if (!node) {
01865       ast_log(LOG_WARNING, "Couldn't find %s %s in XML documentation\n", type, name);
01866       return ret;
01867    }
01868 
01869    node = ast_xml_find_element(ast_xml_node_get_children(node), var, NULL, NULL);
01870 
01871    if (!node || !ast_xml_node_get_children(node)) {
01872       ast_log(LOG_DEBUG, "Cannot find variable '%s' in tree '%s'\n", var, name);
01873       return ret;
01874    }
01875 
01876    formatted = xmldoc_get_formatted(node, raw, raw);
01877    if (ast_str_strlen(formatted) > 0) {
01878       ret = ast_strdup(ast_str_buffer(formatted));
01879    }
01880    ast_free(formatted);
01881 
01882    return ret;
01883 }
01884 
01885 char *ast_xmldoc_build_synopsis(const char *type, const char *name, const char *module)
01886 {
01887    return xmldoc_build_field(type, name, module, "synopsis", 1);
01888 }
01889 
01890 char *ast_xmldoc_build_description(const char *type, const char *name, const char *module)
01891 {
01892    return xmldoc_build_field(type, name, module, "description", 0);
01893 }
01894 
01895 #if !defined(HAVE_GLOB_NOMAGIC) || !defined(HAVE_GLOB_BRACE) || defined(DEBUG_NONGNU)
01896 static int xml_pathmatch(char *xmlpattern, int xmlpattern_maxlen, glob_t *globbuf)
01897 {
01898    int globret;
01899 
01900    snprintf(xmlpattern, xmlpattern_maxlen, "%s/documentation/thirdparty/*-%s.xml",
01901       ast_config_AST_DATA_DIR, documentation_language);
01902    if((globret = glob(xmlpattern, GLOB_NOCHECK, NULL, globbuf))) {
01903       return globret;
01904    }
01905 
01906    snprintf(xmlpattern, xmlpattern_maxlen, "%s/documentation/thirdparty/*-%.2s_??.xml",
01907       ast_config_AST_DATA_DIR, documentation_language);
01908    if((globret = glob(xmlpattern, GLOB_APPEND | GLOB_NOCHECK, NULL, globbuf))) {
01909       return globret;
01910    }
01911 
01912    snprintf(xmlpattern, xmlpattern_maxlen, "%s/documentation/thirdparty/*-%s.xml",
01913       ast_config_AST_DATA_DIR, default_documentation_language);
01914    if((globret = glob(xmlpattern, GLOB_APPEND | GLOB_NOCHECK, NULL, globbuf))) {
01915       return globret;
01916    }
01917 
01918    snprintf(xmlpattern, xmlpattern_maxlen, "%s/documentation/*-%s.xml",
01919       ast_config_AST_DATA_DIR, documentation_language);
01920    if((globret = glob(xmlpattern, GLOB_APPEND | GLOB_NOCHECK, NULL, globbuf))) {
01921       return globret;
01922    }
01923 
01924    snprintf(xmlpattern, xmlpattern_maxlen, "%s/documentation/*-%.2s_??.xml",
01925       ast_config_AST_DATA_DIR, documentation_language);
01926    if((globret = glob(xmlpattern, GLOB_APPEND | GLOB_NOCHECK, NULL, globbuf))) {
01927       return globret;
01928    }
01929 
01930    snprintf(xmlpattern, xmlpattern_maxlen, "%s/documentation/*-%s.xml",
01931       ast_config_AST_DATA_DIR, default_documentation_language);
01932    globret = glob(xmlpattern, GLOB_APPEND | GLOB_NOCHECK, NULL, globbuf);
01933 
01934    return globret;
01935 }
01936 #endif
01937 
01938 /*! \brief Close and unload XML documentation. */
01939 static void xmldoc_unload_documentation(void)
01940 {
01941         struct documentation_tree *doctree;
01942 
01943    AST_RWLIST_WRLOCK(&xmldoc_tree);
01944    while ((doctree = AST_RWLIST_REMOVE_HEAD(&xmldoc_tree, entry))) {
01945       ast_free(doctree->filename);
01946       ast_xml_close(doctree->doc);
01947    }
01948    AST_RWLIST_UNLOCK(&xmldoc_tree);
01949 
01950    ast_xml_finish();
01951 }
01952 
01953 int ast_xmldoc_load_documentation(void)
01954 {
01955    struct ast_xml_node *root_node;
01956    struct ast_xml_doc *tmpdoc;
01957    struct documentation_tree *doc_tree;
01958    char *xmlpattern;
01959    struct ast_config *cfg = NULL;
01960    struct ast_variable *var = NULL;
01961    struct ast_flags cnfflags = { 0 };
01962    int globret, i, dup, duplicate;
01963    glob_t globbuf;
01964 #if !defined(HAVE_GLOB_NOMAGIC) || !defined(HAVE_GLOB_BRACE) || defined(DEBUG_NONGNU)
01965    int xmlpattern_maxlen;
01966 #endif
01967 
01968    /* setup default XML documentation language */
01969    snprintf(documentation_language, sizeof(documentation_language), default_documentation_language);
01970 
01971    if ((cfg = ast_config_load2("asterisk.conf", "" /* core can't reload */, cnfflags)) && cfg != CONFIG_STATUS_FILEINVALID) {
01972       for (var = ast_variable_browse(cfg, "options"); var; var = var->next) {
01973          if (!strcasecmp(var->name, "documentation_language")) {
01974             if (!ast_strlen_zero(var->value)) {
01975                snprintf(documentation_language, sizeof(documentation_language), "%s", var->value);
01976             }
01977          }
01978       }
01979       ast_config_destroy(cfg);
01980    }
01981 
01982    /* initialize the XML library. */
01983    ast_xml_init();
01984 
01985    /* register function to be run when asterisk finish. */
01986    ast_register_atexit(xmldoc_unload_documentation);
01987 
01988    globbuf.gl_offs = 0;    /* slots to reserve in gl_pathv */
01989 
01990 #if !defined(HAVE_GLOB_NOMAGIC) || !defined(HAVE_GLOB_BRACE) || defined(DEBUG_NONGNU)
01991    xmlpattern_maxlen = strlen(ast_config_AST_DATA_DIR) + strlen("/documentation/thirdparty") + strlen("/*-??_??.xml") + 1;
01992    xmlpattern = ast_malloc(xmlpattern_maxlen);
01993    globret = xml_pathmatch(xmlpattern, xmlpattern_maxlen, &globbuf);
01994 #else
01995    /* Get every *-LANG.xml file inside $(ASTDATADIR)/documentation */
01996    if (ast_asprintf(&xmlpattern, "%s/documentation{/thirdparty/,/}*-{%s,%.2s_??,%s}.xml", ast_config_AST_DATA_DIR,
01997       documentation_language, documentation_language, default_documentation_language) < 0) {
01998       return 1;
01999    }
02000    globret = glob(xmlpattern, MY_GLOB_FLAGS, NULL, &globbuf);
02001 #endif
02002 
02003    ast_debug(3, "gl_pathc %zd\n", globbuf.gl_pathc);
02004    if (globret == GLOB_NOSPACE) {
02005       ast_log(LOG_WARNING, "XML load failure, glob expansion of pattern '%s' failed: Not enough memory\n", xmlpattern);
02006       ast_free(xmlpattern);
02007       return 1;
02008    } else if (globret  == GLOB_ABORTED) {
02009       ast_log(LOG_WARNING, "XML load failure, glob expansion of pattern '%s' failed: Read error\n", xmlpattern);
02010       ast_free(xmlpattern);
02011       return 1;
02012    }
02013    ast_free(xmlpattern);
02014 
02015    AST_RWLIST_WRLOCK(&xmldoc_tree);
02016    /* loop over expanded files */
02017    for (i = 0; i < globbuf.gl_pathc; i++) {
02018       /* check for duplicates (if we already [try to] open the same file. */
02019       duplicate = 0;
02020       for (dup = 0; dup < i; dup++) {
02021          if (!strcmp(globbuf.gl_pathv[i], globbuf.gl_pathv[dup])) {
02022             duplicate = 1;
02023             break;
02024          }
02025       }
02026       if (duplicate || strchr(globbuf.gl_pathv[i], '*')) {
02027       /* skip duplicates as well as pathnames not found 
02028        * (due to use of GLOB_NOCHECK in xml_pathmatch) */
02029          continue;
02030       }
02031       tmpdoc = NULL;
02032       tmpdoc = ast_xml_open(globbuf.gl_pathv[i]);
02033       if (!tmpdoc) {
02034          ast_log(LOG_ERROR, "Could not open XML documentation at '%s'\n", globbuf.gl_pathv[i]);
02035          continue;
02036       }
02037       /* Get doc root node and check if it starts with '<docs>' */
02038       root_node = ast_xml_get_root(tmpdoc);
02039       if (!root_node) {
02040          ast_log(LOG_ERROR, "Error getting documentation root node\n");
02041          ast_xml_close(tmpdoc);
02042          continue;
02043       }
02044       /* Check root node name for malformed xmls. */
02045       if (strcmp(ast_xml_node_get_name(root_node), "docs")) {
02046          ast_log(LOG_ERROR, "Documentation file is not well formed!\n");
02047          ast_xml_close(tmpdoc);
02048          continue;
02049       }
02050       doc_tree = ast_calloc(1, sizeof(*doc_tree));
02051       if (!doc_tree) {
02052          ast_log(LOG_ERROR, "Unable to allocate documentation_tree structure!\n");
02053          ast_xml_close(tmpdoc);
02054          continue;
02055       }
02056       doc_tree->doc = tmpdoc;
02057       doc_tree->filename = ast_strdup(globbuf.gl_pathv[i]);
02058       AST_RWLIST_INSERT_TAIL(&xmldoc_tree, doc_tree, entry);
02059    }
02060    AST_RWLIST_UNLOCK(&xmldoc_tree);
02061 
02062    globfree(&globbuf);
02063 
02064    return 0;
02065 }
02066 
02067 #endif /* AST_XML_DOCS */
02068 
02069