diff --git a/include/crm/common/xml_io_internal.h b/include/crm/common/xml_io_internal.h index 52035669da..18a84840c2 100644 --- a/include/crm/common/xml_io_internal.h +++ b/include/crm/common/xml_io_internal.h @@ -1,32 +1,35 @@ /* * Copyright 2017-2024 the Pacemaker project contributors * * The version control history for this file may have further details. * * This source code is licensed under the GNU Lesser General Public License * version 2.1 or later (LGPLv2.1+) WITHOUT ANY WARRANTY. */ #ifndef PCMK__XML_IO_INTERNAL__H #define PCMK__XML_IO_INTERNAL__H /* * Internal-only wrappers for and extensions to libxml2 I/O */ #include // bool #include // xmlNode xmlNode *pcmk__xml_read(const char *filename); xmlNode *pcmk__xml_parse(const char *input); +void pcmk__xml_string(const xmlNode *data, uint32_t options, GString *buffer, + int depth); + int pcmk__xml2fd(int fd, xmlNode *cur); int pcmk__xml_write_fd(const xmlNode *xml, const char *filename, int fd, bool compress, unsigned int *nbytes); int pcmk__xml_write_file(const xmlNode *xml, const char *filename, bool compress, unsigned int *nbytes); gchar *pcmk__xml_dump(const xmlNode *xml, uint32_t flags); #endif // PCMK__XML_IO_INTERNAL__H diff --git a/lib/common/crmcommon_private.h b/lib/common/crmcommon_private.h index 3bfc0e939c..c08fe72139 100644 --- a/lib/common/crmcommon_private.h +++ b/lib/common/crmcommon_private.h @@ -1,358 +1,354 @@ /* * Copyright 2018-2024 the Pacemaker project contributors * * The version control history for this file may have further details. * * This source code is licensed under the GNU Lesser General Public License * version 2.1 or later (LGPLv2.1+) WITHOUT ANY WARRANTY. */ #ifndef CRMCOMMON_PRIVATE__H # define CRMCOMMON_PRIVATE__H /* This header is for the sole use of libcrmcommon, so that functions can be * declared with G_GNUC_INTERNAL for efficiency. */ #include // uint8_t, uint32_t #include // bool #include // size_t #include // GList #include // xmlNode, xmlAttr #include // struct qb_ipc_response_header // Decent chunk size for processing large amounts of data #define PCMK__BUFFER_SIZE 4096 #if defined(PCMK__UNIT_TESTING) #undef G_GNUC_INTERNAL #define G_GNUC_INTERNAL #endif /* When deleting portions of an XML tree, we keep a record so we can know later * (e.g. when checking differences) that something was deleted. */ typedef struct pcmk__deleted_xml_s { char *path; int position; } pcmk__deleted_xml_t; typedef struct xml_node_private_s { long check; uint32_t flags; } xml_node_private_t; typedef struct xml_doc_private_s { long check; uint32_t flags; char *user; GList *acls; GList *deleted_objs; // List of pcmk__deleted_xml_t } xml_doc_private_t; //! libxml2 supports only XML version 1.0, at least as of libxml2-2.12.5 #define PCMK__XML_VERSION ((pcmkXmlStr) "1.0") #define pcmk__set_xml_flags(xml_priv, flags_to_set) do { \ (xml_priv)->flags = pcmk__set_flags_as(__func__, __LINE__, \ LOG_NEVER, "XML", "XML node", (xml_priv)->flags, \ (flags_to_set), #flags_to_set); \ } while (0) #define pcmk__clear_xml_flags(xml_priv, flags_to_clear) do { \ (xml_priv)->flags = pcmk__clear_flags_as(__func__, __LINE__, \ LOG_NEVER, "XML", "XML node", (xml_priv)->flags, \ (flags_to_clear), #flags_to_clear); \ } while (0) -G_GNUC_INTERNAL -void pcmk__xml2text(const xmlNode *data, uint32_t options, GString *buffer, - int depth); - G_GNUC_INTERNAL bool pcmk__tracking_xml_changes(xmlNode *xml, bool lazy); G_GNUC_INTERNAL void pcmk__mark_xml_created(xmlNode *xml); G_GNUC_INTERNAL int pcmk__xml_position(const xmlNode *xml, enum xml_private_flags ignore_if_set); G_GNUC_INTERNAL xmlNode *pcmk__xml_match(const xmlNode *haystack, const xmlNode *needle, bool exact); G_GNUC_INTERNAL void pcmk__xml_update(xmlNode *parent, xmlNode *target, xmlNode *update, bool as_diff); G_GNUC_INTERNAL xmlNode *pcmk__xc_match(const xmlNode *root, const xmlNode *search_comment, bool exact); G_GNUC_INTERNAL void pcmk__xc_update(xmlNode *parent, xmlNode *target, xmlNode *update); G_GNUC_INTERNAL void pcmk__free_acls(GList *acls); G_GNUC_INTERNAL void pcmk__unpack_acl(xmlNode *source, xmlNode *target, const char *user); G_GNUC_INTERNAL bool pcmk__is_user_in_group(const char *user, const char *group); G_GNUC_INTERNAL void pcmk__apply_acl(xmlNode *xml); G_GNUC_INTERNAL void pcmk__apply_creation_acl(xmlNode *xml, bool check_top); G_GNUC_INTERNAL void pcmk__mark_xml_attr_dirty(xmlAttr *a); G_GNUC_INTERNAL bool pcmk__xa_filterable(const char *name); G_GNUC_INTERNAL void pcmk__log_xmllib_err(void *ctx, const char *fmt, ...) G_GNUC_PRINTF(2, 3); G_GNUC_INTERNAL void pcmk__mark_xml_node_dirty(xmlNode *xml); G_GNUC_INTERNAL bool pcmk__marked_as_deleted(xmlAttrPtr a, void *user_data); G_GNUC_INTERNAL void pcmk__dump_xml_attr(const xmlAttr *attr, GString *buffer); /* * Date/times */ // For use with pcmk__add_time_from_xml() enum pcmk__time_component { pcmk__time_unknown, pcmk__time_years, pcmk__time_months, pcmk__time_weeks, pcmk__time_days, pcmk__time_hours, pcmk__time_minutes, pcmk__time_seconds, }; G_GNUC_INTERNAL const char *pcmk__time_component_attr(enum pcmk__time_component component); G_GNUC_INTERNAL int pcmk__add_time_from_xml(crm_time_t *t, enum pcmk__time_component component, const xmlNode *xml); G_GNUC_INTERNAL void pcmk__set_time_if_earlier(crm_time_t *target, const crm_time_t *source); /* * IPC */ #define PCMK__IPC_VERSION 1 #define PCMK__CONTROLD_API_MAJOR "1" #define PCMK__CONTROLD_API_MINOR "0" // IPC behavior that varies by daemon typedef struct pcmk__ipc_methods_s { /*! * \internal * \brief Allocate any private data needed by daemon IPC * * \param[in,out] api IPC API connection * * \return Standard Pacemaker return code */ int (*new_data)(pcmk_ipc_api_t *api); /*! * \internal * \brief Free any private data used by daemon IPC * * \param[in,out] api_data Data allocated by new_data() method */ void (*free_data)(void *api_data); /*! * \internal * \brief Perform daemon-specific handling after successful connection * * Some daemons require clients to register before sending any other * commands. The controller requires a CRM_OP_HELLO (with no reply), and * the CIB manager, executor, and fencer require a CRM_OP_REGISTER (with a * reply). Ideally this would be consistent across all daemons, but for now * this allows each to do its own authorization. * * \param[in,out] api IPC API connection * * \return Standard Pacemaker return code */ int (*post_connect)(pcmk_ipc_api_t *api); /*! * \internal * \brief Check whether an IPC request results in a reply * * \param[in,out] api IPC API connection * \param[in] request IPC request XML * * \return true if request would result in an IPC reply, false otherwise */ bool (*reply_expected)(pcmk_ipc_api_t *api, const xmlNode *request); /*! * \internal * \brief Perform daemon-specific handling of an IPC message * * \param[in,out] api IPC API connection * \param[in,out] msg Message read from IPC connection * * \return true if more IPC reply messages should be expected */ bool (*dispatch)(pcmk_ipc_api_t *api, xmlNode *msg); /*! * \internal * \brief Perform daemon-specific handling of an IPC disconnect * * \param[in,out] api IPC API connection */ void (*post_disconnect)(pcmk_ipc_api_t *api); } pcmk__ipc_methods_t; // Implementation of pcmk_ipc_api_t struct pcmk_ipc_api_s { enum pcmk_ipc_server server; // Daemon this IPC API instance is for enum pcmk_ipc_dispatch dispatch_type; // How replies should be dispatched size_t ipc_size_max; // maximum IPC buffer size crm_ipc_t *ipc; // IPC connection mainloop_io_t *mainloop_io; // If using mainloop, I/O source for IPC bool free_on_disconnect; // Whether disconnect should free object pcmk_ipc_callback_t cb; // Caller-registered callback (if any) void *user_data; // Caller-registered data (if any) void *api_data; // For daemon-specific use pcmk__ipc_methods_t *cmds; // Behavior that varies by daemon }; typedef struct pcmk__ipc_header_s { struct qb_ipc_response_header qb; uint32_t size_uncompressed; uint32_t size_compressed; uint32_t flags; uint8_t version; } pcmk__ipc_header_t; G_GNUC_INTERNAL int pcmk__send_ipc_request(pcmk_ipc_api_t *api, const xmlNode *request); G_GNUC_INTERNAL void pcmk__call_ipc_callback(pcmk_ipc_api_t *api, enum pcmk_ipc_event event_type, crm_exit_t status, void *event_data); G_GNUC_INTERNAL unsigned int pcmk__ipc_buffer_size(unsigned int max); G_GNUC_INTERNAL bool pcmk__valid_ipc_header(const pcmk__ipc_header_t *header); G_GNUC_INTERNAL pcmk__ipc_methods_t *pcmk__attrd_api_methods(void); G_GNUC_INTERNAL pcmk__ipc_methods_t *pcmk__controld_api_methods(void); G_GNUC_INTERNAL pcmk__ipc_methods_t *pcmk__pacemakerd_api_methods(void); G_GNUC_INTERNAL pcmk__ipc_methods_t *pcmk__schedulerd_api_methods(void); /* * Logging */ //! XML is newly created #define PCMK__XML_PREFIX_CREATED "++" //! XML has been deleted #define PCMK__XML_PREFIX_DELETED "--" //! XML has been modified #define PCMK__XML_PREFIX_MODIFIED "+ " //! XML has been moved #define PCMK__XML_PREFIX_MOVED "+~" /* * Output */ G_GNUC_INTERNAL int pcmk__bare_output_new(pcmk__output_t **out, const char *fmt_name, const char *filename, char **argv); G_GNUC_INTERNAL void pcmk__register_option_messages(pcmk__output_t *out); G_GNUC_INTERNAL void pcmk__register_patchset_messages(pcmk__output_t *out); G_GNUC_INTERNAL bool pcmk__output_text_get_fancy(pcmk__output_t *out); /* * Rules */ G_GNUC_INTERNAL int pcmk__unpack_duration(const xmlNode *duration, const crm_time_t *start, crm_time_t **end); G_GNUC_INTERNAL int pcmk__evaluate_date_spec(const xmlNode *date_spec, const crm_time_t *now); /* * Utils */ #define PCMK__PW_BUFFER_LEN 500 /* * Schemas */ typedef struct { unsigned char v[2]; } pcmk__schema_version_t; enum pcmk__schema_validator { pcmk__schema_validator_none, pcmk__schema_validator_rng }; typedef struct { char *name; char *transform; void *cache; enum pcmk__schema_validator validator; pcmk__schema_version_t version; char *transform_enter; bool transform_onleave; } pcmk__schema_t; G_GNUC_INTERNAL int pcmk__find_x_0_schema_index(GList *schemas); #endif // CRMCOMMON_PRIVATE__H diff --git a/lib/common/digest.c b/lib/common/digest.c index 8ece6e80a9..933769fde3 100644 --- a/lib/common/digest.c +++ b/lib/common/digest.c @@ -1,336 +1,336 @@ /* * Copyright 2015-2024 the Pacemaker project contributors * * The version control history for this file may have further details. * * This source code is licensed under the GNU Lesser General Public License * version 2.1 or later (LGPLv2.1+) WITHOUT ANY WARRANTY. */ #include #include #include #include #include #include #include #include #include "crmcommon_private.h" #define BEST_EFFORT_STATUS 0 /*! * \internal * \brief Dump XML in a format used with v1 digests * * \param[in] xml Root of XML to dump * * \return Newly allocated buffer containing dumped XML */ static GString * dump_xml_for_digest(xmlNodePtr xml) { GString *buffer = g_string_sized_new(1024); /* for compatibility with the old result which is used for v1 digests */ g_string_append_c(buffer, ' '); - pcmk__xml2text(xml, 0, buffer, 0); + pcmk__xml_string(xml, 0, buffer, 0); g_string_append_c(buffer, '\n'); return buffer; } /*! * \brief Calculate and return v1 digest of XML tree * * \param[in] input Root of XML to digest * \param[in] sort Whether to sort the XML before calculating digest * \param[in] ignored Not used * * \return Newly allocated string containing digest * \note Example return value: "c048eae664dba840e1d2060f00299e9d" */ static char * calculate_xml_digest_v1(xmlNode *input, gboolean sort, gboolean ignored) { char *digest = NULL; GString *buffer = NULL; xmlNode *copy = NULL; if (sort) { crm_trace("Sorting xml..."); copy = sorted_xml(input, NULL, TRUE); crm_trace("Done"); input = copy; } buffer = dump_xml_for_digest(input); CRM_CHECK(buffer->len > 0, free_xml(copy); g_string_free(buffer, TRUE); return NULL); digest = crm_md5sum((const char *) buffer->str); crm_log_xml_trace(input, "digest:source"); g_string_free(buffer, TRUE); free_xml(copy); return digest; } /*! * \brief Calculate and return v2 digest of XML tree * * \param[in] source Root of XML to digest * \param[in] do_filter Whether to filter certain XML attributes * * \return Newly allocated string containing digest */ static char * calculate_xml_digest_v2(const xmlNode *source, gboolean do_filter) { char *digest = NULL; gchar *buf = NULL; crm_trace("Begin digest %s", do_filter?"filtered":""); buf = pcmk__xml_dump(source, (do_filter? pcmk__xml_fmt_filtered : 0)); digest = crm_md5sum(buf); pcmk__if_tracing( { char *trace_file = crm_strdup_printf("%s/digest-%s", pcmk__get_tmpdir(), digest); crm_trace("Saving %s.%s.%s to %s", crm_element_value(source, PCMK_XA_ADMIN_EPOCH), crm_element_value(source, PCMK_XA_EPOCH), crm_element_value(source, PCMK_XA_NUM_UPDATES), trace_file); save_xml_to_file(source, "digest input", trace_file); free(trace_file); }, {} ); crm_trace("End digest"); g_free(buf); return digest; } /*! * \brief Calculate and return digest of XML tree, suitable for storing on disk * * \param[in] input Root of XML to digest * * \return Newly allocated string containing digest */ char * calculate_on_disk_digest(xmlNode *input) { /* Always use the v1 format for on-disk digests * a) it's a compatibility nightmare * b) we only use this once at startup, all other * invocations are in a separate child process */ return calculate_xml_digest_v1(input, FALSE, FALSE); } /*! * \brief Calculate and return digest of XML operation * * \param[in] input Root of XML to digest * \param[in] version Unused * * \return Newly allocated string containing digest */ char * calculate_operation_digest(xmlNode *input, const char *version) { /* We still need the sorting for operation digests */ return calculate_xml_digest_v1(input, TRUE, FALSE); } /*! * \brief Calculate and return digest of XML tree * * \param[in] input Root of XML to digest * \param[in] sort Whether to sort XML before calculating digest * \param[in] do_filter Whether to filter certain XML attributes * \param[in] version CRM feature set version (used to select v1/v2 digest) * * \return Newly allocated string containing digest */ char * calculate_xml_versioned_digest(xmlNode *input, gboolean sort, gboolean do_filter, const char *version) { /* * @COMPAT digests (on-disk or in diffs/patchsets) created <1.1.4; * removing this affects even full-restart upgrades from old versions * * The sorting associated with v1 digest creation accounted for 23% of * the CIB manager's CPU usage on the server. v2 drops this. * * The filtering accounts for an additional 2.5% and we may want to * remove it in future. * * v2 also uses the xmlBuffer contents directly to avoid additional copying */ if (version == NULL || compare_version("3.0.5", version) > 0) { crm_trace("Using v1 digest algorithm for %s", pcmk__s(version, "unknown feature set")); return calculate_xml_digest_v1(input, sort, do_filter); } crm_trace("Using v2 digest algorithm for %s", pcmk__s(version, "unknown feature set")); return calculate_xml_digest_v2(input, do_filter); } /*! * \internal * \brief Check whether calculated digest of given XML matches expected digest * * \param[in] input Root of XML tree to digest * \param[in] expected Expected digest in on-disk format * * \return true if digests match, false on mismatch or error */ bool pcmk__verify_digest(xmlNode *input, const char *expected) { char *calculated = NULL; bool passed; if (input != NULL) { calculated = calculate_on_disk_digest(input); if (calculated == NULL) { crm_perror(LOG_ERR, "Could not calculate digest for comparison"); return false; } } passed = pcmk__str_eq(expected, calculated, pcmk__str_casei); if (passed) { crm_trace("Digest comparison passed: %s", calculated); } else { crm_err("Digest comparison failed: expected %s, calculated %s", expected, calculated); } free(calculated); return passed; } /*! * \internal * \brief Check whether an XML attribute should be excluded from CIB digests * * \param[in] name XML attribute name * * \return true if XML attribute should be excluded from CIB digest calculation */ bool pcmk__xa_filterable(const char *name) { static const char *filter[] = { PCMK_XA_CRM_DEBUG_ORIGIN, PCMK_XA_CIB_LAST_WRITTEN, PCMK_XA_UPDATE_ORIGIN, PCMK_XA_UPDATE_CLIENT, PCMK_XA_UPDATE_USER, }; for (int i = 0; i < PCMK__NELEM(filter); i++) { if (strcmp(name, filter[i]) == 0) { return true; } } return false; } char * crm_md5sum(const char *buffer) { int lpc = 0, len = 0; char *digest = NULL; unsigned char raw_digest[MD5_DIGEST_SIZE]; if (buffer == NULL) { buffer = ""; } len = strlen(buffer); crm_trace("Beginning digest of %d bytes", len); digest = malloc(2 * MD5_DIGEST_SIZE + 1); if (digest) { md5_buffer(buffer, len, raw_digest); for (lpc = 0; lpc < MD5_DIGEST_SIZE; lpc++) { sprintf(digest + (2 * lpc), "%02x", raw_digest[lpc]); } digest[(2 * MD5_DIGEST_SIZE)] = 0; crm_trace("Digest %s.", digest); } else { crm_err("Could not create digest"); } return digest; } // Return true if a is an attribute that should be filtered static bool should_filter_for_digest(xmlAttrPtr a, void *user_data) { if (strncmp((const char *) a->name, CRM_META "_", sizeof(CRM_META " ") - 1) == 0) { return true; } return pcmk__str_any_of((const char *) a->name, PCMK_XA_ID, PCMK_XA_CRM_FEATURE_SET, PCMK__XA_OP_DIGEST, PCMK__META_ON_NODE, PCMK__META_ON_NODE_UUID, "pcmk_external_ip", NULL); } /*! * \internal * \brief Remove XML attributes not needed for operation digest * * \param[in,out] param_set XML with operation parameters */ void pcmk__filter_op_for_digest(xmlNode *param_set) { char *key = NULL; char *timeout = NULL; guint interval_ms = 0; if (param_set == NULL) { return; } /* Timeout is useful for recurring operation digests, so grab it before * removing meta-attributes */ key = crm_meta_name(PCMK_META_INTERVAL); if (crm_element_value_ms(param_set, key, &interval_ms) != pcmk_ok) { interval_ms = 0; } free(key); key = NULL; if (interval_ms != 0) { key = crm_meta_name(PCMK_META_TIMEOUT); timeout = crm_element_value_copy(param_set, key); } // Remove all CRM_meta_* attributes and certain other attributes pcmk__xe_remove_matching_attrs(param_set, should_filter_for_digest, NULL); // Add timeout back for recurring operation digests if (timeout != NULL) { crm_xml_add(param_set, key, timeout); } free(timeout); free(key); } diff --git a/lib/common/xml_io.c b/lib/common/xml_io.c index 83044d2602..019d1f5a51 100644 --- a/lib/common/xml_io.c +++ b/lib/common/xml_io.c @@ -1,854 +1,854 @@ /* * Copyright 2004-2024 the Pacemaker project contributors * * The version control history for this file may have further details. * * This source code is licensed under the GNU Lesser General Public License * version 2.1 or later (LGPLv2.1+) WITHOUT ANY WARRANTY. */ #include #include #include #include #include #include #include #include #include // xmlOutputBuffer* #include #include #include #include "crmcommon_private.h" /* @COMPAT XML_PARSE_RECOVER allows some XML errors to be silently worked around * by libxml2, which is potentially ambiguous and dangerous. We should drop it * when we can break backward compatibility with configurations that might be * relying on it (i.e. pacemaker 3.0.0). */ #define PCMK__XML_PARSE_OPTS_WITHOUT_RECOVER (XML_PARSE_NOBLANKS) #define PCMK__XML_PARSE_OPTS_WITH_RECOVER (XML_PARSE_NOBLANKS \ |XML_PARSE_RECOVER) /*! * \internal * \brief Read from \c stdin until EOF or error * * \return Newly allocated string containing the bytes read from \c stdin, or * \c NULL on error * * \note The caller is responsible for freeing the return value using \c free(). */ static char * read_stdin(void) { char *buf = NULL; size_t length = 0; do { buf = pcmk__realloc(buf, length + PCMK__BUFFER_SIZE + 1); length += fread(buf + length, 1, PCMK__BUFFER_SIZE, stdin); } while ((feof(stdin) == 0) && (ferror(stdin) == 0)); if (ferror(stdin) != 0) { crm_err("Error reading input from stdin"); free(buf); buf = NULL; } else { buf[length] = '\0'; } clearerr(stdin); return buf; } /*! * \internal * \brief Decompress a bzip2-compressed file into a string buffer * * \param[in] filename Name of file to decompress * * \return Newly allocated string with the decompressed contents of \p filename, * or \c NULL on error. * * \note The caller is responsible for freeing the return value using \c free(). */ static char * decompress_file(const char *filename) { char *buffer = NULL; int rc = pcmk_rc_ok; size_t length = 0; BZFILE *bz_file = NULL; FILE *input = fopen(filename, "r"); if (input == NULL) { crm_perror(LOG_ERR, "Could not open %s for reading", filename); return NULL; } bz_file = BZ2_bzReadOpen(&rc, input, 0, 0, NULL, 0); rc = pcmk__bzlib2rc(rc); if (rc != pcmk_rc_ok) { crm_err("Could not prepare to read compressed %s: %s " CRM_XS " rc=%d", filename, pcmk_rc_str(rc), rc); goto done; } // cppcheck seems not to understand the abort-logic in pcmk__realloc // cppcheck-suppress memleak do { int read_len = 0; buffer = pcmk__realloc(buffer, length + PCMK__BUFFER_SIZE + 1); read_len = BZ2_bzRead(&rc, bz_file, buffer + length, PCMK__BUFFER_SIZE); if ((rc == BZ_OK) || (rc == BZ_STREAM_END)) { crm_trace("Read %ld bytes from file: %d", (long) read_len, rc); length += read_len; } } while (rc == BZ_OK); rc = pcmk__bzlib2rc(rc); if (rc != pcmk_rc_ok) { rc = pcmk__bzlib2rc(rc); crm_err("Could not read compressed %s: %s " CRM_XS " rc=%d", filename, pcmk_rc_str(rc), rc); free(buffer); buffer = NULL; } else { buffer[length] = '\0'; } done: BZ2_bzReadClose(&rc, bz_file); fclose(input); return buffer; } // @COMPAT Remove macro at 3.0.0 when we drop XML_PARSE_RECOVER /*! * \internal * \brief Try to parse XML first without and then with recovery enabled * * \param[out] result Where to store the resulting XML doc (xmlDoc **) * \param[in] fn XML parser function * \param[in] ... All arguments for \p fn except the final one (an * \c xmlParserOption group) */ #define parse_xml_recover(result, fn, ...) do { \ *result = fn(__VA_ARGS__, PCMK__XML_PARSE_OPTS_WITHOUT_RECOVER); \ if (*result == NULL) { \ *result = fn(__VA_ARGS__, PCMK__XML_PARSE_OPTS_WITH_RECOVER); \ \ if (*result != NULL) { \ crm_warn("Successfully recovered from XML errors " \ "(note: a future release will treat this as a " \ "fatal failure)"); \ } \ } \ } while (0); /*! * \internal * \brief Parse XML from a file * * \param[in] filename Name of file containing XML (\c NULL or \c "-" for * \c stdin); if \p filename ends in \c ".bz2", the file * will be decompressed using \c bzip2 * * \return XML tree parsed from the given file; may be \c NULL or only partial * on error */ xmlNode * pcmk__xml_read(const char *filename) { bool use_stdin = pcmk__str_eq(filename, "-", pcmk__str_null_matches); xmlNode *xml = NULL; xmlDoc *output = NULL; xmlParserCtxt *ctxt = NULL; const xmlError *last_error = NULL; // Create a parser context ctxt = xmlNewParserCtxt(); CRM_CHECK(ctxt != NULL, return NULL); xmlCtxtResetLastError(ctxt); xmlSetGenericErrorFunc(ctxt, pcmk__log_xmllib_err); if (use_stdin) { /* @COMPAT After dropping XML_PARSE_RECOVER, we can avoid capturing * stdin into a buffer and instead call * xmlCtxtReadFd(ctxt, STDIN_FILENO, NULL, NULL, XML_PARSE_NOBLANKS); * * For now we have to save the input so that we can use it twice. */ char *input = read_stdin(); if (input != NULL) { parse_xml_recover(&output, xmlCtxtReadDoc, ctxt, (pcmkXmlStr) input, NULL, NULL); free(input); } } else if (pcmk__ends_with_ext(filename, ".bz2")) { char *input = decompress_file(filename); if (input != NULL) { parse_xml_recover(&output, xmlCtxtReadDoc, ctxt, (pcmkXmlStr) input, NULL, NULL); free(input); } } else { parse_xml_recover(&output, xmlCtxtReadFile, ctxt, filename, NULL); } if (output != NULL) { xml = xmlDocGetRootElement(output); if (xml != NULL) { /* @TODO Should we really be stripping out text? This seems like an * overly broad way to get rid of whitespace, if that's the goal. * Text nodes may be invalid in most or all Pacemaker inputs, but * stripping them in a generic "parse XML from file" function may * not be the best way to ignore them. */ pcmk__strip_xml_text(xml); } } // @COMPAT At 3.0.0, free xml and return NULL if xml != NULL on error last_error = xmlCtxtGetLastError(ctxt); if (last_error != NULL) { if (xml != NULL) { crm_log_xml_info(xml, "Partial"); } } xmlFreeParserCtxt(ctxt); return xml; } /*! * \internal * \brief Parse XML from a string * * \param[in] input String to parse * * \return XML tree parsed from the given string; may be \c NULL or only partial * on error */ xmlNode * pcmk__xml_parse(const char *input) { xmlNode *xml = NULL; xmlDoc *output = NULL; xmlParserCtxt *ctxt = NULL; const xmlError *last_error = NULL; if (input == NULL) { return NULL; } ctxt = xmlNewParserCtxt(); if (ctxt == NULL) { return NULL; } xmlCtxtResetLastError(ctxt); xmlSetGenericErrorFunc(ctxt, pcmk__log_xmllib_err); parse_xml_recover(&output, xmlCtxtReadDoc, ctxt, (pcmkXmlStr) input, NULL, NULL); if (output != NULL) { xml = xmlDocGetRootElement(output); } // @COMPAT At 3.0.0, free xml and return NULL if xml != NULL; update doxygen last_error = xmlCtxtGetLastError(ctxt); if (last_error != NULL) { if (xml != NULL) { crm_log_xml_info(xml, "Partial"); } } xmlFreeParserCtxt(ctxt); return xml; } /*! * \internal * \brief Append a string representation of an XML element to a buffer * * \param[in] data XML whose representation to append * \param[in] options Group of \p pcmk__xml_fmt_options flags * \param[in,out] buffer Where to append the content (must not be \p NULL) * \param[in] depth Current indentation level */ static void dump_xml_element(const xmlNode *data, uint32_t options, GString *buffer, int depth) { bool pretty = pcmk_is_set(options, pcmk__xml_fmt_pretty); bool filtered = pcmk_is_set(options, pcmk__xml_fmt_filtered); int spaces = pretty? (2 * depth) : 0; for (int lpc = 0; lpc < spaces; lpc++) { g_string_append_c(buffer, ' '); } pcmk__g_strcat(buffer, "<", data->name, NULL); for (const xmlAttr *attr = pcmk__xe_first_attr(data); attr != NULL; attr = attr->next) { if (!filtered || !pcmk__xa_filterable((const char *) (attr->name))) { pcmk__dump_xml_attr(attr, buffer); } } if (data->children == NULL) { g_string_append(buffer, "/>"); } else { g_string_append_c(buffer, '>'); } if (pretty) { g_string_append_c(buffer, '\n'); } if (data->children) { for (const xmlNode *child = data->children; child != NULL; child = child->next) { - pcmk__xml2text(child, options, buffer, depth + 1); + pcmk__xml_string(child, options, buffer, depth + 1); } for (int lpc = 0; lpc < spaces; lpc++) { g_string_append_c(buffer, ' '); } pcmk__g_strcat(buffer, "name, ">", NULL); if (pretty) { g_string_append_c(buffer, '\n'); } } } /*! * \internal * \brief Append XML text content to a buffer * * \param[in] data XML whose content to append * \param[in] options Group of \p xml_log_options flags * \param[in,out] buffer Where to append the content (must not be \p NULL) * \param[in] depth Current indentation level */ static void dump_xml_text(const xmlNode *data, uint32_t options, GString *buffer, int depth) { bool pretty = pcmk_is_set(options, pcmk__xml_fmt_pretty); int spaces = pretty? (2 * depth) : 0; const char *content = (const char *) data->content; char *content_esc = NULL; if (pcmk__xml_needs_escape(content, false)) { content_esc = pcmk__xml_escape(content, false); content = content_esc; } for (int lpc = 0; lpc < spaces; lpc++) { g_string_append_c(buffer, ' '); } g_string_append(buffer, content); if (pretty) { g_string_append_c(buffer, '\n'); } free(content_esc); } /*! * \internal * \brief Append XML CDATA content to a buffer * * \param[in] data XML whose content to append * \param[in] options Group of \p pcmk__xml_fmt_options flags * \param[in,out] buffer Where to append the content (must not be \p NULL) * \param[in] depth Current indentation level */ static void dump_xml_cdata(const xmlNode *data, uint32_t options, GString *buffer, int depth) { bool pretty = pcmk_is_set(options, pcmk__xml_fmt_pretty); int spaces = pretty? (2 * depth) : 0; for (int lpc = 0; lpc < spaces; lpc++) { g_string_append_c(buffer, ' '); } pcmk__g_strcat(buffer, "content, "]]>", NULL); if (pretty) { g_string_append_c(buffer, '\n'); } } /*! * \internal * \brief Append an XML comment to a buffer * * \param[in] data XML whose content to append * \param[in] options Group of \p pcmk__xml_fmt_options flags * \param[in,out] buffer Where to append the content (must not be \p NULL) * \param[in] depth Current indentation level */ static void dump_xml_comment(const xmlNode *data, uint32_t options, GString *buffer, int depth) { bool pretty = pcmk_is_set(options, pcmk__xml_fmt_pretty); int spaces = pretty? (2 * depth) : 0; for (int lpc = 0; lpc < spaces; lpc++) { g_string_append_c(buffer, ' '); } pcmk__g_strcat(buffer, "", NULL); if (pretty) { g_string_append_c(buffer, '\n'); } } /*! * \internal * \brief Get a string representation of an XML element type * * \param[in] type XML element type * * \return String representation of \p type */ static const char * xml_element_type2str(xmlElementType type) { static const char *const element_type_names[] = { [XML_ELEMENT_NODE] = "element", [XML_ATTRIBUTE_NODE] = "attribute", [XML_TEXT_NODE] = "text", [XML_CDATA_SECTION_NODE] = "CDATA section", [XML_ENTITY_REF_NODE] = "entity reference", [XML_ENTITY_NODE] = "entity", [XML_PI_NODE] = "PI", [XML_COMMENT_NODE] = "comment", [XML_DOCUMENT_NODE] = "document", [XML_DOCUMENT_TYPE_NODE] = "document type", [XML_DOCUMENT_FRAG_NODE] = "document fragment", [XML_NOTATION_NODE] = "notation", [XML_HTML_DOCUMENT_NODE] = "HTML document", [XML_DTD_NODE] = "DTD", [XML_ELEMENT_DECL] = "element declaration", [XML_ATTRIBUTE_DECL] = "attribute declaration", [XML_ENTITY_DECL] = "entity declaration", [XML_NAMESPACE_DECL] = "namespace declaration", [XML_XINCLUDE_START] = "XInclude start", [XML_XINCLUDE_END] = "XInclude end", }; if ((type < 0) || (type >= PCMK__NELEM(element_type_names))) { return "unrecognized type"; } return element_type_names[type]; } /*! * \internal - * \brief Create a text representation of an XML object + * \brief Create a string representation of an XML object * * \param[in] data XML to convert * \param[in] options Group of \p pcmk__xml_fmt_options flags * \param[in,out] buffer Where to store the text (must not be \p NULL) * \param[in] depth Current indentation level */ void -pcmk__xml2text(const xmlNode *data, uint32_t options, GString *buffer, - int depth) +pcmk__xml_string(const xmlNode *data, uint32_t options, GString *buffer, + int depth) { if (data == NULL) { crm_trace("Nothing to dump"); return; } CRM_ASSERT(buffer != NULL); CRM_CHECK(depth >= 0, depth = 0); switch(data->type) { case XML_ELEMENT_NODE: /* Handle below */ dump_xml_element(data, options, buffer, depth); break; case XML_TEXT_NODE: if (pcmk_is_set(options, pcmk__xml_fmt_text)) { dump_xml_text(data, options, buffer, depth); } break; case XML_COMMENT_NODE: dump_xml_comment(data, options, buffer, depth); break; case XML_CDATA_SECTION_NODE: dump_xml_cdata(data, options, buffer, depth); break; default: crm_warn("Cannot convert XML %s node to text " CRM_XS " type=%d", xml_element_type2str(data->type), data->type); break; } } /*! * \internal * \brief Dump an XML tree to a string * * \param[in] xml XML tree to dump * \param[in] flags Group of enum pcmk__xml_fmt_options flags * * \return Newly allocated string representation of \p xml * * \note The caller is responsible for freeing the return value using * \c g_free(). */ gchar * pcmk__xml_dump(const xmlNode *xml, uint32_t flags) { /* libxml2's xmlNodeDumpOutput() doesn't allow filtering, doesn't escape * special characters thoroughly, and doesn't allow a const argument. * * @COMPAT Can we start including text nodes unconditionally? */ GString *g_buffer = g_string_sized_new(1024); - pcmk__xml2text(xml, flags, g_buffer, 0); + pcmk__xml_string(xml, flags, g_buffer, 0); return g_string_free(g_buffer, FALSE); } /*! * \internal * \brief Write a string to a file stream, compressed using \c bzip2 * * \param[in] text String to write * \param[in] filename Name of file being written (for logging only) * \param[in,out] stream Open file stream to write to * \param[out] bytes_out Number of bytes written (valid only on success) * * \return Standard Pacemaker return code */ static int write_compressed_stream(char *text, const char *filename, FILE *stream, unsigned int *bytes_out) { unsigned int bytes_in = 0; int rc = pcmk_rc_ok; // (5, 0, 0): (intermediate block size, silent, default workFactor) BZFILE *bz_file = BZ2_bzWriteOpen(&rc, stream, 5, 0, 0); rc = pcmk__bzlib2rc(rc); if (rc != pcmk_rc_ok) { crm_warn("Not compressing %s: could not prepare file stream: %s " CRM_XS " rc=%d", filename, pcmk_rc_str(rc), rc); goto done; } BZ2_bzWrite(&rc, bz_file, text, strlen(text)); rc = pcmk__bzlib2rc(rc); if (rc != pcmk_rc_ok) { crm_warn("Not compressing %s: could not compress data: %s " CRM_XS " rc=%d errno=%d", filename, pcmk_rc_str(rc), rc, errno); goto done; } BZ2_bzWriteClose(&rc, bz_file, 0, &bytes_in, bytes_out); bz_file = NULL; rc = pcmk__bzlib2rc(rc); if (rc != pcmk_rc_ok) { crm_warn("Not compressing %s: could not write compressed data: %s " CRM_XS " rc=%d errno=%d", filename, pcmk_rc_str(rc), rc, errno); goto done; } crm_trace("Compressed XML for %s from %u bytes to %u", filename, bytes_in, *bytes_out); done: if (bz_file != NULL) { BZ2_bzWriteClose(&rc, bz_file, 0, NULL, NULL); } return rc; } /*! * \internal * \brief Write XML to a file stream * * \param[in] xml XML to write * \param[in] filename Name of file being written (for logging only) * \param[in,out] stream Open file stream corresponding to filename (closed * when this function returns) * \param[in] compress Whether to compress XML before writing * \param[out] nbytes Number of bytes written * * \return Standard Pacemaker return code */ static int write_xml_stream(const xmlNode *xml, const char *filename, FILE *stream, bool compress, unsigned int *nbytes) { // @COMPAT Drop nbytes as arg when we drop write_xml_fd()/write_xml_file() gchar *buffer = NULL; unsigned int bytes_out = 0; int rc = pcmk_rc_ok; buffer = pcmk__xml_dump(xml, pcmk__xml_fmt_pretty); CRM_CHECK(!pcmk__str_empty(buffer), crm_log_xml_info(xml, "dump-failed"); rc = pcmk_rc_error; goto done); crm_log_xml_trace(xml, "writing"); if (compress && (write_compressed_stream(buffer, filename, stream, &bytes_out) == pcmk_rc_ok)) { goto done; } rc = fprintf(stream, "%s", buffer); if (rc < 0) { rc = EIO; crm_perror(LOG_ERR, "writing %s", filename); goto done; } bytes_out = (unsigned int) rc; rc = pcmk_rc_ok; done: if (fflush(stream) != 0) { rc = errno; crm_perror(LOG_ERR, "flushing %s", filename); } // Don't report error if the file does not support synchronization if ((fsync(fileno(stream)) < 0) && (errno != EROFS) && (errno != EINVAL)) { rc = errno; crm_perror(LOG_ERR, "synchronizing %s", filename); } fclose(stream); crm_trace("Saved %u bytes to %s as XML", bytes_out, filename); if (nbytes != NULL) { *nbytes = bytes_out; } g_free(buffer); return rc; } /*! * \internal * \brief Write XML to a file descriptor * * \param[in] xml XML to write * \param[in] filename Name of file being written (for logging only) * \param[in] fd Open file descriptor corresponding to \p filename * \param[in] compress If \c true, compress XML before writing * \param[out] nbytes Number of bytes written (can be \c NULL) * * \return Standard Pacemaker return code */ int pcmk__xml_write_fd(const xmlNode *xml, const char *filename, int fd, bool compress, unsigned int *nbytes) { // @COMPAT Drop compress and nbytes arguments when we drop write_xml_fd() FILE *stream = NULL; CRM_CHECK((xml != NULL) && (fd > 0), return EINVAL); stream = fdopen(fd, "w"); if (stream == NULL) { return errno; } return write_xml_stream(xml, pcmk__s(filename, "unnamed file"), stream, compress, nbytes); } /*! * \internal * \brief Write XML to a file * * \param[in] xml XML to write * \param[in] filename Name of file to write * \param[in] compress If \c true, compress XML before writing * \param[out] nbytes Number of bytes written (can be \c NULL) * * \return Standard Pacemaker return code */ int pcmk__xml_write_file(const xmlNode *xml, const char *filename, bool compress, unsigned int *nbytes) { // @COMPAT Drop nbytes argument when we drop write_xml_fd() FILE *stream = NULL; CRM_CHECK((xml != NULL) && (filename != NULL), return EINVAL); stream = fopen(filename, "w"); if (stream == NULL) { return errno; } return write_xml_stream(xml, filename, stream, compress, nbytes); } /*! * \internal * \brief Serialize XML (using libxml) into provided descriptor * * \param[in] fd File descriptor to (piece-wise) write to * \param[in] cur XML subtree to proceed * * \return a standard Pacemaker return code */ int pcmk__xml2fd(int fd, xmlNode *cur) { bool success; xmlOutputBuffer *fd_out = xmlOutputBufferCreateFd(fd, NULL); CRM_ASSERT(fd_out != NULL); xmlNodeDumpOutput(fd_out, cur->doc, cur, 0, pcmk__xml_fmt_pretty, NULL); success = xmlOutputBufferWrite(fd_out, sizeof("\n") - 1, "\n") != -1; success = xmlOutputBufferClose(fd_out) != -1 && success; if (!success) { return EIO; } fsync(fd); return pcmk_rc_ok; } void save_xml_to_file(const xmlNode *xml, const char *desc, const char *filename) { char *f = NULL; if (filename == NULL) { char *uuid = crm_generate_uuid(); f = crm_strdup_printf("%s/%s", pcmk__get_tmpdir(), uuid); filename = f; free(uuid); } crm_info("Saving %s to %s", desc, filename); pcmk__xml_write_file(xml, filename, false, NULL); free(f); } // Deprecated functions kept only for backward API compatibility // LCOV_EXCL_START #include xmlNode * filename2xml(const char *filename) { return pcmk__xml_read(filename); } xmlNode * stdin2xml(void) { return pcmk__xml_read(NULL); } xmlNode * string2xml(const char *input) { return pcmk__xml_parse(input); } char * dump_xml_formatted(const xmlNode *xml) { char *str = NULL; gchar *g_str = pcmk__xml_dump(xml, pcmk__xml_fmt_pretty); pcmk__str_update(&str, g_str); g_free(g_str); return str; } char * dump_xml_formatted_with_text(const xmlNode *xml) { char *str = NULL; gchar *g_str = pcmk__xml_dump(xml, pcmk__xml_fmt_pretty|pcmk__xml_fmt_text); pcmk__str_update(&str, g_str); g_free(g_str); return str; } char * dump_xml_unformatted(const xmlNode *xml) { char *str = NULL; gchar *g_str = pcmk__xml_dump(xml, 0); pcmk__str_update(&str, g_str); g_free(g_str); return str; } int write_xml_fd(const xmlNode *xml, const char *filename, int fd, gboolean compress) { unsigned int nbytes = 0; int rc = pcmk__xml_write_fd(xml, filename, fd, compress, &nbytes); if (rc != pcmk_rc_ok) { return pcmk_rc2legacy(rc); } return (int) nbytes; } int write_xml_file(const xmlNode *xml, const char *filename, gboolean compress) { unsigned int nbytes = 0; int rc = pcmk__xml_write_file(xml, filename, compress, &nbytes); if (rc != pcmk_rc_ok) { return pcmk_rc2legacy(rc); } return (int) nbytes; } // LCOV_EXCL_STOP // End deprecated API