libxml2 get validation errors - c++

I am using libxml2 to validate an xml file against an xsd schema.
Using xmlSchemaSetParserErrors function, errors are output to stderr.
I need to get these validation errors, store them in memory and display to the user.
How can I redirect these errors ? Could you provide me some examples ?
Thanks,
Andrea

This example uses the validation callback mechanism of the parser module. The signature of callbacks expected by xmlSchemaSetParserErrors seems to be the same.
#include <iostream>
#include <cstdarg>
#include <cstdio>
#include <vector>
#include <string>
#include <iterator>
#include <libxml/parser.h>
#include <libxml/tree.h>
struct ParserContext
{
ParserContext() : context(xmlNewParserCtxt()) {}
~ParserContext() { xmlFreeParserCtxt(context); }
xmlParserCtxtPtr context;
private:
ParserContext(ParserContext&);
void operator=(ParserContext&);
};
struct ErrorHandler
{
std::vector<std::string> errors;
void RegisterErrorHandling(xmlValidCtxt& validationContext)
{
// Change this to register for schema errors...
validationContext.userData = this;
validationContext.error = &ErrorHandler::Handle;
}
private:
static void Handle(void *handler, const char *format, ...)
{
va_list arguments;
va_start(arguments, format);
std::string message = MakeMessage(format, arguments);
va_end(arguments);
ErrorHandler* errorHandler = static_cast<ErrorHandler*>(handler);
errorHandler->errors.push_back(message);
}
static std::string MakeMessage(const char* format, va_list arguments)
{
const size_t bufferSize = 200;
std::vector<char> buffer(bufferSize, 0);
size_t charactersWritten =
vsnprintf(&buffer.front(), bufferSize, format, arguments);
if (charactersWritten == -1)
buffer.back() = 0; // Message truncated!
return std::string(&buffer.front());
}
};
struct XmlDocument
{
static XmlDocument FromFile(const char* fileName)
{
ParserContext parser;
ErrorHandler errorHandler;
errorHandler.RegisterErrorHandling(parser.context->vctxt);
XmlDocument document(xmlCtxtReadFile(
parser.context, fileName, NULL, XML_PARSE_DTDVALID));
document.errors = move(errorHandler.errors);
return document;
}
XmlDocument(XmlDocument&& other) :
xmlPointer(other.xmlPointer),
errors(move(other.errors))
{
other.xmlPointer = nullptr;
}
~XmlDocument()
{
xmlFreeDoc(xmlPointer);
}
xmlDocPtr xmlPointer;
std::vector<std::string> errors;
private:
XmlDocument(xmlDocPtr pointer) : xmlPointer(pointer) {}
XmlDocument(XmlDocument&);
void operator=(XmlDocument&);
};
void DisplayErrorsToUser(
const XmlDocument& document,
std::ostream& displayStream = std::cout)
{
using namespace std;
copy(begin(document.errors), end(document.errors),
ostream_iterator<string>(displayStream, "\n"));
}
int main()
{
auto xml = XmlDocument::FromFile("test.xml");
DisplayErrorsToUser(xml);
}

Or even more concise:
void err(void *ctx, const char *msg, ...)
{
va_list args;
va_start(args, msg);
char *val = va_arg(args,char*);
va_end(args);
}
val now contains validation errors

As said in the API documentation, xmlSchemaSetParserErrors() Set the callback functions used to handle errors for a validation context.
You need to write two callback functions with respect to defined signature :
xmlSchemaValidityErrorFunc err
xmlSchemaValidityWarningFunc warn
An example could be :
void err(void *ctx, const char *msg, ...)
{
char buf[1024];
va_list args;
va_start(args, msg);
int len = vsnprintf_s(buf, sizeof(buf), sizeof(buf)/sizeof(buf[0]), msg, args);
va_end(args);
if(len==0) // Can't create schema validity error!
else // Do something to store `buf`,
// you may need to use void *ctx to achieve this
return;
}
Then just call
xmlSchemaSetValidErrors(valid_ctxt_ptr, (xmlSchemaValidityErrorFunc) err, (xmlSchemaValidityWarningFunc) warn, ctx);
before calling
xmlSchemaValidateDoc()

Related

Mosquitto: Use non-static callback function

