File: plugin.cpp

package info (click to toggle)
falcosecurity-libs 0.1.1dev%2Bgit20220316.e5c53d64-5.1
  • links: PTS, VCS
  • area: main
  • in suites: bookworm
  • size: 4,732 kB
  • sloc: cpp: 55,770; ansic: 37,330; makefile: 74; sh: 13
file content (1189 lines) | stat: -rwxr-xr-x 34,029 bytes parent folder | download
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
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
/*
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.

*/

#ifndef _WIN32
#include <dlfcn.h>
// This makes inttypes.h define PRIu32 (ISO C99 plus older g++ versions)
#define __STDC_FORMAT_MACROS
#include <inttypes.h>
#include <string.h>
#include <vector>
#include <set>
#include <sstream>
#endif
#include <numeric>
#include <json/json.h>
#include <valijson/adapters/jsoncpp_adapter.hpp>
#include <valijson/schema.hpp>
#include <valijson/schema_parser.hpp>
#include <valijson/validator.hpp>

#include "sinsp.h"
#include "sinsp_int.h"
#include "filter.h"
#include "filterchecks.h"
#include "plugin.h"

#include <third-party/tinydir.h>

using namespace std;

///////////////////////////////////////////////////////////////////////////////
// source_plugin filter check implementation
// This class implements a dynamic filter check that acts as a bridge to the
// plugin simplified field extraction implementations
///////////////////////////////////////////////////////////////////////////////

static std::set<uint16_t> s_all_plugin_event_types = {PPME_PLUGINEVENT_E};

class sinsp_filter_check_plugin : public sinsp_filter_check
{
public:
	sinsp_filter_check_plugin()
	{
		m_info.m_name = "plugin";
		m_info.m_fields = NULL;
		m_info.m_nfields = 0;
		m_info.m_flags = filter_check_info::FL_NONE;
		m_cnt = 0;
	}

	sinsp_filter_check_plugin(std::shared_ptr<sinsp_plugin> plugin)
		: m_plugin(plugin)
	{
		m_info.m_name = plugin->name() + string(" (plugin)");
		m_info.m_fields = plugin->fields();
		m_info.m_nfields = plugin->nfields();
		m_info.m_flags = filter_check_info::FL_NONE;
		m_cnt = 0;
	}

	sinsp_filter_check_plugin(const sinsp_filter_check_plugin &p)
	{
		m_plugin = p.m_plugin;
		m_info = p.m_info;
	}

	virtual ~sinsp_filter_check_plugin()
	{
	}

	const std::set<uint16_t> &evttypes()
	{
		return s_all_plugin_event_types;
	}

	int32_t parse_field_name(const char* str, bool alloc_state, bool needed_for_filtering)
	{
		int32_t res = sinsp_filter_check::parse_field_name(str, alloc_state, needed_for_filtering);

		if(res != -1)
		{
			// Read from str to the end-of-string, or first space
			string val(str);
			size_t val_end = val.find_first_of(' ', 0);
			if(val_end != string::npos)
			{
				val = val.substr(0, val_end);
			}

			size_t pos1 = val.find_first_of('[', 0);
			if(pos1 != string::npos)
			{
				size_t argstart = pos1 + 1;
				if(argstart < val.size())
				{
					m_argstr = val.substr(argstart);
					size_t pos2 = m_argstr.find_first_of(']', 0);
					m_argstr = m_argstr.substr(0, pos2);
					m_arg = (char*)m_argstr.c_str();
					return pos1 + pos2 + 2;
				}
			}
		}

		return res;
	}

	sinsp_filter_check* allocate_new()
	{
		return new sinsp_filter_check_plugin(*this);
	}

