Bug 788949 - Final version: Add PrepareAdapter function for registering agent and add reserved services, r=qdot, r=echou

This commit is contained in:
Gina Yeh 2012-09-20 21:22:02 +08:00
Родитель 4392ae0b55
Коммит a8a416d307
6 изменённых файлов: 214 добавлений и 110 удалений

Просмотреть файл

@ -162,7 +162,7 @@ public:
MOZ_ASSERT(NS_IsMainThread());
}
NS_IMETHOD Run()
NS_IMETHOD Run()
{
MOZ_ASSERT(!NS_IsMainThread());
@ -734,8 +734,8 @@ BluetoothService::Notify(const BluetoothSignal& aData)
JSContext* cx = nsContentUtils::GetSafeJSContext();
NS_ASSERTION(!::JS_IsExceptionPending(cx),
"Shouldn't get here when an exception is pending!");
JSAutoRequest jsar(cx);
JSAutoRequest jsar(cx);
JSObject* obj = JS_NewObject(cx, NULL, NULL, NULL);
if (!obj) {
NS_WARNING("Failed to new JSObject for system message!");

Просмотреть файл

@ -252,6 +252,9 @@ public:
SetAuthorizationInternal(const nsAString& aDeviceAddress, bool aAllow,
BluetoothReplyRunnable* aRunnable) = 0;
virtual nsresult
PrepareAdapterInternal(const nsAString& aPath) = 0;
bool
IsEnabled() const
{

Просмотреть файл

@ -126,7 +126,7 @@ BluetoothServiceChildProcess::GetPairedDevicePropertiesInternal(
nsresult
BluetoothServiceChildProcess::StopDiscoveryInternal(
const nsAString& aAdapterPath,
BluetoothReplyRunnable* aRunnable)
BluetoothReplyRunnable* aRunnable)
{
SendRequest(aRunnable, StopDiscoveryRequest(nsString(aAdapterPath)));
return NS_OK;
@ -277,6 +277,13 @@ BluetoothServiceChildProcess::SetAuthorizationInternal(
return NS_OK;
}
nsresult
BluetoothServiceChildProcess::PrepareAdapterInternal(const nsAString& aPath)
{
MOZ_NOT_REACHED("Should never be called from child");
return NS_ERROR_NOT_IMPLEMENTED;
}
nsresult
BluetoothServiceChildProcess::HandleStartup()
{

Просмотреть файл

@ -145,7 +145,9 @@ private:
GetDevicePropertiesInternal(const nsAString& aDevicePath,
const nsAString& aSignalPath) MOZ_OVERRIDE;
// This method should never be called from the child.
virtual nsresult
PrepareAdapterInternal(const nsAString& aPath) MOZ_OVERRIDE;
};
END_BLUETOOTH_NAMESPACE

Просмотреть файл

@ -140,7 +140,7 @@ static const char* sBluetoothDBusSignals[] =
/**
* 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;
@ -203,6 +203,39 @@ public:
}
};
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;
};
static bool
IsDBusMessageError(DBusMessage* aMsg, DBusError* aErr, nsAString& aErrorStr)
{
@ -211,7 +244,7 @@ IsDBusMessageError(DBusMessage* aMsg, DBusError* aErr, nsAString& aErrorStr)
LOG_AND_FREE_DBUS_ERROR(aErr);
return true;
}
DBusError err;
dbus_error_init(&err);
if (dbus_message_get_type(aMsg) == DBUS_MESSAGE_TYPE_ERROR) {
@ -248,7 +281,7 @@ DispatchBluetoothReply(BluetoothReplyRunnable* aRunnable,
MOZ_ASSERT(aValue.type() != BluetoothValue::T__None);
reply = new BluetoothReply(BluetoothReplySuccess(aValue));
}
aRunnable->SetReply(reply);
if (NS_FAILED(NS_DispatchToMainThread(aRunnable))) {
NS_WARNING("Failed to dispatch to main thread!");
@ -305,7 +338,7 @@ KeepDBusPairingMessage(const nsString& aDeviceAddress, DBusMessage* aMsg)
{
sPairingReqTable.Put(aDeviceAddress, aMsg);
// Increase ref count here because we need this message later.
// Increase ref count here because we need this message later.
// It'll be unrefed when set*Internal() is called.
dbus_message_ref(aMsg);
}
@ -367,12 +400,12 @@ AgentEventFilter(DBusConnection *conn, DBusMessage *msg, void *data)
// 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.
// 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.
@ -532,7 +565,7 @@ RegisterLocalAgent(const char* adapterPath,
} else {
dbus_message_unref(reply);
}
dbus_connection_flush(gThreadConnection->GetConnection());
return true;
}
@ -542,8 +575,8 @@ RegisterAgent(const nsAString& aAdapterPath)
{
MOZ_ASSERT(!NS_IsMainThread());
if (!RegisterLocalAgent(NS_ConvertUTF16toUTF8(aAdapterPath).get(),
LOCAL_AGENT_PATH,
if (!RegisterLocalAgent(NS_ConvertUTF16toUTF8(aAdapterPath).get(),
LOCAL_AGENT_PATH,
B2G_AGENT_CAPABILITIES)) {
return false;
}
@ -565,20 +598,94 @@ RegisterAgent(const nsAString& aAdapterPath)
}
static void
AddReservedServices(const nsAString& aAdapterPath)
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::AddReservedServicesInternal(const nsAString& aAdapterPath,
const nsTArray<uint32_t>& aServices,
nsTArray<uint32_t>& aServiceHandlesContainer)
{
MOZ_ASSERT(!NS_IsMainThread());
nsTArray<uint32_t> uuids;
int length = aServices.Length();
if (length == 0) return false;
uuids.AppendElement((uint32_t)(BluetoothServiceUuid::HandsfreeAG >> 32));
uuids.AppendElement((uint32_t)(BluetoothServiceUuid::HeadsetAG >> 32));
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);
sServiceHandles.Clear();
BluetoothDBusService::AddReservedServicesInternal(aAdapterPath, uuids,
sServiceHandles);
if (!reply) {
LOG("Null DBus message. Couldn't extract handles.");
return false;
}
ExtractHandles(reply, aServiceHandlesContainer);
return true;
}
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((uint32_t)(BluetoothServiceUuid::HandsfreeAG >> 32));
uuids.AppendElement((uint32_t)(BluetoothServiceUuid::HeadsetAG >> 32));
sServiceHandles.Clear();
if (!BluetoothDBusService::AddReservedServicesInternal(mPath, uuids, sServiceHandles)) {
NS_WARNING("Failed to add reserved services");
return NS_ERROR_FAILURE;
}
if(!RegisterAgent(mPath)) {
NS_WARNING("Failed to register agent");
return NS_ERROR_FAILURE;
}
return NS_OK;
}
private:
nsString mPath;
};
void
RunDBusCallback(DBusMessage* aMsg, void* aBluetoothReplyRunnable,
UnpackFunc aFunc)
@ -598,7 +705,7 @@ RunDBusCallback(DBusMessage* aMsg, void* aBluetoothReplyRunnable,
nsString replyError;
BluetoothValue v;
aFunc(aMsg, nullptr, v, replyError);
DispatchBluetoothReply(replyRunnable, v, replyError);
DispatchBluetoothReply(replyRunnable, v, replyError);
}
void
@ -652,7 +759,7 @@ GetProperty(DBusMessageIter aIter, Properties* aPropertyTypes,
uint32_t array_type;
int i, type;
if (dbus_message_iter_get_arg_type(&aIter) != DBUS_TYPE_STRING) {
if (dbus_message_iter_get_arg_type(&aIter) != DBUS_TYPE_STRING) {
return false;
}
@ -664,7 +771,7 @@ GetProperty(DBusMessageIter aIter, Properties* aPropertyTypes,
}
for (i = 0; i < aPropertyTypeLen; i++) {
if (!strncmp(property, aPropertyTypes[i].name, strlen(property))) {
if (!strncmp(property, aPropertyTypes[i].name, strlen(property))) {
break;
}
}
@ -692,7 +799,7 @@ GetProperty(DBusMessageIter aIter, Properties* aPropertyTypes,
NS_WARNING(str.get());
return false;
}
BluetoothValue propertyValue;
switch (type) {
case DBUS_TYPE_STRING:
@ -750,7 +857,7 @@ GetProperty(DBusMessageIter aIter, Properties* aPropertyTypes,
return true;
}
void
void
ParseProperties(DBusMessageIter* aIter,
BluetoothValue& aValue,
nsAString& aErrorStr,
@ -869,13 +976,13 @@ ParsePropertyChange(DBusMessage* aMsg, BluetoothValue& aValue,
DBusError err;
int prop_index = -1;
InfallibleTArray<BluetoothNamedValue> props;
dbus_error_init(&err);
if (!dbus_message_iter_init(aMsg, &iter)) {
NS_WARNING("Can't create iterator!");
return;
}
if (!GetProperty(iter, aPropertyTypes, aPropertyTypeLen,
&prop_index, props)) {
NS_WARNING("Can't get property!");
@ -967,12 +1074,12 @@ DBusHandlerResult
EventFilter(DBusConnection* aConn, DBusMessage* aMsg, void* aData)
{
NS_ASSERTION(!NS_IsMainThread(), "Shouldn't be called from Main Thread!");
if (dbus_message_get_type(aMsg) != DBUS_MESSAGE_TYPE_SIGNAL) {
LOG("%s: event handler not interested in %s (not a signal).\n",
__FUNCTION__, dbus_message_get_member(aMsg));
return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
}
}
if (dbus_message_get_path(aMsg) == NULL) {
LOG("DBusMessage %s has no bluetooth destination, ignoring\n",
@ -988,7 +1095,7 @@ EventFilter(DBusConnection* aConn, DBusMessage* aMsg, void* aData)
signalName = NS_ConvertUTF8toUTF16(dbus_message_get_member(aMsg));
nsString errorStr;
BluetoothValue v;
if (dbus_message_is_signal(aMsg, DBUS_ADAPTER_IFACE, "DeviceFound")) {
DBusMessageIter iter;
@ -999,7 +1106,7 @@ EventFilter(DBusConnection* aConn, DBusMessage* aMsg, void* aData)
const char* addr;
dbus_message_iter_get_basic(&iter, &addr);
if (dbus_message_iter_next(&iter)) {
ParseProperties(&iter,
v,
@ -1071,7 +1178,7 @@ EventFilter(DBusConnection* aConn, DBusMessage* aMsg, void* aData)
sDeviceProperties,
ArrayLength(sDeviceProperties));
if (v.get_ArrayOfBluetoothNamedValue()[0].name().EqualsLiteral("Paired")) {
// transfer signal to BluetoothService and
// transfer signal to BluetoothService and
// broadcast system message of bluetooth-pairingstatuschanged
signalName = NS_LITERAL_STRING("PairedStatusChanged");
signalPath = NS_LITERAL_STRING(LOCAL_AGENT_PATH);
@ -1086,8 +1193,13 @@ EventFilter(DBusConnection* aConn, DBusMessage* aMsg, void* aData)
errorStr.AssignLiteral("Cannot parse manager path!");
} else {
sDefaultAdapterPath = NS_ConvertUTF8toUTF16(str);
AddReservedServices(sDefaultAdapterPath);
v = sDefaultAdapterPath;
nsRefPtr<PrepareAdapterTask> b =
new PrepareAdapterTask(sDefaultAdapterPath);
if (NS_FAILED(NS_DispatchToMainThread(b))) {
NS_WARNING("Failed to dispatch to main thread!");
}
}
} else if (dbus_message_is_signal(aMsg, DBUS_MANAGER_IFACE, "PropertyChanged")) {
ParsePropertyChange(aMsg,
@ -1111,7 +1223,7 @@ EventFilter(DBusConnection* aConn, DBusMessage* aMsg, void* aData)
}
BluetoothSignal signal(signalName, signalPath, v);
nsRefPtr<DistributeBluetoothSignalTask>
t = new DistributeBluetoothSignalTask(signal);
if (NS_FAILED(NS_DispatchToMainThread(t))) {
@ -1126,12 +1238,12 @@ BluetoothDBusService::StartInternal()
{
// This could block. It should never be run on the main thread.
MOZ_ASSERT(!NS_IsMainThread());
if (!StartDBus()) {
NS_WARNING("Cannot start DBus thread!");
return NS_ERROR_FAILURE;
}
if (mConnection) {
return NS_OK;
}
@ -1143,7 +1255,7 @@ BluetoothDBusService::StartInternal()
}
gThreadConnection = new RawDBusConnection();
if (NS_FAILED(gThreadConnection->EstablishDBusConnection())) {
NS_WARNING("Cannot start Sync Thread DBus connection!");
StopDBus();
@ -1192,7 +1304,7 @@ BluetoothDBusService::StopInternal()
{
// This could block. It should never be run on the main thread.
MOZ_ASSERT(!NS_IsMainThread());
if (!mConnection) {
StopDBus();
return NS_OK;
@ -1210,7 +1322,19 @@ BluetoothDBusService::StopInternal()
}
dbus_connection_remove_filter(mConnection, EventFilter, nullptr);
if (!dbus_connection_unregister_object_path(gThreadConnection->GetConnection(),
LOCAL_AGENT_PATH)) {
LOG("%s: Can't unregister object path %s for agent!",
__FUNCTION__, LOCAL_AGENT_PATH);
}
if (!dbus_connection_unregister_object_path(gThreadConnection->GetConnection(),
REMOTE_AGENT_PATH)) {
LOG("%s: Can't unregister object path %s for agent!",
__FUNCTION__, LOCAL_AGENT_PATH);
}
mConnection = nullptr;
gThreadConnection = nullptr;
mBluetoothSignalObserverTable.Clear();
@ -1240,7 +1364,7 @@ public:
MOZ_ASSERT(!NS_IsMainThread());
DBusError err;
dbus_error_init(&err);
BluetoothValue v;
nsString replyError;
@ -1263,7 +1387,7 @@ public:
nsString path = v.get_nsString();
nsCString tmp_path = NS_ConvertUTF16toUTF8(path);
const char* object_path = tmp_path.get();
v = InfallibleTArray<BluetoothNamedValue>();
msg = dbus_func_args_timeout(gThreadConnection->GetConnection(),
1000,
@ -1273,7 +1397,7 @@ public:
"GetProperties",
DBUS_TYPE_INVALID);
UnpackAdapterPropertiesMessage(msg, &err, v, replyError);
if (!replyError.IsEmpty()) {
DispatchBluetoothReply(mRunnable, v, replyError);
return NS_ERROR_FAILURE;
@ -1285,10 +1409,8 @@ public:
v.get_ArrayOfBluetoothNamedValue().AppendElement(BluetoothNamedValue(NS_LITERAL_STRING("Path"),
path));
RegisterAgent(path);
DispatchBluetoothReply(mRunnable, v, replyError);
return NS_OK;
}
@ -1353,7 +1475,7 @@ BluetoothDBusService::StopDiscoveryInternal(const nsAString& aAdapterPath,
}
return SendDiscoveryMessage(aAdapterPath, "StopDiscovery", aRunnable);
}
nsresult
BluetoothDBusService::StartDiscoveryInternal(const nsAString& aAdapterPath,
BluetoothReplyRunnable* aRunnable)
@ -1481,10 +1603,10 @@ BluetoothDBusService::GetProperties(BluetoothObjectType aType,
MOZ_ASSERT(aType < ArrayLength(sBluetoothDBusIfaces));
MOZ_ASSERT(aType < ArrayLength(sBluetoothDBusPropCallbacks));
const char* interface = sBluetoothDBusIfaces[aType];
DBusCallback callback = sBluetoothDBusPropCallbacks[aType];
nsRefPtr<BluetoothReplyRunnable> runnable = aRunnable;
if (!dbus_func_args_async(mConnection,
@ -1569,7 +1691,7 @@ BluetoothDBusService::SetProperty(BluetoothObjectType aType,
NS_WARNING("Couldn't append arguments to dbus message!");
return NS_ERROR_FAILURE;
}
int type;
int tmp_int;
void* val;
@ -1592,7 +1714,7 @@ BluetoothDBusService::SetProperty(BluetoothObjectType aType,
dbus_message_unref(msg);
return NS_ERROR_FAILURE;
}
DBusMessageIter value_iter, iter;
dbus_message_iter_init_append(msg, &iter);
char var_type[2] = {(char)type, '\0'};
@ -1605,7 +1727,7 @@ BluetoothDBusService::SetProperty(BluetoothObjectType aType,
}
nsRefPtr<BluetoothReplyRunnable> runnable = aRunnable;
// msg is unref'd as part of dbus_func_send_async
// msg is unref'd as part of dbus_func_send_async
if (!dbus_func_send_async(mConnection,
msg,
1000,
@ -1649,58 +1771,6 @@ GetDeviceServiceChannel(const nsAString& aObjectPath,
return reply ? dbus_returns_int32(reply) : -1;
}
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::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;
}
// static
bool
BluetoothDBusService::RemoveReservedServicesInternal(const nsAString& aAdapterPath,
@ -1774,7 +1844,7 @@ BluetoothDBusService::RemoveDeviceInternal(const nsAString& aAdapterPath,
nsRefPtr<BluetoothReplyRunnable> runnable = aRunnable;
// We don't really care about how long it would take on removing a device,
// just to make sure that the value of timeout is reasonable. So, we use
// just to make sure that the value of timeout is reasonable. So, we use
// -1 for the timeout, which means a reasonable default timeout will be used.
bool ret = dbus_func_args_async(mConnection,
-1,
@ -1906,7 +1976,7 @@ BluetoothDBusService::SetPairingConfirmationInternal(const nsAString& aDeviceAdd
DBusMessage *reply;
if (aConfirm) {
reply = dbus_message_new_method_return(msg);
reply = dbus_message_new_method_return(msg);
} else {
reply = dbus_message_new_error(msg, "org.bluez.Error.Rejected",
"User rejected confirmation");
@ -1940,7 +2010,7 @@ BluetoothDBusService::SetAuthorizationInternal(const nsAString& aDeviceAddress,
nsString errorStr;
BluetoothValue v = true;
DBusMessage *msg;
if (!sAuthorizeReqTable.Get(aDeviceAddress, &msg)) {
LOG("%s: Couldn't get original request message.", __FUNCTION__);
errorStr.AssignLiteral("Couldn't get original request message.");
@ -1951,7 +2021,7 @@ BluetoothDBusService::SetAuthorizationInternal(const nsAString& aDeviceAddress,
DBusMessage *reply;
if (aAllow) {
reply = dbus_message_new_method_return(msg);
reply = dbus_message_new_method_return(msg);
} else {
reply = dbus_message_new_error(msg, "org.bluez.Error.Rejected",
"User rejected authorization");
@ -1977,6 +2047,25 @@ BluetoothDBusService::SetAuthorizationInternal(const nsAString& aDeviceAddress,
return result;
}
nsresult
BluetoothDBusService::PrepareAdapterInternal(const nsAString& aPath)
{
NS_ASSERTION(NS_IsMainThread(), "Must be called from main thread!");
if (!mConnection || !gThreadConnection) {
NS_ERROR("Bluetooth service not started yet!");
return NS_ERROR_FAILURE;
}
nsRefPtr<nsRunnable> func(new PrepareAdapterRunnable(aPath));
if (NS_FAILED(mBluetoothCommandThread->Dispatch(func, NS_DISPATCH_NORMAL))) {
NS_WARNING("Cannot dispatch task!");
return NS_ERROR_FAILURE;
}
return NS_OK;
}
class CreateBluetoothSocketRunnable : public nsRunnable
{
public:

Просмотреть файл

@ -89,14 +89,17 @@ public:
SetPasskeyInternal(const nsAString& aDeviceAddress, uint32_t aPasskey,
BluetoothReplyRunnable* aRunnable);
virtual bool
virtual bool
SetPairingConfirmationInternal(const nsAString& aDeviceAddress, bool aConfirm,
BluetoothReplyRunnable* aRunnable);
virtual bool
virtual bool
SetAuthorizationInternal(const nsAString& aDeviceAddress, bool aAllow,
BluetoothReplyRunnable* aRunnable);
virtual nsresult
PrepareAdapterInternal(const nsAString& aPath);
private:
nsresult SendGetPropertyMessage(const nsAString& aPath,
const char* aInterface,