I've running Mosquitto on my RPI4. But right know I only can set static callback functions. Is there a way to use class members?
I've tried to use std::bind to pass a class member function as callback:
main.cpp
#include <stdio.h>
#include <mosquitto.h>
#include "mqtt.h"
#include <string>
int main(int argc, char **argv)
{
MqttConnector * mqtt = new MqttConnector("piClient", "send", "rc", 1883, "localhost", 60);
mqtt->startClient();
return 0;
}
mqtt.h (only important parts
#include <mosquitto.h>
#include <string>
#include <stdio.h>
class MqttConnector
{
public:
MqttConnector(std::string id,
std::string sendTopic,
std::string receiveTopic,
int port,
std::string host,
int keepalive);
~MqttConnector();
void startClient();
private:
void messageCallback(struct mosquitto *mosq,
void *userdata,
const struct mosquitto_message *message);
struct mosquitto *mosqClient = NULL;
int keepalive;
int port;
std::string id;
std::string host;
std::string sendTopic;
std::string receiveTopic;
};
mqtt.cpp
#include "mqtt.h"
#include <stdio.h>
#include <string>
#include <string.h>
#include <mosquitto.h>
#include <functional>
using namespace std::placeholders;
MqttConnector::MqttConnector(std::string id, std::string sendTopic, std::string receiveTopic, int port, std::string host, int keepalive)
{
mosquitto_lib_init();
mosqClient = mosquitto_new(NULL, true, NULL);
if(!mosqClient){
fprintf(stderr, "Error: Out of memory.\n");
}
this->keepalive = keepalive;
this->id = id;
this->host = host;
this->port = port;
this->sendTopic = sendTopic;
this->receiveTopic = receiveTopic;
}
MqttConnector::~MqttConnector()
{
mosquitto_destroy(mosqClient);
mosquitto_lib_cleanup();
}
void MqttConnector::messageCallback(struct mosquitto *mosq, void *userdata, const struct mosquitto_message *message)
{
// I want to access class members like sendTopic / receiveTopic here
}
void MqttConnector::startClient()
{
// try to bind class members function
mosquitto_message_callback_set(mosqClient, std::bind(&MqttConnector::messageCallback, this, _1, _2, _3));
//other stuff
}
This gives me the following error while compiling:
cannot convert 'std::_Bind_helper<false, void (MqttConnector::*)(mosquitto*, void*, const mosquitto_message*), MqttConnector*, const std::_Placeholder<1>&, const std::_Placeholder<2>&, const std::_Placeholder<3>&>::type' {aka 'std::_Bind<void (MqttConnector::*(MqttConnector*, std::_Placeholder<1>, std::_Placeholder<2>, std::_Placeholder<3>))(mosquitto*, void*, const mosquitto_message*)>'} to 'void (*)(mosquitto*, void*, const mosquitto_message*)'
83 | mosquitto_message_callback_set(mosqClient, std::bind(&MqttConnector::messageCallback, this, _1, _2, _3));
Why doesn't it work?
Thanks!
This is a problem of using C-api from C++. What is the difference between a member function and a free function? When you provide a pointer to a member function a pointer to the class object is implicitly passed as the first parameter. Since C-api doesn't do that, but the problem is well known, the solution was introduced and it is called passing a context. Usually it is done through a void pointer. Functions that register callbacks usually take the pointer to the free function and a pointer to context. Then this pointer will be passed as one of the callback parameters.
In mosquitto case this context pointer is passed beforehand at the creation of a mosquitto object with mosquitto_new.
In order to make the callback function behave like a C function, we declare it static.
Inside the callback function we use static_cast to cast the void pointer to the object that we have provided.
mqtt.h
#include <mosquitto.h>
#include <string>
#include <stdio.h>
class MqttConnector
{
public:
MqttConnector(std::string id,
std::string sendTopic,
std::string receiveTopic,
int port,
std::string host,
int keepalive);
~MqttConnector();
void startClient();
private:
// make this function static
---->
static void messageCallback(struct mosquitto *mosq,
void *userdata,
const struct mosquitto_message *message);
struct mosquitto *mosqClient = NULL;
int keepalive;
int port;
std::string id;
std::string host;
std::string sendTopic;
std::string receiveTopic;
};
mqtt.cpp
#include "mqtt.h"
#include <stdio.h>
#include <string>
#include <string.h>
#include <mosquitto.h>
#include <functional>
using namespace std::placeholders;
MqttConnector::MqttConnector(std::string id, std::string sendTopic, std::string receiveTopic, int port, std::string host, int keepalive)
{
mosquitto_lib_init();
// provide apointer to this as user data
mosqClient = mosquitto_new(NULL, true, this);
---->
if(!mosqClient){
fprintf(stderr, "Error: Out of memory.\n");
}
this->keepalive = keepalive;
this->id = id;
this->host = host;
this->port = port;
this->sendTopic = sendTopic;
this->receiveTopic = receiveTopic;
}
MqttConnector::~MqttConnector()
{
mosquitto_destroy(mosqClient);
mosquitto_lib_cleanup();
}
void MqttConnector::messageCallback(struct mosquitto *mosq, void *userdata, const struct mosquitto_message *message)
{
// Use static cast to get pointer to your class object from userdata
MqttConnector *connector = static_cast<MqttConnector>(userdata);
connector->sendTopic;
}
void MqttConnector::startClient()
{
// static callback
mosquitto_message_callback_set(mosqClient, &MqttConnector::messageCallback);
// lambda callback
// beware, you can't use capture here
mosquitto_message_callback_set(&m, [/*no capture possible*/] (struct mosquitto *, void *userdata, const struct mosquitto_message *)
{
MqttConnector *connector = static_cast<MqttConnector>(userdata);
connector->sendTopic;
});
}

How to create a class that stores pointers to member functions (C++)

I'm trying to create a class that stores pointers to member functions of other classes and that can be executed from a text command (like a game console).
I did something functional, based on an example found here, that stores members with string-like input. Below is my implementation.
file: Command.hpp
#include <string>
#include <functional>
#include <unordered_map>
#include <string>
#include <iostream>
using namespace std;
class Command
{
public:
Command();
virtual ~Command();
void RegisterCommand(string command, function<void(const string&)> fun);
void Run(const string& command, const string& arg);
private:
unordered_map<string, function<void(const string&)>> functions;
};
file: Command.cpp
Command::Command()
{
}
Command::~Command()
{
}
void Command::RegisterCommand(string command, function<void(const string&)> fun)
{
functions[command] = fun;
}
void Command::Run(const string& command, const string& arg)
{
functions[command](arg);
}
file: main.cpp
#include "Command.hpp"
// function to register
void xyz_fun(const string& commandLine)
{
cout << "console output: " << commandLine << endl;
}
int main(int argc, char* argv[])
{
Command m_Cmd;
// Register function
m_Cmd.RegisterCommand("xyz_fun", xyz_fun);
// Run registered function
m_Cmd.Run("xyz_fun", "hello world.");
return EXIT_SUCCESS;
}
My question is how to implement a generic class to store members with unknown input arguments (Booleans, integers, doubles, strings, etc.).
For example, I could do:
m_Cmd.RegisterCommand("xyz_fun2", xyz_function2);
and call
m_Cmd.Run("xyz_fun2", false)
which has a boolean argument instead of a string.
Thanks in advance for your attention and any help is welcome.
Instead of
unordered_map<string, function<void(const string&)>> functions;
you could do
union acceptable_types { int i; char c; bool b; std::string* s; ... };
unordered_map<string, function<void(acceptable_types)>> functions;
Then when calling functions, just place the value wanted by the function into a variable of type acceptable_types.
If a function is wants to use a specific value, it should just use a specific member of the acceptable_types union.
Here's an example:
#include "Command.hpp"
void
my_bool_func (acceptable_types union_param)
{
bool bool_var = union_param.b;
// ...
// Use bool_var
// ...
}
void
my_string_func (acceptable_types union_param)
{
std::string string_var = *(union_param.s);
// ...
// Use string_var
// ...
}
int
main(int argc, char* argv[])
{
Command my_command;
acceptable_types union_var;
my_command.RegisterCommand("my_bool_func", my_bool_func);
my_command.RegisterCommand("my_string_func", my_string_func);
union_var.b = true;
my_command.Run("my_bool_func", union_var);
*(union_var.s) = "hello world.";
my_command.Run("my_string_func", union_var);
return 0;
}

Incorrect function call with variable parameters

I am trying to make a nested function call with a variable number of parameters without retrieving them. And I get the wrong result.
Here is my simple c++ program:
extern "C" {
#include <stdio.h>
}
#include <cstdarg>
class ctty {
public:
ctty();
int logger(int prior, const char* format, ...);
private:
};
ctty::ctty(){};
int ctty::logger(int prior, const char* format, ...)
{
va_list ap;
va_start(ap,format);
printf(format, ap);
va_end(ap);
return 0;
}
int main(int argc, char** argv)
{
ctty tty;
tty.logger(0, "Test %d %d %d\n", 7, 5, 5);
return 0;
}
result:
Test -205200 7 5
I expect a result
Test 7 5 5
I don’t understand what am I doing wrong?
Thanks in advance.
You can't directly pass va_list to printf. va_list is a wrapper around the actual list of arguments (whatever its representation is). Although C way to do should be to use vprintf, in C++ there are safer alternatives, like variadic templates allowing to create a safer version of formatted printing, e.g. (a fictional format string for brevity of example):
#include <iostream>
#include <cstdlib>
class ctty {
public:
ctty();
template<typename T, typename... Args>
int logger(int prior, const char* format, T value, Args... args);
private:
void logger(int prior, const char *s);
};
ctty::ctty(){};
void ctty::logger(int prior, const char *s)
{
while (*s) {
if (*s == '%') {
if (*(s + 1) == '%') {
++s;
}
else {
throw std::runtime_error("invalid format string: missing arguments");
}
}
std::cout << *s++;
}
}
template<typename T, typename... Args>
int ctty::logger(int prior, const char* format, T value, Args... args)
{
while (*format) {
if (*format == '%') {
std::cout << value;
logger(prior, format + 1, args...);
return 0;
}
std::cout << *format++;
}
throw std::logic_error("extra arguments provided to logger");
}
int main(int argc, char** argv)
{
ctty tty;
tty.logger(0, "Test % % %\n", 7.55f, "Tada!", 888);
return 0;
}
This part of your code:
extern "C" {
#include <stdio.h>
}
Is technically an undefined behavior, while it may compile and not have adverse effect in some cases, it's not portable. You have to use C++ headers, e.g. <cstdio>

C++ undefined symbol: NullPointerException error returned from a shared library

I'm having some problems with my code. A shared library is causing an undefined symbol error that I just cannot figure out. All of the files are in the correct locations and the shared library builds successfully but upon executing the program it returns the bellow message.
The error message:
libsp.so: undefined symbol: _ZTIN4Poco20NullPointerExceptionE
From what I can see the problem is the Poco headers I use. The headers I got from an outside source and they should all work, I believe the error is caused by how I call these headers, but I might be wrong.
Bellow is the only code that uses Poco in the libsp library. And the code of the 4 header files I use. I've checked and rechecked and cannot find any issues but am still getting the undefined symbol exception.
File Spexec.cpp (libsp):
#include "../poco/Poco/Base64Encoder.h"
#include "../poco/Poco/DigestEngine.h"
#include "../poco/Poco/MD5Engine.h"
#include "../poco/Poco/Path.h"
using namespace std;
stringstream s_base;
Poco::Base64Encoder encoder(s_base);
Poco::Path path(data.name);
data.path = data.name.substr(0, data.name.length() - path.getFileName().length());
Poco::MD5Engine md5;
stringstream ss;
ss << data.created << data.name;
md5.update(ss.str());
data.name = Poco::DigestEngine::digestToHex(md5.digest());
}
File Base64Encoder.h:
#ifndef Foundation_Base64Encoder_INCLUDED
#define Foundation_Base64Encoder_INCLUDED
#include "Foundation.h"
#include <ostream>
namespace Poco {
class Foundation_API Base64Encoder:, public std::ostream
{
public:
Base64Encoder(std::ostream& ostr);
~Base64Encoder();
private:
Base64Encoder(const Base64Encoder&);
Base64Encoder& operator = (const Base64Encoder&);
};
} // namespace Poco
#endif // Foundation_Base64Encoder_INCLUDED
File DigestEngine.h:
#ifndef Foundation_DigestEngine_INCLUDED
#define Foundation_DigestEngine_INCLUDED
#include "Foundation.h"
#include <vector>
namespace Poco {
class Foundation_API DigestEngine
{
public:
typedef std::vector<unsigned char> Digest;
DigestEngine();
virtual ~DigestEngine();
void update(const void* data, std::size_t length);
void update(char data);
void update(const std::string& data);
virtual std::size_t digestLength() const = 0;
virtual void reset() = 0;
virtual const Digest& digest() = 0;
static std::string digestToHex(const Digest& bytes);
static Digest digestFromHex(const std::string& digest);
presentation
protected:
virtual void updateImpl(const void* data, std::size_t length) = 0;
private:
DigestEngine(const DigestEngine&);
DigestEngine& operator = (const DigestEngine&);
};
File MD5Engine.h:
#ifndef Foundation_MD5Engine_INCLUDED
#define Foundation_MD5Engine_INCLUDED
#include "Foundation.h"
#include "DigestEngine.h"
namespace Poco {
class Foundation_API MD5Engine: public DigestEngine
{
public:
enum
{
BLOCK_SIZE = 64,
DIGEST_SIZE = 16
};
MD5Engine();
~MD5Engine();
std::size_t digestLength() const;
void reset();
const DigestEngine::Digest& digest();
protected:
void updateImpl(const void* data, std::size_t length);
private:
static void transform(UInt32 state[4], const unsigned char block[64]);
static void encode(unsigned char* output, const UInt32* input, std::size_t len);
static void decode(UInt32* output, const unsigned char* input, std::size_t len);
struct Context
{
UInt32 state[4]; // state (ABCD)
UInt32 count[2]; // number of bits, modulo 2^64 (lsb first)
unsigned char buffer[64]; // input buffer
};
Context _context;
DigestEngine::Digest _digest;
MD5Engine(const MD5Engine&);
MD5Engine& operator = (const MD5Engine&);
};
}
File Path.h:
#ifndef Foundation_Path_INCLUDED
#define Foundation_Path_INCLUDED
#include "Foundation.h"
#include <vector>
namespace Poco {
class Foundation_API Path
{
public:
enum Style
{
PATH_UNIX, /// Unix-style path
PATH_WINDOWS, /// Windows-style path
PATH_VMS, /// VMS-style path
PATH_NATIVE, /// The current platform's native style
PATH_GUESS /// Guess the style by examining the path
};
typedef std::vector<std::string> StringVec;
Path();
Path(const char* path);
Path(const std::string& path);
protected:
void parseUnix(const std::string& path);
void parseWindows(const std::string& path);
void parseVMS(const std::string& path);
void parseGuess(const std::string& path);
std::string buildUnix() const;
std::string buildWindows() const;
std::string buildVMS() const;
private:
std::string _node;
std::string _device;
std::string _name;
std::string _version;
StringVec _dirs;
bool _absolute;
};

Error:.. 'va_list' has not been declared

I'v been trying to compile flann but this error shows up! ''va_list' has not been declared'
Can any one help me to solve this error?
Plz guild me so simple if u can, I'm really new in programming!
In file included from ./flann/nn/index_testing.h:41,
from ./flann/flann.hpp:43,
from src/common.hpp:12,
from src/main.cpp:9:
./flann/util/logger.h:74: error: 'va_list' has not been declared
Makefile:43: recipe for target `src/main.o' failed
make: *** [src/main.o] Error 1
Here is logger.h
#ifndef LOGGER_H
#define LOGGER_H
#include <cstdio>
#include "flann/general.h"
namespace flann
{
class Logger
{
FILE* stream;
int logLevel;
public:
Logger() : stream(stdout), logLevel(LOG_WARN) {};
~Logger()
{
if (stream!=NULL && stream!=stdout) {
fclose(stream);
}
}
void setDestination(const char* name)
{
if (name==NULL) {
stream = stdout;
}
else {
stream = fopen(name,"w");
if (stream == NULL) {
stream = stdout;
}
}
}
void setLevel(int level) { logLevel = level; }
int log(int level, const char* fmt, ...);
int log(int level, const char* fmt, va_list arglist);
int fatal(const char* fmt, ...);
int error(const char* fmt, ...);
int warn(const char* fmt, ...);
int info(const char* fmt, ...);
};
extern Logger logger;
}
#endif //LOGGER_H
You miss an include for the relevant macros
#include <cstdarg>