	uint8_t* extract(sinsp_evt *evt, OUT uint32_t* len, bool sanitize_strings)
	{
		//
		// Reject any event that is not generated by a plugin
		//
		if(evt->get_type() != PPME_PLUGINEVENT_E)
		{
			return NULL;
		}

		//
		// If this is a source plugin, reject events that have
		// not been generated by a plugin with this id specifically.
		//
		// XXX/mstemm this should probably check the version as well.
		//
		sinsp_evt_param *parinfo;
		if(m_plugin->type() == TYPE_SOURCE_PLUGIN)
		{
			sinsp_source_plugin *splugin = static_cast<sinsp_source_plugin *>(m_plugin.get());
			parinfo = evt->get_param(0);
			ASSERT(parinfo->m_len == sizeof(int32_t));
			uint32_t pgid = *(int32_t *)parinfo->m_val;
			if(pgid != splugin->id())
			{
				return NULL;
			}
		}

		//
		// If this is an extractor plugin, only attempt to
		// extract if the source is compatible with the event
		// source.
		//
		if(m_plugin->type() == TYPE_EXTRACTOR_PLUGIN)
		{
			sinsp_extractor_plugin *eplugin = static_cast<sinsp_extractor_plugin *>(m_plugin.get());
			parinfo = evt->get_param(0);
			ASSERT(parinfo->m_len == sizeof(int32_t));
			uint32_t pgid = *(int32_t *)parinfo->m_val;

			std::shared_ptr<sinsp_plugin> plugin = m_inspector->get_plugin_by_id(pgid);

			if(!plugin)
			{
				return NULL;
			}

			sinsp_source_plugin *splugin = static_cast<sinsp_source_plugin *>(plugin.get());

			if(!eplugin->source_compatible(splugin->event_source()))
			{
				return NULL;
			}
		}

		//
		// Get the event payload
		//
		parinfo = evt->get_param(1);
		*len = 0;

		ppm_param_type type = m_info.m_fields[m_field_id].m_type;

		ss_plugin_event pevt;
		pevt.evtnum = evt->get_num();
		pevt.data = (uint8_t *) parinfo->m_val;
		pevt.datalen = parinfo->m_len;
		pevt.ts = evt->get_ts();

		sinsp_plugin::ext_field field;
		field.field_id = m_field_id;
		field.field = m_info.m_fields[m_field_id].m_name;
		if(m_arg != NULL)
		{
			field.arg = m_arg;
		}
		field.ftype = type;

		if (!m_plugin->extract_field(pevt, field) ||
		    ! field.field_present)
		{
			return NULL;
		}

		switch(type)
		{
		case PT_CHARBUF:
		{
			m_strstorage = field.res_str;
			*len = m_strstorage.size();
			return (uint8_t*) m_strstorage.c_str();
		}
		case PT_UINT64:
		{
			m_u64_res = field.res_u64;
			return (uint8_t *)&m_u64_res;
		}
		default:
			ASSERT(false);
			throw sinsp_exception("plugin extract error: unsupported field type " + to_string(type));
			break;
		}

		return NULL;
	}

	// XXX/mstemm m_cnt unused so far.
	uint64_t m_cnt;
	string m_argstr;
	char* m_arg = NULL;

	std::string m_strstorage;
	uint64_t m_u64_res;

	std::shared_ptr<sinsp_plugin> m_plugin;
};

///////////////////////////////////////////////////////////////////////////////
// sinsp_plugin implementation
///////////////////////////////////////////////////////////////////////////////
sinsp_plugin::version::version()
	: m_valid(false)
{
}

sinsp_plugin::version::version(const std::string &version_str)
	: m_valid(false)
{
	m_valid = (sscanf(version_str.c_str(), "%" PRIu32 ".%" PRIu32 ".%" PRIu32,
			  &m_version_major, &m_version_minor, &m_version_patch) == 3);
}

sinsp_plugin::version::~version()
{
}

std::string sinsp_plugin::version::as_string() const
{
	return std::to_string(m_version_major) + "." +
		std::to_string(m_version_minor) + "." +
		std::to_string(m_version_patch);
}

bool sinsp_plugin::version::check(version &requested) const
{
	if(this->m_version_major != requested.m_version_major)
	{
		// major numbers disagree
		return false;
	}

	if(this->m_version_minor < requested.m_version_minor)
	{
		// framework's minor version is < requested one
		return false;
	}
	if(this->m_version_minor == requested.m_version_minor && this->m_version_patch < requested.m_version_patch)
	{
		// framework's patch level is < requested one
		return false;
	}
	return true;
}

std::shared_ptr<sinsp_plugin> sinsp_plugin::register_plugin(sinsp* inspector,
							    string filepath,
							    const char* config,
							    filter_check_list &available_checks)
{
	string errstr;
	std::shared_ptr<sinsp_plugin> plugin = create_plugin(filepath, config, errstr);

	if (!plugin)
	{
		throw sinsp_exception("cannot load plugin " + filepath + ": " + errstr.c_str());
	}

	try
	{
		inspector->add_plugin(plugin);
	}
	catch(sinsp_exception const& e)
	{
		throw sinsp_exception("cannot add plugin " + filepath + " to inspector: " + e.what());
	}

	//
	// Create and register the filter checks associated to this plugin
	//

	// Only add the gen_event filter checks for source
	// plugins. Extractor plugins don't deal with event
	// timestamps/etc and don't need these checks (They were
	// probably added by the associated source plugins anyway).
	if(plugin->type() == TYPE_SOURCE_PLUGIN)
	{
		auto evt_filtercheck = new sinsp_filter_check_gen_event();
		available_checks.add_filter_check(evt_filtercheck);
	}

	auto filtercheck = new sinsp_filter_check_plugin(plugin);
	available_checks.add_filter_check(filtercheck);

	return plugin;
}

