/
BluetoothDBusService.cpp
2809 lines (2431 loc) · 88.8 KB
/
BluetoothDBusService.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
/* -*- Mode: c++; c-basic-offset: 2; indent-tabs-mode: nil; tab-width: 40 -*- */
/* vim: set ts=2 et sw=2 tw=80: */
/*
** Copyright 2006, The Android Open Source Project
**
** 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 "base/basictypes.h"
#include "BluetoothDBusService.h"
#include "BluetoothHfpManager.h"
#include "BluetoothOppManager.h"
#include "BluetoothReplyRunnable.h"
#include "BluetoothUnixSocketConnector.h"
#include "BluetoothUtils.h"
#include "BluetoothUuid.h"
#include <cstdio>
#include <dbus/dbus.h>
#include "pratom.h"
#include "nsAutoPtr.h"
#include "nsThreadUtils.h"
#include "nsDebug.h"
#include "nsDataHashtable.h"
#include "mozilla/Hal.h"
#include "mozilla/ipc/UnixSocket.h"
#include "mozilla/ipc/DBusThread.h"
#include "mozilla/ipc/DBusUtils.h"
#include "mozilla/ipc/RawDBusConnection.h"
#include "mozilla/Util.h"
#include "mozilla/dom/bluetooth/BluetoothTypes.h"
#if defined(MOZ_WIDGET_GONK)
#include "cutils/properties.h"
#endif
/**
* Some rules for dealing with memory in DBus:
* - A DBusError only needs to be deleted if it's been set, not just
* initialized. This is why LOG_AND_FREE... is called only when an error is
* set, and the macro cleans up the error itself.
* - A DBusMessage needs to be unrefed when it is newed explicitly. DBusMessages
* from signals do not need to be unrefed, as they will be cleaned by DBus
* after DBUS_HANDLER_RESULT_HANDLED is returned from the filter.
*/
using namespace mozilla;
using namespace mozilla::ipc;
USING_BLUETOOTH_NAMESPACE
#undef LOG
#if defined(MOZ_WIDGET_GONK)
#include <android/log.h>
#define LOG(args...) __android_log_print(ANDROID_LOG_INFO, "GonkDBus", args);
#else
#define BTDEBUG true
#define LOG(args...) if (BTDEBUG) printf(args);
#endif
#define B2G_AGENT_CAPABILITIES "DisplayYesNo"
#define DBUS_MANAGER_IFACE BLUEZ_DBUS_BASE_IFC ".Manager"
#define DBUS_ADAPTER_IFACE BLUEZ_DBUS_BASE_IFC ".Adapter"
#define DBUS_DEVICE_IFACE BLUEZ_DBUS_BASE_IFC ".Device"
#define DBUS_AGENT_IFACE BLUEZ_DBUS_BASE_IFC ".Agent"
#define BLUEZ_DBUS_BASE_PATH "/org/bluez"
#define BLUEZ_DBUS_BASE_IFC "org.bluez"
#define BLUEZ_ERROR_IFC "org.bluez.Error"
#define PROP_DEVICE_CONNECTED_TYPE "org.bluez.device.conn.type"
typedef struct {
const char* name;
int type;
} Properties;
static Properties sDeviceProperties[] = {
{"Address", DBUS_TYPE_STRING},
{"Name", DBUS_TYPE_STRING},
{"Icon", DBUS_TYPE_STRING},
{"Class", DBUS_TYPE_UINT32},
{"UUIDs", DBUS_TYPE_ARRAY},
{"Paired", DBUS_TYPE_BOOLEAN},
{"Connected", DBUS_TYPE_BOOLEAN},
{"Trusted", DBUS_TYPE_BOOLEAN},
{"Blocked", DBUS_TYPE_BOOLEAN},
{"Alias", DBUS_TYPE_STRING},
{"Nodes", DBUS_TYPE_ARRAY},
{"Adapter", DBUS_TYPE_OBJECT_PATH},
{"LegacyPairing", DBUS_TYPE_BOOLEAN},
{"RSSI", DBUS_TYPE_INT16},
{"TX", DBUS_TYPE_UINT32},
{"Type", DBUS_TYPE_STRING},
{"Broadcaster", DBUS_TYPE_BOOLEAN},
{"Services", DBUS_TYPE_ARRAY}
};
static Properties sAdapterProperties[] = {
{"Address", DBUS_TYPE_STRING},
{"Name", DBUS_TYPE_STRING},
{"Class", DBUS_TYPE_UINT32},
{"Powered", DBUS_TYPE_BOOLEAN},
{"Discoverable", DBUS_TYPE_BOOLEAN},
{"DiscoverableTimeout", DBUS_TYPE_UINT32},
{"Pairable", DBUS_TYPE_BOOLEAN},
{"PairableTimeout", DBUS_TYPE_UINT32},
{"Discovering", DBUS_TYPE_BOOLEAN},
{"Devices", DBUS_TYPE_ARRAY},
{"UUIDs", DBUS_TYPE_ARRAY},
{"Type", DBUS_TYPE_STRING}
};
static Properties sManagerProperties[] = {
{"Adapters", DBUS_TYPE_ARRAY},
};
static const char* sBluetoothDBusIfaces[] =
{
DBUS_MANAGER_IFACE,
DBUS_ADAPTER_IFACE,
DBUS_DEVICE_IFACE
};
static const char* sBluetoothDBusSignals[] =
{
"type='signal',interface='org.freedesktop.DBus'",
"type='signal',interface='org.bluez.Adapter'",
"type='signal',interface='org.bluez.Manager'",
"type='signal',interface='org.bluez.Device'",
"type='signal',interface='org.bluez.Input'",
"type='signal',interface='org.bluez.Network'",
"type='signal',interface='org.bluez.NetworkServer'",
"type='signal',interface='org.bluez.HealthDevice'",
"type='signal',interface='org.bluez.AudioSink'"
};
/**
* DBus Connection held for the BluetoothCommandThread to use. Should never be
* used by any other thread.
*
*/
static nsAutoPtr<RawDBusConnection> gThreadConnection;
static nsDataHashtable<nsStringHashKey, DBusMessage* > sPairingReqTable;
static nsDataHashtable<nsStringHashKey, DBusMessage* > sAuthorizeReqTable;
static PRInt32 sIsPairing = 0;
static nsString sAdapterPath;
typedef void (*UnpackFunc)(DBusMessage*, DBusError*, BluetoothValue&, nsAString&);
class RemoveDeviceTask : public nsRunnable {
public:
RemoveDeviceTask(const nsAString& aAdapterPath,
const nsACString& aDeviceObjectPath,
BluetoothReplyRunnable* aRunnable)
: mAdapterPath(aAdapterPath)
, mDeviceObjectPath(aDeviceObjectPath)
, mRunnable(aRunnable)
{
MOZ_ASSERT(!aAdapterPath.IsEmpty());
MOZ_ASSERT(!aDeviceObjectPath.IsEmpty());
MOZ_ASSERT(aRunnable);
}
nsresult Run()
{
MOZ_ASSERT(!NS_IsMainThread());
BluetoothValue v = true;
nsString errorStr;
const char* tempDeviceObjectPath = mDeviceObjectPath.get();
DBusMessage *reply =
dbus_func_args(gThreadConnection->GetConnection(),
NS_ConvertUTF16toUTF8(mAdapterPath).get(),
DBUS_ADAPTER_IFACE, "RemoveDevice",
DBUS_TYPE_OBJECT_PATH, &tempDeviceObjectPath,
DBUS_TYPE_INVALID);
if (reply) {
dbus_message_unref(reply);
} else {
errorStr.AssignLiteral("RemoveDevice failed");
}
DispatchBluetoothReply(mRunnable, v, errorStr);
return NS_OK;
}
private:
nsString mAdapterPath;
nsCString mDeviceObjectPath;
nsRefPtr<BluetoothReplyRunnable> mRunnable;
};
class SendDiscoveryTask : public nsRunnable {
public:
SendDiscoveryTask(const nsAString& aAdapterPath,
const char* aMessageName,
BluetoothReplyRunnable* aRunnable)
: mAdapterPath(aAdapterPath)
, mMessageName(aMessageName)
, mRunnable(aRunnable)
{
MOZ_ASSERT(aMessageName);
MOZ_ASSERT(aRunnable);
}
nsresult Run()
{
MOZ_ASSERT(!NS_IsMainThread());
DBusMessage *reply =
dbus_func_args(gThreadConnection->GetConnection(),
NS_ConvertUTF16toUTF8(mAdapterPath).get(),
DBUS_ADAPTER_IFACE, mMessageName,
DBUS_TYPE_INVALID);
if (reply) {
dbus_message_unref(reply);
}
BluetoothValue v = true;
nsString errorStr;
DispatchBluetoothReply(mRunnable, v, errorStr);
return NS_OK;
}
private:
nsString mAdapterPath;
const char* mMessageName;
nsRefPtr<BluetoothReplyRunnable> mRunnable;
};
class DistributeBluetoothSignalTask : public nsRunnable {
BluetoothSignal mSignal;
public:
DistributeBluetoothSignalTask(const BluetoothSignal& aSignal) :
mSignal(aSignal)
{
}
NS_IMETHOD
Run()
{
MOZ_ASSERT(NS_IsMainThread());
BluetoothService* bs = BluetoothService::Get();
if (!bs) {
NS_WARNING("BluetoothService not available!");
return NS_ERROR_FAILURE;
}
bs->DistributeSignal(mSignal);
return NS_OK;
}
};
class PrepareAdapterTask : public nsRunnable {
public:
PrepareAdapterTask(const nsAString& aPath) :
mPath(aPath)
{
}
NS_IMETHOD
Run()
{
MOZ_ASSERT(NS_IsMainThread());
BluetoothService* bs = BluetoothService::Get();
if (!bs) {
NS_WARNING("BluetoothService not available!");
return NS_ERROR_FAILURE;
}
// Due to the fact that we need to queue the dbus call to the command thread
// inside the bluetoothservice, we have to route the call down to the main
// thread and then back out to the command thread. There has to be a better
// way to do this.
if (NS_FAILED(bs->PrepareAdapterInternal(mPath))) {
NS_WARNING("Prepare adapter failed");
return NS_ERROR_FAILURE;
}
return NS_OK;
}
private:
nsString mPath;
};
class DevicePropertiesSignalHandler : public nsRunnable
{
public:
DevicePropertiesSignalHandler(const BluetoothSignal& aSignal) :
mSignal(aSignal)
{
}
NS_IMETHODIMP
Run()
{
MOZ_ASSERT(NS_IsMainThread());
// Get device properties and then send to BluetoothAdapter
BluetoothService* bs = BluetoothService::Get();
if (!bs) {
NS_WARNING("BluetoothService not available!");
return NS_ERROR_FAILURE;
}
// Due to the fact that we need to queue the dbus call to the command thread
// inside the bluetoothservice, we have to route the call down to the main
// thread and then back out to the command thread. There has to be a better
// way to do this.
if (NS_FAILED(bs->GetDevicePropertiesInternal(mSignal))) {
NS_WARNING("Get device properties failed");
return NS_ERROR_FAILURE;
}
return NS_OK;
}
private:
BluetoothSignal mSignal;
};
static bool
IsDBusMessageError(DBusMessage* aMsg, DBusError* aErr, nsAString& aErrorStr)
{
if (aErr && dbus_error_is_set(aErr)) {
aErrorStr = NS_ConvertUTF8toUTF16(aErr->message);
LOG_AND_FREE_DBUS_ERROR(aErr);
return true;
}
DBusError err;
dbus_error_init(&err);
if (dbus_message_get_type(aMsg) == DBUS_MESSAGE_TYPE_ERROR) {
const char* error_msg;
if (!dbus_message_get_args(aMsg, &err, DBUS_TYPE_STRING,
&error_msg, DBUS_TYPE_INVALID) ||
!error_msg) {
if (dbus_error_is_set(&err)) {
aErrorStr = NS_ConvertUTF8toUTF16(err.message);
LOG_AND_FREE_DBUS_ERROR(&err);
return true;
} else {
aErrorStr.AssignLiteral("Unknown Error");
return true;
}
} else {
aErrorStr = NS_ConvertUTF8toUTF16(error_msg);
return true;
}
}
return false;
}
static void
UnpackIntMessage(DBusMessage* aMsg, DBusError* aErr,
BluetoothValue& aValue, nsAString& aErrorStr)
{
DBusError err;
dbus_error_init(&err);
if (!IsDBusMessageError(aMsg, aErr, aErrorStr)) {
NS_ASSERTION(dbus_message_get_type(aMsg) == DBUS_MESSAGE_TYPE_METHOD_RETURN,
"Got dbus callback that's not a METHOD_RETURN!");
int i;
if (!dbus_message_get_args(aMsg, &err, DBUS_TYPE_INT32,
&i, DBUS_TYPE_INVALID)) {
if (dbus_error_is_set(&err)) {
aErrorStr = NS_ConvertUTF8toUTF16(err.message);
LOG_AND_FREE_DBUS_ERROR(&err);
}
} else {
aValue = (uint32_t)i;
}
}
}
static void
UnpackObjectPathMessage(DBusMessage* aMsg, DBusError* aErr,
BluetoothValue& aValue, nsAString& aErrorStr)
{
DBusError err;
dbus_error_init(&err);
if (!IsDBusMessageError(aMsg, aErr, aErrorStr)) {
NS_ASSERTION(dbus_message_get_type(aMsg) == DBUS_MESSAGE_TYPE_METHOD_RETURN,
"Got dbus callback that's not a METHOD_RETURN!");
const char* object_path;
if (!dbus_message_get_args(aMsg, &err, DBUS_TYPE_OBJECT_PATH,
&object_path, DBUS_TYPE_INVALID) ||
!object_path) {
if (dbus_error_is_set(&err)) {
aErrorStr = NS_ConvertUTF8toUTF16(err.message);
LOG_AND_FREE_DBUS_ERROR(&err);
}
} else {
aValue = NS_ConvertUTF8toUTF16(object_path);
}
}
}
static void
KeepDBusPairingMessage(const nsString& aDeviceAddress, DBusMessage* aMsg)
{
sPairingReqTable.Put(aDeviceAddress, aMsg);
// Increase ref count here because we need this message later.
// It'll be unrefed when set*Internal() is called.
dbus_message_ref(aMsg);
}
static DBusHandlerResult
AgentEventFilter(DBusConnection *conn, DBusMessage *msg, void *data)
{
if (dbus_message_get_type(msg) != DBUS_MESSAGE_TYPE_METHOD_CALL) {
LOG("%s: agent handler not interested (not a method call).\n", __FUNCTION__);
return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
}
DBusError err;
dbus_error_init(&err);
nsString signalPath = NS_ConvertUTF8toUTF16(dbus_message_get_path(msg));
nsString signalName = NS_ConvertUTF8toUTF16(dbus_message_get_member(msg));
nsString errorStr;
BluetoothValue v;
InfallibleTArray<BluetoothNamedValue> parameters;
// The following descriptions of each signal are retrieved from:
//
// http://maemo.org/api_refs/5.0/beta/bluez/agent.html
//
if (dbus_message_is_method_call(msg, DBUS_AGENT_IFACE, "Cancel")) {
// This method gets called to indicate that the agent request failed before a reply
// was returned.
// Return directly
DBusMessage *reply = dbus_message_new_method_return(msg);
if (!reply) {
errorStr.AssignLiteral("Memory can't be allocated for the message.");
} else {
dbus_connection_send(conn, reply, NULL);
dbus_message_unref(reply);
v = parameters;
}
} else if (dbus_message_is_method_call(msg, DBUS_AGENT_IFACE, "Authorize")) {
// This method gets called when the service daemon needs to authorize a
// connection/service request.
char *objectPath;
const char *uuid;
if (!dbus_message_get_args(msg, NULL,
DBUS_TYPE_OBJECT_PATH, &objectPath,
DBUS_TYPE_STRING, &uuid,
DBUS_TYPE_INVALID)) {
LOG("%s: Invalid arguments for Authorize() method", __FUNCTION__);
errorStr.AssignLiteral("Invalid arguments for Authorize() method");
} else {
nsString deviceAddress =
GetAddressFromObjectPath(NS_ConvertUTF8toUTF16(objectPath));
parameters.AppendElement(BluetoothNamedValue(
NS_LITERAL_STRING("deviceAddress"),
deviceAddress));
parameters.AppendElement(BluetoothNamedValue(
NS_LITERAL_STRING("uuid"),
NS_ConvertUTF8toUTF16(uuid)));
// Because we may have authorization request and pairing request from the
// same remote device at the same time, we need two tables to keep these messages.
sAuthorizeReqTable.Put(deviceAddress, msg);
// Increase ref count here because we need this message later.
// It'll be unrefed when setAuthorizationInternal() is called.
dbus_message_ref(msg);
v = parameters;
}
} else if (dbus_message_is_method_call(msg, DBUS_AGENT_IFACE, "RequestConfirmation")) {
// This method gets called when the service daemon needs to confirm a passkey for
// an authentication.
char *objectPath;
uint32_t passkey;
if (!dbus_message_get_args(msg, NULL,
DBUS_TYPE_OBJECT_PATH, &objectPath,
DBUS_TYPE_UINT32, &passkey,
DBUS_TYPE_INVALID)) {
LOG("%s: Invalid arguments for RequestConfirmation() method", __FUNCTION__);
errorStr.AssignLiteral("Invalid arguments for RequestConfirmation() method");
} else {
parameters.AppendElement(BluetoothNamedValue(
NS_LITERAL_STRING("address"),
NS_ConvertUTF8toUTF16(objectPath)));
parameters.AppendElement(BluetoothNamedValue(
NS_LITERAL_STRING("passkey"),
passkey));
KeepDBusPairingMessage(GetAddressFromObjectPath(
NS_ConvertUTF8toUTF16(objectPath)), msg);
BluetoothSignal signal(signalName, signalPath, parameters);
// Fire a Device properties fetcher at the main thread
nsRefPtr<DevicePropertiesSignalHandler> b =
new DevicePropertiesSignalHandler(signal);
if (NS_FAILED(NS_DispatchToMainThread(b))) {
NS_WARNING("Failed to dispatch to main thread!");
}
// Since we're handling this in other threads, just fall out here
return DBUS_HANDLER_RESULT_HANDLED;
}
} else if (dbus_message_is_method_call(msg, DBUS_AGENT_IFACE, "RequestPinCode")) {
// This method gets called when the service daemon needs to get the passkey for an
// authentication. The return value should be a string of 1-16 characters length.
// The string can be alphanumeric.
char *objectPath;
if (!dbus_message_get_args(msg, NULL,
DBUS_TYPE_OBJECT_PATH, &objectPath,
DBUS_TYPE_INVALID)) {
LOG("%s: Invalid arguments for RequestPinCode() method", __FUNCTION__);
errorStr.AssignLiteral("Invalid arguments for RequestPinCode() method");
} else {
parameters.AppendElement(BluetoothNamedValue(
NS_LITERAL_STRING("address"),
NS_ConvertUTF8toUTF16(objectPath)));
KeepDBusPairingMessage(GetAddressFromObjectPath(
NS_ConvertUTF8toUTF16(objectPath)), msg);
BluetoothSignal signal(signalName, signalPath, parameters);
// Fire a Device properties fetcher at the main thread
nsRefPtr<DevicePropertiesSignalHandler> b =
new DevicePropertiesSignalHandler(signal);
if (NS_FAILED(NS_DispatchToMainThread(b))) {
NS_WARNING("Failed to dispatch to main thread!");
}
// Since we're handling this in other threads, just fall out here
return DBUS_HANDLER_RESULT_HANDLED;
}
} else if (dbus_message_is_method_call(msg, DBUS_AGENT_IFACE, "RequestPasskey")) {
// This method gets called when the service daemon needs to get the passkey for an
// authentication. The return value should be a numeric value between 0-999999.
char *objectPath;
if (!dbus_message_get_args(msg, NULL,
DBUS_TYPE_OBJECT_PATH, &objectPath,
DBUS_TYPE_INVALID)) {
LOG("%s: Invalid arguments for RequestPasskey() method", __FUNCTION__);
errorStr.AssignLiteral("Invalid arguments for RequestPasskey() method");
} else {
parameters.AppendElement(BluetoothNamedValue(
NS_LITERAL_STRING("address"),
NS_ConvertUTF8toUTF16(objectPath)));
KeepDBusPairingMessage(GetAddressFromObjectPath(
NS_ConvertUTF8toUTF16(objectPath)), msg);
BluetoothSignal signal(signalName, signalPath, parameters);
// Fire a Device properties fetcher at the main thread
nsRefPtr<DevicePropertiesSignalHandler> b =
new DevicePropertiesSignalHandler(signal);
if (NS_FAILED(NS_DispatchToMainThread(b))) {
NS_WARNING("Failed to dispatch to main thread!");
}
// Since we're handling this in other threads, just fall out here
return DBUS_HANDLER_RESULT_HANDLED;
}
} else if (dbus_message_is_method_call(msg, DBUS_AGENT_IFACE, "Release")) {
// This method gets called when the service daemon unregisters the agent. An agent
// can use it to do cleanup tasks. There is no need to unregister the agent, because
// when this method gets called it has already been unregistered.
DBusMessage *reply = dbus_message_new_method_return(msg);
if (!reply) {
errorStr.AssignLiteral("Memory can't be allocated for the message.");
} else {
dbus_connection_send(conn, reply, NULL);
dbus_message_unref(reply);
// Do not send an notification to upper layer, too annoying.
return DBUS_HANDLER_RESULT_HANDLED;
}
} else {
#ifdef DEBUG
LOG("agent handler %s: Unhandled event. Ignore.", __FUNCTION__);
#endif
return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
}
if (!errorStr.IsEmpty()) {
NS_WARNING(NS_ConvertUTF16toUTF8(errorStr).get());
return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
}
BluetoothSignal signal(signalName, signalPath, v);
nsRefPtr<DistributeBluetoothSignalTask> t =
new DistributeBluetoothSignalTask(signal);
if (NS_FAILED(NS_DispatchToMainThread(t))) {
NS_WARNING("Failed to dispatch to main thread!");
}
return DBUS_HANDLER_RESULT_HANDLED;
}
static const DBusObjectPathVTable agentVtable = {
NULL, AgentEventFilter, NULL, NULL, NULL, NULL
};
// Local agent means agent for Adapter, not agent for Device. Some signals
// will be passed to local agent, some will be passed to device agent.
// For example, if a remote device would like to pair with us, then the
// signal will be passed to local agent. If we start pairing process with
// calling CreatePairedDevice, we'll get signal which should be passed to
// device agent.
static bool
RegisterLocalAgent(const char* adapterPath,
const char* agentPath,
const char* capabilities)
{
MOZ_ASSERT(!NS_IsMainThread());
if (!dbus_connection_register_object_path(gThreadConnection->GetConnection(),
agentPath,
&agentVtable,
NULL)) {
LOG("%s: Can't register object path %s for agent!",
__FUNCTION__, agentPath);
return false;
}
DBusMessage* msg =
dbus_message_new_method_call("org.bluez", adapterPath,
DBUS_ADAPTER_IFACE, "RegisterAgent");
if (!msg) {
LOG("%s: Can't allocate new method call for agent!", __FUNCTION__);
return false;
}
if (!dbus_message_append_args(msg,
DBUS_TYPE_OBJECT_PATH, &agentPath,
DBUS_TYPE_STRING, &capabilities,
DBUS_TYPE_INVALID)) {
LOG("%s: Couldn't append arguments to dbus message.", __FUNCTION__);
return false;
}
DBusError err;
dbus_error_init(&err);
DBusMessage* reply =
dbus_connection_send_with_reply_and_block(gThreadConnection->GetConnection(),
msg, -1, &err);
dbus_message_unref(msg);
if (!reply) {
if (dbus_error_is_set(&err)) {
if (!strcmp(err.name, "org.bluez.Error.AlreadyExists")) {
LOG_AND_FREE_DBUS_ERROR(&err);
#ifdef DEBUG
LOG("Agent already registered, still returning true");
#endif
} else {
LOG_AND_FREE_DBUS_ERROR(&err);
LOG("%s: Can't register agent!", __FUNCTION__);
return false;
}
}
} else {
dbus_message_unref(reply);
}
dbus_connection_flush(gThreadConnection->GetConnection());
return true;
}
static bool
RegisterAgent(const nsAString& aAdapterPath)
{
MOZ_ASSERT(!NS_IsMainThread());
if (!RegisterLocalAgent(NS_ConvertUTF16toUTF8(aAdapterPath).get(),
LOCAL_AGENT_PATH,
B2G_AGENT_CAPABILITIES)) {
return false;
}
// There is no "RegisterAgent" function defined in device interface.
// When we call "CreatePairedDevice", it will do device agent registration for us.
// (See maemo.org/api_refs/5.0/beta/bluez/adapter.html)
if (!dbus_connection_register_object_path(gThreadConnection->GetConnection(),
REMOTE_AGENT_PATH,
&agentVtable,
NULL)) {
LOG("%s: Can't register object path %s for remote device agent!",
__FUNCTION__, REMOTE_AGENT_PATH);
return false;
}
return true;
}
static void
ExtractHandles(DBusMessage *aReply, nsTArray<uint32_t>& aOutHandles)
{
uint32_t* handles = NULL;
int len;
DBusError err;
dbus_error_init(&err);
if (dbus_message_get_args(aReply, &err,
DBUS_TYPE_ARRAY, DBUS_TYPE_UINT32, &handles, &len,
DBUS_TYPE_INVALID)) {
if (!handles) {
LOG("Null array in extract_handles");
} else {
for (int i = 0; i < len; ++i) {
aOutHandles.AppendElement(handles[i]);
}
}
} else {
LOG_AND_FREE_DBUS_ERROR(&err);
}
}
// static
bool
BluetoothDBusService::AddServiceRecords(const nsAString& aAdapterPath,
const char* serviceName,
unsigned long long uuidMsb,
unsigned long long uuidLsb,
int channel)
{
MOZ_ASSERT(!NS_IsMainThread());
DBusMessage *reply;
reply = dbus_func_args(gThreadConnection->GetConnection(),
NS_ConvertUTF16toUTF8(aAdapterPath).get(),
DBUS_ADAPTER_IFACE, "AddRfcommServiceRecord",
DBUS_TYPE_STRING, &serviceName,
DBUS_TYPE_UINT64, &uuidMsb,
DBUS_TYPE_UINT64, &uuidLsb,
DBUS_TYPE_UINT16, &channel,
DBUS_TYPE_INVALID);
return reply ? dbus_returns_uint32(reply) : -1;
}
// static
bool
BluetoothDBusService::AddReservedServicesInternal(const nsAString& aAdapterPath,
const nsTArray<uint32_t>& aServices,
nsTArray<uint32_t>& aServiceHandlesContainer)
{
MOZ_ASSERT(!NS_IsMainThread());
int length = aServices.Length();
if (length == 0) return false;
const uint32_t* services = aServices.Elements();
DBusMessage* reply =
dbus_func_args(gThreadConnection->GetConnection(),
NS_ConvertUTF16toUTF8(aAdapterPath).get(),
DBUS_ADAPTER_IFACE, "AddReservedServiceRecords",
DBUS_TYPE_ARRAY, DBUS_TYPE_UINT32,
&services, length, DBUS_TYPE_INVALID);
if (!reply) {
LOG("Null DBus message. Couldn't extract handles.");
return false;
}
ExtractHandles(reply, aServiceHandlesContainer);
return true;
}
void
BluetoothDBusService::DisconnectAllAcls(const nsAString& aAdapterPath)
{
MOZ_ASSERT(!NS_IsMainThread());
DBusMessage* reply =
dbus_func_args(gThreadConnection->GetConnection(),
NS_ConvertUTF16toUTF8(aAdapterPath).get(),
DBUS_ADAPTER_IFACE, "DisconnectAllConnections",
DBUS_TYPE_INVALID);
if (reply) {
dbus_message_unref(reply);
}
}
class PrepareProfileManagersRunnable : public nsRunnable
{
public:
NS_IMETHOD
Run()
{
BluetoothHfpManager* hfp = BluetoothHfpManager::Get();
if (!hfp || !hfp->Listen()) {
NS_WARNING("Failed to start listening for BluetoothHfpManager!");
return NS_ERROR_FAILURE;
}
BluetoothOppManager* opp = BluetoothOppManager::Get();
if (!opp || !opp->Listen()) {
NS_WARNING("Failed to start listening for BluetoothOppManager!");
return NS_ERROR_FAILURE;
}
return NS_OK;
}
};
class PrepareAdapterRunnable : public nsRunnable
{
public:
PrepareAdapterRunnable(const nsAString& aPath) :
mPath(aPath)
{
MOZ_ASSERT(NS_IsMainThread());
}
NS_IMETHOD
Run()
{
MOZ_ASSERT(!NS_IsMainThread());
nsTArray<uint32_t> uuids;
uuids.AppendElement(BluetoothServiceClass::HANDSFREE_AG);
uuids.AppendElement(BluetoothServiceClass::HEADSET_AG);
uuids.AppendElement(BluetoothServiceClass::OBJECT_PUSH);
// TODO/qdot: This needs to be held for the life of the bluetooth connection
// so we could clean it up. For right now though, we can throw it away.
nsTArray<uint32_t> handles;
if (!BluetoothDBusService::AddReservedServicesInternal(mPath, uuids, handles)) {
NS_WARNING("Failed to add reserved services");
#ifdef MOZ_WIDGET_GONK
return NS_ERROR_FAILURE;
#endif
}
if(!RegisterAgent(mPath)) {
NS_WARNING("Failed to register agent");
return NS_ERROR_FAILURE;
}
NS_DispatchToMainThread(new PrepareProfileManagersRunnable());
return NS_OK;
}
private:
nsString mPath;
};
void
RunDBusCallback(DBusMessage* aMsg, void* aBluetoothReplyRunnable,
UnpackFunc aFunc)
{
#ifdef MOZ_WIDGET_GONK
// Due to the fact that we're running two dbus loops on desktop implicitly by
// being gtk based, sometimes we'll get signals/reply coming in on the main
// thread. There's not a lot we can do about that for the time being and it
// (technically) shouldn't hurt anything. However, on gonk, die.
MOZ_ASSERT(!NS_IsMainThread());
#endif
nsRefPtr<BluetoothReplyRunnable> replyRunnable =
dont_AddRef(static_cast< BluetoothReplyRunnable* >(aBluetoothReplyRunnable));
NS_ASSERTION(replyRunnable, "Callback reply runnable is null!");
nsString replyError;
BluetoothValue v;
aFunc(aMsg, nullptr, v, replyError);
DispatchBluetoothReply(replyRunnable, v, replyError);
}
void
GetObjectPathCallback(DBusMessage* aMsg, void* aBluetoothReplyRunnable)
{
if (sIsPairing) {
RunDBusCallback(aMsg, aBluetoothReplyRunnable,
UnpackObjectPathMessage);
PR_AtomicDecrement(&sIsPairing);
}
}
void
UnpackVoidMessage(DBusMessage* aMsg, DBusError* aErr, BluetoothValue& aValue,
nsAString& aErrorStr)
{
DBusError err;
dbus_error_init(&err);
if (!IsDBusMessageError(aMsg, aErr, aErrorStr) &&
dbus_message_get_type(aMsg) == DBUS_MESSAGE_TYPE_METHOD_RETURN &&
!dbus_message_get_args(aMsg, &err, DBUS_TYPE_INVALID)) {
if (dbus_error_is_set(&err)) {
aErrorStr = NS_ConvertUTF8toUTF16(err.message);
LOG_AND_FREE_DBUS_ERROR(&err);
}
}
// XXXbent Need to figure out something better than this here.
if (aErrorStr.IsEmpty()) {
aValue = true;
}
}
void
GetVoidCallback(DBusMessage* aMsg, void* aBluetoothReplyRunnable)
{
RunDBusCallback(aMsg, aBluetoothReplyRunnable,
UnpackVoidMessage);
}
void
GetIntCallback(DBusMessage* aMsg, void* aBluetoothReplyRunnable)
{
RunDBusCallback(aMsg, aBluetoothReplyRunnable,
UnpackIntMessage);
}
bool
IsDeviceConnectedTypeBoolean()
{
#if defined(MOZ_WIDGET_GONK)
char connProp[PROPERTY_VALUE_MAX];
property_get(PROP_DEVICE_CONNECTED_TYPE, connProp, "boolean");
if (strcmp(connProp, "boolean") == 0) {
return true;
}
return false;
#else
// Assume it's always a boolean on desktop. Fixing someday in Bug 806457.
return true;
#endif
}
void
CopyProperties(Properties* inProp, Properties* outProp, int aPropertyTypeLen)
{
int i;
for (i = 0; i < aPropertyTypeLen; i++) {
outProp[i].name = inProp[i].name;
outProp[i].type = inProp[i].type;
}
}
int
GetPropertyIndex(Properties* prop, const char* propertyName,
int aPropertyTypeLen)
{
int i;
for (i = 0; i < aPropertyTypeLen; i++) {
if (!strncmp(propertyName, prop[i].name, strlen(propertyName))) {
return i;
}
}
return -1;
}
bool
HasAudioService(uint32_t aCodValue)
{
return ((aCodValue & 0x200000) == 0x200000);
}
bool
ContainsIcon(const InfallibleTArray<BluetoothNamedValue>& aProperties)
{
for (uint8_t i = 0; i < aProperties.Length(); i++) {
if (aProperties[i].name().EqualsLiteral("Icon")) {
return true;
}
}
return false;
}
bool
GetProperty(DBusMessageIter aIter, Properties* aPropertyTypes,
int aPropertyTypeLen, int* aPropIndex,
InfallibleTArray<BluetoothNamedValue>& aProperties)