Repository navigation
Expand file tree
/
Copy pathsimple-service.cpp
More file actions
1129 lines (948 loc) · 40.5 KB
/
Copy pathsimple-service.cpp
File metadata and controls
1129 lines (948 loc) · 40.5 KB
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
// GDBus++ - glib2 GDBus C++ wrapper
//
// SPDX-License-Identifier: AGPL-3.0-only
//
// Copyright (C) OpenVPN Inc <sales@openvpn.net>
// Copyright (C) David Sommerseth <davids@openvpn.net>
//
/**
* @file simple-service.cpp
*
* @brief A testing D-Bus service using the base functionality of the
* GDBus++ API. This is required for the test suite run via
* the Meson build system.
*
*/
#include <cstring>
#include <limits>
#include <sstream>
#include <errno.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <glib.h>
#include "../gdbuspp/features/fmt-compat.hpp"
#include <fmt/format.h>
#include <fmt/printf.h>
#include "../gdbuspp/mainloop.hpp"
#include "../gdbuspp/service.hpp"
#include "test-constants.hpp"
namespace GDBusPP {
std::string GetVersion();
uint16_t GetAPIversion();
} // namespace GDBusPP
namespace Tests::Program {
using namespace Tests;
namespace SimpleService {
/**
* Very simple implementation of a simple logging mechanism.
*
* This object can be passed to other D-Bus related objects to send
* D-Bus signal events with some log information when called.
*
* This class and the DBus::Signals::Group class is designed to be
* shared across more users, through the ::Ptr (shared_ptr) to it.
*/
class Logger : public DBus::Signals::Group
{
public:
using Ptr = std::shared_ptr<Logger>;
explicit Logger(DBus::Connection::Ptr conn)
: DBus::Signals::Group(conn,
Constants::GenPath("simple1"),
Constants::GenInterface("simple1"))
{
RegisterSignal("Log", {{"method", "s"}, {"message", "s"}});
}
void Log(const std::string &info, const std::string &details)
{
try
{
GVariantBuilder *b = glib2::Builder::Create("(ss)");
glib2::Builder::Add(b, info);
glib2::Builder::Add(b, details);
SendGVariant("Log", glib2::Builder::Finish(b));
}
catch (const DBus::Signals::Exception &excp)
{
fmt::print(FMT_COMPILE("EXCEPTION :: SimpleLog: {}\n"), excp.what());
}
}
};
/**
* A simple object created on-the-fly via the CreateSimpleObject D-Bus
* method in the gdbuspp.test.simple1 interface in the object path
* /gdbuspp/tests/simple1/methods
*
* These objects are just used to test creating and destroying child objects
* dynamically and to ensure there are no memory leaks or crashes happening
* related to object management.
*
* Path: (set via constructor argument)
* Interface: gdbuspp.test.simple1.child
*/
class Object : public DBus::Object::Base
{
public:
Object(DBus::Object::Manager::Ptr obj_mgr,
const DBus::Object::Path &path,
const std::string &name)
: DBus::Object::Base(path, Constants::GenInterface("simple1.child")),
object_manager(obj_mgr), my_path(path), my_name(name)
{
AddProperty("my_path", my_path, false);
auto getmyname_args = AddMethod("GetMyName",
[this](DBus::Object::Method::Arguments::Ptr args)
{
args->SetMethodReturn(glib2::Value::Create(this->my_name));
});
getmyname_args->AddOutput("name", "s");
AddMethod("RemoveMe",
[this](DBus::Object::Method::Arguments::Ptr args)
{
fmt::print(FMT_COMPILE("---- REMOVING MYSELF: {}\n"), this->GetPath());
this->object_manager->RemoveObject(this->GetPath());
args->SetMethodReturn(nullptr);
});
}
virtual ~Object() override
{
fmt::print(FMT_COMPILE("---- ~SimpleObject() ... path: {}\n"), my_path);
};
bool Authorize(const DBus::Authz::Request::Ptr req) override
{
return true;
}
private:
DBus::Object::Manager::Ptr object_manager = nullptr;
DBus::Object::Path my_path;
const std::string my_name;
};
/**
* Separate object to test various property interfaces in
* DBus::Object::Property
*
* Path: /gdbuspp/tests/properties
* Interface: gdbuspp.test.simple1
*/
class PropertyTests : public DBus::Object::Base
{
public:
explicit PropertyTests(DBus::Connection::Ptr conn_, Logger::Ptr log_)
: DBus::Object::Base(Constants::GenPath("simple1/properties"),
Constants::GenInterface("simple1")),
log(log_)
{
SetConnection(conn_);
DisableIdleDetector(true);
RegisterSignals(log);
// Test simple data type based properties. These D-Bus object properties
// are tied to a local member variable of this class and will be updated
// and read as a D-Bus caller reads or writes to these properties
AddProperty("string_val", string_val, true);
AddProperty("string_array", string_array, true);
AddProperty("uint_val", uint_val, true);
AddProperty("int_val", int_val, true);
AddProperty("uint_array", uint_array, true);
AddProperty("int_array", int_array, true);
AddProperty("long_val", long_val, true);
AddProperty("ulonglong_val", ulonglong_val, true);
AddProperty("bool_val", bool_val, true);
// These two lambda functions wraps the call to methods in this
// object to read and update a more complex property data types.
//
// In this implementation this is done through a classic struct
// approach, but it is up to the Get/Set methods to build up and
// extract the values as appropriate. It does not need to be a
// struct by itself
auto complex_get = [this](const DBus::Object::Property::BySpec &prop)
{
return this->GetComplexProperty(prop);
};
auto complex_set = [this](const DBus::Object::Property::BySpec &prop, GVariant *v)
{
return this->SetComplexProperty(prop, v);
};
AddPropertyBySpec("complex", "(bis)", complex_get, complex_set);
AddPropertyBySpec("complex_readonly", "(bis)", complex_get);
auto more_complex_get = [this](const DBus::Object::Property::BySpec &prop)
{
return this->GetMoreComplexProperty(prop);
};
AddPropertyBySpec("more_complex_readonly", "(bas(isb)a(isb))", more_complex_get);
AddPropertyBySpec("dictionary",
"a{sv}",
[this](const DBus::Object::Property::BySpec &prop)
{
return this->GetDictionary(prop);
});
auto arg_set_string = AddMethod("SetStringValue",
[this](DBus::Object::Method::Arguments::Ptr args)
{
this->property_update_method(args, "string_val");
});
arg_set_string->AddInput("new_value", glib2::DataType::DBus<std::string>());
auto arg_set_stringarr = AddMethod("SetStringArray",
[this](DBus::Object::Method::Arguments::Ptr args)
{
this->property_update_method(args, "string_array");
});
arg_set_stringarr->AddInput("new_value", glib2::DataType::DBus<std::string>());
auto arg_set_longval = AddMethod("SetLongVal",
[this](DBus::Object::Method::Arguments::Ptr args)
{
this->property_update_method(args, "long_val");
});
arg_set_longval->AddInput("new_value", glib2::DataType::DBus<long>());
auto arg_set_uintarr = AddMethod("SetUintArray",
[this](DBus::Object::Method::Arguments::Ptr args)
{
this->property_update_method(args, "uint_array");
});
arg_set_uintarr->AddInput("new_value", glib2::DataType::DBus<std::string>());
Log(__func__, "Initialized");
}
~PropertyTests() noexcept override
{
Log(__func__, "Removed PropertyTests");
fmt::print(FMT_COMPILE("{} -- ~PropertyTests() called\n"), __func__);
}
bool Authorize(const DBus::Authz::Request::Ptr request) override
{
Log(__func__, fmt::format(FMT_COMPILE("Authorization request approved: {}"), request));
return true;
}
private:
Logger::Ptr log = nullptr;
// Property variables -- Property::SingleType
std::string string_val = "Initial string";
std::vector<std::string> string_array = {"line 1", "line 2", "line 3"};
uint32_t uint_val = 123;
int32_t int_val = -345;
std::vector<uint32_t> uint_array = {0, 15, 16, 31, 32, 65534, 65535};
std::vector<int> int_array = {-10, 3, 16, 9388};
long long_val = std::numeric_limits<long>::max();
unsigned long int ulonglong_val = std::numeric_limits<unsigned long int>::max();
bool bool_val = true;
// Property variables -- Property::BySpec (complex type)
struct complex_t
{
bool boolval;
int intval;
std::string stringval;
};
complex_t complex = {
.boolval = true,
.intval = 98877,
.stringval = "Initial complex string value"};
GVariant *GetComplexProperty(const DBus::Object::Property::BySpec &property)
{
fmt::print(FMT_COMPILE("[Get Complex Property] name={}\n"), property.GetName());
GVariantBuilder *bld = glib2::Builder::Create("(bis)");
glib2::Builder::Add(bld, complex.boolval);
glib2::Builder::Add(bld, complex.intval);
glib2::Builder::Add(bld, complex.stringval);
Log(__func__, "Complex Property retrieved");
return glib2::Builder::Finish(bld);
}
GVariant *GetDictionary(const DBus::Object::Property::BySpec &property)
{
fmt::print(FMT_COMPILE("[Get Dictionary Property] name={}\n"), property.GetName());
GVariantDict *dict = glib2::Dict::Create();
glib2::Dict::Add(dict, "name", std::string("dictionary test"));
glib2::Dict::Add<std::string>(dict, "key", "value");
glib2::Dict::Add(dict, "numbers", 123);
std::vector<uint32_t> num_array = {0, 1, 2, 4, 8, 16, 32, 64, 128};
glib2::Dict::Add(dict, "nummeric_array", num_array);
glib2::Dict::Add(dict, "bool", true);
return glib2::Dict::Finish(dict);
}
DBus::Object::Property::Update::Ptr SetComplexProperty(const DBus::Object::Property::BySpec &property,
GVariant *value)
{
glib2::Utils::checkParams(__func__, value, "(bis)", 3);
complex.boolval = glib2::Value::Extract<bool>(value, 0);
complex.intval = glib2::Value::Extract<int>(value, 1);
complex.stringval = glib2::Value::Extract<std::string>(value, 2);
fmt::print(FMT_COMPILE("[Set Complex Property]"
"name={}, bool={}, int={}, string-2='{}'\n"),
property.GetName(),
complex.boolval,
complex.intval,
complex.stringval);
auto upd = property.PrepareUpdate();
upd->AddValue(complex.boolval);
upd->AddValue(complex.intval);
upd->AddValue(complex.stringval);
Log(__func__, "Complex Property updated");
return upd;
}
/**
* Simple key/value storage container used by
* the PropertyTests - morecomplex_readonly
*/
struct key_value
{
int key;
std::string value;
bool even;
};
/**
* This will build a fairly complex structured GVariant object. The
* C struct equivalent would look like this:
*
* @code
* struct key_value {
* int32_t key;
* char *value
* bool even_key;
* };
*
* struct root_object {
* bool bool_value1;
* char *array_of_string[];
* struct key_value *single_keyval;
* struct key_value *array_of_keyval[];
* };
* @endcode
*
* It is the `struct root_object` which is the returned data from this
* method, returned as a GVariant object.
*
* The first _bool_value1_ has the D-Bus data type: `b`
*
* The _array_of_strings_ has the `as` D-Bus data type - `a` indicates
* an array, `s` is the D-Bus type for strings.
*
* Data structures (the `struct key_value` in this example) are always
* encapsulated in parantheses, with the data types of the elements included.
*
* The `struct key_value` consists of 3 members, an `int32_t` (_key_), a string
* (`char *`, _value_) and finally a `bool` value (_even_key_). The D-Bus types
* for each of these members are: `isb`. And since it is a structure, the final
* D-Bus type for the `single_keyval` element will be: `(isb)`
*
* Finally, there is an array of `struct key_value`. This has the same
* D-Bus data type as the _single_keyval_, but is denoted with a leading `"a"`
* to indicate it is an array. The D-Bus type for the _array_of_keyval_ will
* then be: `a(isb)`.
*
* When all of these elements are combined, the final D-Bus data type for the
* `struct root_object` will be: `"bas(isb)a(isb)"`
*
* @param property
* @return GVariant*
*/
GVariant *GetMoreComplexProperty(const DBus::Object::Property::BySpec &property)
{
fmt::print(FMT_COMPILE("[Get More Complex Property] name={}\n"), property.GetName());
// Helper lambda function which extracts data from
// a single struct key_value into a new GVariant object
// representing the `struct key_value`.
//
// This function will be called via Builder::AddStructData()
//
// D-Bus data type of the output: (isb)
//
auto data_extractor = [](void const *data_ptr) -> GVariant *
{
const auto *data = static_cast<const key_value *>(data_ptr);
GVariantBuilder *bld = glib2::Builder::Create("(isb)");
glib2::Builder::Add(bld, data->key);
glib2::Builder::Add(bld, data->value);
glib2::Builder::Add(bld, data->even);
return glib2::Builder::Finish(bld);
};
// Create the container for the main result - picking the data type
// as indicated in the introspection data. This should be the
// root object's data type: bas(isb)a(isb)
GVariantBuilder *builder = glib2::Builder::Create(property.GetDBusType());
// Add the first boolean value to the container
// - D-Bus type: b
glib2::Builder::Add(builder, true);
// Add the data with an array of strings to the container
// - D-Bus type: as
glib2::Builder::Add(builder, string_array);
// Add a single key_value data set into the container.
// This makes use of the lambda function declared earlier
// in this method.
//
// - D-Bus type: (isb)
//
key_value stand_alone = {
.key = 255,
.value = "A single stand-alone structured element",
.even = false};
glib2::Builder::AddStructData(builder, stand_alone, data_extractor);
// Add the array of key_value elements to the container,
// using the same lambda function as above.
//
// - D-Bus type: a(isb)
//
// First, generate some test data
std::vector<key_value> dataset;
for (int i = 0; i < 10; i++)
{
dataset.push_back({(i + 1), // .key
fmt::format(FMT_COMPILE("Element #{}"), i), // .value
(i % 2 == 0)}); // .even
}
// Add the complete array/vector of key_value elements. The
// data_extractor lambda fuction will be called for each element
// in the vector
glib2::Builder::AddStructData(builder, dataset, data_extractor);
Log(__func__, "More Complex Property retrieved");
// This wraps all of these elements into the final
// main result - as a GVariant object - with the
// ending D-Bus data type: (bas(isb)a(isb))
return glib2::Builder::Finish(builder);
};
void Log(const std::string &func, const std::string &msg) const
{
log->Log(fmt::format(FMT_COMPILE("PropertyTests::{}"), func), msg);
}
void property_update_method(DBus::Object::Method::Arguments::Ptr args, const std::string &property_name)
{
GVariant *params = args->GetMethodParameters();
if ("string_val" == property_name)
{
glib2::Utils::checkParams(__func__, params, "(s)", 1);
UpdateProperty(property_name, glib2::Value::Extract<std::string>(params, 0));
}
else if ("string_array" == property_name)
{
glib2::Utils::checkParams(__func__, params, "(s)", 1);
std::stringstream input(glib2::Value::Extract<std::string>(params, 0));
std::string v;
std::vector<std::string> values;
while (std::getline(input, v, '|'))
{
values.push_back(v);
}
UpdateProperty(property_name, values);
}
else if ("long_val" == property_name)
{
glib2::Utils::checkParams(__func__, params, "(x)", 1);
auto value = glib2::Value::Extract<long>(params, 0);
UpdateProperty(property_name, value);
}
else if ("uint_array" == property_name)
{
// This parses a string of elements separated by '|'
// and converts that to an array of uint32_t
glib2::Utils::checkParams(__func__, params, "(s)", 1);
std::stringstream input(glib2::Value::Extract<std::string>(params, 0));
std::string v;
std::vector<uint32_t> values;
while (std::getline(input, v, '|'))
{
values.push_back(static_cast<uint32_t>(std::stoi(v)));
}
UpdateProperty(property_name, values);
}
}
};
/**
* Separate object to test various D-Bus methods with functionality which
* must succeed and work correctly
*
* Path: /gdbuspp/tests/methods
* Interface: gdbuspp.test.simple1
*/
class MethodTests : public DBus::Object::Base
{
public:
MethodTests(DBus::Object::Manager::Ptr obj_mgr_, Logger::Ptr log_)
: DBus::Object::Base(Constants::GenPath("simple1/methods"),
Constants::GenInterface("simple1")),
object_manager(obj_mgr_), log(log_)
{
DisableIdleDetector(true);
RegisterSignals(log);
// Just a simple D-Bus method not requiring any input arguments nor
// giving anything back to the caller.
AddMethod("MethodNoArgs",
[](DBus::Object::Method::Arguments::Ptr args)
{
fmt::print(FMT_COMPILE("[Method call: MethodNoArgs] {}\n"), args);
args->SetMethodReturn(nullptr);
});
// A simple string lenght function, taking a string as input
// and returning an integer back to the caller with the length of
// the input string
auto stringlen_args = AddMethod("StringLength",
[this](DBus::Object::Method::Arguments::Ptr args)
{
this->StringLength(args);
});
stringlen_args->AddInput("string", "s");
stringlen_args->AddOutput("length", "i");
auto ret_string_array = AddMethod(
"GetStringArray",
[](DBus::Object::Method::Arguments::Ptr args)
{
std::vector<std::string> data = {
"String line 1",
"String line B",
"String line III"};
GVariant *ret = glib2::Value::Create(data);
args->SetMethodReturn(ret);
});
ret_string_array->AddOutput("string_array", "as");
// Return the bus name of the caller back to the caller. This is
// used so the proxy test program can check if that matches the
// assigned bus name of the calling client
auto get_caller_args = AddMethod("GetCallerBusName",
[](DBus::Object::Method::Arguments::Ptr args)
{
args->SetMethodReturn(glib2::Value::Create(args->GetCallerBusName()));
});
get_caller_args->AddOutput("caller_busname", glib2::DataType::DBus<std::string>());
// This creates a new child object, as defined in the SimpleObject class
// The "name" of the object, becomes part of the D-Bus path which is
// given as an input string. It returns the full D-Bus object path
// to this new object
auto createobj_args = AddMethod("CreateSimpleObject",
[this](DBus::Object::Method::Arguments::Ptr args)
{
this->CreateSimpleObject(args);
});
createobj_args->AddInput("name", "s");
createobj_args->AddOutput("path", "o");
// This removes a child object based on the "name" of the object, as
// given when creating it.
//
// This approach deletes the object without the object itself being
// involved in the deletion, but the destructor should be called.
// The SimpleObject also implements a method where it can delete
// itself as well.
auto rmobj_args = AddMethod("RemoveSimpleObject",
[this](DBus::Object::Method::Arguments::Ptr args)
{
this->RemoveSimpleObject(args);
});
rmobj_args->AddInput("name", "s");
auto get_removd_objs_args = AddMethod(
"GetRemovedObjects",
[this](DBus::Object::Method::Arguments::Ptr args)
{
GVariant *r = glib2::Value::Create(removed_objects);
args->SetMethodReturn(r);
removed_objects.clear();
});
get_removd_objs_args->AddOutput("paths", "ao");
// This method will open a file with the file name provided as an
// input argument and will return a file descriptor to the opened file.
// This is for testing sending file descriptors from the service to the
// caller of this method.
auto openfile_args = AddMethod("OpenFilePassFD",
[this](DBus::Object::Method::Arguments::Ptr args)
{
this->OpenFile(args);
});
openfile_args->AddInput("file", "s");
openfile_args->AddOutput("success", "b");
openfile_args->PassFileDescriptor(DBus::Object::Method::PassFDmode::SEND);
// This method will receive a file descriptor to a file from the caller
// and this method will do a fstat() call on that file descriptor and
// extract a few details it will send back to the caller.
// This is for testing receiving file descriptors via a D-Bus
// method call
auto fstat_args = AddMethod("fstatFileFromFD",
[this](DBus::Object::Method::Arguments::Ptr args)
{
this->fstatFile(args);
});
fstat_args->AddOutput("owner_uid", "u");
fstat_args->AddOutput("owner_gid", "u");
fstat_args->AddOutput("size", "t");
fstat_args->PassFileDescriptor(DBus::Object::Method::PassFDmode::RECEIVE);
Log(__func__, "Initialized");
}
~MethodTests() noexcept
{
Log(__func__, "Removed MethodTests");
fmt::print(FMT_COMPILE("{} -- ~MethodTests() called\n"), __func__);
}
bool Authorize(const DBus::Authz::Request::Ptr request) override
{
Log(__func__, fmt::format(FMT_COMPILE("Authorization request approved: {}"), request));
return true;
}
private:
DBus::Object::Manager::Ptr object_manager = nullptr;
Logger::Ptr log = nullptr;
std::vector<DBus::Object::Path> removed_objects = {};
void Log(const std::string &func, const std::string &msg) const
{
log->Log(fmt::format(FMT_COMPILE("MethodTests::{}"), func), msg);
}
void StringLength(DBus::Object::Method::Arguments::Ptr args)
{
Log(__func__, "StringLength called");
fmt::print(FMT_COMPILE("[StringLength call] {}\n"), args);
GVariant *params = args->GetMethodParameters();
std::string in = glib2::Value::Extract<std::string>(params, 0);
size_t l = in.length();
fmt::print(FMT_COMPILE("Input: '{}' length: {}\n"), in, l);
args->SetMethodReturn(glib2::Value::Create<int32_t>(l));
}
void CreateSimpleObject(DBus::Object::Method::Arguments::Ptr args)
{
fmt::print(FMT_COMPILE("[CreateSimpleObject call] {}\n"), args);
GVariant *params = args->GetMethodParameters();
std::string name = glib2::Value::Extract<std::string>(params, 0);
const std::string child_path = Constants::GenPath("simple1/childs/") + name;
auto obj = object_manager->CreateObject<Object>(object_manager,
child_path,
name);
object_manager->AttachRemoveCallback(
child_path,
[&](const DBus::Object::Path &path)
{
// A bit complicated way - but showcasing the idea
// how to use this callback
auto obj = object_manager->GetObject<Object>(path);
removed_objects.push_back(obj->GetPath());
fmt::print(FMT_COMPILE("AttachRemoveCallback: Removed object {}\n"),
path);
Log("AttachRemoveCallback",
fmt::format(FMT_COMPILE("Object removed: {}"), path));
});
fmt::print(FMT_COMPILE(">>>> NEW OBJECT: {}\n"), obj->GetPath());
Log(__func__, fmt::format(FMT_COMPILE("New child object created: {}"), obj->str()));
args->SetMethodReturn(glib2::Value::Create(obj->GetPath()));
}
void RemoveSimpleObject(DBus::Object::Method::Arguments::Ptr args)
{
fmt::print(FMT_COMPILE("[RemoveSimpleObject call] {}\n"), args);
GVariant *params = args->GetMethodParameters();
std::string name = glib2::Value::Extract<std::string>(params, 0);
if (name.empty() || "/" == name)
{
throw DBus::Object::Exception("Path cannot be empty");
}
const std::string path = Constants::GenPath("simple1/childs/") + name;
object_manager->RemoveObject(path);
fmt::print(FMT_COMPILE(">>> DELETED OBJECT: {}\n"), path);
Log(__func__, fmt::format(FMT_COMPILE("Child object removed: {}"), path));
args->SetMethodReturn(nullptr);
}
void OpenFile(DBus::Object::Method::Arguments::Ptr args)
{
fmt::print(FMT_COMPILE("[OpenFile - Read] {}\n"), args);
GVariant *params = args->GetMethodParameters();
std::string fname = glib2::Value::Extract<std::string>(params, 0);
int fd = -1;
try
{
fd = open(fname.c_str(), O_RDONLY);
args->SendFD(fd);
Log(__func__, fmt::format(FMT_COMPILE("File '{}' opened, fd={}"), fname, fd));
}
catch (const DBus::AsyncProcess::Exception &excp)
{
Log(__func__, fmt::format(FMT_COMPILE("** ERROR ** {}"), excp.GetRawError()));
fmt::print(FMT_COMPILE("** ERROR ** {}\n"), excp.what());
}
args->SetMethodReturn(glib2::Value::Create(fd > 0));
}
void fstatFile(DBus::Object::Method::Arguments::Ptr args)
{
fmt::print(FMT_COMPILE("[fstatFile] {}\n"), args);
int fd = args->ReceiveFD();
struct stat fileinfo = {};
GVariant *ret = nullptr;
if (fstat(fd, &fileinfo) >= 0)
{
fmt::print(FMT_COMPILE("fstat() success: "
"uid={}, gid={}, size={}\n"),
fileinfo.st_uid,
fileinfo.st_gid,
fileinfo.st_size);
auto *bld = glib2::Builder::Create("(uut)");
glib2::Builder::Add<uint32_t>(bld, fileinfo.st_uid);
glib2::Builder::Add<uint32_t>(bld, fileinfo.st_gid);
glib2::Builder::Add<uint64_t>(bld, fileinfo.st_size);
ret = glib2::Builder::Finish(bld);
Log(__func__, fmt::format(FMT_COMPILE("fstat({}) successful"), fd));
}
else
{
Log(__func__, fmt::format(FMT_COMPILE("fstat({}) failed!"), fd));
throw DBus::Object::Exception(
this,
fmt::format(FMT_COMPILE("fstat() call failed: {}"), std::strerror(errno)));
}
args->SetMethodReturn(ret);
}
};
/**
* These D-Bus methods in this D-Bus object is expected to all fail
*
* This is used to test the error handling and how errors are reported back
* to the caller as well as ensuring the service itself does not crash
*
* Path: /gdbuspp/tests/method_failures
* Interface: gdbuspp.test.simple1
*/
class FailingMethodTests : public DBus::Object::Base
{
public:
FailingMethodTests()
: DBus::Object::Base(Constants::GenPath("simple1/method_failures"),
Constants::GenInterface("simple1"))
{
DisableIdleDetector(true);
auto wrong_args1 = AddMethod("NoReceive123",
[](DBus::Object::Method::Arguments::Ptr args)
{
args->SetMethodReturn(glib2::Value::Create<int32_t>(123));
});
wrong_args1->AddOutput("length", "s");
auto wrong_args2 = AddMethod("InputMismatch",
[](DBus::Object::Method::Arguments::Ptr args)
{
GVariant *p = args->GetMethodParameters();
glib2::Utils::checkParams(__func__, p, "(i)", 1);
(void)glib2::Value::Extract<int>(p, 0);
args->SetMethodReturn(glib2::Value::Create(false));
});
wrong_args2->AddInput("not_an_int", "s");
wrong_args2->AddOutput("failed", "b");
auto wrong_args3 = AddMethod("OutputMismatch",
[](DBus::Object::Method::Arguments::Ptr args)
{
args->SetMethodReturn(glib2::Value::Create<int32_t>(123));
});
wrong_args3->AddOutput("failed", "b");
AddMethod("NoReceiveFD",
[](DBus::Object::Method::Arguments::Ptr args)
{
args->ReceiveFD();
args->SetMethodReturn(nullptr);
});
auto no_send_fd = AddMethod("NoSendFD",
[](DBus::Object::Method::Arguments::Ptr args)
{
int fd = open("/dev/null", O_RDONLY);
args->SendFD(fd);
args->SetMethodReturn(nullptr);
});
no_send_fd->PassFileDescriptor(DBus::Object::Method::PassFDmode::RECEIVE);
}
bool Authorize(const DBus::Authz::Request::Ptr request) override
{
return true;
}
};
class MainHandler : public DBus::Object::Base
{
public:
using Ptr = std::shared_ptr<MainHandler>;
MainHandler(DBus::Connection::Ptr conn,
DBus::Object::Manager::Ptr object_mgr)
: DBus::Object::Base(Constants::GenPath("simple1"),
Constants::GenInterface("simple1"))
{
DisableIdleDetector(true);
log = DBus::Signals::Group::Create<Logger>(conn);
RegisterSignals(log);
log->AddTarget("");
property_tests = object_mgr->CreateObject<PropertyTests>(conn, log);
method_tests = object_mgr->CreateObject<MethodTests>(object_mgr, log);
failing_meths = object_mgr->CreateObject<FailingMethodTests>();
AddProperty("version", version, false);
log->Log("SimpleHandler", "Handler is initialized");
}
~MainHandler()
{
try
{
log->Log("SimpleHandler", "Handler is shutting down");
}
catch (const DBus::Exception &excp)
{
fmt::print(stderr,
FMT_COMPILE("** ERROR ** Failed to send Log signal: {}\n"),
excp.what());
}
fmt::print(stderr, "\nDESTRUCTOR ~SimpleHandler\n");
}
bool Authorize(const DBus::Authz::Request::Ptr request) override
{
log->Log("SimpleHandler::Authorize",
fmt::format(FMT_COMPILE("Authorization request approved: {}"), request));
return true;
}
PropertyTests::Ptr GetPropertyTestsObject() const
{
return property_tests;
}
MethodTests::Ptr GetMethodTestsObject() const
{
return method_tests;
}
FailingMethodTests::Ptr GetFailingMethodsTestsObject() const
{
return failing_meths;
}
private:
Logger::Ptr log = nullptr;
PropertyTests::Ptr property_tests = nullptr;
MethodTests::Ptr method_tests = nullptr;
FailingMethodTests::Ptr failing_meths = nullptr;
std::string version = "0.1.2.3";
};
template <typename CLASS1, typename CLASS2>
const bool compare_shared_ptr_obj(const std::shared_ptr<CLASS1> &lhs,
const std::shared_ptr<CLASS2> &rhs)
{
return (lhs == rhs) && (lhs.get() == rhs.get());
}
/**
* Initialises a D-Bus service and registers the service unto the D-Bus
* given D-Bus connection.
*
* Well-known bus name: net.openvpn.gdbuspp.test.simple
*/
class Service1 : public DBus::Service
{
public:
Service1(DBus::Connection::Ptr con)
: DBus::Service(con, Constants::GenServiceName("simple"))
{
}
virtual ~Service1() = default;
// This is a callback method which is called when this D-Bus service
// is registered on the D-Bus connection
void BusNameAcquired(const std::string &busname) override
{
fmt::print(FMT_COMPILE("Bus name acquired: {}\n"), busname);
}
// This callback method will be called if the D-Bus service for some reason
// does not get the service registered on the D-Bus connection or the
// registration is lost (the D-Bus daemon kicks the service off the D-Bus).
void BusNameLost(const std::string &busname) override
{
fmt::print(FMT_COMPILE("** WARNING ** Bus name lost: {}\n"), busname);
Stop();
}
void InternalTests(DBus::Object::Manager::Ptr object_mgr, MainHandler::Ptr handler)
{
fmt::print("** Internal tests - "
"DBus::Object::Manager::GetObject() / DBus::Object::Manager::GetAllObjects()\n");
std::map<std::string, DBus::Object::Base::Ptr> check;