std::shared_ptr<sinsp_plugin> sinsp_plugin::create_plugin(string &filepath, const char* config, std::string &errstr)
{
	std::shared_ptr<sinsp_plugin> ret;

#ifdef _WIN32
	sinsp_plugin_handle handle = LoadLibrary(filepath.c_str());
#else
	sinsp_plugin_handle handle = dlopen(filepath.c_str(), RTLD_LAZY);
#endif
	if(handle == NULL)
	{
		errstr = "error loading plugin " + filepath + ": " + dlerror();
		return ret;
	}

	// Before doing anything else, check the required api
	// version. If it doesn't match, return an error.

	// The pointer indirection and reference is because c++ doesn't
	// strictly allow casting void * to a function pointer. (See
	// http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#195).
	char * (*get_required_api_version)();
	*(void **) (&get_required_api_version) = getsym(handle, "plugin_get_required_api_version", errstr);
	if(get_required_api_version == NULL)
	{
		errstr = string("Could not resolve plugin_get_required_api_version function");
		return ret;
	}

	char *version_cstr = get_required_api_version();
	std::string version_str = version_cstr;
	version requestedVers(version_str);
	if(!requestedVers.m_valid)
	{
		errstr = string("Could not parse version string from ") + version_str;
		return ret;
	}
	// This is always valid
	version frameworkVers(PLUGIN_API_VERSION_STR);
	if(!frameworkVers.check(requestedVers))
	{
		errstr = string("Unsupported plugin required api version ") + version_str;
		return ret;
	}

	ss_plugin_type (*get_type)();
	*(void **) (&get_type) = getsym(handle, "plugin_get_type", errstr);
	if(get_type == NULL)
	{
		errstr = string("Could not resolve plugin_get_type function");
		return ret;
	}

	ss_plugin_type plugin_type = get_type();

	sinsp_source_plugin *splugin;
	sinsp_extractor_plugin *eplugin;

	switch(plugin_type)
	{
	case TYPE_SOURCE_PLUGIN:
		splugin = new sinsp_source_plugin(handle);
		if(!splugin->resolve_dylib_symbols(errstr))
		{
			delete splugin;
			return ret;
		}
		ret.reset(splugin);
		break;
	case TYPE_EXTRACTOR_PLUGIN:
		eplugin = new sinsp_extractor_plugin(handle);
		if(!eplugin->resolve_dylib_symbols(errstr))
		{
			delete eplugin;
			return ret;
		}
		ret.reset(eplugin);
		break;
	default:
		errstr = string("Wrong plugin type.");
		destroy_handle(handle);
		return ret;
	}

	errstr = "";

	// Initialize the plugin
	ret->validate_init_config(config);
	if (!ret->init(config))
	{
		errstr = string("Could not initialize plugin: " + ret->get_last_error());
		ret = NULL;
	}

	return ret;
}

std::list<sinsp_plugin::info> sinsp_plugin::plugin_infos(sinsp* inspector)
{
	std::list<sinsp_plugin::info> ret;

	for(auto p : inspector->get_plugins())
	{
		sinsp_plugin::info info;
		info.name = p->name();
		info.description = p->description();
		info.contact = p->contact();
		info.plugin_version = p->plugin_version();
		info.required_api_version = p->required_api_version();
		info.type = p->type();

		if(info.type == TYPE_SOURCE_PLUGIN)
		{
			sinsp_source_plugin *sp = static_cast<sinsp_source_plugin *>(p.get());
			info.id = sp->id();
		}
		ret.push_back(info);
	}

	return ret;
}

bool sinsp_plugin::is_plugin_loaded(std::string &filepath)
{
#ifdef _WIN32
	/*
	 * LoadLibrary maps the module into the address space of the calling process, if necessary,
	 * and increments the modules reference count, if it is already mapped.
	 * GetModuleHandle, however, returns the handle to a mapped module
	 * without incrementing its reference count.
	 *
	 * This returns an HMODULE indeed, but they are the same thing
	 */
	sinsp_plugin_handle handle = (HINSTANCE)GetModuleHandle(filepath.c_str());
#else
	/*
	 * RTLD_NOLOAD (since glibc 2.2)
	 *	Don't load the shared object. This can be used to test if
	 *	the object is already resident (dlopen() returns NULL if
	 *	it is not, or the object's handle if it is resident).
	 *	This does not increment dlobject reference count.
	 */
	sinsp_plugin_handle handle = dlopen(filepath.c_str(), RTLD_LAZY | RTLD_NOLOAD);
#endif
	return handle != NULL;
}

sinsp_plugin::sinsp_plugin(sinsp_plugin_handle handle)
	: m_handle(handle), m_nfields(0)
{
}

sinsp_plugin::~sinsp_plugin()
{
	destroy_handle(m_handle);
}

bool sinsp_plugin::init(const char *config)
{
	if (!m_plugin_info.init)
	{
		return false;
	}

	ss_plugin_rc rc;

	ss_plugin_t *state = m_plugin_info.init(config, &rc);
	if (state != NULL)
	{
		// Plugins can return a state even if the result code is
		// SS_PLUGIN_FAILURE, which can be useful to set an init
		// error that can later be retrieved through get_last_error().
		set_plugin_state(state);
	}

	return rc == SS_PLUGIN_SUCCESS;
}

