Repository navigation
Expand file tree
/
Copy pathIpcService.cpp
More file actions
988 lines (810 loc) · 26.4 KB
/
Copy pathIpcService.cpp
File metadata and controls
988 lines (810 loc) · 26.4 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
/*
* If not stated otherwise in this file or this component's LICENSE file the
* following copyright and licenses apply:
*
* Copyright 2020 Sky UK
*
* 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.
*/
/*
* IpcService.cpp
*
* Created on: 5 Jun 2015
* Author: riyadh
*/
#include "IpcCommon.h"
#include "IpcService.h"
#include "AsyncReplySender.h"
#include "AsyncReplyGetter.h"
#include "DbusEventDispatcher.h"
#include "DbusMessageParser.h"
#include "IpcUtilities.h"
#include <Common/Interface.h>
#include <Logging.h>
#include <dbus/dbus.h>
#include <boost/optional.hpp>
#include <boost/lexical_cast.hpp>
#include <thread>
#include <future>
#include <string>
#include <exception>
#include <stdexcept>
#include <list>
#include <mutex>
#include <set>
namespace {
std::string getMatchRule(const AI_IPC::RemoteEntry& entry)
{
std::string matchRule;
if( entry.type == AI_IPC::RemoteEntry::SIGNAL )
{
matchRule += "type='signal'";
}
else if( entry.type == AI_IPC::RemoteEntry::METHOD )
{
matchRule += "type='method_call'";
}
else
{
throw std::runtime_error("Entry has to be either method not signal");
}
if( !entry.interface.empty() )
{
matchRule += ",interface='"+ entry.interface +"'";
}
if( !entry.name.empty() )
{
matchRule += ",member='"+ entry.name +"'";
}
if( !entry.object.empty() )
{
matchRule += ",path='"+ entry.object +"'";
}
if( entry.type == AI_IPC::RemoteEntry::METHOD )
{
matchRule += ",destination='"+ entry.service +"'";
}
return matchRule;
}
bool validRemoteEntry(const AI_IPC::RemoteEntry& entry)
{
return ( (!entry.name.empty()) && (!entry.interface.empty()) && (!entry.object.empty()) );
}
}
using namespace AI_IPC;
IpcService::IpcService(BusType busType, const std::string& serviceName, int defaultTimeoutMs /*= -1*/)
: mServiceName(serviceName)
, mHandlerDispatcher("AI_DBUS_DISPATCH")
, mRunning(false)
, mNextSignalHandlerRegId(1)
, mDefaultTimeoutMs(defaultTimeoutMs)
, mValid(false)
#if (AI_BUILD_TYPE == AI_DEBUG)
, mInMonitorMode(false)
, mMonitorCb(nullptr)
#endif
{
AI_LOG_FN_ENTRY();
if ( serviceName.empty() )
{
throw std::runtime_error( "Invalid construction parameter for dbus service" );
}
DBusBusType type;
char* env_address;
switch (busType)
{
case BusType::SessionBus:
type = DBUS_BUS_SESSION;
env_address = getenv("DBUS_SESSION_BUS_ADDRESS");
if (env_address)
{
mBusAddress = std::string(env_address);
}
else
{
AI_LOG_WARN("Attempting to connect to session bus but DBUS_SESSION_BUS_ADDRESS not set");
mBusAddress = "";
}
break;
case BusType::SystemBus:
type = DBUS_BUS_SYSTEM;
env_address = getenv("DBUS_SYSTEM_BUS_ADDRESS");
if (env_address)
{
mBusAddress = std::string(env_address);
}
else
{
mBusAddress = "unix:path=/var/run/dbus/system_bus_socket";
}
break;
default:
throw std::runtime_error( "Invalid bus type" );
}
mDbusConnection = std::make_shared<DbusConnection>();
if ( !mDbusConnection || !mDbusConnection->connect(type, serviceName) )
{
throw std::runtime_error( "Failed to connect to dbus" );
}
mValid = true;
AI_LOG_FN_EXIT();
}
IpcService::IpcService(const std::string& dbusAddress, const std::string& serviceName, int defaultTimeoutMs)
: mServiceName(serviceName)
, mHandlerDispatcher("AI_DBUS_DISPATCH")
, mRunning(false)
, mNextSignalHandlerRegId(1)
, mDefaultTimeoutMs(defaultTimeoutMs)
, mBusAddress(dbusAddress)
#if (AI_BUILD_TYPE == AI_DEBUG)
, mInMonitorMode(false)
, mMonitorCb(nullptr)
#endif
{
AI_LOG_FN_ENTRY();
if (dbusAddress.empty())
{
throw std::runtime_error("Invalid address parameter for dbus service");
}
if (serviceName.empty())
{
throw std::runtime_error("Invalid construction parameter for dbus service");
}
mDbusConnection = std::make_shared<DbusConnection>();
if (!mDbusConnection || !mDbusConnection->connect(dbusAddress, serviceName))
{
throw std::runtime_error("Failed to connect to dbus");
}
mValid = true;
AI_LOG_FN_EXIT();
}
IpcService::~IpcService()
{
AI_LOG_FN_ENTRY();
stop();
unregisterHandlers();
if (mDbusConnection)
{
mDbusConnection->disconnect();
mDbusConnection.reset();
}
AI_LOG_FN_EXIT();
}
bool IpcService::isValid() const
{
return mValid;
}
std::shared_ptr<IAsyncReplyGetter> IpcService::invokeMethod(const Method& method, const VariantList& args, int timeoutMs /*= -1*/)
{
AI_LOG_FN_ENTRY();
#if (AI_BUILD_TYPE == AI_DEBUG)
if ( !mRunning )
{
AI_LOG_WARN("Trying to call a method without IpcService event loop running");
}
#endif
std::shared_ptr<IAsyncReplyGetter> replyGetter;
if ( validRemoteEntry(method) )
{
DBusMessage *msg = dbus_message_new_method_call( method.service.c_str(), method.object.c_str(), method.interface.c_str(), method.name.c_str() );
if ( msg != NULL )
{
if( appendArgsToDbusMsg(msg, args) )
{
// If the timeout is set to the default, override with the Service's default timeout
if (timeoutMs == -1)
{
timeoutMs = mDefaultTimeoutMs;
}
// Send the message and get a token to wait on for the reply
uint64_t token = mDbusConnection->sendMessageWithReply(msg, timeoutMs);
if (token != 0)
{
replyGetter = std::make_shared<AsyncReplyGetter>(mDbusConnection, token);
}
}
else
{
AI_LOG_ERROR("Unable to append arguments to dbus message");
}
dbus_message_unref(msg);
}
else
{
AI_LOG_ERROR( "Error: dbus_message_new_method_call failed" );
}
}
else
{
AI_LOG_ERROR( "Invalid method: name %s, interface %s, path %s", method.name.c_str(), method.interface.c_str(), method.object.c_str());
}
AI_LOG_FN_EXIT();
return replyGetter;
}
bool IpcService::invokeMethod(const Method& method, const VariantList& sendArgs, VariantList& replyArgs, int timeoutMs /*= -1*/)
{
AI_LOG_FN_ENTRY();
bool res = false;
std::shared_ptr<IAsyncReplyGetter> replyGetter = invokeMethod(method, sendArgs, timeoutMs);
if( replyGetter )
{
res = replyGetter->getReply(replyArgs);
}
else
{
AI_LOG_ERROR("Unable to create reply getter");
}
AI_LOG_FN_EXIT();
return res;
}
bool IpcService::emitSignal( const Signal& signal, const VariantList& args )
{
AI_LOG_FN_ENTRY();
bool res = false;
if ( validRemoteEntry(signal) )
{
DBusMessage *msg = dbus_message_new_signal( signal.object.c_str(), signal.interface.c_str(), signal.name.c_str() );
if ( msg != NULL )
{
if( appendArgsToDbusMsg(msg, args) )
{
res = mDbusConnection->sendMessageNoReply(msg);
}
else
{
AI_LOG_ERROR("Unable to append arguments to dbus message");
}
dbus_message_unref(msg);
}
else
{
AI_LOG_ERROR( "Unable to create dbus message for new signal" );
}
}
else
{
AI_LOG_ERROR( "Invalid signal: name %s, interface %s, path %s", signal.name.c_str(), signal.interface.c_str(), signal.object.c_str());
}
AI_LOG_FN_EXIT();
return res;
}
std::string IpcService::registerMethodHandler(const Method& method, const MethodHandler& handler)
{
AI_LOG_FN_ENTRY();
std::string regId;
if ( validRemoteEntry(method) )
{
if( method.service == mServiceName )
{
std::unique_lock<std::mutex> lock(mMutex);
const std::string matchRule = getMatchRule(method);
if ( mMethodHandlers.find(matchRule) == mMethodHandlers.end() )
{
// Add the object path for the dbus handler filter
registerObjectPath(method.object);
// Add the handler
regId = matchRule;
mMethodHandlers[matchRule] = std::pair<Method, MethodHandler>(method, handler);
// We need to drop the lock when calling the dbus API as it may callback our handler
// which in turn will try and take the lock (we could use recursive mutex, but seems
// overkill in this situation)
lock.unlock();
// Finally try and add the rule, if fails then remove the handler
if (!mDbusConnection->addMatch(matchRule.c_str()))
{
AI_LOG_ERROR("failed to add match rule");
lock.lock();
// Failed - retake the lock and remove the handler and return an empty id
mMethodHandlers.erase(matchRule);
regId.clear();
}
}
else
{
AI_LOG_ERROR( "Method handler already registered for this match rule %s", matchRule.c_str() );
}
}
else
{
AI_LOG_ERROR( "Invalid service name %s", method.service.c_str() );
}
}
else
{
AI_LOG_ERROR( "Invalid method: name %s, interface %s, path %s", method.name.c_str(), method.interface.c_str(), method.object.c_str() );
}
AI_LOG_FN_EXIT();
return regId;
}
std::string IpcService::registerSignalHandler(const Signal& signal, const SignalHandler& handler)
{
AI_LOG_FN_ENTRY();
std::string regId;
if ( validRemoteEntry(signal) )
{
std::string matchRule = getMatchRule(signal);
if (mDbusConnection->addMatch(matchRule) == true)
{
std::lock_guard<std::mutex> lock(mMutex);
// Add the object path for the dbus handler filter
registerObjectPath(signal.object);
// We do not use match rule as multiple handler can be registered for same signal
regId = boost::lexical_cast<std::string>(mNextSignalHandlerRegId++);
mSignalHandlers[regId] = std::pair<Signal, SignalHandler>(signal, handler);
}
else
{
AI_LOG_ERROR( "Failed to add signal match rule \"%s\"", matchRule.c_str() );
}
}
else
{
AI_LOG_ERROR( "Invalid signal: name %s, interface %s, path %s", signal.name.c_str(), signal.interface.c_str(), signal.object.c_str() );
}
AI_LOG_FN_EXIT();
return regId;
}
bool IpcService::unregisterHandler(const std::string& regId)
{
AI_LOG_FN_ENTRY();
bool res = true;
std::lock_guard<std::mutex> lock(mMutex);
std::string matchRule;
std::string objectPath;
auto iterMethodHandler = mMethodHandlers.find(regId);
if( iterMethodHandler != mMethodHandlers.end() )
{
matchRule = getMatchRule(iterMethodHandler->second.first);
objectPath = iterMethodHandler->second.first.object;
mMethodHandlers.erase(iterMethodHandler);
}
else
{
auto iterSignalHandler = mSignalHandlers.find(regId);
if( iterSignalHandler != mSignalHandlers.end() )
{
matchRule = getMatchRule(iterSignalHandler->second.first);
objectPath = iterSignalHandler->second.first.object;
mSignalHandlers.erase(iterSignalHandler);
}
else
{
AI_LOG_ERROR( "Unable to unregister: invalid registration Id %s", regId.c_str() );
res = false;
}
}
if ( !objectPath.empty() )
{
unregisterObjectPath(objectPath);
}
if ( !matchRule.empty() )
{
mDbusConnection->removeMatch(matchRule);
}
AI_LOG_FN_EXIT();
return res;
}
DBusHandlerResult IpcService::handleDbusMessageCb( DBusMessage *message )
{
AI_LOG_FN_ENTRY();
DBusHandlerResult res = DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
#if (AI_BUILD_TYPE == AI_DEBUG)
if (mInMonitorMode)
{
res = handleDbusMonitorEvent(message);
}
else
#endif
{
res = handleDbusMessage(message);
}
AI_LOG_FN_EXIT();
return res;
}
#if (AI_BUILD_TYPE == AI_DEBUG)
DBusHandlerResult IpcService::handleDbusMonitorEvent( DBusMessage *dbusMsg )
{
AI_LOG_FN_ENTRY();
const char *sender = dbus_message_get_sender(dbusMsg);
const char *destination = dbus_message_get_destination(dbusMsg);
const char *objectPath = nullptr;
const char *interface = nullptr;
const char *name = nullptr;
std::lock_guard<std::mutex> lock(mMutex);
if ( mMonitorCb )
{
EventType type;
unsigned int serial;
switch ( dbus_message_get_type(dbusMsg) )
{
case DBUS_MESSAGE_TYPE_METHOD_CALL:
type = MethodCallEvent;
serial = dbus_message_get_serial(dbusMsg),
objectPath = dbus_message_get_path(dbusMsg),
interface = dbus_message_get_interface(dbusMsg),
name = dbus_message_get_member(dbusMsg);
break;
case DBUS_MESSAGE_TYPE_SIGNAL:
type = SignalEvent;
serial = dbus_message_get_serial(dbusMsg),
objectPath = dbus_message_get_path(dbusMsg),
interface = dbus_message_get_interface(dbusMsg),
name = dbus_message_get_member(dbusMsg);
break;
case DBUS_MESSAGE_TYPE_METHOD_RETURN:
type = MethodReturnEvent;
serial = dbus_message_get_reply_serial(dbusMsg);
break;
case DBUS_MESSAGE_TYPE_ERROR:
type = ErrorEvent;
serial = dbus_message_get_reply_serial(dbusMsg);
name = dbus_message_get_error_name(dbusMsg);
break;
default:
AI_LOG_ERROR_EXIT("Unknown message type received");
return DBUS_HANDLER_RESULT_HANDLED;
}
DbusMessageParser dbusMessageParser(dbusMsg);
if ( !dbusMessageParser.parseMsg() )
{
AI_LOG_ERROR_EXIT("Failed to parse args for monitor event of type %d", type);
return DBUS_HANDLER_RESULT_HANDLED;
}
mHandlerDispatcher.post( std::bind( mMonitorCb, type, serial,
std::string(sender ? sender : ""),
std::string(destination ? destination : ""),
std::string(objectPath ? objectPath : ""),
std::string(interface ? interface : ""),
std::string(name ? name : ""),
dbusMessageParser.getArgList() ) );
}
AI_LOG_FN_EXIT();
return DBUS_HANDLER_RESULT_HANDLED;
}
#endif // if(AI_BUILD_TYPE == AI_DEBUG)
DBusHandlerResult IpcService::handleDbusMessage( DBusMessage *dbusMsg )
{
AI_LOG_FN_ENTRY();
DBusHandlerResult res = DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
const char *objectPath = dbus_message_get_path(dbusMsg);
const char *interface = dbus_message_get_interface(dbusMsg);
const char *name = dbus_message_get_member(dbusMsg);
#if (AI_BUILD_TYPE == AI_DEBUG)
if(objectPath && interface && name)
{
const char *sender = dbus_message_get_sender(dbusMsg);
const char *destination = dbus_message_get_destination (dbusMsg);
AI_LOG_DEBUG( "Received objectPath %s", objectPath );
AI_LOG_DEBUG( "Received interface %s", interface );
AI_LOG_DEBUG( "Received name %s", name );
AI_LOG_DEBUG( "Received sender %s", sender );
AI_LOG_DEBUG( "Received destination %s", destination );
}
#endif
if( objectPath && isRegisteredObjectPath(objectPath) )
{
bool isSignal = false;
bool isMethod = false;
if ( (objectPath != NULL) && (interface != NULL) && (name != NULL) )
{
if( dbus_message_is_method_call(dbusMsg, interface, name) )
{
isMethod = true;
AI_LOG_DEBUG( "Method call received" );
}
else if( dbus_message_is_signal(dbusMsg, interface, name) )
{
isSignal = true;
AI_LOG_DEBUG( "Signal received" );
}
}
if ( isSignal || isMethod )
{
DbusMessageParser dbusMessageParser(dbusMsg);
if ( dbusMessageParser.parseMsg() )
{
if ( isSignal )
{
res = handleDbusSignal( Signal(objectPath, interface, name), dbusMessageParser.getArgList() );
}
else
{
const char *sender = dbus_message_get_sender(dbusMsg);
if(isDbusMessageAllowed(sender, interface))
{
res = handleDbusMethodCall( Method(mServiceName, objectPath, interface, name), dbusMessageParser.getArgList(), dbusMsg );
}
}
}
else
{
AI_LOG_ERROR( "Unable to parse arguments" );
}
}
}
AI_LOG_FN_EXIT();
return res;
}
bool IpcService::isDbusMessageAllowed(const std::string& sender, const std::string& interface)
{
AI_LOG_FN_ENTRY();
AI_LOG_FN_EXIT();
// Always allow dbus messages to Dobby (enforce restictions elsewhere)
return true;
}
DBusHandlerResult IpcService::handleDbusSignal( const Signal& signal, const VariantList& argList )
{
AI_LOG_FN_ENTRY();
DBusHandlerResult res = DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
std::lock_guard<std::mutex> lock(mMutex);
for ( auto iter = mSignalHandlers.begin(); iter != mSignalHandlers.end(); ++iter )
{
if( iter->second.first == signal )
{
mHandlerDispatcher.post( std::bind(iter->second.second, argList ) );
res = DBUS_HANDLER_RESULT_HANDLED; // continue as many can be interested in the same signal
}
}
AI_LOG_FN_EXIT();
return res;
}
DBusHandlerResult IpcService::handleDbusMethodCall( const Method& method, const VariantList& argList, DBusMessage *dbusMsg )
{
AI_LOG_FN_ENTRY();
DBusHandlerResult res = DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
std::lock_guard<std::mutex> lock(mMutex);
auto iter = mMethodHandlers.find(getMatchRule(method));
if( iter != mMethodHandlers.end() )
{
DBusMessage *replyMsg = dbus_message_new_method_return(dbusMsg);
if ( replyMsg )
{
std::shared_ptr<AsyncReplySender> asyncReplySender = std::make_shared<AsyncReplySender>(mDbusConnection, dbusMsg, replyMsg, argList);
mHandlerDispatcher.post(std::bind(iter->second.second, asyncReplySender));
}
res = DBUS_HANDLER_RESULT_HANDLED;
}
AI_LOG_FN_EXIT();
return res;
}
void IpcService::flush()
{
AI_LOG_FN_ENTRY();
// This will ensure that any handlers queued on the dispatcher are processed
// before returning
mHandlerDispatcher.sync();
AI_LOG_FN_EXIT();
}
bool IpcService::start()
{
AI_LOG_FN_ENTRY();
bool res = false;
if ( !mRunning )
{
mRunning = true;
mDbusConnection->registerMessageHandler(std::bind(&IpcService::handleDbusMessageCb, this, std::placeholders::_1));
res = true;
}
else
{
AI_LOG_ERROR("IPC service already started: start() has not impact");
}
AI_LOG_FN_EXIT();
return res;
}
bool IpcService::stop()
{
AI_LOG_FN_ENTRY();
bool res = false;
if ( mRunning )
{
mRunning = false;
mDbusConnection->registerMessageHandler(nullptr);
mHandlerDispatcher.sync();
res = true;
}
else
{
AI_LOG_INFO("IPC service not running - stop() has no impact");
}
AI_LOG_FN_EXIT();
return res;
}
void IpcService::registerObjectPath(const std::string& path)
{
#if (AI_BUILD_TYPE == AI_DEBUG)
if( mMutex.try_lock() )
{
AI_LOG_ERROR("registerObjectPath called without lock held");
mMutex.unlock();
}
#endif
std::map<std::string,int>::iterator it = mObjectPaths.find(path);
if( it == mObjectPaths.end() )
{
mObjectPaths[path] = 1;
}
else
{
it->second++;
}
}
void IpcService::unregisterObjectPath(const std::string& path)
{
#if (AI_BUILD_TYPE == AI_DEBUG)
if( mMutex.try_lock() )
{
AI_LOG_ERROR("unregisterObjectPath called without lock held");
mMutex.unlock();
}
#endif
std::map<std::string,int>::iterator it = mObjectPaths.find(path);
if( it == mObjectPaths.end() )
{
AI_LOG_ERROR("object path '%s' not registered", path.c_str());
}
else if( --(it->second) == 0 )
{
mObjectPaths.erase(it);
}
}
bool IpcService::isRegisteredObjectPath(const std::string& path)
{
std::lock_guard<std::mutex> lock(mMutex);
return ( mObjectPaths.find(path) != mObjectPaths.end() );
}
void IpcService::unregisterHandlers()
{
AI_LOG_FN_ENTRY();
std::lock_guard<std::mutex> lock(mMutex);
std::string matchRule;
for ( auto iterMH = mMethodHandlers.begin(); iterMH != mMethodHandlers.end(); ++iterMH )
{
matchRule = getMatchRule(iterMH->second.first);
mDbusConnection->removeMatch(matchRule);
}
mMethodHandlers.clear();
for ( auto iterSH = mSignalHandlers.begin(); iterSH != mSignalHandlers.end(); ++iterSH )
{
matchRule = getMatchRule(iterSH->second.first);
mDbusConnection->removeMatch(matchRule);
}
mSignalHandlers.clear();
AI_LOG_FN_EXIT();
}
// -----------------------------------------------------------------------------
/**
* @brief Enables monitor mode on the IPC service, this will effectively
* disable all registered method and signal handlers
*
* This function is for debugging only, it can be used to monitor the entire
* bus and the interactions between clients.
*
* For production builds this function always returns false.
*
* @note As of dbus version 1.9.10 a new API was added to the daemon;
* org.freedesktop.DBus.Monitoring.BecomeMonitor, this is more convenient than
* using the magic eavesdrop=true match pattern. However currently we're still
* on an old dbus version that doesn't have that support.
*
*/
bool IpcService::enableMonitor(const std::set<std::string> &matchRules, const MonitorHandler &handler)
{
#if (AI_BUILD_TYPE != AI_DEBUG)
return false;
#else // (AI_BUILD_TYPE == AI_DEBUG)
AI_LOG_FN_ENTRY();
std::lock_guard<std::mutex> lock(mMutex);
// If already in monitor mode then remove any previous monitor match rules first
if (mInMonitorMode)
{
for (const std::string &rule : mMonitorMatchRules)
{
mDbusConnection->removeMatch(rule);
}
}
// Clear all the previous match rules
mMonitorMatchRules.clear();
// If no match rules were supplied then add the default capture all rule
if (matchRules.empty())
{
mMonitorMatchRules.emplace("eavesdrop=true");
}
else
{
const std::string rulePrefix("eavesdrop=true,");
for (const std::string &rule : matchRules)
{
mMonitorMatchRules.emplace(rulePrefix + rule);
}
}
// Set the handler and enable monitor mode now before setting the eavesdrop rules
mMonitorCb = handler;
mInMonitorMode = true;
// Add all the match rules
for (const std::string &rule : mMonitorMatchRules)
{
mDbusConnection->addMatch(rule);
}
AI_LOG_FN_EXIT();
return true;
#endif // if (AI_BUILD_TYPE == AI_DEBUG)
}
// -----------------------------------------------------------------------------
/**
* @brief Disables monitor mode and restores normal behaviour
*
* It's recommended that @a flush() is called after this function to ensure
* that the monitor callback will no longer be called.
*
*
*/
bool IpcService::disableMonitor()
{
#if (AI_BUILD_TYPE != AI_DEBUG)
return false;
#else // if (AI_BUILD_TYPE == AI_DEBUG)
AI_LOG_FN_ENTRY();
std::lock_guard<std::mutex> lock(mMutex);
// If monitor mode wasn't enabled of the match rules were empty then we were
// never in monitor mode in the first place
if ( !mInMonitorMode || mMonitorMatchRules.empty() )
{
AI_LOG_WARN("Not in monitor mode");
AI_LOG_FN_EXIT();
return false;
}
// Remove all the monitor match rules
for (const std::string& rule : mMonitorMatchRules)
{
mDbusConnection->removeMatch(rule);
}
// Disable the monitor mode flag and clear the callback
mInMonitorMode = false;
mMonitorCb = nullptr;
AI_LOG_FN_EXIT();
return true;
#endif // if (AI_BUILD_TYPE == AI_DEBUG)
}
// -----------------------------------------------------------------------------
/**
* @brief Checks if the named service is available on the bus
*
* This method is expected to be used at start to determine if the daemons
* are up and running.
*
* The method doesn't wait for the service to arrive, that would be nice to
* have and could be done by looking for the signals dbus send when a new
* client arrives. We could add that in the future rather than having this
* polling interface.
*
* @param[in] serviceName The name of the service to check for.
*
* @return false if an error occurried or the serviceName doesn't exist,
* otherwise true.
*/
bool IpcService::isServiceAvailable(const std::string& serviceName) const
{
AI_LOG_FN_ENTRY();
#if (AI_BUILD_TYPE == AI_DEBUG)
if ( !mRunning )
{
AI_LOG_WARN("Trying to check the serviceName without IpcService event loop running");
}
#endif
return mDbusConnection->nameHasOwner(serviceName);
}
std::string IpcService::getBusAddress() const
{
return mBusAddress;
}