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 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388
use arrayvec::ArrayVec;
use std::fmt;
use crate::binary::{BArray, BKeyValue, BMap, Binary, TYPE_ARRAY, TYPE_MAP};
use crate::bookmark::Bookmark;
use crate::bookmark::MAX_POINTERS;
use crate::Ptrs;
use super::parser::Node;
// Node is the type that a parser puts out. each
// node should implement the trait functions below
pub trait Discoverable {
fn find(&self, bin: &Binary, b: Bookmark) -> Option<Ptrs>;
}
#[derive(Debug, PartialEq)]
pub struct FieldLiteral {
name: String,
}
// FieldLiteral is an actual field name in the dapt packet. These can be
// chained together with `.` in order to create a path. For instance
// `log.level` would be two field literals, which point to the json structure
// `{"log": {"level": "info"}}`. Anything that is not interpreted as a different
// type is considered a field literal. Special characters can be escaped by wrapping
// the field name in double quotes. For instance `"log.level"` would be a single
// field literal that points to the json structure `{"log.level": "info"}`.
impl FieldLiteral {
pub fn new(name: &str) -> FieldLiteral {
// name is a string which optionally is wrapped in double quotes.
// here we remove the double quotes if they exist and remove any
// escape characters.
FieldLiteral {
name: name.trim_matches('"').replace("\\\"", "\""),
}
}
}
impl Discoverable for FieldLiteral {
// find returns a list of pointers to the
// child that matches the specified name.
fn find(&self, bin: &Binary, b: Bookmark) -> Option<Ptrs> {
let mut res: ArrayVec<Bookmark, MAX_POINTERS> = ArrayVec::new();
let n = b.value_node(bin)?;
match n.type_of(bin)? {
TYPE_MAP => {
let bcoll: BMap = n.token_at(bin)?.try_into().unwrap();
if let Some(child_location) = bcoll.child_key(&self.name, bin) {
res.push(child_location.into());
}
}
_ => (),
}
if res.len() > 0 {
Some(res)
} else {
None
}
}
}
impl fmt::Display for FieldLiteral {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
// if there is a . or a " in the name we need to wrap
// it in double quotes. We will wrap spaces in double
// quotes too, even though we don't have to.
if self.name.contains('.') || self.name.contains('"') || self.name.contains(' ') {
write!(f, "\"{}\"", self.name)
} else {
write!(f, "{}", self.name)
}
}
}
// The Array operator `[]` allows you to traverse arrays. When you
// supply an index, like so `[1]`, it will select the specifie element
// at the provided index. Dapt packets can point to multiple locations
// in a document at once, which means supplying no index `[]` will point
// to all elements in the array.
#[derive(Debug, PartialEq)]
pub struct Array {
index: Option<usize>,
}
impl Array {
pub fn new(index: Option<usize>) -> Array {
Array { index }
}
}
impl Discoverable for Array {
// find returns a list of pointers to the
// child that matches the specified name.
fn find(&self, bin: &Binary, b: Bookmark) -> Option<Ptrs> {
let mut res: ArrayVec<Bookmark, MAX_POINTERS> = ArrayVec::new();
let n = b.value_node(bin)?;
match n.type_of(bin)? {
TYPE_ARRAY => {
let bcoll: BArray = n.token_at(bin)?.try_into().unwrap();
if let None = self.index {
unsafe {
res.set_len(bcoll.length()); // set the length to hold the
// indexes
bcoll.child_indexes(&mut res) // add the indexes
}
} else {
if let Some(child_location) = bcoll.child_index(self.index.unwrap()) {
res.push(child_location.into());
}
}
}
_ => (),
}
if res.len() > 0 {
Some(res)
} else {
None
}
}
}
impl fmt::Display for Array {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self.index {
Some(i) => write!(f, "[{}]", i),
None => write!(f, "[]"),
}
}
}
// Wildcard will select all the children within the map we are currently
// in.
#[derive(Debug, PartialEq)]
pub struct Wildcard;
impl Discoverable for Wildcard {
// find returns a list of pointers to the
// child that matches the specified name.
fn find(&self, bin: &Binary, b: Bookmark) -> Option<Ptrs> {
let mut res: ArrayVec<Bookmark, MAX_POINTERS> = ArrayVec::new();
let n = b.value_node(bin)?;
match n.type_of(bin)? {
TYPE_MAP => {
let bcoll: BMap = n.token_at(bin)?.try_into().unwrap();
unsafe {
res.set_len(bcoll.length()); // set the length to hold the
// indexes
bcoll.child_indexes(&mut res) // add the indexes
}
}
_ => (),
}
if res.len() > 0 {
Some(res)
} else {
None
}
}
}
impl fmt::Display for Wildcard {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "*")
}
}
// recursive will traverse the tree until it finds the node that matches.
// `~.message` would match the `message` field in the json structure
// `{"something":{ "something-else": { "message": "hello" }}}`.
#[derive(Debug, PartialEq)]
pub struct Recursive {
child: Box<Node>,
}
impl Recursive {
pub fn new(child: Node) -> Recursive {
Recursive {
child: Box::new(child),
}
}
}
impl Discoverable for Recursive {
// find returns a list of pointers to the
// child that matches the specified name.
fn find(&self, bin: &Binary, b: Bookmark) -> Option<Ptrs> {
let mut res: ArrayVec<Bookmark, MAX_POINTERS> = ArrayVec::new();
b.walk(bin, &mut res, &|childb, res| {
if let Some(ptrs) = self.child.find(bin, childb) {
res.try_extend_from_slice(&ptrs[..]).unwrap();
}
true
});
if res.len() > 0 {
Some(res)
} else {
None
}
}
}
impl fmt::Display for Recursive {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "~.{}", self.child)
}
}
// First will find the first non empty value and return that.
// `{~.message|~.error}` would match the `message` field in the json
// structure `{"message": "hello"}` and the `error` field in the json
// structure `{"error": "something went wrong"}`.
#[derive(Debug, PartialEq)]
pub struct First {
paths: Vec<Node>,
}
impl First {
pub fn new(paths: Vec<Node>) -> First {
First { paths }
}
}
impl Discoverable for First {
// find returns a list of pointers to the
// child that matches the specified name.
fn find(&self, bin: &Binary, b: Bookmark) -> Option<Ptrs> {
let mut res: ArrayVec<Bookmark, MAX_POINTERS> = ArrayVec::new();
for path in &self.paths {
if let Some(ptrs) = path.find(bin, b) {
res.try_extend_from_slice(&ptrs[..]).unwrap();
break;
}
}
if res.len() > 0 {
Some(res)
} else {
None
}
}
}
impl fmt::Display for First {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{{")?;
for (x, path) in self.paths.iter().enumerate() {
if x > 0 {
write!(f, ",")?;
}
write!(f, "{}", path)?;
}
write!(f, "}}")?;
Ok(())
}
}
// Multi works much like first, but will match on all the values
// that are not empty. example `(~.message,~.error)` would match
// both fields in the json structure:
// `{"message": "hello", "error": "something went wrong"}`.
#[derive(Debug, PartialEq)]
pub struct Multi {
paths: Vec<Node>,
}
impl Multi {
pub fn new(paths: Vec<Node>) -> Multi {
Multi { paths }
}
}
impl Discoverable for Multi {
// find returns a list of pointers to the
// child that matches the specified name.
fn find(&self, bin: &Binary, b: Bookmark) -> Option<Ptrs> {
let mut res: ArrayVec<Bookmark, MAX_POINTERS> = ArrayVec::new();
for path in &self.paths {
if let Some(ptrs) = path.find(bin, b) {
res.try_extend_from_slice(&ptrs[..]).unwrap();
}
}
if res.len() == 0 {
return None;
}
Some(res)
}
}
impl fmt::Display for Multi {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "(")?;
for (x, path) in self.paths.iter().enumerate() {
if x > 0 {
write!(f, "|")?;
}
write!(f, "{}", path)?;
}
write!(f, ")")?;
Ok(())
}
}
#[derive(Debug)]
pub struct Regexp {
name: regex::Regex,
}
impl Regexp {
pub fn new(name: &str) -> Regexp {
// name is a string which optionally is wrapped in double quotes.
// here we remove the double quotes if they exist and remove any
// escape characters.
Regexp {
name: regex::Regex::new(name).unwrap(),
}
}
}
impl PartialEq for Regexp {
fn eq(&self, other: &Self) -> bool {
self.name.as_str() == other.name.as_str()
}
}
impl Discoverable for Regexp {
// find returns a list of pointers to the
// child that matches the specified name.
fn find(&self, bin: &Binary, b: Bookmark) -> Option<Ptrs> {
let mut res: ArrayVec<Bookmark, MAX_POINTERS> = ArrayVec::new();
let n = b.value_node(bin)?;
match n.type_of(bin)? {
TYPE_MAP => {
let bcoll: BMap = n.token_at(bin)?.try_into().unwrap();
let mut indexes = vec![Bookmark::new(0); bcoll.length()];
bcoll.child_indexes(&mut indexes);
println!("{:?}", indexes);
for i in indexes {
let child = match bin.token_at(i.into()) {
Some(c) => c,
None => continue,
};
let child = BKeyValue::try_from(child).unwrap();
if self.name.is_match(child.key()) {
res.push(i.into());
}
}
}
_ => (),
}
if res.len() > 0 {
Some(res)
} else {
None
}
}
}
impl fmt::Display for Regexp {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
// if there is a . or a " in the name we need to wrap
// it in double quotes. We will wrap spaces in double
// quotes too, even though we don't have to.
write!(f, "/{}/", self.name)
}
}