void sinsp_plugin::destroy()
{
	if(plugin_state() && m_plugin_info.destroy)
	{
		m_plugin_info.destroy(plugin_state());
		set_plugin_state(NULL);
	}
}

std::string sinsp_plugin::get_last_error()
{
	std::string ret;

	if(plugin_state() && m_plugin_info.get_last_error)
	{
		ret = str_from_alloc_charbuf(m_plugin_info.get_last_error(plugin_state()));
	}
	else
	{
		ret = "Plugin handle or get_last_error function not defined";
	}

	return ret;
}

const std::string &sinsp_plugin::name()
{
	return m_name;
}

const std::string &sinsp_plugin::description()
{
	return m_description;
}

const std::string &sinsp_plugin::contact()
{
	return m_contact;
}

const sinsp_plugin::version &sinsp_plugin::plugin_version()
{
	return m_plugin_version;
}

const sinsp_plugin::version &sinsp_plugin::required_api_version()
{
	return m_required_api_version;
}

const filtercheck_field_info *sinsp_plugin::fields()
{
	return m_fields.get();
}

uint32_t sinsp_plugin::nfields()
{
	return m_nfields;
}

bool sinsp_plugin::extract_field(ss_plugin_event &evt, sinsp_plugin::ext_field &field)
{
	if(!m_plugin_info.extract_fields || !plugin_state())
	{
		return false;
	}

	uint32_t num_fields = 1;
	ss_plugin_extract_field efield;
	efield.field_id = field.field_id;
	efield.field = field.field.c_str();
	efield.arg = field.arg.c_str();
	efield.ftype = field.ftype;

	ss_plugin_rc rc;

	rc = m_plugin_info.extract_fields(plugin_state(), &evt, num_fields, &efield);

	if (rc != SS_PLUGIN_SUCCESS)
	{
		return false;
	}

	field.field_present = efield.field_present;
	if (field.field_present) {
		switch(field.ftype)
		{
		case PT_CHARBUF:
			field.res_str = str_from_alloc_charbuf(efield.res_str);
			break;
		case PT_UINT64:
			field.res_u64 = efield.res_u64;
			break;
		default:
			ASSERT(false);
			throw sinsp_exception("plugin extract error: unsupported field type " + to_string(field.ftype));
			break;
		}
	}

	return true;
}

void* sinsp_plugin::getsym(sinsp_plugin_handle handle, const char* name, std::string &errstr)
{
	void *ret;

#ifdef _WIN32
	ret = GetProcAddress(handle, name);
#else
	ret = dlsym(handle, name);
#endif

	if(ret == NULL)
	{
		errstr = string("Dynamic library symbol ") + name + " not present";
	} else {
		errstr = "";
	}

	return ret;
}

// Used below--set a std::string from the provided allocated charbuf and free() the charbuf.
std::string sinsp_plugin::str_from_alloc_charbuf(const char* charbuf)
{
	std::string str;

	if(charbuf != NULL)
	{
		str = charbuf;
	}

	return str;
}

