-
Notifications
You must be signed in to change notification settings - Fork 156
/
sinsp.cpp
2899 lines (2527 loc) · 68.6 KB
/
sinsp.cpp
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
// SPDX-License-Identifier: Apache-2.0
/*
Copyright (C) 2023 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.
*/
#include <stdio.h>
#include <stdlib.h>
#ifndef _WIN32
#include <unistd.h>
#include <sys/stat.h>
#include <sys/mman.h>
#include <fcntl.h>
#include <poll.h>
#include <sys/time.h>
#endif // _WIN32
#include "scap_open_exception.h"
#include "sinsp.h"
#include "sinsp_int.h"
#include "sinsp_auth.h"
#include "filter.h"
#include "filterchecks.h"
#include "cyclewriter.h"
#include "protodecoder.h"
#include "dns_manager.h"
#include "plugin.h"
#include "plugin_manager.h"
#include "plugin_filtercheck.h"
#include "strl.h"
#if !defined(CYGWING_AGENT)
#if !defined(MINIMAL_BUILD) && !defined(__EMSCRIPTEN__)
#include "k8s_api_handler.h"
#if defined(HAS_CAPTURE)
#include <curl/curl.h>
#endif // defined(HAS_CAPTURE)
#else // !defined(MINIMAL_BUILD) && !defined(__EMSCRIPTEN__)
struct k8s_api_handler{}; // note: makes the unique_ptr static asserts happy
#endif // !defined(MINIMAL_BUILD) && !defined(__EMSCRIPTEN__)
#endif // !defined(CYGWING_AGENT)
#ifdef GATHER_INTERNAL_STATS
#include "stats.h"
#else // GATHER_INTERNAL_STATS
struct sinsp_stats{}; // note: makes the unique_ptr static asserts happy
#endif // GATHER_INTERNAL_STATS
#ifdef HAS_ANALYZER
#include "analyzer_int.h"
#include "analyzer.h"
#include "tracer_emitter.h"
#endif
void on_new_entry_from_proc(void* context, int64_t tid, scap_threadinfo* tinfo,
scap_fdinfo* fdinfo);
///////////////////////////////////////////////////////////////////////////////
// sinsp implementation
///////////////////////////////////////////////////////////////////////////////
std::atomic<int> sinsp::instance_count{0};
sinsp::sinsp(bool static_container, const std::string &static_id, const std::string &static_name, const std::string &static_image) :
m_external_event_processor(),
m_evt(this),
m_lastevent_ts(0),
m_host_root(scap_get_host_root()),
m_container_manager(this, static_container, static_id, static_name, static_image),
m_usergroup_manager(this),
m_k8s_api_handler(nullptr),
m_k8s_ext_handler(nullptr),
m_stats(nullptr),
m_suppressed_comms(),
m_inited(false)
{
++instance_count;
#if !defined(MINIMAL_BUILD) && !defined(CYGWING_AGENT) && !defined(__EMSCRIPTEN__) && defined(HAS_CAPTURE)
// used by mesos and container_manager
curl_global_init(CURL_GLOBAL_DEFAULT);
#endif
m_h = NULL;
m_parser = NULL;
m_is_dumping = false;
m_metaevt = NULL;
m_meinfo.m_piscapevt = NULL;
m_parser = new sinsp_parser(this);
m_thread_manager = new sinsp_thread_manager(this);
m_max_fdtable_size = MAX_FD_TABLE_SIZE;
m_inactive_container_scan_time_ns = DEFAULT_INACTIVE_CONTAINER_SCAN_TIME_S * ONE_SECOND_IN_NS;
m_deleted_users_groups_scan_time_ns = DEFAULT_DELETED_USERS_GROUPS_SCAN_TIME_S * ONE_SECOND_IN_NS;
m_cycle_writer = NULL;
m_write_cycling = false;
m_filter = NULL;
m_fds_to_remove = new std::vector<int64_t>;
m_machine_info = NULL;
m_agent_info = NULL;
#ifdef SIMULATE_DROP_MODE
m_isdropping = false;
#endif
m_snaplen = DEFAULT_SNAPLEN;
m_buffer_format = sinsp_evt::PF_NORMAL;
m_input_fd = 0;
m_isdebug_enabled = false;
m_isfatfile_enabled = false;
m_isinternal_events_enabled = false;
m_hostname_and_port_resolution_enabled = false;
m_output_time_flag = 'h';
m_max_evt_output_len = 0;
m_filesize = -1;
m_track_tracers_state = false;
m_next_flush_time_ns = 0;
m_last_procrequest_tod = 0;
m_get_procs_cpu_from_driver = false;
m_is_tracers_capture_enabled = false;
m_flush_memory_dump = false;
m_next_stats_print_time_ns = 0;
m_large_envs_enabled = false;
m_increased_snaplen_port_range = DEFAULT_INCREASE_SNAPLEN_PORT_RANGE;
m_statsd_port = -1;
// Unless the cmd line arg "-pc" or "-pcontainer" is supplied this is false
m_print_container_data = false;
#if defined(HAS_CAPTURE)
m_self_pid = getpid();
#endif
#ifdef GATHER_INTERNAL_STATS
m_stats = std::make_unique<sinsp_stats()>;
#endif
m_proc_scan_timeout_ms = SCAP_PROC_SCAN_TIMEOUT_NONE;
m_proc_scan_log_interval_ms = SCAP_PROC_SCAN_LOG_NONE;
uint32_t evlen = sizeof(scap_evt) + 2 * sizeof(uint16_t) + 2 * sizeof(uint64_t);
m_meinfo.m_piscapevt = (scap_evt*)new char[evlen];
m_meinfo.m_piscapevt->type = PPME_PROCINFO_E;
m_meinfo.m_piscapevt->len = evlen;
m_meinfo.m_piscapevt->nparams = 2;
uint16_t* lens = (uint16_t*)((char *)m_meinfo.m_piscapevt + sizeof(struct ppm_evt_hdr));
lens[0] = 8;
lens[1] = 8;
m_meinfo.m_piscapevt_vals = (uint64_t*)(lens + 2);
m_meinfo.m_pievt.m_inspector = this;
m_meinfo.m_pievt.m_info = &(g_infotables.m_event_info[PPME_SCAPEVENT_X]);
m_meinfo.m_pievt.m_pevt = NULL;
m_meinfo.m_pievt.m_cpuid = 0;
m_meinfo.m_pievt.m_evtnum = 0;
m_meinfo.m_pievt.m_pevt = m_meinfo.m_piscapevt;
m_meinfo.m_pievt.m_fdinfo = NULL;
m_meinfo.m_n_procinfo_evts = 0;
m_meta_event_callback = NULL;
m_meta_event_callback_data = NULL;
#if !defined(CYGWING_AGENT) && !defined(MINIMAL_BUILD) && !defined(__EMSCRIPTEN__)
m_k8s_client = NULL;
m_k8s_last_watch_time_ns = 0;
m_k8s_client = NULL;
m_k8s_api_server = NULL;
m_k8s_api_cert = NULL;
m_mesos_client = NULL;
m_mesos_last_watch_time_ns = 0;
#endif // !defined(CYGWING_AGENT) && !defined(MINIMAL_BUILD)
m_replay_scap_evt = NULL;
// the "syscall" event source is implemented by sinsp itself
// and is always present
m_plugin_parsers.clear();
m_event_sources.push_back(sinsp_syscall_event_source_name);
m_plugin_manager = std::make_shared<sinsp_plugin_manager>(m_event_sources);
// create state tables registry
m_table_registry = std::make_shared<libsinsp::state::table_registry>();
m_table_registry->add_table(m_thread_manager);
}
sinsp::~sinsp()
{
close();
if(m_fds_to_remove)
{
delete m_fds_to_remove;
}
if(m_parser)
{
delete m_parser;
m_parser = NULL;
}
if(m_thread_manager)
{
delete m_thread_manager;
m_thread_manager = NULL;
}
if(m_cycle_writer)
{
delete m_cycle_writer;
m_cycle_writer = NULL;
}
if(m_meinfo.m_piscapevt)
{
delete[] m_meinfo.m_piscapevt;
}
m_container_manager.cleanup();
#if !defined(CYGWING_AGENT) && !defined(MINIMAL_BUILD) && !defined(__EMSCRIPTEN__)
delete m_k8s_client;
delete m_k8s_api_server;
delete m_k8s_api_cert;
delete m_mesos_client;
#ifdef HAS_CAPTURE
curl_global_cleanup();
if (--instance_count == 0)
{
sinsp_dns_manager::get().cleanup();
}
#endif
#endif
}
void sinsp::add_protodecoders()
{
m_parser->add_protodecoder("syslog");
}
void sinsp::enable_tracers_capture()
{
#if defined(HAS_CAPTURE) && ! defined(CYGWING_AGENT) && ! defined(_WIN32)
if(!m_is_tracers_capture_enabled)
{
if(is_live() && m_h != NULL)
{
if(scap_enable_tracers_capture(m_h) != SCAP_SUCCESS)
{
throw sinsp_exception("error enabling tracers capture");
}
}
m_is_tracers_capture_enabled = true;
}
#endif
}
bool sinsp::is_initialstate_event(scap_evt* pevent)
{
return pevent->type == PPME_CONTAINER_E ||
pevent->type == PPME_CONTAINER_JSON_E ||
pevent->type == PPME_CONTAINER_JSON_2_E ||
pevent->type == PPME_USER_ADDED_E ||
pevent->type == PPME_USER_DELETED_E ||
pevent->type == PPME_GROUP_ADDED_E ||
pevent->type == PPME_GROUP_DELETED_E;
}
void sinsp::consume_initialstate_events()
{
scap_evt* pevent;
uint16_t pcpuid;
sinsp_evt* tevt;
uint32_t flags;
if (m_external_event_processor)
{
m_external_event_processor->on_capture_start();
}
//
// Consume every state event we have
//
while(true)
{
int32_t res = scap_next(m_h, &pevent, &pcpuid, &flags);
if(res == SCAP_SUCCESS)
{
// Setting these to non-null will make sinsp::next use them as a scap event
// to avoid a call to scap_next. In this way, we can avoid the state parsing phase
// once we reach a container-unrelated event.
m_replay_scap_evt = pevent;
m_replay_scap_cpuid = pcpuid;
m_replay_scap_flags = flags;
if(!is_initialstate_event(pevent))
{
break;
}
else
{
next(&tevt);
continue;
}
}
else
{
break;
}
}
}
void sinsp::init()
{
//
// Retrieve machine information
//
m_machine_info = scap_get_machine_info(m_h);
if(m_machine_info != NULL)
{
m_num_cpus = m_machine_info->num_cpus;
}
else
{
ASSERT(false);
m_num_cpus = 0;
}
//
// Retrieve agent information
//
m_agent_info = scap_get_agent_info(m_h);
if (m_agent_info == NULL)
{
ASSERT(false);
}
//
// Attach the protocol decoders
//
#ifndef HAS_ANALYZER
add_protodecoders();
#endif
//
// Allocate the cycle writer
//
if(m_cycle_writer)
{
delete m_cycle_writer;
m_cycle_writer = NULL;
}
m_cycle_writer = new cycle_writer(!is_offline());
//
// Basic inits
//
#ifdef GATHER_INTERNAL_STATS
m_stats->clear();
#endif
m_nevts = 0;
m_tid_to_remove = -1;
m_lastevent_ts = 0;
m_firstevent_ts = 0;
m_fds_to_remove->clear();
//
// Return the tracers to the pool and clear the tracers list
//
for(auto it = m_partial_tracers_list.begin(); it != m_partial_tracers_list.end(); ++it)
{
m_partial_tracers_pool->push(*it);
}
m_partial_tracers_list.clear();
//
// If we're reading from file, we try to pre-parse the container events before
// importing the thread table, so that thread table filtering will work with
// container filters
//
if(is_capture())
{
consume_initialstate_events();
}
if(is_capture())
{
import_thread_table();
}
import_ifaddr_list();
import_user_list();
/* Create parent/child dependencies */
m_thread_manager->create_thread_dependencies_after_proc_scan();
//
// Scan the list to fix the direction of the sockets
//
m_thread_manager->fix_sockets_coming_from_proc();
// If we are in capture, this is already called by consume_initialstate_events
if (!is_capture() && m_external_event_processor)
{
m_external_event_processor->on_capture_start();
}
//
// If m_snaplen was modified, we set snaplen now
//
if(m_snaplen != DEFAULT_SNAPLEN)
{
set_snaplen(m_snaplen);
}
//
// If the port range for increased snaplen was modified, set it now
//
#ifndef _WIN32
if(increased_snaplen_port_range_set())
{
set_fullcapture_port_range(m_increased_snaplen_port_range.range_start,
m_increased_snaplen_port_range.range_end);
}
#endif
//
// If the statsd port was modified, push it to the kernel now.
//
if(m_statsd_port != -1)
{
set_statsd_port(m_statsd_port);
}
#if defined(HAS_CAPTURE)
if(is_live())
{
int32_t res = scap_getpid_global(m_h, &m_self_pid);
ASSERT(res == SCAP_SUCCESS || res == SCAP_NOT_SUPPORTED);
(void)res;
}
#endif
m_inited = true;
}
void sinsp::set_import_users(bool import_users)
{
m_usergroup_manager.m_import_users = import_users;
}
/*=============================== OPEN METHODS ===============================*/
void sinsp::open_common(scap_open_args* oargs)
{
g_logger.log("Trying to open the right engine!");
/* Reset the thread manager */
m_thread_manager->clear();
/* We need to save the actual mode and the engine used by the inspector. */
m_mode = oargs->mode;
if(oargs->mode != SCAP_MODE_CAPTURE)
{
oargs->proc_callback = ::on_new_entry_from_proc;
oargs->proc_callback_context = this;
}
oargs->import_users = m_usergroup_manager.m_import_users;
// We need to subscribe to container manager notifiers before
// scap starts scanning proc.
m_usergroup_manager.subscribe_container_mgr();
add_suppressed_comms(oargs);
oargs->log_fn = &sinsp_scap_log_fn;
oargs->proc_scan_timeout_ms = m_proc_scan_timeout_ms;
oargs->proc_scan_log_interval_ms = m_proc_scan_log_interval_ms;
m_h = scap_alloc();
if(m_h == NULL)
{
throw scap_open_exception("failed to allocate scap handle", SCAP_FAILURE);
}
int32_t scap_rc = scap_init(m_h, oargs);
if(scap_rc != SCAP_SUCCESS)
{
std::string error = scap_getlasterr(m_h);
scap_close(m_h);
m_h = NULL;
if(error.empty())
{
error = "Initialization issues during scap_init";
}
throw scap_open_exception(error, scap_rc);
}
init();
// enable generation of async meta-events for all loaded plugins supporting
// that capability. Meta-events are considered only during live captures,
// because offline captures will have the async events already encoded
// in the event stream.
if (!is_capture())
{
// note(jasondellaluce,rohith-raju): for now the emscripten build does not support
// tbb queues, so async event production is disabled
#ifndef __EMSCRIPTEN__
for (auto& p : m_plugin_manager->plugins())
{
if (p->caps() & CAP_ASYNC)
{
auto res = p->set_async_event_handler([this](auto& p, auto e){
this->handle_plugin_async_event(p, std::move(e));
});
if (!res)
{
throw sinsp_exception("can't set async event handler for plugin '"
+ p->name() + "' : " + p->get_last_error());
}
}
}
#endif
}
}
scap_open_args sinsp::factory_open_args(const char* engine_name, scap_mode_t scap_mode)
{
scap_open_args oargs{};
oargs.engine_name = engine_name;
oargs.mode = scap_mode;
return oargs;
}
void sinsp::mark_ppm_sc_of_interest(ppm_sc_code ppm_sc, bool enable)
{
/* This API must be used only after the initialization phase. */
if (!m_inited)
{
throw sinsp_exception("you cannot use this method before opening the inspector!");
}
if (ppm_sc >= PPM_SC_MAX)
{
throw sinsp_exception("inexistent ppm_sc code: " + std::to_string(ppm_sc));
}
int ret = scap_set_ppm_sc(m_h, ppm_sc, enable);
if (ret != SCAP_SUCCESS)
{
throw sinsp_exception(scap_getlasterr(m_h));
}
}
static void fill_ppm_sc_of_interest(scap_open_args *oargs, const libsinsp::events::set<ppm_sc_code> &ppm_sc_of_interest)
{
for (int i = 0; i < PPM_SC_MAX; i++)
{
/* If the set is empty, fallback to all interesting syscalls */
if (ppm_sc_of_interest.empty())
{
oargs->ppm_sc_of_interest.ppm_sc[i] = true;
}
else
{
oargs->ppm_sc_of_interest.ppm_sc[i] = ppm_sc_of_interest.contains((ppm_sc_code)i);
}
}
}
void sinsp::open_kmod(unsigned long driver_buffer_bytes_dim, const libsinsp::events::set<ppm_sc_code> &ppm_sc_of_interest)
{
scap_open_args oargs = factory_open_args(KMOD_ENGINE, SCAP_MODE_LIVE);
/* Set interesting syscalls and tracepoints. */
fill_ppm_sc_of_interest(&oargs, ppm_sc_of_interest);
/* Engine-specific args. */
struct scap_kmod_engine_params params;
params.buffer_bytes_dim = driver_buffer_bytes_dim;
oargs.engine_params = ¶ms;
open_common(&oargs);
}
void sinsp::open_bpf(const std::string& bpf_path, unsigned long driver_buffer_bytes_dim, const libsinsp::events::set<ppm_sc_code> &ppm_sc_of_interest)
{
/* Validate the BPF path. */
if(bpf_path.empty())
{
throw sinsp_exception("When you use the 'BPF' engine you need to provide a path to the bpf object file.");
}
scap_open_args oargs = factory_open_args(BPF_ENGINE, SCAP_MODE_LIVE);
/* Set interesting syscalls and tracepoints. */
fill_ppm_sc_of_interest(&oargs, ppm_sc_of_interest);
/* Engine-specific args. */
struct scap_bpf_engine_params params;
params.buffer_bytes_dim = driver_buffer_bytes_dim;
params.bpf_probe = bpf_path.data();
oargs.engine_params = ¶ms;
open_common(&oargs);
}
void sinsp::open_udig()
{
scap_open_args oargs = factory_open_args(UDIG_ENGINE, SCAP_MODE_LIVE);
open_common(&oargs);
}
void sinsp::open_nodriver(bool full_proc_scan)
{
scap_open_args oargs = factory_open_args(NODRIVER_ENGINE, SCAP_MODE_NODRIVER);
struct scap_nodriver_engine_params params;
params.full_proc_scan = full_proc_scan;
oargs.engine_params = ¶ms;
open_common(&oargs);
}
void sinsp::open_savefile(const std::string& filename, int fd)
{
scap_open_args oargs = factory_open_args(SAVEFILE_ENGINE, SCAP_MODE_CAPTURE);
struct scap_savefile_engine_params params;
m_input_filename = filename;
m_input_fd = fd; /* default is 0. */
if(m_input_fd != 0)
{
/* In this case, we can't get a reliable filesize */
params.fd = m_input_fd;
params.fname = NULL;
m_filesize = 0;
}
else
{
if(filename.empty())
{
throw sinsp_exception("When you use the 'savefile' engine you need to provide a path to the file.");
}
params.fname = filename.c_str();
params.fd = 0;
char error[SCAP_LASTERR_SIZE] = {0};
m_filesize = get_file_size(params.fname, error);
if(m_filesize < 0)
{
throw sinsp_exception(error);
}
}
params.start_offset = 0;
params.fbuffer_size = 0;
oargs.engine_params = ¶ms;
open_common(&oargs);
}
void sinsp::open_plugin(const std::string& plugin_name, const std::string& plugin_open_params, scap_mode_t mode)
{
scap_open_args oargs = factory_open_args(SOURCE_PLUGIN_ENGINE, mode);
struct scap_source_plugin_engine_params params;
set_input_plugin(plugin_name, plugin_open_params);
params.input_plugin = &m_input_plugin->as_scap_source();
params.input_plugin_params = (char*)m_input_plugin_open_params.c_str();
oargs.engine_params = ¶ms;
open_common(&oargs);
}
void sinsp::open_gvisor(const std::string& config_path, const std::string& root_path, bool no_events, int epoll_timeout)
{
if(config_path.empty())
{
throw sinsp_exception("When you use the 'gvisor' engine you need to provide a path to the config file.");
}
scap_open_args oargs = factory_open_args(GVISOR_ENGINE, SCAP_MODE_LIVE);
struct scap_gvisor_engine_params params;
params.gvisor_root_path = root_path.c_str();
params.gvisor_config_path = config_path.c_str();
params.no_events = no_events;
params.gvisor_epoll_timeout = epoll_timeout;
oargs.engine_params = ¶ms;
open_common(&oargs);
set_get_procs_cpu_from_driver(false);
}
void sinsp::open_modern_bpf(unsigned long driver_buffer_bytes_dim, uint16_t cpus_for_each_buffer, bool online_only, const libsinsp::events::set<ppm_sc_code> &ppm_sc_of_interest)
{
scap_open_args oargs = factory_open_args(MODERN_BPF_ENGINE, SCAP_MODE_LIVE);
/* Set interesting syscalls and tracepoints. */
fill_ppm_sc_of_interest(&oargs, ppm_sc_of_interest);
/* Engine-specific args. */
struct scap_modern_bpf_engine_params params;
params.buffer_bytes_dim = driver_buffer_bytes_dim;
params.cpus_for_each_buffer = cpus_for_each_buffer;
params.allocate_online_only = online_only;
params.verbose = g_logger.has_output() && g_logger.is_enabled(sinsp_logger::severity::SEV_DEBUG);
oargs.engine_params = ¶ms;
open_common(&oargs);
}
void sinsp::open_test_input(scap_test_input_data* data, scap_mode_t mode)
{
scap_open_args oargs = factory_open_args(TEST_INPUT_ENGINE, mode);
struct scap_test_input_engine_params params;
params.test_input_data = data;
oargs.engine_params = ¶ms;
open_common(&oargs);
set_get_procs_cpu_from_driver(false);
}
/*=============================== OPEN METHODS ===============================*/
/*=============================== Engine related ===============================*/
bool sinsp::check_current_engine(const std::string& engine_name)
{
return scap_check_current_engine(m_h, engine_name.data());
}
/*=============================== Engine related ===============================*/
std::string sinsp::generate_gvisor_config(std::string socket_path)
{
return gvisor_config::generate(socket_path);
}
int64_t sinsp::get_file_size(const std::string& fname, char *error)
{
static std::string err_str = "Could not determine capture file size: ";
std::string errdesc;
#ifdef _WIN32
LARGE_INTEGER li = { 0 };
HANDLE fh = CreateFile(fname.c_str(), GENERIC_READ, FILE_SHARE_READ, NULL,
OPEN_EXISTING, FILE_ATTRIBUTE_READONLY, NULL);
if (fh != INVALID_HANDLE_VALUE)
{
if (0 != GetFileSizeEx(fh, &li))
{
CloseHandle(fh);
return li.QuadPart;
}
errdesc = get_error_desc(err_str);
CloseHandle(fh);
}
#else
struct stat st;
if (0 == stat(fname.c_str(), &st))
{
return st.st_size;
}
#endif
if(errdesc.empty()) errdesc = get_error_desc(err_str);
strlcpy(error, errdesc.c_str(), SCAP_LASTERR_SIZE);
return -1;
}
unsigned sinsp::m_num_possible_cpus = 0;
unsigned sinsp::num_possible_cpus()
{
if(m_num_possible_cpus == 0)
{
m_num_possible_cpus = read_num_possible_cpus();
if(m_num_possible_cpus == 0)
{
g_logger.log("Unable to read num_possible_cpus, falling back to 128", sinsp_logger::SEV_WARNING);
m_num_possible_cpus = 128;
}
}
return m_num_possible_cpus;
}
std::vector<long> sinsp::get_n_tracepoint_hit()
{
std::vector<long> ret(num_possible_cpus(), 0);
if(scap_get_n_tracepoint_hit(m_h, ret.data()) != SCAP_SUCCESS)
{
throw sinsp_exception(scap_getlasterr(m_h));
}
return ret;
}
std::string sinsp::get_error_desc(const std::string& msg)
{
#ifdef _WIN32
DWORD err_no = GetLastError(); // first, so error is not wiped out by intermediate calls
std::string errstr = msg;
DWORD flg = FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS;
LPTSTR msg_buf = 0;
if(FormatMessageA(flg, 0, err_no, 0, (LPTSTR)&msg_buf, 0, NULL))
if(msg_buf)
{
errstr.append(msg_buf, strlen(msg_buf));
LocalFree(msg_buf);
}
#else
char* msg_buf = strerror(errno); // first, so error is not wiped out by intermediate calls
std::string errstr = msg;
if(msg_buf)
{
errstr.append(msg_buf, strlen(msg_buf));
}
#endif
return errstr;
}
void sinsp::close()
{
if(m_h)
{
scap_close(m_h);
m_h = NULL;
}
if(m_dumper != nullptr)
{
m_dumper->close();
m_dumper.reset(nullptr);
}
m_is_dumping = false;
deinit_state();
if(m_filter != NULL)
{
delete m_filter;
m_filter = NULL;
}
// unset the meta-event callback to all plugins that support it
if (!is_capture() && m_mode != SCAP_MODE_NONE)
{
std::string err;
// note(jasondellaluce,rohith-raju): for now the emscripten build does not support
// tbb queues, so async event production is disabled
#ifndef __EMSCRIPTEN__
for (auto& p : m_plugin_manager->plugins())
{
if (p->caps() & CAP_ASYNC)
{
// collect errors but let's make sure we reset all the handlers
// event in case of one failure.
auto res = p->set_async_event_handler(nullptr);
if (!res)
{
err += err.empty() ? "" : ", ";
err += "can't reset async event handler for plugin '"
+ p->name() + "' : " + p->get_last_error();
}
}
}
#endif
if (!err.empty())
{
throw sinsp_exception(err);
}
}
m_mode = SCAP_MODE_NONE;
}
//
// This deinitializes the sinsp internal state, and it's used
// internally while closing or restarting the capture.
//
void sinsp::deinit_state()
{
m_network_interfaces.clear();
m_thread_manager->clear();
}
void sinsp::autodump_start(const std::string& dump_filename, bool compress)
{
if(NULL == m_h)
{
throw sinsp_exception("inspector not opened yet");
}
std::unique_ptr<sinsp_dumper> dumper(new sinsp_dumper);
if(compress)
{
dumper->open(this, dump_filename.c_str(), SCAP_COMPRESSION_GZIP, false);
}
else
{
dumper->open(this, dump_filename.c_str(), SCAP_COMPRESSION_NONE, false);
}
m_is_dumping = true;
m_dumper = std::move(dumper);
m_container_manager.dump_containers(*m_dumper);
m_usergroup_manager.dump_users_groups(*m_dumper);
}
void sinsp::autodump_next_file()
{
autodump_stop();
autodump_start(m_cycle_writer->get_current_file_name(), m_compress);
}
void sinsp::autodump_stop()
{
if(NULL == m_h)
{
throw sinsp_exception("inspector not opened yet");
}
if(m_dumper != NULL)
{
m_dumper->close();
m_dumper = NULL;
}
m_is_dumping = false;
}
void sinsp::on_new_entry_from_proc(void* context,
int64_t tid,
scap_threadinfo* tinfo,
scap_fdinfo* fdinfo)
{
ASSERT(tinfo != NULL);
//
// Retrieve machine information if we don't have it yet
//
{
m_machine_info = scap_get_machine_info(m_h);
if(m_machine_info != NULL)
{
m_num_cpus = m_machine_info->num_cpus;
}
else
{
ASSERT(false);
m_num_cpus = 0;
}
}
//
// Add the thread or FD
//
if(fdinfo == NULL)
{
bool thread_added = false;
sinsp_threadinfo* newti = build_threadinfo();
newti->init(tinfo);
if(is_nodriver())
{
auto sinsp_tinfo = find_thread(tid, true);
if(sinsp_tinfo == nullptr || newti->m_clone_ts > sinsp_tinfo->m_clone_ts)
{
thread_added = m_thread_manager->add_thread(newti, true);
}
}
else
{
thread_added = m_thread_manager->add_thread(newti, true);
}
if (!thread_added) {
delete newti;
}
}
else
{
auto sinsp_tinfo = find_thread(tid, true);
if(!sinsp_tinfo)
{
sinsp_threadinfo* newti = build_threadinfo();
newti->init(tinfo);
if (!m_thread_manager->add_thread(newti, true)) {
ASSERT(false);
delete newti;
return;
}
sinsp_tinfo = find_thread(tid, true);