1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133
|
/*
Copyright (C) 2021 The Falco Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
//
// json_parser.h
//
// jq wrapper
//
#ifdef __linux__
#include "json_query.h"
#include "sinsp.h"
json_query::json_query(const std::string& json, const std::string& filter, bool dbg) :
m_jq(jq_init()), m_input{0}, m_result{0}, m_processed(false)
{
if(!m_jq) { cleanup(); }
process(json, filter, dbg);
}
json_query::~json_query()
{
cleanup();
}
bool json_query::process(const std::string& json, const std::string& filter, bool dbg)
{
cleanup(m_input);
cleanup(m_result);
clear();
if(!m_jq) { cleanup(); }
if(!jq_compile(m_jq, filter.c_str()))
{
m_error = "Filter parsing failed.";
return false;
}
m_input = jv_parse/*_sized*/(json.c_str()/*, json.length()*/);
if (!jv_is_valid(m_input))
{
cleanup(m_input, "JSON parse error.");
return false;
}
jq_start(m_jq, m_input, dbg ? JQ_DEBUG_TRACE : 0);
m_input = jv_null(); // jq_start() freed it
m_result = jq_next(m_jq);
if (!jv_is_valid(m_result))
{
cleanup(m_result, "json_query filtering result invalid.");
return false;
}
m_json = json;
m_filter = filter;
return m_processed = true;
}
const std::string& json_query::result(int flags)
{
if(m_processed)
{
static const std::string ret;
if(!m_error.empty()) { return ret; }
char* buf;
size_t len;
FILE* f = open_memstream(&buf, &len);
if(f == NULL)
{
m_error = "Can't open memory stream for writing.";
return ret;
}
jv_dumpf(m_result, f, flags);
m_result = jv_null();
clear();
fclose (f);
m_filtered_json.assign(buf, len);
free (buf);
m_processed = false;
}
return m_filtered_json;
}
void json_query::clear()
{
m_result = jv_null();
m_input = jv_null();
m_filtered_json.clear();
m_error.clear();
m_processed = false;
}
void json_query::cleanup()
{
if(m_jq)
{
cleanup(m_input);
cleanup(m_result);
clear();
jq_teardown(&m_jq);
m_jq = 0;
}
else
{
throw std::runtime_error("json_query handle is null.");
}
}
void json_query::cleanup(jv& j, const std::string& msg)
{
if(j.u.ptr)
{
jv_free(j);
j = jv_null();
}
m_error = msg;
}
#endif // __linux__
|