bool sinsp_plugin::resolve_dylib_symbols(std::string &errstr)
{
	// Some functions are required and return false if not found.
	if((*(void **) (&(m_plugin_info.get_required_api_version)) = getsym(m_handle, "plugin_get_required_api_version", errstr)) == NULL ||
	   (*(void **) (&(m_plugin_info.get_last_error)) = getsym(m_handle, "plugin_get_last_error", errstr)) == NULL ||
	   (*(void **) (&(m_plugin_info.get_name)) = getsym(m_handle, "plugin_get_name", errstr)) == NULL ||
	   (*(void **) (&(m_plugin_info.get_description)) = getsym(m_handle, "plugin_get_description", errstr)) == NULL ||
	   (*(void **) (&(m_plugin_info.get_contact)) = getsym(m_handle, "plugin_get_contact", errstr)) == NULL ||
	   (*(void **) (&(m_plugin_info.get_version)) = getsym(m_handle, "plugin_get_version", errstr)) == NULL)
	{
		return false;
	}

	// Others are not and the values will be checked when needed.
	(*(void **) (&m_plugin_info.init)) = getsym(m_handle, "plugin_init", errstr);
	(*(void **) (&m_plugin_info.destroy)) = getsym(m_handle, "plugin_destroy", errstr);
	(*(void **) (&m_plugin_info.get_fields)) = getsym(m_handle, "plugin_get_fields", errstr);
	(*(void **) (&m_plugin_info.extract_fields)) = getsym(m_handle, "plugin_extract_fields", errstr);
	(*(void **) (&m_plugin_info.get_init_schema)) = getsym(m_handle, "plugin_get_init_schema", errstr);

	m_name = str_from_alloc_charbuf(m_plugin_info.get_name());
	m_description = str_from_alloc_charbuf(m_plugin_info.get_description());
	m_contact = str_from_alloc_charbuf(m_plugin_info.get_contact());
	std::string version_str = str_from_alloc_charbuf(m_plugin_info.get_version());
	m_plugin_version = sinsp_plugin::version(version_str);
	if(!m_plugin_version.m_valid)
	{
		errstr = string("Could not parse version string from ") + version_str;
		return false;
	}

	// The required api version was already checked in
	// create_plugin to be valid and compatible. This just saves it for info/debugging.
	version_str = str_from_alloc_charbuf(m_plugin_info.get_required_api_version());
	m_required_api_version = sinsp_plugin::version(version_str);

	//
	// If filter fields are exported by the plugin, get the json from get_fields(),
	// parse it, create our list of fields, and create a filtercheck from the fields.
	//
	if(m_plugin_info.get_fields)
	{
		const char* sfields = m_plugin_info.get_fields();
		if(sfields == NULL)
		{
			throw sinsp_exception(string("error in plugin ") + m_name + ": get_fields returned a null string");
		}
		string json(sfields);
		SINSP_DEBUG("Parsing Fields JSON=%s", json.c_str());
		Json::Value root;
		if(Json::Reader().parse(json, root) == false || root.type() != Json::arrayValue)
		{
			throw sinsp_exception(string("error in plugin ") + m_name + ": get_fields returned an invalid JSON");
		}

		filtercheck_field_info *fields = new filtercheck_field_info[root.size()];
		if(fields == NULL)
		{
			throw sinsp_exception(string("error in plugin ") + m_name + ": could not allocate memory");
		}

		// Take ownership of the pointer right away so it can't be leaked.
		m_fields.reset(fields);
		m_nfields = root.size();

		for(Json::Value::ArrayIndex j = 0; j < root.size(); j++)
		{
			filtercheck_field_info &tf = m_fields.get()[j];
			tf.m_flags = EPF_NONE;

			const Json::Value &jvtype = root[j]["type"];
			string ftype = jvtype.asString();
			if(ftype == "")
			{
				throw sinsp_exception(string("error in plugin ") + m_name + ": field JSON entry has no type");
			}
			const Json::Value &jvname = root[j]["name"];
			string fname = jvname.asString();
			if(fname == "")
			{
				throw sinsp_exception(string("error in plugin ") + m_name + ": field JSON entry has no name");
			}
			const Json::Value &jvdisplay = root[j]["display"];
			string fdisplay = jvdisplay.asString();
			const Json::Value &jvdesc = root[j]["desc"];
			string fdesc = jvdesc.asString();
			if(fdesc == "")
			{
				throw sinsp_exception(string("error in plugin ") + m_name + ": field JSON entry has no desc");
			}

			strlcpy(tf.m_name, fname.c_str(), sizeof(tf.m_name));
			strlcpy(tf.m_display, fdisplay.c_str(), sizeof(tf.m_display));
			strlcpy(tf.m_description, fdesc.c_str(), sizeof(tf.m_description));
			tf.m_print_format = PF_DEC;
			if(ftype == "string")
			{
				tf.m_type = PT_CHARBUF;
			}
			else if(ftype == "uint64")
			{
				tf.m_type = PT_UINT64;
			}
			// XXX/mstemm are these actually supported?
			else if(ftype == "int64")
			{
				tf.m_type = PT_INT64;
			}
			else if(ftype == "float")
			{
				tf.m_type = PT_DOUBLE;
			}
			else
			{
				throw sinsp_exception(string("error in plugin ") + m_name + ": invalid field type " + ftype);
			}
			const Json::Value &jvargRequired = root[j].get("argRequired", Json::Value::null);
			if (!jvargRequired.isNull())
			{
				if (!jvargRequired.isBool())
				{
					throw sinsp_exception(string("error in plugin ") + m_name + ": field " + fname + " argRequired property is not boolean ");
				}

				if (jvargRequired.asBool() == true)
				{
					// All the extra casting is because this is the one flags value
					// that is strongly typed and not just an int.
					tf.m_flags = (filtercheck_field_flags) ((int) tf.m_flags | (int) filtercheck_field_flags::EPF_REQUIRES_ARGUMENT);
				}
			}

			const Json::Value &jvProperties = root[j].get("properties", Json::Value::null);
			if (!jvProperties.isNull())
			{
				if (!jvProperties.isArray())
				{
					throw sinsp_exception(string("error in plugin ") + m_name + ": field " + fname + " properties property is not array ");
				}

				for(Json::Value::ArrayIndex k = 0; k < jvProperties.size(); k++)
				{
					const Json::Value &prop = jvProperties[k];

					if (!prop.isString())
					{
						throw sinsp_exception(string("error in plugin ") + m_name + ": field " + fname + " properties value is not string ");
					}

					const std::string &str = prop.asString();

					// "hidden" is used inside and outside libs. "info" and "conversation" are used outside libs.
					if(str == "hidden")
					{
						tf.m_flags = (filtercheck_field_flags) ((int) tf.m_flags | (int) filtercheck_field_flags::EPF_TABLE_ONLY);
					}
					else if(str == "info")
					{
						tf.m_flags = (filtercheck_field_flags) ((int) tf.m_flags | (int) filtercheck_field_flags::EPF_INFO);
					}
					else if(str == "conversation")
					{
						tf.m_flags = (filtercheck_field_flags) ((int) tf.m_flags | (int) filtercheck_field_flags::EPF_CONVERSATION);
					}
				}
			}
		}

	}

	return true;
}

std::string sinsp_plugin::get_init_schema(ss_plugin_schema_type& schema_type)
{
	schema_type = SS_PLUGIN_SCHEMA_NONE;
	if (m_plugin_info.get_init_schema != NULL)
	{
		return str_from_alloc_charbuf(m_plugin_info.get_init_schema(&schema_type));
	}
	return std::string("");
}

void sinsp_plugin::validate_init_config(const char* config)
{
	ss_plugin_schema_type schema_type;
	std::string conf = str_from_alloc_charbuf(config);
	std::string schema = get_init_schema(schema_type);
	if (schema.size() > 0 && schema_type != SS_PLUGIN_SCHEMA_NONE)
	{
		switch (schema_type)
		{
			case SS_PLUGIN_SCHEMA_JSON:
				validate_init_config_json_schema(conf, schema);
				break;
			default:
				ASSERT(false);
				throw sinsp_exception(
					string("error in plugin ")
					+ name()
					+ ": get_init_schema returned an unknown schema type "
					+ to_string(schema_type));
		}
	}
}

void sinsp_plugin::validate_init_config_json_schema(std::string config, std::string &schema)
{
	Json::Value schemaJson;
	if(!Json::Reader().parse(schema, schemaJson) || schemaJson.type() != Json::objectValue)
	{
		throw sinsp_exception(
			string("error in plugin ")
			+ name()
			+ ": get_init_schema did not return a json object");
	}

	// stub empty configs to an empty json object
	if (config.size() == 0)
	{
		config = "{}";
	}
	Json::Value configJson;
	if(!Json::Reader().parse(config, configJson))
	{
		throw sinsp_exception(
			string("error in plugin ")
			+ name()
			+ ": init config is not a valid json");
	}

	// validate config with json schema
	valijson::Schema schemaDef;
	valijson::SchemaParser schemaParser;
	valijson::Validator validator;
	valijson::ValidationResults validationResults;
	valijson::adapters::JsonCppAdapter configAdapter(configJson);
	valijson::adapters::JsonCppAdapter schemaAdapter(schemaJson);
	schemaParser.populateSchema(schemaAdapter, schemaDef);
	if (!validator.validate(schemaDef, configAdapter, &validationResults))
	{
		valijson::ValidationResults::Error error;
		// report only the top-most error
		if (validationResults.popError(error))
		{
			throw sinsp_exception(
				string("error in plugin ")
				+ name()
				+ " init config: In "
				+ std::accumulate(error.context.begin(), error.context.end(), std::string(""))
				+ ", "
				+ error.description);
		}
		// validation failed with no specific error
		throw sinsp_exception(
			string("error in plugin ")
			+ name()
			+ " init config: failed parsing with provided schema");
	}
}

void sinsp_plugin::destroy_handle(sinsp_plugin_handle handle) {
#ifdef _WIN32
	FreeLibrary(handle);
#else
	dlclose(handle);
#endif
}

sinsp_source_plugin::sinsp_source_plugin(sinsp_plugin_handle handle) :
	sinsp_plugin(handle)
{
	memset(&m_source_plugin_info, 0, sizeof(m_source_plugin_info));
}

sinsp_source_plugin::~sinsp_source_plugin()
{
	close();
	destroy();
}

uint32_t sinsp_source_plugin::id()
{
	return m_id;
}

const std::string &sinsp_source_plugin::event_source()
{
	return m_event_source;
}

source_plugin_info *sinsp_source_plugin::plugin_info()
{
	return &m_source_plugin_info;
}

bool sinsp_source_plugin::open(const char *params, ss_plugin_rc &rc)
{
	ss_plugin_rc orc;

	if(!plugin_state())
	{
		return false;
	}

	m_source_plugin_info.handle = m_source_plugin_info.open(plugin_state(), params, &orc);

	rc = orc;

	return (m_source_plugin_info.handle != NULL);
}

void sinsp_source_plugin::close()
{
	if(!plugin_state() || !m_source_plugin_info.handle)
	{
		return;
	}

	m_source_plugin_info.close(plugin_state(), m_source_plugin_info.handle);
	m_source_plugin_info.handle = NULL;
}

std::string sinsp_source_plugin::get_progress(uint32_t &progress_pct)
{
	std::string ret;
	progress_pct = 0;

	if(!m_source_plugin_info.get_progress || !m_source_plugin_info.handle)
	{
		return ret;
	}

	uint32_t ppct;
	ret = str_from_alloc_charbuf(m_source_plugin_info.get_progress(plugin_state(), m_source_plugin_info.handle, &ppct));

	progress_pct = ppct;

	return ret;
}

std::string sinsp_source_plugin::event_to_string(const uint8_t *data, uint32_t datalen)
{
	std::string ret = "<NA>";

	if (!m_source_plugin_info.event_to_string)
	{
		return ret;
	}

	ret = str_from_alloc_charbuf(m_source_plugin_info.event_to_string(plugin_state(), data, datalen));

	return ret;
}

std::vector<sinsp_source_plugin::open_param> sinsp_source_plugin::list_open_params()
{
	std::vector<sinsp_source_plugin::open_param> list;
	if(plugin_state() && m_source_plugin_info.list_open_params)
	{
		ss_plugin_rc rc;
		string jsonString = str_from_alloc_charbuf(m_source_plugin_info.list_open_params(plugin_state(), &rc));
		if (rc != SS_PLUGIN_SUCCESS)
		{
			throw sinsp_exception(string("error in plugin ") + name() + ": list_open_params has error " + get_last_error());
		}

		if (jsonString.size() > 0)
		{
			Json::Value root;
			if(Json::Reader().parse(jsonString, root) == false || root.type() != Json::arrayValue)
			{
				throw sinsp_exception(string("error in plugin ") + name() + ": list_open_params returned a non-array JSON");
			}
			for(Json::Value::ArrayIndex i = 0; i < root.size(); i++)
			{
				sinsp_source_plugin::open_param param;
				param.value = root[i]["value"].asString();
				if(param.value == "")
				{
					throw sinsp_exception(string("error in plugin ") + name() + ": list_open_params has entry with no value");
				}
				param.desc = root[i]["desc"].asString();
				list.push_back(param);
			}
		}
	}

	return list;
}

void sinsp_source_plugin::set_plugin_state(ss_plugin_t *state)
{
	m_source_plugin_info.state = state;
}

ss_plugin_t *sinsp_source_plugin::plugin_state()
{
	return m_source_plugin_info.state;
}

bool sinsp_source_plugin::resolve_dylib_symbols(std::string &errstr)
{
	if (!sinsp_plugin::resolve_dylib_symbols(errstr))
	{
		return false;
	}

	// We resolve every symbol, even those that are not actually
	// used by this derived class, just to ensure that
	// m_source_plugin_info is complete. (The struct can be passed
	// down to libscap when reading/writing capture files).
	//
	// Some functions are required and return false if not found.
	if((*(void **) (&(m_source_plugin_info.get_required_api_version)) = getsym(m_handle, "plugin_get_required_api_version", errstr)) == NULL ||
	   (*(void **) (&(m_source_plugin_info.init)) = getsym(m_handle, "plugin_init", errstr)) == NULL ||
	   (*(void **) (&(m_source_plugin_info.destroy)) = getsym(m_handle, "plugin_destroy", errstr)) == NULL ||
	   (*(void **) (&(m_source_plugin_info.get_last_error)) = getsym(m_handle, "plugin_get_last_error", errstr)) == NULL ||
	   (*(void **) (&(m_source_plugin_info.get_type)) = getsym(m_handle, "plugin_get_type", errstr)) == NULL ||
	   (*(void **) (&(m_source_plugin_info.get_id)) = getsym(m_handle, "plugin_get_id", errstr)) == NULL ||
	   (*(void **) (&(m_source_plugin_info.get_name)) = getsym(m_handle, "plugin_get_name", errstr)) == NULL ||
	   (*(void **) (&(m_source_plugin_info.get_description)) = getsym(m_handle, "plugin_get_description", errstr)) == NULL ||
	   (*(void **) (&(m_source_plugin_info.get_contact)) = getsym(m_handle, "plugin_get_contact", errstr)) == NULL ||
	   (*(void **) (&(m_source_plugin_info.get_version)) = getsym(m_handle, "plugin_get_version", errstr)) == NULL ||
	   (*(void **) (&(m_source_plugin_info.get_event_source)) = getsym(m_handle, "plugin_get_event_source", errstr)) == NULL ||
	   (*(void **) (&(m_source_plugin_info.open)) = getsym(m_handle, "plugin_open", errstr)) == NULL ||
	   (*(void **) (&(m_source_plugin_info.close)) = getsym(m_handle, "plugin_close", errstr)) == NULL ||
	   (*(void **) (&(m_source_plugin_info.next_batch)) = getsym(m_handle, "plugin_next_batch", errstr)) == NULL ||
	   (*(void **) (&(m_source_plugin_info.event_to_string)) = getsym(m_handle, "plugin_event_to_string", errstr)) == NULL)
	{
		return false;
	}

	// Others are not.
	(*(void **) (&m_source_plugin_info.get_fields)) = getsym(m_handle, "plugin_get_fields", errstr);
	(*(void **) (&m_source_plugin_info.get_progress)) = getsym(m_handle, "plugin_get_progress", errstr);
	(*(void **) (&m_source_plugin_info.event_to_string)) = getsym(m_handle, "plugin_event_to_string", errstr);
	(*(void **) (&m_source_plugin_info.extract_fields)) = getsym(m_handle, "plugin_extract_fields", errstr);
	(*(void **) (&m_source_plugin_info.list_open_params)) = getsym(m_handle, "plugin_list_open_params", errstr);
	(*(void **) (&m_source_plugin_info.get_init_schema)) = getsym(m_handle, "plugin_get_init_schema", errstr);

	m_id = m_source_plugin_info.get_id();
	m_event_source = str_from_alloc_charbuf(m_source_plugin_info.get_event_source());

	return true;
}

sinsp_extractor_plugin::sinsp_extractor_plugin(sinsp_plugin_handle handle) :
	sinsp_plugin(handle)
{
	memset(&m_extractor_plugin_info, 0, sizeof(m_extractor_plugin_info));
}

sinsp_extractor_plugin::~sinsp_extractor_plugin()
{
	destroy();
}

const std::set<std::string> &sinsp_extractor_plugin::extract_event_sources()
{
	return m_extract_event_sources;
}

bool sinsp_extractor_plugin::source_compatible(const std::string &source)
{
	return(m_extract_event_sources.size() == 0 ||
	       m_extract_event_sources.find(source) != m_extract_event_sources.end());
}

void sinsp_extractor_plugin::set_plugin_state(ss_plugin_t *state)
{
	m_extractor_plugin_info.state = state;
}

ss_plugin_t *sinsp_extractor_plugin::plugin_state()
{
	return m_extractor_plugin_info.state;
}

bool sinsp_extractor_plugin::resolve_dylib_symbols(std::string &errstr)
{
	if (!sinsp_plugin::resolve_dylib_symbols(errstr))
	{
		return false;
	}

	// We resolve every symbol, even those that are not actually
	// used by this derived class, just to ensure that
	// m_extractor_plugin_info is complete. (The struct can be passed
	// down to libscap when reading/writing capture files).
	//
	// Some functions are required and return false if not found.
	if((*(void **) (&(m_extractor_plugin_info.get_required_api_version)) = getsym(m_handle, "plugin_get_required_api_version", errstr)) == NULL ||
	   (*(void **) (&(m_extractor_plugin_info.init)) = getsym(m_handle, "plugin_init", errstr)) == NULL ||
	   (*(void **) (&(m_extractor_plugin_info.destroy)) = getsym(m_handle, "plugin_destroy", errstr)) == NULL ||
	   (*(void **) (&(m_extractor_plugin_info.get_last_error)) = getsym(m_handle, "plugin_get_last_error", errstr)) == NULL ||
	   (*(void **) (&(m_extractor_plugin_info.get_type)) = getsym(m_handle, "plugin_get_type", errstr)) == NULL ||
	   (*(void **) (&(m_extractor_plugin_info.get_name)) = getsym(m_handle, "plugin_get_name", errstr)) == NULL ||
	   (*(void **) (&(m_extractor_plugin_info.get_description)) = getsym(m_handle, "plugin_get_description", errstr)) == NULL ||
	   (*(void **) (&(m_extractor_plugin_info.get_contact)) = getsym(m_handle, "plugin_get_contact", errstr)) == NULL ||
	   (*(void **) (&(m_extractor_plugin_info.get_version)) = getsym(m_handle, "plugin_get_version", errstr)) == NULL ||
	   (*(void **) (&(m_extractor_plugin_info.get_fields)) = getsym(m_handle, "plugin_get_fields", errstr)) == NULL ||
	   (*(void **) (&(m_extractor_plugin_info.extract_fields)) = getsym(m_handle, "plugin_extract_fields", errstr)) == NULL)
	{
		return false;
	}

	// Others are not.
	(*(void **) (&m_extractor_plugin_info.get_extract_event_sources)) = getsym(m_handle, "plugin_get_extract_event_sources", errstr);
	(*(void **) (&m_extractor_plugin_info.get_init_schema)) = getsym(m_handle, "plugin_get_init_schema", errstr);


	if (m_extractor_plugin_info.get_extract_event_sources != NULL)
	{
		std::string esources = str_from_alloc_charbuf(m_extractor_plugin_info.get_extract_event_sources());

		if (esources.length() == 0)
		{
			throw sinsp_exception(string("error in plugin ") + name() + ": get_extract_event_sources returned an empty string");
		}

		Json::Value root;
		if(Json::Reader().parse(esources, root) == false || root.type() != Json::arrayValue)
		{
			throw sinsp_exception(string("error in plugin ") + name() + ": get_extract_event_sources did not return a json array");
		}

		for(Json::Value::ArrayIndex j = 0; j < root.size(); j++)
		{
			if(! root[j].isConvertibleTo(Json::stringValue))
			{
				throw sinsp_exception(string("error in plugin ") + name() + ": get_extract_event_sources did not return a json array");
			}

			m_extract_event_sources.insert(root[j].asString());
		}
	}

	return true;
}