diff options
Diffstat (limited to 'plugins')
-rw-r--r-- | plugins/dbusoob.c | 234 | ||||
-rw-r--r-- | plugins/echo.c | 167 | ||||
-rw-r--r-- | plugins/formfactor.c | 148 | ||||
-rw-r--r-- | plugins/hal.c | 144 | ||||
-rw-r--r-- | plugins/hciops.c | 3744 | ||||
-rw-r--r-- | plugins/maemo6.c | 252 | ||||
-rw-r--r-- | plugins/mgmtops.c | 1937 | ||||
-rw-r--r-- | plugins/pnat.c | 526 | ||||
-rw-r--r-- | plugins/service.c | 824 | ||||
-rw-r--r-- | plugins/storage.c | 43 |
10 files changed, 8019 insertions, 0 deletions
diff --git a/plugins/dbusoob.c b/plugins/dbusoob.c new file mode 100644 index 0000000..2c03780 --- /dev/null +++ b/plugins/dbusoob.c @@ -0,0 +1,234 @@ +/* + * + * BlueZ - Bluetooth protocol stack for Linux + * + * Copyright (C) 2011 ST-Ericsson SA + * + * Author: Szymon Janc <szymon.janc@tieto.com> for ST-Ericsson + * + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + * + */ + +#ifdef HAVE_CONFIG_H +#include <config.h> +#endif + +#include <errno.h> +#include <gdbus.h> + +#include <bluetooth/bluetooth.h> +#include <bluetooth/hci.h> +#include <bluetooth/sdp.h> + +#include "plugin.h" +#include "log.h" +#include "adapter.h" +#include "device.h" +#include "manager.h" +#include "dbus-common.h" +#include "event.h" +#include "error.h" +#include "oob.h" + +#define OOB_INTERFACE "org.bluez.OutOfBand" + +struct oob_request { + struct btd_adapter *adapter; + DBusMessage *msg; +}; + +static GSList *oob_requests = NULL; +static DBusConnection *connection = NULL; + +static gint oob_request_cmp(gconstpointer a, gconstpointer b) +{ + const struct oob_request *data = a; + const struct btd_adapter *adapter = b; + + return data->adapter != adapter; +} + +static struct oob_request *find_oob_request(struct btd_adapter *adapter) +{ + GSList *match; + + match = g_slist_find_custom(oob_requests, adapter, oob_request_cmp); + + if (match) + return match->data; + + return NULL; +} + +static void read_local_data_complete(struct btd_adapter *adapter, uint8_t *hash, + uint8_t *randomizer) +{ + struct DBusMessage *reply; + struct oob_request *oob_request; + + oob_request = find_oob_request(adapter); + if (!oob_request) + return; + + if (hash && randomizer) + reply = g_dbus_create_reply(oob_request->msg, + DBUS_TYPE_ARRAY, DBUS_TYPE_BYTE, &hash, 16, + DBUS_TYPE_ARRAY, DBUS_TYPE_BYTE, &randomizer, 16, + DBUS_TYPE_INVALID); + else + reply = btd_error_failed(oob_request->msg, + "Failed to read local OOB data."); + + oob_requests = g_slist_remove(oob_requests, oob_request); + dbus_message_unref(oob_request->msg); + g_free(oob_request); + + if (!reply) { + error("Couldn't allocate D-Bus message"); + return; + } + + if (!g_dbus_send_message(connection, reply)) + error("D-Bus send failed"); +} + +static DBusMessage *read_local_data(DBusConnection *conn, DBusMessage *msg, + void *data) +{ + struct btd_adapter *adapter = data; + struct oob_request *oob_request; + + if (find_oob_request(adapter)) + return btd_error_in_progress(msg); + + if (btd_adapter_read_local_oob_data(adapter)) + return btd_error_failed(msg, "Request failed."); + + oob_request = g_new(struct oob_request, 1); + oob_request->adapter = adapter; + oob_requests = g_slist_append(oob_requests, oob_request); + oob_request->msg = dbus_message_ref(msg); + + return NULL; +} + +static DBusMessage *add_remote_data(DBusConnection *conn, DBusMessage *msg, + void *data) +{ + struct btd_adapter *adapter = data; + uint8_t *hash, *randomizer; + int32_t hlen, rlen; + const char *addr; + bdaddr_t bdaddr; + + if (!dbus_message_get_args(msg, NULL, + DBUS_TYPE_STRING, &addr, + DBUS_TYPE_ARRAY, DBUS_TYPE_BYTE, &hash, &hlen, + DBUS_TYPE_ARRAY, DBUS_TYPE_BYTE, &randomizer, &rlen, + DBUS_TYPE_INVALID)) + return btd_error_invalid_args(msg); + + if (hlen != 16 || rlen != 16 || bachk(addr)) + return btd_error_invalid_args(msg); + + str2ba(addr, &bdaddr); + + if (btd_adapter_add_remote_oob_data(adapter, &bdaddr, hash, randomizer)) + return btd_error_failed(msg, "Request failed"); + + return g_dbus_create_reply(msg, DBUS_TYPE_INVALID); +} + +static DBusMessage *remove_remote_data(DBusConnection *conn, DBusMessage *msg, + void *data) +{ + struct btd_adapter *adapter = data; + const char *addr; + bdaddr_t bdaddr; + + if (!dbus_message_get_args(msg, NULL, DBUS_TYPE_STRING, &addr, + DBUS_TYPE_INVALID)) + return btd_error_invalid_args(msg); + + if (bachk(addr)) + return btd_error_invalid_args(msg); + + str2ba(addr, &bdaddr); + + if (btd_adapter_remove_remote_oob_data(adapter, &bdaddr)) + return btd_error_failed(msg, "Request failed"); + + return g_dbus_create_reply(msg, DBUS_TYPE_INVALID); +} + +static GDBusMethodTable oob_methods[] = { + {"AddRemoteData", "sayay", "", add_remote_data}, + {"RemoveRemoteData", "s", "", remove_remote_data}, + {"ReadLocalData", "", "ayay", read_local_data, + G_DBUS_METHOD_FLAG_ASYNC}, + {} +}; + +static int oob_probe(struct btd_adapter *adapter) +{ + const char *path = adapter_get_path(adapter); + + if (!g_dbus_register_interface(connection, path, OOB_INTERFACE, + oob_methods, NULL, NULL, adapter, NULL)) { + error("OOB interface init failed on path %s", path); + return -EIO; + } + + return 0; +} + +static void oob_remove(struct btd_adapter *adapter) +{ + read_local_data_complete(adapter, NULL, NULL); + + g_dbus_unregister_interface(connection, adapter_get_path(adapter), + OOB_INTERFACE); +} + +static struct btd_adapter_driver oob_driver = { + .name = "oob", + .probe = oob_probe, + .remove = oob_remove, +}; + +static int dbusoob_init(void) +{ + DBG("Setup dbusoob plugin"); + + connection = get_dbus_connection(); + + oob_register_cb(read_local_data_complete); + + return btd_register_adapter_driver(&oob_driver); +} + +static void dbusoob_exit(void) +{ + DBG("Cleanup dbusoob plugin"); + + manager_foreach_adapter((adapter_cb) oob_remove, NULL); + + btd_unregister_adapter_driver(&oob_driver); +} + +BLUETOOTH_PLUGIN_DEFINE(dbusoob, VERSION, BLUETOOTH_PLUGIN_PRIORITY_DEFAULT, + dbusoob_init, dbusoob_exit) diff --git a/plugins/echo.c b/plugins/echo.c new file mode 100644 index 0000000..23f6e49 --- /dev/null +++ b/plugins/echo.c @@ -0,0 +1,167 @@ +/* + * + * BlueZ - Bluetooth protocol stack for Linux + * + * Copyright (C) 2004-2010 Marcel Holtmann <marcel@holtmann.org> + * + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + * + */ + +#ifdef HAVE_CONFIG_H +#include <config.h> +#endif + +#include <errno.h> +#include <unistd.h> +#include <sys/socket.h> + +#include <bluetooth/bluetooth.h> +#include <bluetooth/rfcomm.h> + +#include <glib.h> + +#include <gdbus.h> + +#include "plugin.h" +#include "adapter.h" +#include "log.h" + +static gboolean session_event(GIOChannel *chan, + GIOCondition cond, gpointer data) +{ + unsigned char buf[672]; + gsize len, written; + GIOError err; + + if (cond & (G_IO_HUP | G_IO_ERR | G_IO_NVAL)) + return FALSE; + + err = g_io_channel_read(chan, (gchar *) buf, sizeof(buf), &len); + if (err == G_IO_ERROR_AGAIN) + return TRUE; + + g_io_channel_write(chan, (const gchar *) buf, len, &written); + + return TRUE; +} + +static gboolean connect_event(GIOChannel *chan, + GIOCondition cond, gpointer data) +{ + GIOChannel *io; + struct sockaddr_rc addr; + socklen_t optlen; + char address[18]; + int sk, nsk; + + sk = g_io_channel_unix_get_fd(chan); + + memset(&addr, 0, sizeof(addr)); + optlen = sizeof(addr); + + nsk = accept(sk, (struct sockaddr *) &addr, &optlen); + if (nsk < 0) + return TRUE; + + io = g_io_channel_unix_new(nsk); + g_io_channel_set_close_on_unref(io, TRUE); + + ba2str(&addr.rc_bdaddr, address); + + g_io_add_watch(io, G_IO_IN | G_IO_HUP | G_IO_ERR | G_IO_NVAL, + session_event, NULL); + + return TRUE; +} + +static GIOChannel *setup_rfcomm(uint8_t channel) +{ + GIOChannel *io; + struct sockaddr_rc addr; + int sk; + + sk = socket(PF_BLUETOOTH, SOCK_STREAM, BTPROTO_RFCOMM); + if (sk < 0) + return NULL; + + memset(&addr, 0, sizeof(addr)); + addr.rc_family = AF_BLUETOOTH; + bacpy(&addr.rc_bdaddr, BDADDR_ANY); + addr.rc_channel = channel; + + if (bind(sk, (struct sockaddr *) &addr, sizeof(addr)) < 0) { + close(sk); + return NULL; + } + + if (listen(sk, 10) < 0) { + close(sk); + return NULL; + } + + io = g_io_channel_unix_new(sk); + g_io_channel_set_close_on_unref(io, TRUE); + + g_io_add_watch(io, G_IO_IN, connect_event, NULL); + + return io; +} + +static GIOChannel *chan = NULL; + +static int echo_probe(struct btd_adapter *adapter) +{ + const char *path = adapter_get_path(adapter); + + DBG("path %s", path); + + chan = setup_rfcomm(23); + + return 0; +} + +static void echo_remove(struct btd_adapter *adapter) +{ + const char *path = adapter_get_path(adapter); + + DBG("path %s", path); + + g_io_channel_unref(chan); +} + +static struct btd_adapter_driver echo_server = { + .name = "echo-server", + .probe = echo_probe, + .remove = echo_remove, +}; + +static int echo_init(void) +{ + DBG("Setup echo plugin"); + + return btd_register_adapter_driver(&echo_server); +} + +static void echo_exit(void) +{ + DBG("Cleanup echo plugin"); + + btd_unregister_adapter_driver(&echo_server); +} + +BLUETOOTH_PLUGIN_DEFINE(echo, VERSION, + BLUETOOTH_PLUGIN_PRIORITY_DEFAULT, echo_init, echo_exit) diff --git a/plugins/formfactor.c b/plugins/formfactor.c new file mode 100644 index 0000000..758d481 --- /dev/null +++ b/plugins/formfactor.c @@ -0,0 +1,148 @@ +/* + * + * BlueZ - Bluetooth protocol stack for Linux + * + * Copyright (C) 2004-2010 Marcel Holtmann <marcel@holtmann.org> + * + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + * + */ + +#ifdef HAVE_CONFIG_H +#include <config.h> +#endif + +#include <stdlib.h> +#include <errno.h> + +#include <bluetooth/bluetooth.h> + +#include "plugin.h" +#include "adapter.h" +#include "log.h" + +#define DMI_CHASSIS_FILE "/sys/class/dmi/id/chassis_type" +#define DMI_CHASSIS_FILE_FALLBACK "/sys/devices/virtual/dmi/id/chassis_type" + +/* Map the chassis type from chassis_type to a sensible type used in hal + * + * See also 3.3.4.1 of the "System Management BIOS Reference Specification, + * Version 2.6.1" (Preliminary Standard) document, available from + * http://www.dmtf.org/standards/smbios. + * + * TODO: figure out WTF the mapping should be; "Lunch Box"? Give me a break :-) + * + * Copied from hal/hald/linux/osspec.c + */ +static const char *chassis_map[] = { + "Other", "unknown", /* 0x01 */ + "Unknown", "unknown", + "Desktop", "desktop", + "Low Profile Desktop", "desktop", + "Pizza Box", "server", + "Mini Tower", "desktop", + "Tower", "desktop", + "Portable", "laptop", + "Laptop", "laptop", + "Notebook", "laptop", + "Hand Held", "handheld", + "Docking Station", "laptop", + "All In One", "unknown", + "Sub Notebook", "laptop", + "Space-saving", "desktop", + "Lunch Box", "unknown", + "Main Server Chassis", "server", + "Expansion Chassis", "unknown", + "Sub Chassis", "unknown", + "Bus Expansion Chassis", "unknown", + "Peripheral Chassis", "unknown", + "RAID Chassis", "unknown", + "Rack Mount Chassis", "unknown", + "Sealed-case PC", "unknown", + "Multi-system", "unknown", + "CompactPCI", "unknonw", + "AdvancedTCA", "unknown", + "Blade", "server", + "Blade Enclosure" "unknown", /* 0x1D */ + NULL +}; + +static int formfactor_probe(struct btd_adapter *adapter) +{ + int chassis_type; + uint8_t minor = 0; + const char *formfactor; + char *contents; + + if (g_file_get_contents(DMI_CHASSIS_FILE, + &contents, NULL, NULL) == FALSE) { + if (g_file_get_contents(DMI_CHASSIS_FILE_FALLBACK, + &contents, NULL, NULL) == FALSE) { + error("Could not get the contents of DMI chassis type"); + return 0; + } + } + + chassis_type = atoi(contents); + g_free (contents); + + if (chassis_type > 0x1D || chassis_type <= 0) { + error ("Chassis type is not a known chassis type"); + return 0; + } + + formfactor = chassis_map[chassis_type * 2]; + if (formfactor != NULL) { + if (g_str_equal(formfactor, "laptop") == TRUE) + minor |= (1 << 2) | (1 << 3); + else if (g_str_equal(formfactor, "desktop") == TRUE) + minor |= 1 << 2; + else if (g_str_equal(formfactor, "server") == TRUE) + minor |= 1 << 3; + else if (g_str_equal(formfactor, "handheld") == TRUE) + minor += 1 << 4; + } + + /* Computer major class */ + DBG("Setting 0x%06x for major/minor device class", (1 << 8) | minor); + + btd_adapter_set_class(adapter, 0x01, minor); + + return 0; +} + +static void formfactor_remove(struct btd_adapter *adapter) +{ +} + +static struct btd_adapter_driver formfactor_driver = { + .name = "formfactor", + .probe = formfactor_probe, + .remove = formfactor_remove, +}; + +static int formfactor_init(void) +{ + return btd_register_adapter_driver(&formfactor_driver); +} + +static void formfactor_exit(void) +{ + btd_unregister_adapter_driver(&formfactor_driver); +} + +BLUETOOTH_PLUGIN_DEFINE(formfactor, VERSION, + BLUETOOTH_PLUGIN_PRIORITY_LOW, formfactor_init, formfactor_exit) diff --git a/plugins/hal.c b/plugins/hal.c new file mode 100644 index 0000000..21d7688 --- /dev/null +++ b/plugins/hal.c @@ -0,0 +1,144 @@ +/* + * + * BlueZ - Bluetooth protocol stack for Linux + * + * Copyright (C) 2004-2010 Marcel Holtmann <marcel@holtmann.org> + * + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + * + */ + +#ifdef HAVE_CONFIG_H +#include <config.h> +#endif + +#include <errno.h> +#include <dbus/dbus.h> + +#include <bluetooth/bluetooth.h> + +#include "plugin.h" +#include "adapter.h" +#include "log.h" + +static void formfactor_reply(DBusPendingCall *call, void *user_data) +{ + struct btd_adapter *adapter = user_data; + const char *formfactor = NULL; + DBusMessage *reply; + uint8_t minor = 0; + + reply = dbus_pending_call_steal_reply(call); + + if (dbus_set_error_from_message(NULL, reply) == TRUE) { + error("Failed to access HAL"); + dbus_message_unref(reply); + return; + } + + if (dbus_message_get_args(reply, NULL, DBUS_TYPE_STRING, &formfactor, + DBUS_TYPE_INVALID) == FALSE) { + error("Wrong formfactor arguments"); + dbus_message_unref(reply); + return; + } + + DBG("Computer is classified as %s", formfactor); + + if (formfactor != NULL) { + if (g_str_equal(formfactor, "laptop") == TRUE) + minor |= (1 << 2) | (1 << 3); + else if (g_str_equal(formfactor, "desktop") == TRUE) + minor |= 1 << 2; + else if (g_str_equal(formfactor, "server") == TRUE) + minor |= 1 << 3; + else if (g_str_equal(formfactor, "handheld") == TRUE) + minor += 1 << 4; + } + + dbus_message_unref(reply); + + /* Computer major class */ + DBG("Setting 0x%06x for major/minor device class", (1 << 8) | minor); + + btd_adapter_set_class(adapter, 0x01, minor); +} + +static DBusConnection *connection; + +static int hal_probe(struct btd_adapter *adapter) +{ + const char *property = "system.formfactor"; + DBusMessage *message; + DBusPendingCall *call; + + connection = dbus_bus_get(DBUS_BUS_SYSTEM, NULL); + if (connection == NULL) + return -ENOMEM; + + message = dbus_message_new_method_call("org.freedesktop.Hal", + "/org/freedesktop/Hal/devices/computer", + "org.freedesktop.Hal.Device", + "GetPropertyString"); + if (message == NULL) { + error("Failed to create formfactor request"); + dbus_connection_unref(connection); + return -ENOMEM; + } + + dbus_message_append_args(message, DBUS_TYPE_STRING, &property, + DBUS_TYPE_INVALID); + + if (dbus_connection_send_with_reply(connection, message, + &call, -1) == FALSE) { + error("Failed to send formfactor request"); + dbus_message_unref(message); + dbus_connection_unref(connection); + return -EIO; + } + + dbus_pending_call_set_notify(call, formfactor_reply, adapter, NULL); + + dbus_pending_call_unref(call); + + dbus_message_unref(message); + + return 0; +} + +static void hal_remove(struct btd_adapter *adapter) +{ + dbus_connection_unref(connection); +} + +static struct btd_adapter_driver hal_driver = { + .name = "hal", + .probe = hal_probe, + .remove = hal_remove, +}; + +static int hal_init(void) +{ + return btd_register_adapter_driver(&hal_driver); +} + +static void hal_exit(void) +{ + btd_unregister_adapter_driver(&hal_driver); +} + +BLUETOOTH_PLUGIN_DEFINE(hal, VERSION, + BLUETOOTH_PLUGIN_PRIORITY_LOW, hal_init, hal_exit) diff --git a/plugins/hciops.c b/plugins/hciops.c new file mode 100644 index 0000000..93f6f21 --- /dev/null +++ b/plugins/hciops.c @@ -0,0 +1,3744 @@ +/* + * + * BlueZ - Bluetooth protocol stack for Linux + * + * Copyright (C) 2004-2010 Marcel Holtmann <marcel@holtmann.org> + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + * + */ + +#ifdef HAVE_CONFIG_H +#include <config.h> +#endif + +#include <stdio.h> +#include <errno.h> +#include <unistd.h> +#include <stdlib.h> +#include <sys/types.h> +#include <sys/ioctl.h> +#include <sys/wait.h> + +#include <bluetooth/bluetooth.h> +#include <bluetooth/hci.h> +#include <bluetooth/hci_lib.h> +#include <bluetooth/sdp.h> +#include <bluetooth/sdp_lib.h> + +#include <glib.h> + +#include "hcid.h" +#include "sdpd.h" +#include "btio.h" +#include "adapter.h" +#include "device.h" +#include "plugin.h" +#include "log.h" +#include "storage.h" +#include "event.h" +#include "manager.h" +#include "oob.h" + +static int child_pipe[2] = { -1, -1 }; + +static guint child_io_id = 0; +static guint ctl_io_id = 0; + +/* Commands sent by kernel on starting an adapter */ +enum { + PENDING_BDADDR, + PENDING_VERSION, + PENDING_FEATURES, + PENDING_NAME, +}; + +struct uuid_info { + uuid_t uuid; + uint8_t svc_hint; +}; + +struct bt_conn { + struct dev_info *dev; + bdaddr_t bdaddr; + uint16_t handle; + uint8_t loc_cap; + uint8_t loc_auth; + uint8_t rem_cap; + uint8_t rem_auth; + uint8_t rem_oob_data; + gboolean bonding_initiator; + gboolean secmode3; + GIOChannel *io; /* For raw L2CAP socket (bonding) */ +}; + +struct oob_data { + bdaddr_t bdaddr; + uint8_t hash[16]; + uint8_t randomizer[16]; +}; + +static int max_dev = -1; +static struct dev_info { + int id; + int sk; + bdaddr_t bdaddr; + char name[249]; + uint8_t eir[240]; + uint8_t features[8]; + uint8_t ssp_mode; + + int8_t tx_power; + + uint32_t current_cod; + uint32_t wanted_cod; + uint32_t pending_cod; + gboolean cache_enable; + gboolean already_up; + gboolean registered; + gboolean pairable; + + uint8_t io_capability; + + struct hci_version ver; + + uint16_t did_vendor; + uint16_t did_product; + uint16_t did_version; + + gboolean up; + uint32_t pending; + + GIOChannel *io; + guint watch_id; + + gboolean debug_keys; + GSList *keys; + uint8_t pin_length; + + GSList *oob_data; + + GSList *uuids; + + GSList *connections; +} *devs = NULL; + +static int ignore_device(struct hci_dev_info *di) +{ + return hci_test_bit(HCI_RAW, &di->flags) || di->type >> 4 != HCI_BREDR; +} + +static struct dev_info *init_dev_info(int index, int sk, gboolean registered, + gboolean already_up) +{ + struct dev_info *dev = &devs[index]; + + memset(dev, 0, sizeof(*dev)); + + dev->id = index; + dev->sk = sk; + dev->cache_enable = TRUE; + dev->registered = registered; + dev->already_up = already_up; + dev->io_capability = 0x03; /* No Input No Output */ + + return dev; +} + +/* Async HCI command handling with callback support */ + +struct hci_cmd_data { + bt_hci_result_t cb; + uint16_t handle; + uint16_t ocf; + gpointer caller_data; +}; + +static gboolean hci_event_watch(GIOChannel *io, + GIOCondition cond, gpointer user_data) +{ + unsigned char buf[HCI_MAX_EVENT_SIZE], *body; + struct hci_cmd_data *cmd = user_data; + evt_cmd_status *evt_status; + evt_auth_complete *evt_auth; + evt_encrypt_change *evt_enc; + hci_event_hdr *hdr; + set_conn_encrypt_cp cp; + int dd; + uint16_t ocf; + uint8_t status = HCI_OE_POWER_OFF; + + if (cond & G_IO_NVAL) { + cmd->cb(status, cmd->caller_data); + return FALSE; + } + + if (cond & (G_IO_ERR | G_IO_HUP)) + goto failed; + + dd = g_io_channel_unix_get_fd(io); + + if (read(dd, buf, sizeof(buf)) < 0) + goto failed; + + hdr = (hci_event_hdr *) (buf + 1); + body = buf + (1 + HCI_EVENT_HDR_SIZE); + + switch (hdr->evt) { + case EVT_CMD_STATUS: + evt_status = (evt_cmd_status *) body; + ocf = cmd_opcode_ocf(evt_status->opcode); + if (ocf != cmd->ocf) + return TRUE; + switch (ocf) { + case OCF_AUTH_REQUESTED: + case OCF_SET_CONN_ENCRYPT: + if (evt_status->status != 0) { + /* Baseband rejected command */ + status = evt_status->status; + goto failed; + } + break; + default: + return TRUE; + } + /* Wait for the next event */ + return TRUE; + case EVT_AUTH_COMPLETE: + evt_auth = (evt_auth_complete *) body; + if (evt_auth->handle != cmd->handle) { + /* Skipping */ + return TRUE; + } + + if (evt_auth->status != 0x00) { + status = evt_auth->status; + /* Abort encryption */ + goto failed; + } + + memset(&cp, 0, sizeof(cp)); + cp.handle = cmd->handle; + cp.encrypt = 1; + + cmd->ocf = OCF_SET_CONN_ENCRYPT; + + if (hci_send_cmd(dd, OGF_LINK_CTL, OCF_SET_CONN_ENCRYPT, + SET_CONN_ENCRYPT_CP_SIZE, &cp) < 0) { + status = HCI_COMMAND_DISALLOWED; + goto failed; + } + /* Wait for encrypt change event */ + return TRUE; + case EVT_ENCRYPT_CHANGE: + evt_enc = (evt_encrypt_change *) body; + if (evt_enc->handle != cmd->handle) + return TRUE; + + /* Procedure finished: reporting status */ + status = evt_enc->status; + break; + default: + /* Skipping */ + return TRUE; + } + +failed: + cmd->cb(status, cmd->caller_data); + g_io_channel_shutdown(io, TRUE, NULL); + + return FALSE; +} + +static int write_inq_mode(int index, uint8_t mode) +{ + struct dev_info *dev = &devs[index]; + write_inquiry_mode_cp cp; + + memset(&cp, 0, sizeof(cp)); + cp.mode = mode; + + if (hci_send_cmd(dev->sk, OGF_HOST_CTL, OCF_WRITE_INQUIRY_MODE, + WRITE_INQUIRY_MODE_CP_SIZE, &cp) < 0) + return -errno; + + return 0; +} + +static uint8_t get_inquiry_mode(int index) +{ + struct dev_info *dev = &devs[index]; + + if (dev->features[6] & LMP_EXT_INQ) + return 2; + + if (dev->features[3] & LMP_RSSI_INQ) + return 1; + + if (dev->ver.manufacturer == 11 && dev->ver.hci_rev == 0x00 && + dev->ver.lmp_subver == 0x0757) + return 1; + + if (dev->ver.manufacturer == 15) { + if (dev->ver.hci_rev == 0x03 && + dev->ver.lmp_subver == 0x6963) + return 1; + if (dev->ver.hci_rev == 0x09 && + dev->ver.lmp_subver == 0x6963) + return 1; + if (dev->ver.hci_rev == 0x00 && + dev->ver.lmp_subver == 0x6965) + return 1; + } + + if (dev->ver.manufacturer == 31 && dev->ver.hci_rev == 0x2005 && + dev->ver.lmp_subver == 0x1805) + return 1; + + return 0; +} + +static int init_ssp_mode(int index) +{ + struct dev_info *dev = &devs[index]; + write_simple_pairing_mode_cp cp; + + if (ioctl(dev->sk, HCIGETAUTHINFO, NULL) < 0 && errno == EINVAL) + return 0; + + memset(&cp, 0, sizeof(cp)); + cp.mode = 0x01; + + if (hci_send_cmd(dev->sk, OGF_HOST_CTL, + OCF_WRITE_SIMPLE_PAIRING_MODE, + WRITE_SIMPLE_PAIRING_MODE_CP_SIZE, &cp) < 0) + return -errno; + + return 0; +} + +static int hciops_set_discoverable(int index, gboolean discoverable) +{ + struct dev_info *dev = &devs[index]; + uint8_t mode; + + if (discoverable) + mode = (SCAN_PAGE | SCAN_INQUIRY); + else + mode = SCAN_PAGE; + + DBG("hci%d discoverable %d", index, discoverable); + + if (hci_send_cmd(dev->sk, OGF_HOST_CTL, OCF_WRITE_SCAN_ENABLE, + 1, &mode) < 0) + return -errno; + + return 0; +} + +static int hciops_set_pairable(int index, gboolean pairable) +{ + struct btd_adapter *adapter; + + DBG("hci%d pairable %d", index, pairable); + + adapter = manager_find_adapter(&devs[index].bdaddr); + if (adapter) + btd_adapter_pairable_changed(adapter, pairable); + + devs[index].pairable = pairable; + + return 0; +} + +static int hciops_power_off(int index) +{ + struct dev_info *dev = &devs[index]; + + DBG("hci%d", index); + + if (ioctl(dev->sk, HCIDEVDOWN, index) < 0 && errno != EALREADY) + return -errno; + + return 0; +} + +static void set_event_mask(int index) +{ + struct dev_info *dev = &devs[index]; + /* The second byte is 0xff instead of 0x9f (two reserved bits + * disabled) since a Broadcom 1.2 dongle doesn't respond to the + * command otherwise */ + uint8_t events[8] = { 0xff, 0xff, 0xfb, 0xff, 0x00, 0x00, 0x00, 0x00 }; + + /* Events for 1.2 and newer controllers */ + if (dev->ver.lmp_ver > 1) { + events[4] |= 0x01; /* Flow Specification Complete */ + events[4] |= 0x02; /* Inquiry Result with RSSI */ + events[4] |= 0x04; /* Read Remote Extended Features Complete */ + events[5] |= 0x08; /* Synchronous Connection Complete */ + events[5] |= 0x10; /* Synchronous Connection Changed */ + } + + if (dev->features[3] & LMP_RSSI_INQ) + events[4] |= 0x04; /* Inquiry Result with RSSI */ + + if (dev->features[5] & LMP_SNIFF_SUBR) + events[5] |= 0x20; /* Sniff Subrating */ + + if (dev->features[5] & LMP_PAUSE_ENC) + events[5] |= 0x80; /* Encryption Key Refresh Complete */ + + if (dev->features[6] & LMP_EXT_INQ) + events[5] |= 0x40; /* Extended Inquiry Result */ + + if (dev->features[6] & LMP_NFLUSH_PKTS) + events[7] |= 0x01; /* Enhanced Flush Complete */ + + if (dev->features[7] & LMP_LSTO) + events[6] |= 0x80; /* Link Supervision Timeout Changed */ + + if (dev->features[6] & LMP_SIMPLE_PAIR) { + events[6] |= 0x01; /* IO Capability Request */ + events[6] |= 0x02; /* IO Capability Response */ + events[6] |= 0x04; /* User Confirmation Request */ + events[6] |= 0x08; /* User Passkey Request */ + events[6] |= 0x10; /* Remote OOB Data Request */ + events[6] |= 0x20; /* Simple Pairing Complete */ + events[7] |= 0x04; /* User Passkey Notification */ + events[7] |= 0x08; /* Keypress Notification */ + events[7] |= 0x10; /* Remote Host Supported + * Features Notification */ + } + + if (dev->features[4] & LMP_LE) + events[7] |= 0x20; /* LE Meta-Event */ + + hci_send_cmd(dev->sk, OGF_HOST_CTL, OCF_SET_EVENT_MASK, + sizeof(events), events); +} + +static void start_adapter(int index) +{ + struct dev_info *dev = &devs[index]; + uint8_t inqmode; + uint16_t link_policy; + + set_event_mask(index); + + if (dev->features[6] & LMP_SIMPLE_PAIR) + init_ssp_mode(index); + + inqmode = get_inquiry_mode(index); + if (inqmode) + write_inq_mode(index, inqmode); + + if (dev->features[7] & LMP_INQ_TX_PWR) + hci_send_cmd(dev->sk, OGF_HOST_CTL, + OCF_READ_INQ_RESPONSE_TX_POWER_LEVEL, 0, NULL); + + /* Set default link policy */ + link_policy = main_opts.link_policy; + + if (!(dev->features[0] & LMP_RSWITCH)) + link_policy &= ~HCI_LP_RSWITCH; + if (!(dev->features[0] & LMP_HOLD)) + link_policy &= ~HCI_LP_HOLD; + if (!(dev->features[0] & LMP_SNIFF)) + link_policy &= ~HCI_LP_SNIFF; + if (!(dev->features[1] & LMP_PARK)) + link_policy &= ~HCI_LP_PARK; + + link_policy = htobs(link_policy); + hci_send_cmd(dev->sk, OGF_LINK_POLICY, OCF_WRITE_DEFAULT_LINK_POLICY, + sizeof(link_policy), &link_policy); + + dev->current_cod = 0; + memset(dev->eir, 0, sizeof(dev->eir)); +} + +static int hciops_stop_inquiry(int index) +{ + struct dev_info *dev = &devs[index]; + struct hci_dev_info di; + int err; + + DBG("hci%d", index); + + if (hci_devinfo(index, &di) < 0) + return -errno; + + if (hci_test_bit(HCI_INQUIRY, &di.flags)) + err = hci_send_cmd(dev->sk, OGF_LINK_CTL, + OCF_INQUIRY_CANCEL, 0, 0); + else + err = hci_send_cmd(dev->sk, OGF_LINK_CTL, + OCF_EXIT_PERIODIC_INQUIRY, 0, 0); + if (err < 0) + err = -errno; + + return err; +} + +static gboolean init_adapter(int index) +{ + struct dev_info *dev = &devs[index]; + struct btd_adapter *adapter = NULL; + gboolean existing_adapter = dev->registered; + uint8_t mode, on_mode; + gboolean pairable, discoverable; + + if (!dev->registered) { + adapter = btd_manager_register_adapter(index); + if (adapter) + dev->registered = TRUE; + } else { + adapter = manager_find_adapter(&dev->bdaddr); + /* FIXME: manager_find_adapter should return a new ref */ + btd_adapter_ref(adapter); + } + + if (adapter == NULL) + return FALSE; + + btd_adapter_get_mode(adapter, &mode, &on_mode, &pairable); + + if (existing_adapter) + mode = on_mode; + + if (mode == MODE_OFF) { + hciops_power_off(index); + goto done; + } + + start_adapter(index); + btd_adapter_start(adapter); + + discoverable = (mode == MODE_DISCOVERABLE); + + hciops_set_discoverable(index, discoverable); + hciops_set_pairable(index, pairable); + + if (dev->already_up) + hciops_stop_inquiry(index); + +done: + btd_adapter_unref(adapter); + return TRUE; +} + +static int hciops_encrypt_link(int index, bdaddr_t *dst, bt_hci_result_t cb, + gpointer user_data) +{ + GIOChannel *io; + struct hci_cmd_data *cmd; + struct hci_conn_info_req *cr; + auth_requested_cp cp; + struct hci_filter nf; + int dd, err; + uint32_t link_mode; + uint16_t handle; + + dd = hci_open_dev(index); + if (dd < 0) + return -errno; + + cr = g_malloc0(sizeof(*cr) + sizeof(struct hci_conn_info)); + cr->type = ACL_LINK; + bacpy(&cr->bdaddr, dst); + + err = ioctl(dd, HCIGETCONNINFO, cr); + link_mode = cr->conn_info->link_mode; + handle = cr->conn_info->handle; + g_free(cr); + + if (err < 0) { + err = -errno; + goto fail; + } + + if (link_mode & HCI_LM_ENCRYPT) { + err = -EALREADY; + goto fail; + } + + memset(&cp, 0, sizeof(cp)); + cp.handle = htobs(handle); + + if (hci_send_cmd(dd, OGF_LINK_CTL, OCF_AUTH_REQUESTED, + AUTH_REQUESTED_CP_SIZE, &cp) < 0) { + err = -errno; + goto fail; + } + + cmd = g_new0(struct hci_cmd_data, 1); + cmd->handle = handle; + cmd->ocf = OCF_AUTH_REQUESTED; + cmd->cb = cb; + cmd->caller_data = user_data; + + hci_filter_clear(&nf); + hci_filter_set_ptype(HCI_EVENT_PKT, &nf); + hci_filter_set_event(EVT_CMD_STATUS, &nf); + hci_filter_set_event(EVT_AUTH_COMPLETE, &nf); + hci_filter_set_event(EVT_ENCRYPT_CHANGE, &nf); + + if (setsockopt(dd, SOL_HCI, HCI_FILTER, &nf, sizeof(nf)) < 0) { + err = -errno; + g_free(cmd); + goto fail; + } + + io = g_io_channel_unix_new(dd); + g_io_channel_set_close_on_unref(io, FALSE); + g_io_add_watch_full(io, G_PRIORITY_DEFAULT, + G_IO_HUP | G_IO_ERR | G_IO_NVAL | G_IO_IN, + hci_event_watch, cmd, g_free); + g_io_channel_unref(io); + + return 0; + +fail: + close(dd); + return err; +} + +static int hciops_set_did(int index, uint16_t vendor, uint16_t product, + uint16_t version) +{ + struct dev_info *dev = &devs[index]; + + dev->did_vendor = vendor; + dev->did_product = product; + dev->did_version = version; + + return 0; +} + +/* End async HCI command handling */ + +/* Start of HCI event callbacks */ + +static gint conn_handle_cmp(gconstpointer a, gconstpointer b) +{ + const struct bt_conn *conn = a; + uint16_t handle = *((const uint16_t *) b); + + return (int) conn->handle - (int) handle; +} + +static struct bt_conn *find_conn_by_handle(struct dev_info *dev, + uint16_t handle) +{ + GSList *match; + + match = g_slist_find_custom(dev->connections, &handle, + conn_handle_cmp); + if (match) + return match->data; + + return NULL; +} + +static gint conn_bdaddr_cmp(gconstpointer a, gconstpointer b) +{ + const struct bt_conn *conn = a; + const bdaddr_t *bdaddr = b; + + return bacmp(&conn->bdaddr, bdaddr); +} + +static struct bt_conn *find_connection(struct dev_info *dev, bdaddr_t *bdaddr) +{ + GSList *match; + + match = g_slist_find_custom(dev->connections, bdaddr, conn_bdaddr_cmp); + if (match) + return match->data; + + return NULL; +} + +static struct bt_conn *get_connection(struct dev_info *dev, bdaddr_t *bdaddr) +{ + struct bt_conn *conn; + + conn = find_connection(dev, bdaddr); + if (conn) + return conn; + + conn = g_new0(struct bt_conn, 1); + + conn->dev = dev; + conn->loc_cap = dev->io_capability; + conn->loc_auth = 0xff; + conn->rem_auth = 0xff; + bacpy(&conn->bdaddr, bdaddr); + + dev->connections = g_slist_append(dev->connections, conn); + + return conn; +} + +static int get_handle(int index, bdaddr_t *bdaddr, uint16_t *handle) +{ + struct dev_info *dev = &devs[index]; + struct bt_conn *conn; + char addr[18]; + + ba2str(bdaddr, addr); + DBG("hci%d dba %s", index, addr); + + conn = find_connection(dev, bdaddr); + if (conn == NULL) + return -ENOENT; + + *handle = conn->handle; + + return 0; +} + +static int disconnect_addr(int index, bdaddr_t *dba, uint8_t reason) +{ + disconnect_cp cp; + uint16_t handle; + int err; + + err = get_handle(index, dba, &handle); + if (err < 0) + return err; + + memset(&cp, 0, sizeof(cp)); + cp.handle = htobs(handle); + cp.reason = reason; + + if (hci_send_cmd(devs[index].sk, OGF_LINK_CTL, OCF_DISCONNECT, + DISCONNECT_CP_SIZE, &cp) < 0) + return -errno; + + return 0; +} + +static void bonding_complete(struct dev_info *dev, struct bt_conn *conn, + uint8_t status) +{ + DBG("status 0x%02x", status); + + if (conn->io != NULL) { + /* bonding_connect_cb takes care of the successul case */ + if (status != 0) + g_io_channel_shutdown(conn->io, TRUE, NULL); + g_io_channel_unref(conn->io); + conn->io = NULL; + } + + conn->bonding_initiator = FALSE; + + btd_event_bonding_complete(&dev->bdaddr, &conn->bdaddr, status); +} + +static int get_auth_info(int index, bdaddr_t *bdaddr, uint8_t *auth) +{ + struct dev_info *dev = &devs[index]; + struct hci_auth_info_req req; + char addr[18]; + + ba2str(bdaddr, addr); + DBG("hci%d dba %s", index, addr); + + memset(&req, 0, sizeof(req)); + bacpy(&req.bdaddr, bdaddr); + + if (ioctl(dev->sk, HCIGETAUTHINFO, (unsigned long) &req) < 0) + return -errno; + + if (auth) + *auth = req.type; + + return 0; +} + +/* Link Key handling */ + +static void link_key_request(int index, bdaddr_t *dba) +{ + struct dev_info *dev = &devs[index]; + struct link_key_info *key_info; + struct bt_conn *conn; + GSList *match; + char da[18]; + + ba2str(dba, da); + DBG("hci%d dba %s", index, da); + + conn = get_connection(dev, dba); + if (conn->handle == 0) + conn->secmode3 = TRUE; + + get_auth_info(index, dba, &conn->loc_auth); + + DBG("kernel auth requirements = 0x%02x", conn->loc_auth); + + match = g_slist_find_custom(dev->keys, dba, (GCompareFunc) bacmp); + if (match) + key_info = match->data; + else + key_info = NULL; + + DBG("Matching key %s", key_info ? "found" : "not found"); + + if (key_info == NULL || (!dev->debug_keys && key_info->type == 0x03)) { + /* Link key not found */ + hci_send_cmd(dev->sk, OGF_LINK_CTL, OCF_LINK_KEY_NEG_REPLY, + 6, dba); + return; + } + + /* Link key found */ + + DBG("link key type 0x%02x", key_info->type); + + /* Don't use unauthenticated combination keys if MITM is + * required */ + if (key_info->type == 0x04 && conn->loc_auth != 0xff && + (conn->loc_auth & 0x01)) + hci_send_cmd(dev->sk, OGF_LINK_CTL, OCF_LINK_KEY_NEG_REPLY, + 6, dba); + else { + link_key_reply_cp lr; + + memcpy(lr.link_key, key_info->key, 16); + bacpy(&lr.bdaddr, dba); + + hci_send_cmd(dev->sk, OGF_LINK_CTL, OCF_LINK_KEY_REPLY, + LINK_KEY_REPLY_CP_SIZE, &lr); + } +} + +static void link_key_notify(int index, void *ptr) +{ + struct dev_info *dev = &devs[index]; + evt_link_key_notify *evt = ptr; + bdaddr_t *dba = &evt->bdaddr; + struct link_key_info *key_info; + uint8_t old_key_type, key_type; + struct bt_conn *conn; + GSList *match; + char da[18]; + uint8_t status = 0; + + ba2str(dba, da); + DBG("hci%d dba %s type %d", index, da, evt->key_type); + + conn = get_connection(dev, &evt->bdaddr); + + match = g_slist_find_custom(dev->keys, dba, (GCompareFunc) bacmp); + if (match) + key_info = match->data; + else + key_info = NULL; + + if (key_info == NULL) { + key_info = g_new0(struct link_key_info, 1); + bacpy(&key_info->bdaddr, &evt->bdaddr); + old_key_type = 0xff; + } else { + dev->keys = g_slist_remove(dev->keys, key_info); + old_key_type = key_info->type; + } + + memcpy(key_info->key, evt->link_key, sizeof(evt->link_key)); + key_info->type = evt->key_type; + key_info->pin_len = dev->pin_length; + + key_type = evt->key_type; + + DBG("key type 0x%02x old key type 0x%02x", key_type, old_key_type); + DBG("local auth 0x%02x and remote auth 0x%02x", + conn->loc_auth, conn->rem_auth); + + if (key_type == 0x06) { + /* Some buggy controller combinations generate a changed + * combination key for legacy pairing even when there's no + * previous key */ + if ((!conn || conn->rem_auth == 0xff) && old_key_type == 0xff) + key_type = 0x00; + else if (old_key_type != 0xff) + key_type = old_key_type; + else + /* This is Changed Combination Link Key for + * a temporary link key.*/ + goto done; + } + + key_info->type = key_type; + + /* Skip the storage check if this is a debug key */ + if (key_type == 0x03) + goto done; + + /* Store the link key persistently if one of the following is true: + * 1. this is a legacy link key + * 2. this is a changed combination key and there was a previously + * stored one + * 3. neither local nor remote side had no-bonding as a requirement + * 4. the local side had dedicated bonding as a requirement + * 5. the remote side is using dedicated bonding since in that case + * also the local requirements are set to dedicated bonding + * If none of the above match only keep the link key around for + * this connection and set the temporary flag for the device. + */ + if (key_type < 0x03 || (key_type == 0x06 && old_key_type != 0xff) || + (conn->loc_auth > 0x01 && conn->rem_auth > 0x01) || + (conn->loc_auth == 0x02 || conn->loc_auth == 0x03) || + (conn->rem_auth == 0x02 || conn->rem_auth == 0x03)) { + int err; + + err = btd_event_link_key_notify(&dev->bdaddr, dba, + evt->link_key, key_type, + dev->pin_length); + + if (err == -ENODEV) + status = HCI_OE_LOW_RESOURCES; + else if (err < 0) + status = HCI_MEMORY_FULL; + + goto done; + } + +done: + dev->pin_length = 0; + + if (status != 0) { + g_free(key_info); + bonding_complete(dev, conn, status); + disconnect_addr(index, dba, status); + return; + } + + dev->keys = g_slist_prepend(dev->keys, key_info); + + /* If we're connected and not dedicated bonding initiators we're + * done with the bonding process */ + if (!conn->bonding_initiator && conn->handle != 0) + bonding_complete(dev, conn, 0); +} + +static void return_link_keys(int index, void *ptr) +{ + struct dev_info *dev = &devs[index]; + evt_return_link_keys *evt = ptr; + uint8_t num = evt->num_keys; + unsigned char key[16]; + char da[18]; + bdaddr_t dba; + int i; + + DBG("hci%d num_keys %u", index, num); + + ptr++; + + for (i = 0; i < num; i++) { + bacpy(&dba, ptr); ba2str(&dba, da); + memcpy(key, ptr + 6, 16); + + DBG("hci%d returned key for %s", index, da); + + btd_event_returned_link_key(&dev->bdaddr, &dba); + + ptr += 22; + } +} + +/* Simple Pairing handling */ + +static int hciops_confirm_reply(int index, bdaddr_t *bdaddr, gboolean success) +{ + struct dev_info *dev = &devs[index]; + user_confirm_reply_cp cp; + char addr[18]; + int err; + + ba2str(bdaddr, addr); + DBG("hci%d dba %s success %d", index, addr, success); + + memset(&cp, 0, sizeof(cp)); + bacpy(&cp.bdaddr, bdaddr); + + if (success) + err = hci_send_cmd(dev->sk, OGF_LINK_CTL, + OCF_USER_CONFIRM_REPLY, + USER_CONFIRM_REPLY_CP_SIZE, &cp); + else + err = hci_send_cmd(dev->sk, OGF_LINK_CTL, + OCF_USER_CONFIRM_NEG_REPLY, + USER_CONFIRM_REPLY_CP_SIZE, &cp); + + if (err < 0) + err = -errno; + + return err; +} + +static void user_confirm_request(int index, void *ptr) +{ + struct dev_info *dev = &devs[index]; + evt_user_confirm_request *req = ptr; + gboolean loc_mitm, rem_mitm; + struct bt_conn *conn; + + DBG("hci%d", index); + + conn = find_connection(dev, &req->bdaddr); + if (conn == NULL) + return; + + loc_mitm = (conn->loc_auth & 0x01) ? TRUE : FALSE; + rem_mitm = (conn->rem_auth & 0x01) ? TRUE : FALSE; + + /* If we require MITM but the remote device can't provide that + * (it has NoInputNoOutput) then reject the confirmation + * request. The only exception is when we're dedicated bonding + * initiators since then we always have the MITM bit set. */ + if (!conn->bonding_initiator && loc_mitm && conn->rem_cap == 0x03) { + error("Rejecting request: remote device can't provide MITM"); + goto fail; + } + + /* If no side requires MITM protection; auto-accept */ + if ((conn->loc_auth == 0xff || !loc_mitm || conn->rem_cap == 0x03) && + (!rem_mitm || conn->loc_cap == 0x03)) { + DBG("auto accept of confirmation"); + + /* Wait 5 milliseconds before doing auto-accept */ + usleep(5000); + + if (hciops_confirm_reply(index, &req->bdaddr, TRUE) < 0) + goto fail; + + return; + } + + if (btd_event_user_confirm(&dev->bdaddr, &req->bdaddr, + btohl(req->passkey)) == 0) + return; + +fail: + hci_send_cmd(dev->sk, OGF_LINK_CTL, OCF_USER_CONFIRM_NEG_REPLY, + 6, ptr); +} + +static void user_passkey_request(int index, void *ptr) +{ + struct dev_info *dev = &devs[index]; + evt_user_passkey_request *req = ptr; + + DBG("hci%d", index); + + if (btd_event_user_passkey(&dev->bdaddr, &req->bdaddr) < 0) + hci_send_cmd(dev->sk, OGF_LINK_CTL, + OCF_USER_PASSKEY_NEG_REPLY, 6, ptr); +} + +static void user_passkey_notify(int index, void *ptr) +{ + struct dev_info *dev = &devs[index]; + evt_user_passkey_notify *req = ptr; + + DBG("hci%d", index); + + btd_event_user_notify(&dev->bdaddr, &req->bdaddr, + btohl(req->passkey)); +} + +static gint oob_bdaddr_cmp(gconstpointer a, gconstpointer b) +{ + const struct oob_data *data = a; + const bdaddr_t *bdaddr = b; + + return bacmp(&data->bdaddr, bdaddr); +} + +static void remote_oob_data_request(int index, bdaddr_t *bdaddr) +{ + struct dev_info *dev = &devs[index]; + GSList *match; + + DBG("hci%d", index); + + match = g_slist_find_custom(dev->oob_data, bdaddr, oob_bdaddr_cmp); + + if (match) { + struct oob_data *data; + remote_oob_data_reply_cp cp; + + data = match->data; + + bacpy(&cp.bdaddr, &data->bdaddr); + memcpy(cp.hash, data->hash, sizeof(cp.hash)); + memcpy(cp.randomizer, data->randomizer, sizeof(cp.randomizer)); + + dev->oob_data = g_slist_delete_link(dev->oob_data, match); + + hci_send_cmd(dev->sk, OGF_LINK_CTL, OCF_REMOTE_OOB_DATA_REPLY, + REMOTE_OOB_DATA_REPLY_CP_SIZE, &cp); + + } else { + hci_send_cmd(dev->sk, OGF_LINK_CTL, + OCF_REMOTE_OOB_DATA_NEG_REPLY, 6, bdaddr); + } +} + +static int get_io_cap(int index, bdaddr_t *bdaddr, uint8_t *cap, uint8_t *auth) +{ + struct dev_info *dev = &devs[index]; + struct bt_conn *conn; + int err; + + conn = find_connection(dev, bdaddr); + if (conn == NULL) + return -ENOENT; + + err = get_auth_info(index, bdaddr, &conn->loc_auth); + if (err < 0) + return err; + + DBG("initial authentication requirement is 0x%02x", conn->loc_auth); + + if (!dev->pairable && !conn->bonding_initiator) { + if (conn->rem_auth < 0x02) { + DBG("Allowing no bonding in non-bondable mode"); + /* Kernel defaults to general bonding and so + * overwrite for this special case. Otherwise + * non-pairable test cases will fail. */ + conn->loc_auth = conn->rem_auth; + goto done; + } + + return -EPERM; + } + + /* If the kernel doesn't know the local requirement just mirror + * the remote one */ + if (conn->loc_auth == 0xff) + conn->loc_auth = conn->rem_auth; + + if (conn->loc_auth == 0x00 || conn->loc_auth == 0x04) { + /* If remote requests dedicated bonding follow that lead */ + if (conn->rem_auth == 0x02 || conn->rem_auth == 0x03) { + + /* If both remote and local IO capabilities allow MITM + * then require it, otherwise don't */ + if (conn->rem_cap == 0x03 || conn->loc_cap == 0x03) + conn->loc_auth = 0x02; + else + conn->loc_auth = 0x03; + } + + /* If remote indicates no bonding then follow that. This + * is important since the kernel might give general bonding + * as default. */ + if (conn->rem_auth == 0x00 || conn->rem_auth == 0x01) + conn->loc_auth = 0x00; + + /* If remote requires MITM then also require it, unless + * our IO capability is NoInputNoOutput (so some + * just-works security cases can be tested) */ + if (conn->rem_auth != 0xff && (conn->rem_auth & 0x01) && + conn->loc_cap != 0x03) + conn->loc_auth |= 0x01; + } + +done: + *cap = conn->loc_cap; + *auth = conn->loc_auth; + + DBG("final authentication requirement is 0x%02x", *auth); + + return 0; +} + +static void io_capa_request(int index, void *ptr) +{ + struct dev_info *dev = &devs[index]; + bdaddr_t *dba = ptr; + uint8_t cap, auth = 0xff; + char da[18]; + int err; + + ba2str(dba, da); + DBG("hci%d IO capability request for %s", index, da); + + err = get_io_cap(index, dba, &cap, &auth); + if (err < 0) { + io_capability_neg_reply_cp cp; + + error("Getting IO capability failed: %s (%d)", + strerror(-err), -err); + + memset(&cp, 0, sizeof(cp)); + bacpy(&cp.bdaddr, dba); + cp.reason = HCI_PAIRING_NOT_ALLOWED; + hci_send_cmd(dev->sk, OGF_LINK_CTL, + OCF_IO_CAPABILITY_NEG_REPLY, + IO_CAPABILITY_NEG_REPLY_CP_SIZE, &cp); + } else { + io_capability_reply_cp cp; + struct bt_conn *conn; + GSList *match; + + memset(&cp, 0, sizeof(cp)); + bacpy(&cp.bdaddr, dba); + cp.capability = cap; + cp.authentication = auth; + + conn = find_connection(dev, dba); + match = g_slist_find_custom(dev->oob_data, dba, oob_bdaddr_cmp); + + if ((conn->bonding_initiator || conn->rem_oob_data == 0x01) && + match) + cp.oob_data = 0x01; + else + cp.oob_data = 0x00; + + hci_send_cmd(dev->sk, OGF_LINK_CTL, OCF_IO_CAPABILITY_REPLY, + IO_CAPABILITY_REPLY_CP_SIZE, &cp); + } +} + +static void io_capa_response(int index, void *ptr) +{ + struct dev_info *dev = &devs[index]; + evt_io_capability_response *evt = ptr; + struct bt_conn *conn; + char da[18]; + + ba2str(&evt->bdaddr, da); + DBG("hci%d IO capability response from %s", index, da); + + conn = find_connection(dev, &evt->bdaddr); + if (conn) { + conn->rem_cap = evt->capability; + conn->rem_auth = evt->authentication; + conn->rem_oob_data = evt->oob_data; + } +} + +/* PIN code handling */ + +static void pin_code_request(int index, bdaddr_t *dba) +{ + struct dev_info *dev = &devs[index]; + struct bt_conn *conn; + char addr[18]; + int err; + + ba2str(dba, addr); + DBG("hci%d PIN request for %s", index, addr); + + conn = get_connection(dev, dba); + if (conn->handle == 0) + conn->secmode3 = TRUE; + + /* Check if the adapter is not pairable and if there isn't a bonding in + * progress */ + if (!dev->pairable && !conn->bonding_initiator) { + DBG("Rejecting PIN request in non-pairable mode"); + goto reject; + } + + err = btd_event_request_pin(&dev->bdaddr, dba); + if (err < 0) { + error("PIN code negative reply: %s", strerror(-err)); + goto reject; + } + + return; + +reject: + hci_send_cmd(dev->sk, OGF_LINK_CTL, OCF_PIN_CODE_NEG_REPLY, 6, dba); +} + +static void start_inquiry(bdaddr_t *local, uint8_t status, gboolean periodic) +{ + struct btd_adapter *adapter; + int state; + + /* Don't send the signal if the cmd failed */ + if (status) { + error("Inquiry Failed with status 0x%02x", status); + return; + } + + adapter = manager_find_adapter(local); + if (!adapter) { + error("Unable to find matching adapter"); + return; + } + + state = adapter_get_state(adapter); + + if (periodic) + state |= STATE_PINQ; + else + state |= STATE_STDINQ; + + adapter_set_state(adapter, state); +} + +static void inquiry_complete(bdaddr_t *local, uint8_t status, + gboolean periodic) +{ + struct btd_adapter *adapter; + int state; + + /* Don't send the signal if the cmd failed */ + if (status) { + error("Inquiry Failed with status 0x%02x", status); + return; + } + + adapter = manager_find_adapter(local); + if (!adapter) { + error("Unable to find matching adapter"); + return; + } + + state = adapter_get_state(adapter); + state &= ~(STATE_STDINQ | STATE_PINQ); + adapter_set_state(adapter, state); +} + +static inline void remote_features_notify(int index, void *ptr) +{ + struct dev_info *dev = &devs[index]; + evt_remote_host_features_notify *evt = ptr; + + if (evt->features[0] & 0x01) + btd_event_set_legacy_pairing(&dev->bdaddr, &evt->bdaddr, + FALSE); + else + btd_event_set_legacy_pairing(&dev->bdaddr, &evt->bdaddr, + TRUE); + + write_features_info(&dev->bdaddr, &evt->bdaddr, NULL, evt->features); +} + +static void write_le_host_complete(int index, uint8_t status) +{ + struct dev_info *dev = &devs[index]; + uint8_t page_num = 0x01; + + if (status) + return; + + if (hci_send_cmd(dev->sk, OGF_INFO_PARAM, + OCF_READ_LOCAL_EXT_FEATURES, 1, &page_num) < 0) + error("Unable to read extended local features: %s (%d)", + strerror(errno), errno); +} + +static void read_local_version_complete(int index, + const read_local_version_rp *rp) +{ + struct dev_info *dev = &devs[index]; + + if (rp->status) + return; + + dev->ver.manufacturer = btohs(bt_get_unaligned(&rp->manufacturer)); + dev->ver.hci_ver = rp->hci_ver; + dev->ver.hci_rev = btohs(bt_get_unaligned(&rp->hci_rev)); + dev->ver.lmp_ver = rp->lmp_ver; + dev->ver.lmp_subver = btohs(bt_get_unaligned(&rp->lmp_subver)); + + if (!dev->pending) + return; + + hci_clear_bit(PENDING_VERSION, &dev->pending); + + DBG("Got version for hci%d", index); + + if (!dev->pending && dev->up) + init_adapter(index); +} + +static void read_local_features_complete(int index, + const read_local_features_rp *rp) +{ + struct dev_info *dev = &devs[index]; + + if (rp->status) + return; + + memcpy(dev->features, rp->features, 8); + + if (!dev->pending) + return; + + hci_clear_bit(PENDING_FEATURES, &dev->pending); + + DBG("Got features for hci%d", index); + + if (!dev->pending && dev->up) + init_adapter(index); +} + +#define SIZEOF_UUID128 16 + +static void eir_generate_uuid128(GSList *list, uint8_t *ptr, uint16_t *eir_len) +{ + int i, k, uuid_count = 0; + uint16_t len = *eir_len; + uint8_t *uuid128; + gboolean truncated = FALSE; + + /* Store UUIDs in place, skip 2 bytes to write type and length later */ + uuid128 = ptr + 2; + + for (; list; list = list->next) { + struct uuid_info *uuid = list->data; + uint8_t *uuid128_data = uuid->uuid.value.uuid128.data; + + if (uuid->uuid.type != SDP_UUID128) + continue; + + /* Stop if not enough space to put next UUID128 */ + if ((len + 2 + SIZEOF_UUID128) > EIR_DATA_LENGTH) { + truncated = TRUE; + break; + } + + /* Check for duplicates, EIR data is Little Endian */ + for (i = 0; i < uuid_count; i++) { + for (k = 0; k < SIZEOF_UUID128; k++) { + if (uuid128[i * SIZEOF_UUID128 + k] != + uuid128_data[SIZEOF_UUID128 - 1 - k]) + break; + } + if (k == SIZEOF_UUID128) + break; + } + + if (i < uuid_count) + continue; + + /* EIR data is Little Endian */ + for (k = 0; k < SIZEOF_UUID128; k++) + uuid128[uuid_count * SIZEOF_UUID128 + k] = + uuid128_data[SIZEOF_UUID128 - 1 - k]; + + len += SIZEOF_UUID128; + uuid_count++; + } + + if (uuid_count > 0 || truncated) { + /* EIR Data length */ + ptr[0] = (uuid_count * SIZEOF_UUID128) + 1; + /* EIR Data type */ + ptr[1] = truncated ? EIR_UUID128_SOME : EIR_UUID128_ALL; + len += 2; + *eir_len = len; + } +} + +static void create_ext_inquiry_response(int index, uint8_t *data) +{ + struct dev_info *dev = &devs[index]; + GSList *l; + uint8_t *ptr = data; + uint16_t eir_len = 0; + uint16_t uuid16[EIR_DATA_LENGTH / 2]; + int i, uuid_count = 0; + gboolean truncated = FALSE; + size_t name_len; + + name_len = strlen(dev->name); + + if (name_len > 0) { + /* EIR Data type */ + if (name_len > 48) { + name_len = 48; + ptr[1] = EIR_NAME_SHORT; + } else + ptr[1] = EIR_NAME_COMPLETE; + + /* EIR Data length */ + ptr[0] = name_len + 1; + + memcpy(ptr + 2, dev->name, name_len); + + eir_len += (name_len + 2); + ptr += (name_len + 2); + } + + if (dev->tx_power != 0) { + *ptr++ = 2; + *ptr++ = EIR_TX_POWER; + *ptr++ = (uint8_t) dev->tx_power; + eir_len += 3; + } + + if (dev->did_vendor != 0x0000) { + uint16_t source = 0x0002; + *ptr++ = 9; + *ptr++ = EIR_DEVICE_ID; + *ptr++ = (source & 0x00ff); + *ptr++ = (source & 0xff00) >> 8; + *ptr++ = (dev->did_vendor & 0x00ff); + *ptr++ = (dev->did_vendor & 0xff00) >> 8; + *ptr++ = (dev->did_product & 0x00ff); + *ptr++ = (dev->did_product & 0xff00) >> 8; + *ptr++ = (dev->did_version & 0x00ff); + *ptr++ = (dev->did_version & 0xff00) >> 8; + eir_len += 10; + } + + /* Group all UUID16 types */ + for (l = dev->uuids; l != NULL; l = g_slist_next(l)) { + struct uuid_info *uuid = l->data; + + if (uuid->uuid.type != SDP_UUID16) + continue; + + if (uuid->uuid.value.uuid16 < 0x1100) + continue; + + if (uuid->uuid.value.uuid16 == PNP_INFO_SVCLASS_ID) + continue; + + /* Stop if not enough space to put next UUID16 */ + if ((eir_len + 2 + sizeof(uint16_t)) > EIR_DATA_LENGTH) { + truncated = TRUE; + break; + } + + /* Check for duplicates */ + for (i = 0; i < uuid_count; i++) + if (uuid16[i] == uuid->uuid.value.uuid16) + break; + + if (i < uuid_count) + continue; + + uuid16[uuid_count++] = uuid->uuid.value.uuid16; + eir_len += sizeof(uint16_t); + } + + if (uuid_count > 0) { + /* EIR Data length */ + ptr[0] = (uuid_count * sizeof(uint16_t)) + 1; + /* EIR Data type */ + ptr[1] = truncated ? EIR_UUID16_SOME : EIR_UUID16_ALL; + + ptr += 2; + eir_len += 2; + + for (i = 0; i < uuid_count; i++) { + *ptr++ = (uuid16[i] & 0x00ff); + *ptr++ = (uuid16[i] & 0xff00) >> 8; + } + } + + /* Group all UUID128 types */ + if (eir_len <= EIR_DATA_LENGTH - 2) + eir_generate_uuid128(dev->uuids, ptr, &eir_len); +} + +static void update_ext_inquiry_response(int index) +{ + struct dev_info *dev = &devs[index]; + write_ext_inquiry_response_cp cp; + + DBG("hci%d", index); + + if (!(dev->features[6] & LMP_EXT_INQ)) + return; + + if (dev->ssp_mode == 0) + return; + + if (dev->cache_enable) + return; + + memset(&cp, 0, sizeof(cp)); + + create_ext_inquiry_response(index, cp.data); + + if (memcmp(cp.data, dev->eir, sizeof(cp.data)) == 0) + return; + + memcpy(dev->eir, cp.data, sizeof(cp.data)); + + if (hci_send_cmd(dev->sk, OGF_HOST_CTL, + OCF_WRITE_EXT_INQUIRY_RESPONSE, + WRITE_EXT_INQUIRY_RESPONSE_CP_SIZE, &cp) < 0) + error("Unable to write EIR data: %s (%d)", + strerror(errno), errno); +} + +static void update_name(int index, const char *name) +{ + struct btd_adapter *adapter; + + adapter = manager_find_adapter_by_id(index); + if (adapter) + adapter_update_local_name(adapter, name); + + update_ext_inquiry_response(index); +} + +static void read_local_name_complete(int index, read_local_name_rp *rp) +{ + struct dev_info *dev = &devs[index]; + + DBG("hci%d status %u", index, rp->status); + + if (rp->status) + return; + + memcpy(dev->name, rp->name, 248); + + if (!dev->pending) { + update_name(index, (char *) rp->name); + return; + } + + hci_clear_bit(PENDING_NAME, &dev->pending); + + DBG("Got name for hci%d", index); + + /* Even though it shouldn't happen (assuming the kernel behaves + * properly) it seems like we might miss the very first + * initialization commands that the kernel sends. So check for + * it here (since read_local_name is one of the last init + * commands) and resend the first ones if we haven't seen + * their results yet */ + + if (hci_test_bit(PENDING_FEATURES, &dev->pending)) + hci_send_cmd(dev->sk, OGF_INFO_PARAM, + OCF_READ_LOCAL_FEATURES, 0, NULL); + + if (hci_test_bit(PENDING_VERSION, &dev->pending)) + hci_send_cmd(dev->sk, OGF_INFO_PARAM, + OCF_READ_LOCAL_VERSION, 0, NULL); + + if (!dev->pending && dev->up) + init_adapter(index); +} + +static void read_tx_power_complete(int index, void *ptr) +{ + struct dev_info *dev = &devs[index]; + + read_inq_response_tx_power_level_rp *rp = ptr; + + DBG("hci%d status %u", index, rp->status); + + if (rp->status) + return; + + dev->tx_power = rp->level; + update_ext_inquiry_response(index); +} + +static void read_simple_pairing_mode_complete(int index, void *ptr) +{ + struct dev_info *dev = &devs[index]; + read_simple_pairing_mode_rp *rp = ptr; + struct btd_adapter *adapter; + + DBG("hci%d status %u", index, rp->status); + + if (rp->status) + return; + + dev->ssp_mode = rp->mode; + update_ext_inquiry_response(index); + + adapter = manager_find_adapter(&dev->bdaddr); + if (!adapter) { + error("No matching adapter found"); + return; + } + + adapter_update_ssp_mode(adapter, rp->mode); +} + +static void read_local_ext_features_complete(int index, + const read_local_ext_features_rp *rp) +{ + struct btd_adapter *adapter; + + DBG("hci%d status %u", index, rp->status); + + if (rp->status) + return; + + adapter = manager_find_adapter_by_id(index); + if (!adapter) { + error("No matching adapter found"); + return; + } + + /* Local Extended feature page number is 1 */ + if (rp->page_num != 1) + return; + + btd_adapter_update_local_ext_features(adapter, rp->features); +} + +static void read_bd_addr_complete(int index, read_bd_addr_rp *rp) +{ + struct dev_info *dev = &devs[index]; + + DBG("hci%d status %u", index, rp->status); + + if (rp->status) + return; + + bacpy(&dev->bdaddr, &rp->bdaddr); + + if (!dev->pending) + return; + + hci_clear_bit(PENDING_BDADDR, &dev->pending); + + DBG("Got bdaddr for hci%d", index); + + if (!dev->pending && dev->up) + init_adapter(index); +} + +static inline void cmd_status(int index, void *ptr) +{ + struct dev_info *dev = &devs[index]; + evt_cmd_status *evt = ptr; + uint16_t opcode = btohs(evt->opcode); + + if (opcode == cmd_opcode_pack(OGF_LINK_CTL, OCF_INQUIRY)) + start_inquiry(&dev->bdaddr, evt->status, FALSE); +} + +static void read_scan_complete(int index, uint8_t status, void *ptr) +{ + struct btd_adapter *adapter; + read_scan_enable_rp *rp = ptr; + + DBG("hci%d status %u", index, status); + + adapter = manager_find_adapter_by_id(index); + if (!adapter) { + error("Unable to find matching adapter"); + return; + } + + adapter_mode_changed(adapter, rp->enable); +} + +static int write_class(int index, uint32_t class) +{ + struct dev_info *dev = &devs[index]; + write_class_of_dev_cp cp; + + DBG("hci%d class 0x%06x", index, class); + + memcpy(cp.dev_class, &class, 3); + + if (hci_send_cmd(dev->sk, OGF_HOST_CTL, OCF_WRITE_CLASS_OF_DEV, + WRITE_CLASS_OF_DEV_CP_SIZE, &cp) < 0) + return -errno; + + dev->pending_cod = class; + + return 0; +} + +/* Limited Discoverable bit mask in CoD */ +#define LIMITED_BIT 0x002000 + +static int hciops_set_limited_discoverable(int index, gboolean limited) +{ + struct dev_info *dev = &devs[index]; + int num = (limited ? 2 : 1); + uint8_t lap[] = { 0x33, 0x8b, 0x9e, 0x00, 0x8b, 0x9e }; + write_current_iac_lap_cp cp; + + DBG("hci%d limited %d", index, limited); + + /* Check if limited bit needs to be set/reset */ + if (limited) + dev->wanted_cod |= LIMITED_BIT; + else + dev->wanted_cod &= ~LIMITED_BIT; + + /* If we dont need the toggling, save an unnecessary CoD write */ + if (dev->pending_cod || dev->wanted_cod == dev->current_cod) + return 0; + + /* + * 1: giac + * 2: giac + liac + */ + memset(&cp, 0, sizeof(cp)); + cp.num_current_iac = num; + memcpy(&cp.lap, lap, num * 3); + + if (hci_send_cmd(dev->sk, OGF_HOST_CTL, OCF_WRITE_CURRENT_IAC_LAP, + (num * 3 + 1), &cp) < 0) + return -errno; + + return write_class(index, dev->wanted_cod); +} + +static void write_class_complete(int index, uint8_t status) +{ + struct dev_info *dev = &devs[index]; + struct btd_adapter *adapter; + + if (status) + return; + + if (dev->pending_cod == 0) + return; + + dev->current_cod = dev->pending_cod; + dev->pending_cod = 0; + + adapter = manager_find_adapter(&dev->bdaddr); + if (adapter) + btd_adapter_class_changed(adapter, dev->current_cod); + + update_ext_inquiry_response(index); + + if (dev->wanted_cod == dev->current_cod) + return; + + if (dev->wanted_cod & LIMITED_BIT && + !(dev->current_cod & LIMITED_BIT)) + hciops_set_limited_discoverable(index, TRUE); + else if (!(dev->wanted_cod & LIMITED_BIT) && + (dev->current_cod & LIMITED_BIT)) + hciops_set_limited_discoverable(index, FALSE); + else + write_class(index, dev->wanted_cod); +} + +static void read_local_oob_data_complete(int index, uint8_t status, + read_local_oob_data_rp *rp) +{ + struct btd_adapter *adapter = manager_find_adapter_by_id(index); + + if (!adapter) + return; + + if (status) + oob_read_local_data_complete(adapter, NULL, NULL); + else + oob_read_local_data_complete(adapter, rp->hash, rp->randomizer); +} + +static inline void cmd_complete(int index, void *ptr) +{ + struct dev_info *dev = &devs[index]; + evt_cmd_complete *evt = ptr; + uint16_t opcode = btohs(evt->opcode); + uint8_t status = *((uint8_t *) ptr + EVT_CMD_COMPLETE_SIZE); + + switch (opcode) { + case cmd_opcode_pack(OGF_INFO_PARAM, OCF_READ_LOCAL_VERSION): + ptr += sizeof(evt_cmd_complete); + read_local_version_complete(index, ptr); + break; + case cmd_opcode_pack(OGF_INFO_PARAM, OCF_READ_LOCAL_FEATURES): + ptr += sizeof(evt_cmd_complete); + read_local_features_complete(index, ptr); + break; + case cmd_opcode_pack(OGF_INFO_PARAM, OCF_READ_LOCAL_EXT_FEATURES): + ptr += sizeof(evt_cmd_complete); + read_local_ext_features_complete(index, ptr); + break; + case cmd_opcode_pack(OGF_INFO_PARAM, OCF_READ_BD_ADDR): + ptr += sizeof(evt_cmd_complete); + read_bd_addr_complete(index, ptr); + break; + case cmd_opcode_pack(OGF_LINK_CTL, OCF_PERIODIC_INQUIRY): + start_inquiry(&dev->bdaddr, status, TRUE); + break; + case cmd_opcode_pack(OGF_LINK_CTL, OCF_EXIT_PERIODIC_INQUIRY): + inquiry_complete(&dev->bdaddr, status, TRUE); + break; + case cmd_opcode_pack(OGF_LINK_CTL, OCF_INQUIRY_CANCEL): + inquiry_complete(&dev->bdaddr, status, FALSE); + break; + case cmd_opcode_pack(OGF_HOST_CTL, OCF_WRITE_LE_HOST_SUPPORTED): + write_le_host_complete(index, status); + break; + case cmd_opcode_pack(OGF_LE_CTL, OCF_LE_SET_SCAN_ENABLE): + btd_event_le_set_scan_enable_complete(&dev->bdaddr, status); + break; + case cmd_opcode_pack(OGF_HOST_CTL, OCF_CHANGE_LOCAL_NAME): + if (!status) + hci_send_cmd(dev->sk, OGF_HOST_CTL, + OCF_READ_LOCAL_NAME, 0, 0); + break; + case cmd_opcode_pack(OGF_HOST_CTL, OCF_WRITE_SCAN_ENABLE): + hci_send_cmd(dev->sk, OGF_HOST_CTL, OCF_READ_SCAN_ENABLE, + 0, NULL); + break; + case cmd_opcode_pack(OGF_HOST_CTL, OCF_READ_SCAN_ENABLE): + ptr += sizeof(evt_cmd_complete); + read_scan_complete(index, status, ptr); + break; + case cmd_opcode_pack(OGF_HOST_CTL, OCF_WRITE_CLASS_OF_DEV): + write_class_complete(index, status); + break; + case cmd_opcode_pack(OGF_HOST_CTL, OCF_WRITE_SIMPLE_PAIRING_MODE): + if (!status) + hci_send_cmd(dev->sk, OGF_HOST_CTL, + OCF_READ_SIMPLE_PAIRING_MODE, 0, NULL); + break; + case cmd_opcode_pack(OGF_HOST_CTL, OCF_READ_SIMPLE_PAIRING_MODE): + ptr += sizeof(evt_cmd_complete); + read_simple_pairing_mode_complete(index, ptr); + break; + case cmd_opcode_pack(OGF_HOST_CTL, OCF_READ_LOCAL_NAME): + ptr += sizeof(evt_cmd_complete); + read_local_name_complete(index, ptr); + break; + case cmd_opcode_pack(OGF_HOST_CTL, + OCF_READ_INQ_RESPONSE_TX_POWER_LEVEL): + ptr += sizeof(evt_cmd_complete); + read_tx_power_complete(index, ptr); + break; + case cmd_opcode_pack(OGF_HOST_CTL, OCF_READ_LOCAL_OOB_DATA): + ptr += sizeof(evt_cmd_complete); + read_local_oob_data_complete(index, status, ptr); + break; + }; +} + +static inline void remote_name_information(int index, void *ptr) +{ + struct dev_info *dev = &devs[index]; + evt_remote_name_req_complete *evt = ptr; + char name[MAX_NAME_LENGTH + 1]; + + DBG("hci%d status %u", index, evt->status); + + memset(name, 0, sizeof(name)); + + if (!evt->status) + memcpy(name, evt->name, MAX_NAME_LENGTH); + + btd_event_remote_name(&dev->bdaddr, &evt->bdaddr, evt->status, name); +} + +static inline void remote_version_information(int index, void *ptr) +{ + struct dev_info *dev = &devs[index]; + evt_read_remote_version_complete *evt = ptr; + struct bt_conn *conn; + + DBG("hci%d status %u", index, evt->status); + + if (evt->status) + return; + + conn = find_conn_by_handle(dev, btohs(evt->handle)); + if (conn == NULL) + return; + + write_version_info(&dev->bdaddr, &conn->bdaddr, + btohs(evt->manufacturer), evt->lmp_ver, + btohs(evt->lmp_subver)); +} + +static inline void inquiry_result(int index, int plen, void *ptr) +{ + struct dev_info *dev = &devs[index]; + uint8_t num = *(uint8_t *) ptr++; + int i; + + for (i = 0; i < num; i++) { + inquiry_info *info = ptr; + uint32_t class = info->dev_class[0] | + (info->dev_class[1] << 8) | + (info->dev_class[2] << 16); + + btd_event_device_found(&dev->bdaddr, &info->bdaddr, class, + 0, NULL); + ptr += INQUIRY_INFO_SIZE; + } +} + +static inline void inquiry_result_with_rssi(int index, int plen, void *ptr) +{ + struct dev_info *dev = &devs[index]; + uint8_t num = *(uint8_t *) ptr++; + int i; + + if (!num) + return; + + if ((plen - 1) / num == INQUIRY_INFO_WITH_RSSI_AND_PSCAN_MODE_SIZE) { + for (i = 0; i < num; i++) { + inquiry_info_with_rssi_and_pscan_mode *info = ptr; + uint32_t class = info->dev_class[0] + | (info->dev_class[1] << 8) + | (info->dev_class[2] << 16); + + btd_event_device_found(&dev->bdaddr, &info->bdaddr, + class, info->rssi, NULL); + ptr += INQUIRY_INFO_WITH_RSSI_AND_PSCAN_MODE_SIZE; + } + } else { + for (i = 0; i < num; i++) { + inquiry_info_with_rssi *info = ptr; + uint32_t class = info->dev_class[0] + | (info->dev_class[1] << 8) + | (info->dev_class[2] << 16); + + btd_event_device_found(&dev->bdaddr, &info->bdaddr, + class, info->rssi, NULL); + ptr += INQUIRY_INFO_WITH_RSSI_SIZE; + } + } +} + +static inline void extended_inquiry_result(int index, int plen, void *ptr) +{ + struct dev_info *dev = &devs[index]; + uint8_t num = *(uint8_t *) ptr++; + int i; + + for (i = 0; i < num; i++) { + extended_inquiry_info *info = ptr; + uint32_t class = info->dev_class[0] + | (info->dev_class[1] << 8) + | (info->dev_class[2] << 16); + + btd_event_device_found(&dev->bdaddr, &info->bdaddr, class, + info->rssi, info->data); + ptr += EXTENDED_INQUIRY_INFO_SIZE; + } +} + +static inline void remote_features_information(int index, void *ptr) +{ + struct dev_info *dev = &devs[index]; + evt_read_remote_features_complete *evt = ptr; + struct bt_conn *conn; + + DBG("hci%d status %u", index, evt->status); + + if (evt->status) + return; + + conn = find_conn_by_handle(dev, btohs(evt->handle)); + if (conn == NULL) + return; + + write_features_info(&dev->bdaddr, &conn->bdaddr, evt->features, NULL); +} + +struct remote_version_req { + int index; + uint16_t handle; +}; + +static gboolean __get_remote_version(gpointer user_data) +{ + struct remote_version_req *req = user_data; + struct dev_info *dev = &devs[req->index]; + read_remote_version_cp cp; + + DBG("hci%d handle %u", req->index, req->handle); + + memset(&cp, 0, sizeof(cp)); + cp.handle = htobs(req->handle); + + hci_send_cmd(dev->sk, OGF_LINK_CTL, OCF_READ_REMOTE_VERSION, + READ_REMOTE_VERSION_CP_SIZE, &cp); + + return FALSE; +} + +static void get_remote_version(int index, uint16_t handle) +{ + struct remote_version_req *req; + + req = g_new0(struct remote_version_req, 1); + req->handle = handle; + req->index = index; + + g_timeout_add_seconds_full(G_PRIORITY_DEFAULT, 1, __get_remote_version, + req, g_free); +} + +static void conn_free(struct bt_conn *conn) +{ + if (conn->io != NULL) { + g_io_channel_shutdown(conn->io, TRUE, NULL); + g_io_channel_unref(conn->io); + } + + g_free(conn); +} + +static inline void conn_failed(int index, bdaddr_t *bdaddr, uint8_t status) +{ + struct dev_info *dev = &devs[index]; + struct bt_conn *conn; + + btd_event_conn_failed(&dev->bdaddr, bdaddr, status); + + conn = find_connection(dev, bdaddr); + if (conn == NULL) + return; + + bonding_complete(dev, conn, status); + + dev->connections = g_slist_remove(dev->connections, conn); + conn_free(conn); +} + +static inline void conn_complete(int index, void *ptr) +{ + struct dev_info *dev = &devs[index]; + evt_conn_complete *evt = ptr; + char filename[PATH_MAX]; + char local_addr[18], peer_addr[18], *str; + struct bt_conn *conn; + + if (evt->link_type != ACL_LINK) + return; + + DBG("status 0x%02x", evt->status); + + if (evt->status != 0) { + conn_failed(index, &evt->bdaddr, evt->status); + return; + } + + conn = get_connection(dev, &evt->bdaddr); + conn->handle = btohs(evt->handle); + + btd_event_conn_complete(&dev->bdaddr, &evt->bdaddr); + + if (conn->secmode3) + bonding_complete(dev, conn, 0); + + /* check if the remote version needs be requested */ + ba2str(&dev->bdaddr, local_addr); + ba2str(&evt->bdaddr, peer_addr); + + create_name(filename, sizeof(filename), STORAGEDIR, local_addr, + "manufacturers"); + + str = textfile_get(filename, peer_addr); + if (!str) + get_remote_version(index, btohs(evt->handle)); + else + free(str); +} + +static inline void le_conn_complete(int index, void *ptr) +{ + struct dev_info *dev = &devs[index]; + evt_le_connection_complete *evt = ptr; + char filename[PATH_MAX]; + char local_addr[18], peer_addr[18], *str; + struct bt_conn *conn; + + if (evt->status) { + btd_event_conn_failed(&dev->bdaddr, &evt->peer_bdaddr, + evt->status); + return; + } + + conn = get_connection(dev, &evt->peer_bdaddr); + conn->handle = btohs(evt->handle); + + btd_event_conn_complete(&dev->bdaddr, &evt->peer_bdaddr); + + /* check if the remote version needs be requested */ + ba2str(&dev->bdaddr, local_addr); + ba2str(&evt->peer_bdaddr, peer_addr); + + create_name(filename, sizeof(filename), STORAGEDIR, local_addr, + "manufacturers"); + + str = textfile_get(filename, peer_addr); + if (!str) + get_remote_version(index, btohs(evt->handle)); + else + free(str); +} + +static inline void disconn_complete(int index, void *ptr) +{ + struct dev_info *dev = &devs[index]; + evt_disconn_complete *evt = ptr; + struct bt_conn *conn; + + DBG("handle %u status 0x%02x", btohs(evt->handle), evt->status); + + if (evt->status != 0) + return; + + conn = find_conn_by_handle(dev, btohs(evt->handle)); + if (conn == NULL) + return; + + dev->connections = g_slist_remove(dev->connections, conn); + + btd_event_disconn_complete(&dev->bdaddr, &conn->bdaddr); + + conn_free(conn); +} + +static inline void auth_complete(int index, void *ptr) +{ + struct dev_info *dev = &devs[index]; + evt_auth_complete *evt = ptr; + struct bt_conn *conn; + + DBG("hci%d status %u", index, evt->status); + + conn = find_conn_by_handle(dev, btohs(evt->handle)); + if (conn == NULL) + return; + + bonding_complete(dev, conn, evt->status); +} + +static inline void simple_pairing_complete(int index, void *ptr) +{ + struct dev_info *dev = &devs[index]; + evt_simple_pairing_complete *evt = ptr; + + DBG("hci%d status %u", index, evt->status); + + btd_event_simple_pairing_complete(&dev->bdaddr, &evt->bdaddr, + evt->status); +} + +static inline void conn_request(int index, void *ptr) +{ + struct dev_info *dev = &devs[index]; + evt_conn_request *evt = ptr; + uint32_t class = evt->dev_class[0] | (evt->dev_class[1] << 8) + | (evt->dev_class[2] << 16); + + btd_event_remote_class(&dev->bdaddr, &evt->bdaddr, class); +} + +static inline void le_advertising_report(int index, evt_le_meta_event *meta) +{ + struct dev_info *dev = &devs[index]; + le_advertising_info *info; + uint8_t num_reports; + const uint8_t RSSI_SIZE = 1; + + num_reports = meta->data[0]; + + info = (le_advertising_info *) &meta->data[1]; + btd_event_advertising_report(&dev->bdaddr, info); + num_reports--; + + while (num_reports--) { + info = (le_advertising_info *) (info->data + info->length + + RSSI_SIZE); + btd_event_advertising_report(&dev->bdaddr, info); + } +} + +static inline void le_metaevent(int index, void *ptr) +{ + evt_le_meta_event *meta = ptr; + + DBG("hci%d LE Meta Event %u", index, meta->subevent); + + switch (meta->subevent) { + case EVT_LE_ADVERTISING_REPORT: + le_advertising_report(index, meta); + break; + + case EVT_LE_CONN_COMPLETE: + le_conn_complete(index, meta->data); + break; + } +} + +static void stop_hci_dev(int index) +{ + struct dev_info *dev = &devs[index]; + + if (dev->sk < 0) + return; + + info("Stopping hci%d event socket", index); + + if (dev->watch_id > 0) + g_source_remove(dev->watch_id); + + if (dev->io != NULL) + g_io_channel_unref(dev->io); + + hci_close_dev(dev->sk); + + g_slist_foreach(dev->keys, (GFunc) g_free, NULL); + g_slist_free(dev->keys); + + g_slist_foreach(dev->uuids, (GFunc) g_free, NULL); + g_slist_free(dev->uuids); + + g_slist_foreach(dev->connections, (GFunc) conn_free, NULL); + g_slist_free(dev->connections); + + init_dev_info(index, -1, dev->registered, dev->already_up); +} + +static gboolean io_security_event(GIOChannel *chan, GIOCondition cond, + gpointer data) +{ + unsigned char buf[HCI_MAX_EVENT_SIZE], *ptr = buf; + int type, index = GPOINTER_TO_INT(data); + struct dev_info *dev = &devs[index]; + struct hci_dev_info di; + ssize_t len; + hci_event_hdr *eh; + evt_cmd_status *evt; + int fd; + + if (cond & (G_IO_NVAL | G_IO_HUP | G_IO_ERR)) { + stop_hci_dev(index); + return FALSE; + } + + fd = g_io_channel_unix_get_fd(chan); + + len = read(fd, buf, sizeof(buf)); + if (len < 0) { + if (errno == EAGAIN) + return TRUE; + stop_hci_dev(index); + return FALSE; + } + + type = *ptr++; + + if (type != HCI_EVENT_PKT) + return TRUE; + + eh = (hci_event_hdr *) ptr; + ptr += HCI_EVENT_HDR_SIZE; + + memset(&di, 0, sizeof(di)); + if (hci_devinfo(index, &di) == 0) { + bacpy(&dev->bdaddr, &di.bdaddr); + + if (ignore_device(&di)) + return TRUE; + } + + switch (eh->evt) { + case EVT_CMD_STATUS: + cmd_status(index, ptr); + break; + + case EVT_CMD_COMPLETE: + cmd_complete(index, ptr); + break; + + case EVT_REMOTE_NAME_REQ_COMPLETE: + remote_name_information(index, ptr); + break; + + case EVT_READ_REMOTE_VERSION_COMPLETE: + remote_version_information(index, ptr); + break; + + case EVT_READ_REMOTE_FEATURES_COMPLETE: + remote_features_information(index, ptr); + break; + + case EVT_REMOTE_HOST_FEATURES_NOTIFY: + remote_features_notify(index, ptr); + break; + + case EVT_INQUIRY_COMPLETE: + evt = (evt_cmd_status *) ptr; + inquiry_complete(&dev->bdaddr, evt->status, FALSE); + break; + + case EVT_INQUIRY_RESULT: + inquiry_result(index, eh->plen, ptr); + break; + + case EVT_INQUIRY_RESULT_WITH_RSSI: + inquiry_result_with_rssi(index, eh->plen, ptr); + break; + + case EVT_EXTENDED_INQUIRY_RESULT: + extended_inquiry_result(index, eh->plen, ptr); + break; + + case EVT_CONN_COMPLETE: + conn_complete(index, ptr); + break; + + case EVT_DISCONN_COMPLETE: + disconn_complete(index, ptr); + break; + + case EVT_AUTH_COMPLETE: + auth_complete(index, ptr); + break; + + case EVT_SIMPLE_PAIRING_COMPLETE: + simple_pairing_complete(index, ptr); + break; + + case EVT_CONN_REQUEST: + conn_request(index, ptr); + break; + case EVT_LE_META_EVENT: + le_metaevent(index, ptr); + break; + case EVT_PIN_CODE_REQ: + pin_code_request(index, (bdaddr_t *) ptr); + break; + + case EVT_LINK_KEY_REQ: + link_key_request(index, (bdaddr_t *) ptr); + break; + + case EVT_LINK_KEY_NOTIFY: + link_key_notify(index, ptr); + break; + + case EVT_RETURN_LINK_KEYS: + return_link_keys(index, ptr); + break; + + case EVT_IO_CAPABILITY_REQUEST: + io_capa_request(index, ptr); + break; + + case EVT_IO_CAPABILITY_RESPONSE: + io_capa_response(index, ptr); + break; + + case EVT_USER_CONFIRM_REQUEST: + user_confirm_request(index, ptr); + break; + + case EVT_USER_PASSKEY_REQUEST: + user_passkey_request(index, ptr); + break; + + case EVT_USER_PASSKEY_NOTIFY: + user_passkey_notify(index, ptr); + break; + + case EVT_REMOTE_OOB_DATA_REQUEST: + remote_oob_data_request(index, (bdaddr_t *) ptr); + break; + } + + return TRUE; +} + +static void start_hci_dev(int index) +{ + struct dev_info *dev = &devs[index]; + GIOChannel *chan = dev->io; + GIOCondition cond; + struct hci_filter flt; + + if (chan) + return; + + info("Listening for HCI events on hci%d", index); + + /* Set filter */ + hci_filter_clear(&flt); + hci_filter_set_ptype(HCI_EVENT_PKT, &flt); + hci_filter_set_event(EVT_CMD_STATUS, &flt); + hci_filter_set_event(EVT_CMD_COMPLETE, &flt); + hci_filter_set_event(EVT_PIN_CODE_REQ, &flt); + hci_filter_set_event(EVT_LINK_KEY_REQ, &flt); + hci_filter_set_event(EVT_LINK_KEY_NOTIFY, &flt); + hci_filter_set_event(EVT_RETURN_LINK_KEYS, &flt); + hci_filter_set_event(EVT_IO_CAPABILITY_REQUEST, &flt); + hci_filter_set_event(EVT_IO_CAPABILITY_RESPONSE, &flt); + hci_filter_set_event(EVT_USER_CONFIRM_REQUEST, &flt); + hci_filter_set_event(EVT_USER_PASSKEY_REQUEST, &flt); + hci_filter_set_event(EVT_REMOTE_OOB_DATA_REQUEST, &flt); + hci_filter_set_event(EVT_USER_PASSKEY_NOTIFY, &flt); + hci_filter_set_event(EVT_KEYPRESS_NOTIFY, &flt); + hci_filter_set_event(EVT_SIMPLE_PAIRING_COMPLETE, &flt); + hci_filter_set_event(EVT_AUTH_COMPLETE, &flt); + hci_filter_set_event(EVT_REMOTE_NAME_REQ_COMPLETE, &flt); + hci_filter_set_event(EVT_READ_REMOTE_VERSION_COMPLETE, &flt); + hci_filter_set_event(EVT_READ_REMOTE_FEATURES_COMPLETE, &flt); + hci_filter_set_event(EVT_REMOTE_HOST_FEATURES_NOTIFY, &flt); + hci_filter_set_event(EVT_INQUIRY_COMPLETE, &flt); + hci_filter_set_event(EVT_INQUIRY_RESULT, &flt); + hci_filter_set_event(EVT_INQUIRY_RESULT_WITH_RSSI, &flt); + hci_filter_set_event(EVT_EXTENDED_INQUIRY_RESULT, &flt); + hci_filter_set_event(EVT_CONN_REQUEST, &flt); + hci_filter_set_event(EVT_CONN_COMPLETE, &flt); + hci_filter_set_event(EVT_DISCONN_COMPLETE, &flt); + hci_filter_set_event(EVT_LE_META_EVENT, &flt); + if (setsockopt(dev->sk, SOL_HCI, HCI_FILTER, &flt, sizeof(flt)) < 0) { + error("Can't set filter on hci%d: %s (%d)", + index, strerror(errno), errno); + return; + } + + chan = g_io_channel_unix_new(dev->sk); + cond = G_IO_IN | G_IO_NVAL | G_IO_HUP | G_IO_ERR; + dev->watch_id = g_io_add_watch_full(chan, G_PRIORITY_LOW, cond, + io_security_event, + GINT_TO_POINTER(index), NULL); + dev->io = chan; + dev->pin_length = 0; + +} + +/* End of HCI event callbacks */ + +static gboolean child_exit(GIOChannel *io, GIOCondition cond, void *user_data) +{ + int status, fd = g_io_channel_unix_get_fd(io); + pid_t child_pid; + + if (read(fd, &child_pid, sizeof(child_pid)) != sizeof(child_pid)) { + error("child_exit: unable to read child pid from pipe"); + return TRUE; + } + + if (waitpid(child_pid, &status, 0) != child_pid) + error("waitpid(%d) failed", child_pid); + else + DBG("child %d exited", child_pid); + + return TRUE; +} + +static void at_child_exit(void) +{ + pid_t pid = getpid(); + + if (write(child_pipe[1], &pid, sizeof(pid)) != sizeof(pid)) + error("unable to write to child pipe"); +} + +static void device_devup_setup(int index) +{ + struct dev_info *dev = &devs[index]; + struct hci_dev_info di; + read_stored_link_key_cp cp; + + DBG("hci%d", index); + + if (hci_devinfo(index, &di) < 0) + return; + + if (ignore_device(&di)) + return; + + bacpy(&dev->bdaddr, &di.bdaddr); + memcpy(dev->features, di.features, 8); + + /* Set page timeout */ + if ((main_opts.flags & (1 << HCID_SET_PAGETO))) { + write_page_timeout_cp cp; + + cp.timeout = htobs(main_opts.pageto); + hci_send_cmd(dev->sk, OGF_HOST_CTL, OCF_WRITE_PAGE_TIMEOUT, + WRITE_PAGE_TIMEOUT_CP_SIZE, &cp); + } + + bacpy(&cp.bdaddr, BDADDR_ANY); + cp.read_all = 1; + hci_send_cmd(dev->sk, OGF_HOST_CTL, OCF_READ_STORED_LINK_KEY, + READ_STORED_LINK_KEY_CP_SIZE, &cp); + + if (!dev->pending) + init_adapter(index); +} + +static void init_pending(int index) +{ + struct dev_info *dev = &devs[index]; + + hci_set_bit(PENDING_BDADDR, &dev->pending); + hci_set_bit(PENDING_VERSION, &dev->pending); + hci_set_bit(PENDING_FEATURES, &dev->pending); + hci_set_bit(PENDING_NAME, &dev->pending); +} + +static struct dev_info *init_device(int index, gboolean already_up) +{ + struct dev_info *dev; + struct hci_dev_req dr; + int dd; + pid_t pid; + + DBG("hci%d", index); + + dd = hci_open_dev(index); + if (dd < 0) { + error("Unable to open hci%d: %s (%d)", index, + strerror(errno), errno); + return NULL; + } + + if (index > max_dev) { + max_dev = index; + devs = g_realloc(devs, sizeof(devs[0]) * (max_dev + 1)); + } + + dev = init_dev_info(index, dd, FALSE, already_up); + init_pending(index); + start_hci_dev(index); + + /* Avoid forking if nothing else has to be done */ + if (already_up) + return dev; + + /* Do initialization in the separate process */ + pid = fork(); + switch (pid) { + case 0: + atexit(at_child_exit); + break; + case -1: + error("Fork failed. Can't init device hci%d: %s (%d)", + index, strerror(errno), errno); + default: + DBG("child %d forked", pid); + return dev; + } + + memset(&dr, 0, sizeof(dr)); + dr.dev_id = index; + + /* Set link mode */ + dr.dev_opt = main_opts.link_mode; + if (ioctl(dd, HCISETLINKMODE, (unsigned long) &dr) < 0) + error("Can't set link mode on hci%d: %s (%d)", + index, strerror(errno), errno); + + /* Start HCI device */ + if (ioctl(dd, HCIDEVUP, index) < 0 && errno != EALREADY) { + error("Can't init device hci%d: %s (%d)", + index, strerror(errno), errno); + goto fail; + } + + hci_close_dev(dd); + exit(0); + +fail: + hci_close_dev(dd); + exit(1); +} + +static void init_conn_list(int index) +{ + struct dev_info *dev = &devs[index]; + struct hci_conn_list_req *cl; + struct hci_conn_info *ci; + int err, i; + + DBG("hci%d", index); + + cl = g_malloc0(10 * sizeof(*ci) + sizeof(*cl)); + + cl->dev_id = index; + cl->conn_num = 10; + ci = cl->conn_info; + + if (ioctl(dev->sk, HCIGETCONNLIST, cl) < 0) { + error("Unable to get connection list: %s (%d)", + strerror(errno), errno); + goto failed; + } + + for (i = 0; i < cl->conn_num; i++, ci++) { + struct bt_conn *conn; + + if (ci->type != ACL_LINK) + continue; + + conn = get_connection(dev, &ci->bdaddr); + conn->handle = ci->handle; + } + + err = 0; + +failed: + g_free(cl); +} + +static void device_event(int event, int index) +{ + switch (event) { + case HCI_DEV_REG: + info("HCI dev %d registered", index); + init_device(index, FALSE); + break; + + case HCI_DEV_UNREG: + info("HCI dev %d unregistered", index); + stop_hci_dev(index); + if (devs[index].registered) + btd_manager_unregister_adapter(index); + break; + + case HCI_DEV_UP: + info("HCI dev %d up", index); + devs[index].up = TRUE; + device_devup_setup(index); + break; + + case HCI_DEV_DOWN: + info("HCI dev %d down", index); + devs[index].up = FALSE; + devs[index].pending_cod = 0; + devs[index].cache_enable = TRUE; + if (!devs[index].pending) { + struct btd_adapter *adapter; + + adapter = manager_find_adapter_by_id(index); + if (adapter) + btd_adapter_stop(adapter); + + init_pending(index); + } + break; + } +} + +static gboolean init_known_adapters(gpointer user_data) +{ + struct hci_dev_list_req *dl; + struct hci_dev_req *dr; + int i, err, ctl = GPOINTER_TO_INT(user_data); + size_t req_size; + + DBG(""); + + req_size = HCI_MAX_DEV * sizeof(struct hci_dev_req) + sizeof(uint16_t); + + dl = g_try_malloc0(req_size); + if (!dl) { + error("Can't allocate devlist buffer"); + return FALSE; + } + + dl->dev_num = HCI_MAX_DEV; + dr = dl->dev_req; + + if (ioctl(ctl, HCIGETDEVLIST, dl) < 0) { + err = -errno; + error("Can't get device list: %s (%d)", strerror(-err), -err); + g_free(dl); + return FALSE; + } + + for (i = 0; i < dl->dev_num; i++, dr++) { + struct dev_info *dev; + gboolean already_up; + + already_up = hci_test_bit(HCI_UP, &dr->dev_opt); + + dev = init_device(dr->dev_id, already_up); + if (dev == NULL) + continue; + + if (!dev->already_up) + continue; + + init_conn_list(dr->dev_id); + + dev->pending = 0; + hci_set_bit(PENDING_VERSION, &dev->pending); + hci_send_cmd(dev->sk, OGF_INFO_PARAM, + OCF_READ_LOCAL_VERSION, 0, NULL); + device_event(HCI_DEV_UP, dr->dev_id); + } + + g_free(dl); + + return FALSE; +} + +static gboolean io_stack_event(GIOChannel *chan, GIOCondition cond, + gpointer data) +{ + unsigned char buf[HCI_MAX_FRAME_SIZE], *ptr; + evt_stack_internal *si; + evt_si_device *sd; + hci_event_hdr *eh; + int type, fd; + ssize_t len; + + ptr = buf; + + fd = g_io_channel_unix_get_fd(chan); + + len = read(fd, buf, sizeof(buf)); + if (len < 0) { + if (errno == EAGAIN) + return TRUE; + + error("Read from control socket failed: %s (%d)", + strerror(errno), errno); + return FALSE; + } + + type = *ptr++; + + if (type != HCI_EVENT_PKT) + return TRUE; + + eh = (hci_event_hdr *) ptr; + if (eh->evt != EVT_STACK_INTERNAL) + return TRUE; + + ptr += HCI_EVENT_HDR_SIZE; + + si = (evt_stack_internal *) ptr; + switch (si->type) { + case EVT_SI_DEVICE: + sd = (void *) &si->data; + device_event(sd->event, sd->dev_id); + break; + } + + return TRUE; +} + +static int hciops_setup(void) +{ + struct sockaddr_hci addr; + struct hci_filter flt; + GIOChannel *ctl_io, *child_io; + int sock, err; + + DBG(""); + + if (child_pipe[0] != -1) + return -EALREADY; + + if (pipe(child_pipe) < 0) { + err = -errno; + error("pipe(): %s (%d)", strerror(-err), -err); + return err; + } + + child_io = g_io_channel_unix_new(child_pipe[0]); + g_io_channel_set_close_on_unref(child_io, TRUE); + child_io_id = g_io_add_watch(child_io, + G_IO_IN | G_IO_ERR | G_IO_HUP | G_IO_NVAL, + child_exit, NULL); + g_io_channel_unref(child_io); + + /* Create and bind HCI socket */ + sock = socket(AF_BLUETOOTH, SOCK_RAW, BTPROTO_HCI); + if (sock < 0) { + err = -errno; + error("Can't open HCI socket: %s (%d)", strerror(-err), + -err); + return err; + } + + /* Set filter */ + hci_filter_clear(&flt); + hci_filter_set_ptype(HCI_EVENT_PKT, &flt); + hci_filter_set_event(EVT_STACK_INTERNAL, &flt); + if (setsockopt(sock, SOL_HCI, HCI_FILTER, &flt, sizeof(flt)) < 0) { + err = -errno; + error("Can't set filter: %s (%d)", strerror(-err), -err); + return err; + } + + memset(&addr, 0, sizeof(addr)); + addr.hci_family = AF_BLUETOOTH; + addr.hci_dev = HCI_DEV_NONE; + if (bind(sock, (struct sockaddr *) &addr, sizeof(addr)) < 0) { + err = -errno; + error("Can't bind HCI socket: %s (%d)", strerror(-err), -err); + return err; + } + + ctl_io = g_io_channel_unix_new(sock); + g_io_channel_set_close_on_unref(ctl_io, TRUE); + + ctl_io_id = g_io_add_watch(ctl_io, G_IO_IN, io_stack_event, NULL); + + g_io_channel_unref(ctl_io); + + g_idle_add(init_known_adapters, GINT_TO_POINTER(sock)); + + return 0; +} + +static void hciops_cleanup(void) +{ + int i; + + DBG(""); + + for (i = 0; i <= max_dev; i++) + stop_hci_dev(i); + + g_free(devs); + devs = NULL; + max_dev = -1; + + if (child_io_id) { + g_source_remove(child_io_id); + child_io_id = 0; + } + + if (ctl_io_id) { + g_source_remove(ctl_io_id); + ctl_io_id = 0; + } + + if (child_pipe[0] >= 0) { + close(child_pipe[0]); + child_pipe[0] = -1; + } + + if (child_pipe[1] >= 0) { + close(child_pipe[1]); + child_pipe[1] = -1; + } +} + +static int hciops_set_powered(int index, gboolean powered) +{ + struct dev_info *dev = &devs[index]; + int err; + + DBG("hci%d powered %d", index, powered); + + if (powered == FALSE) + return hciops_power_off(index); + + if (ioctl(dev->sk, HCIDEVUP, index) == 0) + return 0; + + if (errno == EALREADY) + return 0; + + err = -errno; + error("Can't init device hci%d: %s (%d)", + index, strerror(-err), -err); + + return err; +} + +static int hciops_set_dev_class(int index, uint8_t major, uint8_t minor) +{ + struct dev_info *dev = &devs[index]; + int err; + + DBG("hci%d major %u minor %u", index, major, minor); + + /* Update only the major and minor class bits keeping remaining bits + * intact*/ + dev->wanted_cod &= 0xffe000; + dev->wanted_cod |= ((major & 0x1f) << 8) | minor; + + if (dev->wanted_cod == dev->current_cod || + dev->cache_enable || dev->pending_cod) + return 0; + + DBG("Changing Major/Minor class to 0x%06x", dev->wanted_cod); + + err = write_class(index, dev->wanted_cod); + if (err < 0) + error("Adapter class update failed: %s (%d)", + strerror(-err), -err); + + return err; +} + +static int hciops_start_inquiry(int index, uint8_t length, gboolean periodic) +{ + struct dev_info *dev = &devs[index]; + uint8_t lap[3] = { 0x33, 0x8b, 0x9e }; + int err; + + DBG("hci%d length %u periodic %d", index, length, periodic); + + if (periodic) { + periodic_inquiry_cp cp; + + memset(&cp, 0, sizeof(cp)); + memcpy(&cp.lap, lap, 3); + cp.max_period = htobs(24); + cp.min_period = htobs(16); + cp.length = length; + cp.num_rsp = 0x00; + + err = hci_send_cmd(dev->sk, OGF_LINK_CTL, + OCF_PERIODIC_INQUIRY, + PERIODIC_INQUIRY_CP_SIZE, &cp); + } else { + inquiry_cp inq_cp; + + memset(&inq_cp, 0, sizeof(inq_cp)); + memcpy(&inq_cp.lap, lap, 3); + inq_cp.length = length; + inq_cp.num_rsp = 0x00; + + err = hci_send_cmd(dev->sk, OGF_LINK_CTL, + OCF_INQUIRY, INQUIRY_CP_SIZE, &inq_cp); + } + + if (err < 0) + err = -errno; + + return err; +} + +static int le_set_scan_enable(int index, uint8_t enable) +{ + struct dev_info *dev = &devs[index]; + le_set_scan_enable_cp cp; + + DBG("hci%d enable %u", index, enable); + + memset(&cp, 0, sizeof(cp)); + cp.enable = enable; + cp.filter_dup = 0; + + if (hci_send_cmd(dev->sk, OGF_LE_CTL, OCF_LE_SET_SCAN_ENABLE, + LE_SET_SCAN_ENABLE_CP_SIZE, &cp) < 0) + return -errno; + + return 0; +} + +static int hciops_start_scanning(int index) +{ + struct dev_info *dev = &devs[index]; + le_set_scan_parameters_cp cp; + + DBG("hci%d", index); + + memset(&cp, 0, sizeof(cp)); + cp.type = 0x01; /* Active scanning */ + /* The recommended value for scan interval and window is 11.25 msec. + * It is calculated by: time = n * 0.625 msec */ + cp.interval = htobs(0x0012); + cp.window = htobs(0x0012); + cp.own_bdaddr_type = 0; /* Public address */ + cp.filter = 0; /* Accept all adv packets */ + + if (hci_send_cmd(dev->sk, OGF_LE_CTL, OCF_LE_SET_SCAN_PARAMETERS, + LE_SET_SCAN_PARAMETERS_CP_SIZE, &cp) < 0) + return -errno; + + return le_set_scan_enable(index, 1); +} + +static int hciops_stop_scanning(int index) +{ + DBG("hci%d", index); + + return le_set_scan_enable(index, 0); +} + +static int hciops_resolve_name(int index, bdaddr_t *bdaddr) +{ + struct dev_info *dev = &devs[index]; + remote_name_req_cp cp; + char addr[18]; + + ba2str(bdaddr, addr); + DBG("hci%d dba %s", index, addr); + + memset(&cp, 0, sizeof(cp)); + bacpy(&cp.bdaddr, bdaddr); + cp.pscan_rep_mode = 0x02; + + if (hci_send_cmd(dev->sk, OGF_LINK_CTL, OCF_REMOTE_NAME_REQ, + REMOTE_NAME_REQ_CP_SIZE, &cp) < 0) + return -errno; + + return 0; +} + +static int hciops_set_name(int index, const char *name) +{ + struct dev_info *dev = &devs[index]; + change_local_name_cp cp; + + DBG("hci%d, name %s", index, name); + + memset(&cp, 0, sizeof(cp)); + strncpy((char *) cp.name, name, sizeof(cp.name)); + + if (hci_send_cmd(dev->sk, OGF_HOST_CTL, OCF_CHANGE_LOCAL_NAME, + CHANGE_LOCAL_NAME_CP_SIZE, &cp) < 0) + return -errno; + + memcpy(dev->name, cp.name, 248); + update_ext_inquiry_response(index); + + return 0; +} + +static int hciops_cancel_resolve_name(int index, bdaddr_t *bdaddr) +{ + struct dev_info *dev = &devs[index]; + remote_name_req_cancel_cp cp; + char addr[18]; + + ba2str(bdaddr, addr); + DBG("hci%d dba %s", index, addr); + + memset(&cp, 0, sizeof(cp)); + bacpy(&cp.bdaddr, bdaddr); + + if (hci_send_cmd(dev->sk, OGF_LINK_CTL, OCF_REMOTE_NAME_REQ_CANCEL, + REMOTE_NAME_REQ_CANCEL_CP_SIZE, &cp) < 0) + return -errno; + + return 0; +} + +static int hciops_fast_connectable(int index, gboolean enable) +{ + struct dev_info *dev = &devs[index]; + write_page_activity_cp cp; + uint8_t type; + + DBG("hci%d enable %d", index, enable); + + if (enable) { + type = PAGE_SCAN_TYPE_INTERLACED; + cp.interval = 0x0024; /* 22.5 msec page scan interval */ + } else { + type = PAGE_SCAN_TYPE_STANDARD; /* default */ + cp.interval = 0x0800; /* default 1.28 sec page scan */ + } + + cp.window = 0x0012; /* default 11.25 msec page scan window */ + + if (hci_send_cmd(dev->sk, OGF_HOST_CTL, OCF_WRITE_PAGE_ACTIVITY, + WRITE_PAGE_ACTIVITY_CP_SIZE, &cp) < 0) + return -errno; + else if (hci_send_cmd(dev->sk, OGF_HOST_CTL, + OCF_WRITE_PAGE_SCAN_TYPE, 1, &type) < 0) + return -errno; + + return 0; +} + +static int hciops_read_clock(int index, bdaddr_t *bdaddr, int which, + int timeout, uint32_t *clock, + uint16_t *accuracy) +{ + struct dev_info *dev = &devs[index]; + uint16_t handle = 0; + char addr[18]; + int ret; + + ba2str(bdaddr, addr); + DBG("hci%d addr %s which %d timeout %d", index, addr, which, timeout); + + ret = get_handle(index, bdaddr, &handle); + if (ret < 0) + return ret; + + if (hci_read_clock(dev->sk, htobs(handle), which, clock, accuracy, + timeout) < 0) + return -errno; + + return 0; +} + +static int hciops_read_bdaddr(int index, bdaddr_t *bdaddr) +{ + struct dev_info *dev = &devs[index]; + + DBG("hci%d", index); + + bacpy(bdaddr, &dev->bdaddr); + + return 0; +} + +static int hciops_block_device(int index, bdaddr_t *bdaddr) +{ + struct dev_info *dev = &devs[index]; + char addr[18]; + + ba2str(bdaddr, addr); + DBG("hci%d dba %s", index, addr); + + if (ioctl(dev->sk, HCIBLOCKADDR, bdaddr) < 0) + return -errno; + + return 0; +} + +static int hciops_unblock_device(int index, bdaddr_t *bdaddr) +{ + struct dev_info *dev = &devs[index]; + char addr[18]; + + ba2str(bdaddr, addr); + DBG("hci%d dba %s", index, addr); + + if (ioctl(dev->sk, HCIUNBLOCKADDR, bdaddr) < 0) + return -errno; + + return 0; +} + +static int hciops_get_conn_list(int index, GSList **conns) +{ + struct dev_info *dev = &devs[index]; + GSList *l; + + DBG("hci%d", index); + + *conns = NULL; + + for (l = dev->connections; l != NULL; l = g_slist_next(l)) { + struct bt_conn *conn = l->data; + + *conns = g_slist_append(*conns, + g_memdup(&conn->bdaddr, sizeof(bdaddr_t))); + } + + return 0; +} + +static int hciops_read_local_version(int index, struct hci_version *ver) +{ + struct dev_info *dev = &devs[index]; + + DBG("hci%d", index); + + memcpy(ver, &dev->ver, sizeof(*ver)); + + return 0; +} + +static int hciops_read_local_features(int index, uint8_t *features) +{ + struct dev_info *dev = &devs[index]; + + DBG("hci%d", index); + + memcpy(features, dev->features, 8); + + return 0; +} + +static int hciops_disconnect(int index, bdaddr_t *bdaddr) +{ + DBG("hci%d", index); + + return disconnect_addr(index, bdaddr, HCI_OE_USER_ENDED_CONNECTION); +} + +static int hciops_remove_bonding(int index, bdaddr_t *bdaddr) +{ + struct dev_info *dev = &devs[index]; + delete_stored_link_key_cp cp; + GSList *match; + char addr[18]; + + ba2str(bdaddr, addr); + DBG("hci%d dba %s", index, addr); + + match = g_slist_find_custom(dev->keys, bdaddr, (GCompareFunc) bacmp); + if (match) { + g_free(match->data); + dev->keys = g_slist_delete_link(dev->keys, match); + } + + memset(&cp, 0, sizeof(cp)); + bacpy(&cp.bdaddr, bdaddr); + + /* Delete the link key from the Bluetooth chip */ + if (hci_send_cmd(dev->sk, OGF_HOST_CTL, OCF_DELETE_STORED_LINK_KEY, + DELETE_STORED_LINK_KEY_CP_SIZE, &cp) < 0) + return -errno; + + return 0; +} + +static int hciops_pincode_reply(int index, bdaddr_t *bdaddr, const char *pin) +{ + struct dev_info *dev = &devs[index]; + char addr[18]; + int err; + + ba2str(bdaddr, addr); + DBG("hci%d dba %s", index, addr); + + if (pin) { + pin_code_reply_cp pr; + size_t len = strlen(pin); + + dev->pin_length = len; + + memset(&pr, 0, sizeof(pr)); + bacpy(&pr.bdaddr, bdaddr); + memcpy(pr.pin_code, pin, len); + pr.pin_len = len; + err = hci_send_cmd(dev->sk, OGF_LINK_CTL, + OCF_PIN_CODE_REPLY, + PIN_CODE_REPLY_CP_SIZE, &pr); + } else + err = hci_send_cmd(dev->sk, OGF_LINK_CTL, + OCF_PIN_CODE_NEG_REPLY, 6, bdaddr); + + if (err < 0) + err = -errno; + + return err; +} + +static int hciops_passkey_reply(int index, bdaddr_t *bdaddr, uint32_t passkey) +{ + struct dev_info *dev = &devs[index]; + char addr[18]; + int err; + + ba2str(bdaddr, addr); + DBG("hci%d dba %s", index, addr); + + if (passkey != INVALID_PASSKEY) { + user_passkey_reply_cp cp; + + memset(&cp, 0, sizeof(cp)); + bacpy(&cp.bdaddr, bdaddr); + cp.passkey = passkey; + + err = hci_send_cmd(dev->sk, OGF_LINK_CTL, + OCF_USER_PASSKEY_REPLY, + USER_PASSKEY_REPLY_CP_SIZE, &cp); + } else + err = hci_send_cmd(dev->sk, OGF_LINK_CTL, + OCF_USER_PASSKEY_NEG_REPLY, 6, bdaddr); + + if (err < 0) + err = -errno; + + return err; +} + +static int hciops_enable_le(int index) +{ + struct dev_info *dev = &devs[index]; + write_le_host_supported_cp cp; + + DBG("hci%d", index); + + if (!(dev->features[4] & LMP_LE)) + return -ENOTSUP; + + cp.le = 0x01; + cp.simul = (dev->features[6] & LMP_LE_BREDR) ? 0x01 : 0x00; + + if (hci_send_cmd(dev->sk, OGF_HOST_CTL, + OCF_WRITE_LE_HOST_SUPPORTED, + WRITE_LE_HOST_SUPPORTED_CP_SIZE, &cp) < 0) + return -errno; + + return 0; +} + +static uint8_t generate_service_class(int index) +{ + struct dev_info *dev = &devs[index]; + GSList *l; + uint8_t val = 0; + + for (l = dev->uuids; l != NULL; l = g_slist_next(l)) { + struct uuid_info *uuid = l->data; + + val |= uuid->svc_hint; + } + + return val; +} + +static int update_service_classes(int index) +{ + struct dev_info *dev = &devs[index]; + uint8_t value; + int err; + + value = generate_service_class(index); + + DBG("hci%d value %u", index, value); + + /* Update only the service class, keep the limited bit, + * major/minor class bits intact */ + dev->wanted_cod &= 0x00ffff; + dev->wanted_cod |= (value << 16); + + /* If the cache is enabled or an existing CoD write is in progress + * just bail out */ + if (dev->cache_enable || dev->pending_cod) + return 0; + + /* If we already have the CoD we want, update EIR and return */ + if (dev->current_cod == dev->wanted_cod) { + update_ext_inquiry_response(index); + return 0; + } + + DBG("Changing service classes to 0x%06x", dev->wanted_cod); + + err = write_class(index, dev->wanted_cod); + if (err < 0) + error("Adapter class update failed: %s (%d)", + strerror(-err), -err); + + return err; +} + +static int hciops_add_uuid(int index, uuid_t *uuid, uint8_t svc_hint) +{ + struct dev_info *dev = &devs[index]; + struct uuid_info *info; + + DBG("hci%d", index); + + info = g_new0(struct uuid_info, 1); + memcpy(&info->uuid, uuid, sizeof(*uuid)); + info->svc_hint = svc_hint; + + dev->uuids = g_slist_append(dev->uuids, info); + + return update_service_classes(index); +} + +static int hciops_remove_uuid(int index, uuid_t *uuid) +{ + struct dev_info *dev = &devs[index]; + GSList *match; + + match = g_slist_find_custom(dev->uuids, uuid, sdp_uuid_cmp); + if (match) { + g_free(match->data); + dev->uuids = g_slist_delete_link(dev->uuids, match); + } + + DBG("hci%d", index); + + return update_service_classes(index); +} + +static int hciops_disable_cod_cache(int index) +{ + struct dev_info *dev = &devs[index]; + + DBG("hci%d cache_enable %d", index, dev->cache_enable); + + if (!dev->cache_enable) + return 0; + + DBG("hci%d current_cod 0x%06x wanted_cod 0x%06x", index, + dev->current_cod, dev->wanted_cod); + + /* Disable and flush svc cache. All successive service class + * updates * will be written to the device */ + dev->cache_enable = FALSE; + + if (dev->current_cod == dev->wanted_cod) { + update_ext_inquiry_response(index); + return 0; + } + + return write_class(index, dev->wanted_cod); +} + +static int hciops_restore_powered(int index) +{ + struct dev_info *dev = &devs[index]; + + if (!dev->already_up && dev->up) + return hciops_power_off(index); + + return 0; +} + +static int hciops_load_keys(int index, GSList *keys, gboolean debug_keys) +{ + struct dev_info *dev = &devs[index]; + + DBG("hci%d keys %d debug_keys %d", index, g_slist_length(keys), + debug_keys); + + if (dev->keys != NULL) + return -EEXIST; + + dev->keys = keys; + dev->debug_keys = debug_keys; + + return 0; +} + +static int hciops_set_io_capability(int index, uint8_t io_capability) +{ + struct dev_info *dev = &devs[index]; + + dev->io_capability = io_capability; + + return 0; +} + +static int request_authentication(int index, bdaddr_t *bdaddr) +{ + struct dev_info *dev = &devs[index]; + auth_requested_cp cp; + uint16_t handle; + int err; + + DBG("hci%d", index); + + err = get_handle(index, bdaddr, &handle); + if (err < 0) + return err; + + memset(&cp, 0, sizeof(cp)); + cp.handle = htobs(handle); + + if (hci_send_cmd(dev->sk, OGF_LINK_CTL, OCF_AUTH_REQUESTED, + AUTH_REQUESTED_CP_SIZE, &cp) < 0) + return -errno; + + return 0; +} + +static void bonding_connect_cb(GIOChannel *io, GError *err, gpointer user_data) +{ + struct bt_conn *conn = user_data; + struct dev_info *dev = conn->dev; + + if (!conn->io) { + if (!err) + g_io_channel_shutdown(io, TRUE, NULL); + return; + } + + if (err) + /* Wait proper error to be propagated by bonding complete */ + return; + + if (request_authentication(dev->id, &conn->bdaddr) < 0) + goto failed; + + return; + +failed: + bonding_complete(dev, conn, HCI_UNSPECIFIED_ERROR); +} + +static int hciops_create_bonding(int index, bdaddr_t *bdaddr, uint8_t io_cap) +{ + struct dev_info *dev = &devs[index]; + BtIOSecLevel sec_level; + struct bt_conn *conn; + GError *err = NULL; + + conn = get_connection(dev, bdaddr); + + if (conn->io != NULL) + return -EBUSY; + + conn->loc_cap = io_cap; + + /* If our IO capability is NoInputNoOutput use medium security + * level (i.e. don't require MITM protection) else use high + * security level */ + if (io_cap == 0x03) + sec_level = BT_IO_SEC_MEDIUM; + else + sec_level = BT_IO_SEC_HIGH; + + conn->io = bt_io_connect(BT_IO_L2RAW, bonding_connect_cb, conn, + NULL, &err, + BT_IO_OPT_SOURCE_BDADDR, &dev->bdaddr, + BT_IO_OPT_DEST_BDADDR, bdaddr, + BT_IO_OPT_SEC_LEVEL, sec_level, + BT_IO_OPT_INVALID); + if (conn->io == NULL) { + error("bt_io_connect: %s", err->message); + g_error_free(err); + return -EIO; + } + + conn->bonding_initiator = TRUE; + + return 0; +} + +static int hciops_cancel_bonding(int index, bdaddr_t *bdaddr) +{ + struct dev_info *dev = &devs[index]; + struct bt_conn *conn; + + DBG("hci%d", index); + + conn = find_connection(dev, bdaddr); + if (conn == NULL || conn->io == NULL) + return -ENOTCONN; + + g_io_channel_shutdown(conn->io, TRUE, NULL); + g_io_channel_unref(conn->io); + conn->io = NULL; + + return 0; +} + +static int hciops_read_local_oob_data(int index) +{ + struct dev_info *dev = &devs[index]; + + DBG("hci%d", index); + + if (hci_send_cmd(dev->sk, OGF_HOST_CTL, OCF_READ_LOCAL_OOB_DATA, 0, 0) + < 0) + return -errno; + + return 0; +} + +static int hciops_add_remote_oob_data(int index, bdaddr_t *bdaddr, + uint8_t *hash, uint8_t *randomizer) +{ + char addr[18]; + struct dev_info *dev = &devs[index]; + GSList *match; + struct oob_data *data; + + ba2str(bdaddr, addr); + DBG("hci%d bdaddr %s", index, addr); + + match = g_slist_find_custom(dev->oob_data, &bdaddr, oob_bdaddr_cmp); + + if (match) { + data = match->data; + } else { + data = g_new(struct oob_data, 1); + bacpy(&data->bdaddr, bdaddr); + dev->oob_data = g_slist_prepend(dev->oob_data, data); + } + + memcpy(data->hash, hash, sizeof(data->hash)); + memcpy(data->randomizer, randomizer, sizeof(data->randomizer)); + + return 0; +} + +static int hciops_remove_remote_oob_data(int index, bdaddr_t *bdaddr) +{ + char addr[18]; + struct dev_info *dev = &devs[index]; + GSList *match; + + ba2str(bdaddr, addr); + DBG("hci%d bdaddr %s", index, addr); + + match = g_slist_find_custom(dev->oob_data, &bdaddr, oob_bdaddr_cmp); + + if (!match) + return -ENOENT; + + g_free(match->data); + dev->oob_data = g_slist_delete_link(dev->oob_data, match); + + return 0; +} + +static struct btd_adapter_ops hci_ops = { + .setup = hciops_setup, + .cleanup = hciops_cleanup, + .set_powered = hciops_set_powered, + .set_discoverable = hciops_set_discoverable, + .set_pairable = hciops_set_pairable, + .set_limited_discoverable = hciops_set_limited_discoverable, + .start_inquiry = hciops_start_inquiry, + .stop_inquiry = hciops_stop_inquiry, + .start_scanning = hciops_start_scanning, + .stop_scanning = hciops_stop_scanning, + .resolve_name = hciops_resolve_name, + .cancel_resolve_name = hciops_cancel_resolve_name, + .set_name = hciops_set_name, + .set_dev_class = hciops_set_dev_class, + .set_fast_connectable = hciops_fast_connectable, + .read_clock = hciops_read_clock, + .read_bdaddr = hciops_read_bdaddr, + .block_device = hciops_block_device, + .unblock_device = hciops_unblock_device, + .get_conn_list = hciops_get_conn_list, + .read_local_version = hciops_read_local_version, + .read_local_features = hciops_read_local_features, + .disconnect = hciops_disconnect, + .remove_bonding = hciops_remove_bonding, + .pincode_reply = hciops_pincode_reply, + .confirm_reply = hciops_confirm_reply, + .passkey_reply = hciops_passkey_reply, + .enable_le = hciops_enable_le, + .encrypt_link = hciops_encrypt_link, + .set_did = hciops_set_did, + .add_uuid = hciops_add_uuid, + .remove_uuid = hciops_remove_uuid, + .disable_cod_cache = hciops_disable_cod_cache, + .restore_powered = hciops_restore_powered, + .load_keys = hciops_load_keys, + .set_io_capability = hciops_set_io_capability, + .create_bonding = hciops_create_bonding, + .cancel_bonding = hciops_cancel_bonding, + .read_local_oob_data = hciops_read_local_oob_data, + .add_remote_oob_data = hciops_add_remote_oob_data, + .remove_remote_oob_data = hciops_remove_remote_oob_data, +}; + +static int hciops_init(void) +{ + DBG(""); + return btd_register_adapter_ops(&hci_ops, FALSE); +} + +static void hciops_exit(void) +{ + DBG(""); + btd_adapter_cleanup_ops(&hci_ops); +} + +BLUETOOTH_PLUGIN_DEFINE(hciops, VERSION, + BLUETOOTH_PLUGIN_PRIORITY_LOW, hciops_init, hciops_exit) diff --git a/plugins/maemo6.c b/plugins/maemo6.c new file mode 100644 index 0000000..56f2664 --- /dev/null +++ b/plugins/maemo6.c @@ -0,0 +1,252 @@ +/* + * + * BlueZ - Bluetooth protocol stack for Linux + * + * Copyright (C) 2006-2010 Nokia Corporation + * Copyright (C) 2004-2010 Marcel Holtmann <marcel@holtmann.org> + * + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + * + */ + +#ifdef HAVE_CONFIG_H +#include <config.h> +#endif + +#include <glib.h> +#include <dbus/dbus.h> + +#include "adapter.h" +#include "plugin.h" +#include "log.h" +#include "gdbus.h" + +/* from mce/mode-names.h */ +#define MCE_RADIO_STATE_BLUETOOTH (1 << 3) + +/* from mce/dbus-names.h */ +#define MCE_SERVICE "com.nokia.mce" +#define MCE_REQUEST_IF "com.nokia.mce.request" +#define MCE_SIGNAL_IF "com.nokia.mce.signal" +#define MCE_REQUEST_PATH "/com/nokia/mce/request" +#define MCE_SIGNAL_PATH "/com/nokia/mce/signal" +#define MCE_RADIO_STATES_CHANGE_REQ "req_radio_states_change" +#define MCE_RADIO_STATES_GET "get_radio_states" +#define MCE_RADIO_STATES_SIG "radio_states_ind" + +static guint watch_id; +static DBusConnection *conn = NULL; +static gboolean mce_bt_set = FALSE; +static gboolean collision = FALSE; + +static gboolean mce_signal_callback(DBusConnection *connection, + DBusMessage *message, void *user_data) +{ + DBusMessageIter args; + uint32_t sigvalue; + struct btd_adapter *adapter = user_data; + + DBG("received mce signal"); + + if (!dbus_message_iter_init(message, &args)) + error("message has no arguments"); + else if (DBUS_TYPE_UINT32 != dbus_message_iter_get_arg_type(&args)) + error("argument is not uint32"); + else { + dbus_message_iter_get_basic(&args, &sigvalue); + DBG("got signal with value %u", sigvalue); + + /* set the adapter according to the mce signal + and remember the value */ + mce_bt_set = sigvalue & MCE_RADIO_STATE_BLUETOOTH ? + TRUE : FALSE; + + if (mce_bt_set) + btd_adapter_switch_online(adapter); + else + btd_adapter_switch_offline(adapter); + } + + return TRUE; +} + +static void read_radio_states_cb(DBusPendingCall *call, void *user_data) +{ + DBusError err; + DBusMessage *reply; + dbus_uint32_t radio_states; + struct btd_adapter *adapter = user_data; + + reply = dbus_pending_call_steal_reply(call); + + dbus_error_init(&err); + if (dbus_set_error_from_message(&err, reply)) { + error("mce replied with an error: %s, %s", + err.name, err.message); + dbus_error_free(&err); + goto done; + } + + dbus_error_init(&err); + if (dbus_message_get_args(reply, &err, + DBUS_TYPE_UINT32, &radio_states, + DBUS_TYPE_INVALID) == FALSE) { + error("unable to parse get_radio_states reply: %s, %s", + err.name, err.message); + dbus_error_free(&err); + goto done; + } + + DBG("radio_states: %d", radio_states); + + mce_bt_set = radio_states & MCE_RADIO_STATE_BLUETOOTH ? TRUE : FALSE; + + /* check if the adapter has not completed the initial power + * cycle, if so delay action to mce_notify_powered */ + collision = mce_bt_set && adapter_powering_down(adapter); + + if (collision) + goto done; + + if (mce_bt_set) + btd_adapter_switch_online(adapter); + else + btd_adapter_switch_offline(adapter); + +done: + dbus_message_unref(reply); +} + +static void adapter_powered(struct btd_adapter *adapter, gboolean powered) +{ + DBusMessage *msg; + dbus_uint32_t radio_states = 0; + dbus_uint32_t radio_mask = MCE_RADIO_STATE_BLUETOOTH; + static gboolean startup = TRUE; + + DBG("adapter_powered called with %d", powered); + + if (startup) { + startup = FALSE; + return; + } + + /* check if the plugin got the get_radio_states reply from the + * mce when the adapter was not yet down during the power + * cycling when bluetoothd is started */ + if (collision) { + error("maemo6: powered state collision"); + collision = FALSE; + + if (mce_bt_set) + btd_adapter_switch_online(adapter); + + return; + } + + /* nothing to do if the states match */ + if (mce_bt_set == powered) + return; + + /* set the mce value according to the state of the adapter */ + msg = dbus_message_new_method_call(MCE_SERVICE, MCE_REQUEST_PATH, + MCE_REQUEST_IF, MCE_RADIO_STATES_CHANGE_REQ); + + if (powered) + radio_states = MCE_RADIO_STATE_BLUETOOTH; + + dbus_message_append_args(msg, DBUS_TYPE_UINT32, &radio_states, + DBUS_TYPE_UINT32, &radio_mask, + DBUS_TYPE_INVALID); + + if (dbus_connection_send(conn, msg, NULL)) + mce_bt_set = powered; + else + error("calling %s failed", MCE_RADIO_STATES_CHANGE_REQ); + + dbus_message_unref(msg); +} + +static int mce_probe(struct btd_adapter *adapter) +{ + DBusMessage *msg; + DBusPendingCall *call; + + DBG("path %s", adapter_get_path(adapter)); + + msg = dbus_message_new_method_call(MCE_SERVICE, MCE_REQUEST_PATH, + MCE_REQUEST_IF, MCE_RADIO_STATES_GET); + + if (!dbus_connection_send_with_reply(conn, msg, &call, -1)) { + error("calling %s failed", MCE_RADIO_STATES_GET); + dbus_message_unref(msg); + return -1; + } + + dbus_pending_call_set_notify(call, read_radio_states_cb, adapter, NULL); + dbus_pending_call_unref(call); + dbus_message_unref(msg); + + watch_id = g_dbus_add_signal_watch(conn, NULL, MCE_SIGNAL_PATH, + MCE_SIGNAL_IF, MCE_RADIO_STATES_SIG, + mce_signal_callback, adapter, NULL); + + btd_adapter_register_powered_callback(adapter, adapter_powered); + + return 0; +} + +static void mce_remove(struct btd_adapter *adapter) +{ + DBG("path %s", adapter_get_path(adapter)); + + if (watch_id > 0) + g_dbus_remove_watch(conn, watch_id); + + btd_adapter_unregister_powered_callback(adapter, adapter_powered); +} + +static struct btd_adapter_driver mce_driver = { + .name = "mce", + .probe = mce_probe, + .remove = mce_remove, +}; + +static int maemo6_init(void) +{ + DBG("init maemo6 plugin"); + + conn = dbus_bus_get(DBUS_BUS_SYSTEM, NULL); + if (conn == NULL) { + error("Unable to connect to D-Bus"); + return -1; + } + + return btd_register_adapter_driver(&mce_driver); +} + +static void maemo6_exit(void) +{ + DBG("exit maemo6 plugin"); + + if (conn != NULL) + dbus_connection_unref(conn); + + btd_unregister_adapter_driver(&mce_driver); +} + +BLUETOOTH_PLUGIN_DEFINE(maemo6, VERSION, + BLUETOOTH_PLUGIN_PRIORITY_DEFAULT, maemo6_init, maemo6_exit) diff --git a/plugins/mgmtops.c b/plugins/mgmtops.c new file mode 100644 index 0000000..65b32e6 --- /dev/null +++ b/plugins/mgmtops.c @@ -0,0 +1,1937 @@ +/* + * + * BlueZ - Bluetooth protocol stack for Linux + * + * Copyright (C) 2010 Nokia Corporation + * Copyright (C) 2010 Marcel Holtmann <marcel@holtmann.org> + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + * + */ + +#ifdef HAVE_CONFIG_H +#include <config.h> +#endif + +#include <stdio.h> +#include <errno.h> +#include <unistd.h> +#include <stdlib.h> +#include <sys/types.h> +#include <sys/ioctl.h> +#include <sys/wait.h> + +#include <glib.h> + +#include <bluetooth/bluetooth.h> +#include <bluetooth/hci.h> +#include <bluetooth/sdp.h> +#include <bluetooth/sdp_lib.h> +#include <bluetooth/mgmt.h> + +#include "plugin.h" +#include "log.h" +#include "adapter.h" +#include "manager.h" +#include "device.h" +#include "event.h" +#include "oob.h" + +#define MGMT_BUF_SIZE 1024 + +static int max_index = -1; +static struct controller_info { + gboolean valid; + gboolean notified; + uint8_t type; + bdaddr_t bdaddr; + uint8_t features[8]; + uint8_t dev_class[3]; + uint16_t manufacturer; + uint8_t hci_ver; + uint16_t hci_rev; + gboolean enabled; + gboolean connectable; + gboolean discoverable; + gboolean pairable; + uint8_t sec_mode; + GSList *connections; +} *controllers = NULL; + +static int mgmt_sock = -1; +static guint mgmt_watch = 0; + +static uint8_t mgmt_version = 0; +static uint16_t mgmt_revision = 0; + +static void read_version_complete(int sk, void *buf, size_t len) +{ + struct mgmt_hdr hdr; + struct mgmt_rp_read_version *rp = buf; + + if (len < sizeof(*rp)) { + error("Too small read version complete event"); + return; + } + + mgmt_revision = btohs(bt_get_unaligned(&rp->revision)); + mgmt_version = rp->version; + + DBG("version %u revision %u", mgmt_version, mgmt_revision); + + memset(&hdr, 0, sizeof(hdr)); + hdr.opcode = htobs(MGMT_OP_READ_INDEX_LIST); + hdr.index = htobs(MGMT_INDEX_NONE); + if (write(sk, &hdr, sizeof(hdr)) < 0) + error("Unable to read controller index list: %s (%d)", + strerror(errno), errno); +} + +static void add_controller(uint16_t index) +{ + if (index > max_index) { + size_t size = sizeof(struct controller_info) * (index + 1); + max_index = index; + controllers = g_realloc(controllers, size); + } + + memset(&controllers[index], 0, sizeof(struct controller_info)); + + controllers[index].valid = TRUE; + + DBG("Added controller %u", index); +} + +static void read_info(int sk, uint16_t index) +{ + struct mgmt_hdr hdr; + + memset(&hdr, 0, sizeof(hdr)); + hdr.opcode = htobs(MGMT_OP_READ_INFO); + hdr.index = htobs(index); + + if (write(sk, &hdr, sizeof(hdr)) < 0) + error("Unable to send read_info command: %s (%d)", + strerror(errno), errno); +} + +static void get_connections(int sk, uint16_t index) +{ + struct mgmt_hdr hdr; + + memset(&hdr, 0, sizeof(hdr)); + hdr.opcode = htobs(MGMT_OP_GET_CONNECTIONS); + hdr.index = htobs(index); + + if (write(sk, &hdr, sizeof(hdr)) < 0) + error("Unable to send get_connections command: %s (%d)", + strerror(errno), errno); +} + +static void mgmt_index_added(int sk, uint16_t index) +{ + add_controller(index); + read_info(sk, index); +} + +static void remove_controller(uint16_t index) +{ + if (index > max_index) + return; + + if (!controllers[index].valid) + return; + + btd_manager_unregister_adapter(index); + + memset(&controllers[index], 0, sizeof(struct controller_info)); + + DBG("Removed controller %u", index); +} + +static void mgmt_index_removed(int sk, uint16_t index) +{ + remove_controller(index); +} + +static int mgmt_set_mode(int index, uint16_t opcode, uint8_t val) +{ + char buf[MGMT_HDR_SIZE + sizeof(struct mgmt_mode)]; + struct mgmt_hdr *hdr = (void *) buf; + struct mgmt_mode *cp = (void *) &buf[sizeof(*hdr)]; + + memset(buf, 0, sizeof(buf)); + hdr->opcode = htobs(opcode); + hdr->index = htobs(index); + hdr->len = htobs(sizeof(*cp)); + + cp->val = val; + + if (write(mgmt_sock, buf, sizeof(buf)) < 0) + return -errno; + + return 0; +} + +static int mgmt_set_connectable(int index, gboolean connectable) +{ + DBG("index %d connectable %d", index, connectable); + return mgmt_set_mode(index, MGMT_OP_SET_CONNECTABLE, connectable); +} + +static int mgmt_set_discoverable(int index, gboolean discoverable) +{ + DBG("index %d discoverable %d", index, discoverable); + return mgmt_set_mode(index, MGMT_OP_SET_DISCOVERABLE, discoverable); +} + +static int mgmt_set_pairable(int index, gboolean pairable) +{ + DBG("index %d pairable %d", index, pairable); + return mgmt_set_mode(index, MGMT_OP_SET_PAIRABLE, pairable); +} + +static int mgmt_update_powered(int index, uint8_t powered) +{ + struct controller_info *info; + struct btd_adapter *adapter; + gboolean pairable, discoverable; + uint8_t on_mode; + + if (index > max_index) { + error("Unexpected index %u", index); + return -ENODEV; + } + + info = &controllers[index]; + + info->enabled = powered; + + adapter = manager_find_adapter(&info->bdaddr); + if (adapter == NULL) { + DBG("Adapter not found"); + return -ENODEV; + } + + if (!powered) { + info->connectable = FALSE; + info->pairable = FALSE; + info->discoverable = FALSE; + + btd_adapter_stop(adapter); + return 0; + } + + btd_adapter_start(adapter); + + btd_adapter_get_mode(adapter, NULL, &on_mode, &pairable); + + discoverable = (on_mode == MODE_DISCOVERABLE); + + if (on_mode == MODE_DISCOVERABLE && !info->discoverable) + mgmt_set_discoverable(index, TRUE); + else if (on_mode == MODE_CONNECTABLE && !info->connectable) + mgmt_set_connectable(index, TRUE); + else { + uint8_t mode = 0; + + if (info->connectable) + mode |= SCAN_PAGE; + if (info->discoverable) + mode |= SCAN_INQUIRY; + + adapter_mode_changed(adapter, mode); + } + + if (info->pairable != pairable) + mgmt_set_pairable(index, pairable); + + return 0; +} + +static void mgmt_powered(int sk, uint16_t index, void *buf, size_t len) +{ + struct mgmt_mode *ev = buf; + + if (len < sizeof(*ev)) { + error("Too small powered event"); + return; + } + + DBG("Controller %u powered %u", index, ev->val); + + mgmt_update_powered(index, ev->val); +} + +static void mgmt_discoverable(int sk, uint16_t index, void *buf, size_t len) +{ + struct mgmt_mode *ev = buf; + struct controller_info *info; + struct btd_adapter *adapter; + uint8_t mode; + + if (len < sizeof(*ev)) { + error("Too small discoverable event"); + return; + } + + DBG("Controller %u discoverable %u", index, ev->val); + + if (index > max_index) { + error("Unexpected index %u in discoverable event", index); + return; + } + + info = &controllers[index]; + + info->discoverable = ev->val ? TRUE : FALSE; + + adapter = manager_find_adapter(&info->bdaddr); + if (!adapter) + return; + + if (info->connectable) + mode = SCAN_PAGE; + else + mode = 0; + + if (info->discoverable) + mode |= SCAN_INQUIRY; + + adapter_mode_changed(adapter, mode); +} + +static void mgmt_connectable(int sk, uint16_t index, void *buf, size_t len) +{ + struct mgmt_mode *ev = buf; + struct controller_info *info; + struct btd_adapter *adapter; + uint8_t mode; + + if (len < sizeof(*ev)) { + error("Too small connectable event"); + return; + } + + DBG("Controller %u connectable %u", index, ev->val); + + if (index > max_index) { + error("Unexpected index %u in connectable event", index); + return; + } + + info = &controllers[index]; + + info->connectable = ev->val ? TRUE : FALSE; + + adapter = manager_find_adapter(&info->bdaddr); + if (!adapter) + return; + + if (info->discoverable) + mode = SCAN_INQUIRY; + else + mode = 0; + + if (info->connectable) + mode |= SCAN_PAGE; + + adapter_mode_changed(adapter, mode); +} + +static void mgmt_pairable(int sk, uint16_t index, void *buf, size_t len) +{ + struct mgmt_mode *ev = buf; + struct controller_info *info; + struct btd_adapter *adapter; + + if (len < sizeof(*ev)) { + error("Too small pairable event"); + return; + } + + DBG("Controller %u pairable %u", index, ev->val); + + if (index > max_index) { + error("Unexpected index %u in pairable event", index); + return; + } + + info = &controllers[index]; + + info->pairable = ev->val ? TRUE : FALSE; + + adapter = manager_find_adapter(&info->bdaddr); + if (!adapter) + return; + + btd_adapter_pairable_changed(adapter, info->pairable); +} + +static void mgmt_new_key(int sk, uint16_t index, void *buf, size_t len) +{ + struct mgmt_ev_new_key *ev = buf; + struct controller_info *info; + + if (len != sizeof(*ev)) { + error("new_key event size mismatch (%zu != %zu)", + len, sizeof(*ev)); + return; + } + + DBG("Controller %u new key of type %u pin_len %u", index, + ev->key.type, ev->key.pin_len); + + if (index > max_index) { + error("Unexpected index %u in new_key event", index); + return; + } + + if (ev->key.pin_len > 16) { + error("Invalid PIN length (%u) in new_key event", + ev->key.pin_len); + return; + } + + info = &controllers[index]; + + btd_event_link_key_notify(&info->bdaddr, &ev->key.bdaddr, + ev->key.val, ev->key.type, + ev->key.pin_len); + + btd_event_bonding_complete(&info->bdaddr, &ev->key.bdaddr, 0); +} + +static void mgmt_device_connected(int sk, uint16_t index, void *buf, size_t len) +{ + struct mgmt_ev_device_connected *ev = buf; + struct controller_info *info; + char addr[18]; + + if (len < sizeof(*ev)) { + error("Too small device_connected event"); + return; + } + + ba2str(&ev->bdaddr, addr); + + DBG("hci%u device %s connected", index, addr); + + if (index > max_index) { + error("Unexpected index %u in device_connected event", index); + return; + } + + info = &controllers[index]; + + btd_event_conn_complete(&info->bdaddr, &ev->bdaddr); +} + +static void mgmt_device_disconnected(int sk, uint16_t index, void *buf, + size_t len) +{ + struct mgmt_ev_device_disconnected *ev = buf; + struct controller_info *info; + char addr[18]; + + if (len < sizeof(*ev)) { + error("Too small device_disconnected event"); + return; + } + + ba2str(&ev->bdaddr, addr); + + DBG("hci%u device %s disconnected", index, addr); + + if (index > max_index) { + error("Unexpected index %u in device_disconnected event", index); + return; + } + + info = &controllers[index]; + + btd_event_disconn_complete(&info->bdaddr, &ev->bdaddr); +} + +static void mgmt_connect_failed(int sk, uint16_t index, void *buf, size_t len) +{ + struct mgmt_ev_connect_failed *ev = buf; + struct controller_info *info; + char addr[18]; + + if (len < sizeof(*ev)) { + error("Too small connect_failed event"); + return; + } + + ba2str(&ev->bdaddr, addr); + + DBG("hci%u %s status %u", index, addr, ev->status); + + if (index > max_index) { + error("Unexpected index %u in connect_failed event", index); + return; + } + + info = &controllers[index]; + + btd_event_conn_failed(&info->bdaddr, &ev->bdaddr, ev->status); + + /* In the case of security mode 3 devices */ + btd_event_bonding_complete(&info->bdaddr, &ev->bdaddr, ev->status); +} + +static int mgmt_pincode_reply(int index, bdaddr_t *bdaddr, const char *pin) +{ + char buf[MGMT_HDR_SIZE + sizeof(struct mgmt_cp_pin_code_reply)]; + struct mgmt_hdr *hdr = (void *) buf; + size_t buf_len; + char addr[18]; + + ba2str(bdaddr, addr); + DBG("index %d addr %s pin %s", index, addr, pin ? pin : "<none>"); + + memset(buf, 0, sizeof(buf)); + + if (pin == NULL) { + struct mgmt_cp_pin_code_neg_reply *cp; + + hdr->opcode = htobs(MGMT_OP_PIN_CODE_NEG_REPLY); + hdr->len = htobs(sizeof(*cp)); + hdr->index = htobs(index); + + cp = (void *) &buf[sizeof(*hdr)]; + bacpy(&cp->bdaddr, bdaddr); + + buf_len = sizeof(*hdr) + sizeof(*cp); + } else { + struct mgmt_cp_pin_code_reply *cp; + size_t pin_len; + + pin_len = strlen(pin); + if (pin_len > 16) + return -EINVAL; + + hdr->opcode = htobs(MGMT_OP_PIN_CODE_REPLY); + hdr->len = htobs(sizeof(*cp)); + hdr->index = htobs(index); + + cp = (void *) &buf[sizeof(*hdr)]; + bacpy(&cp->bdaddr, bdaddr); + cp->pin_len = pin_len; + memcpy(cp->pin_code, pin, pin_len); + + buf_len = sizeof(*hdr) + sizeof(*cp); + } + + if (write(mgmt_sock, buf, buf_len) < 0) + return -errno; + + return 0; +} + +static void mgmt_pin_code_request(int sk, uint16_t index, void *buf, size_t len) +{ + struct mgmt_ev_pin_code_request *ev = buf; + struct controller_info *info; + char addr[18]; + int err; + + if (len < sizeof(*ev)) { + error("Too small pin_code_request event"); + return; + } + + ba2str(&ev->bdaddr, addr); + + DBG("hci%u %s", index, addr); + + if (index > max_index) { + error("Unexpected index %u in pin_code_request event", index); + return; + } + + info = &controllers[index]; + + err = btd_event_request_pin(&info->bdaddr, &ev->bdaddr); + if (err < 0) { + error("btd_event_request_pin: %s", strerror(-err)); + mgmt_pincode_reply(index, &ev->bdaddr, NULL); + } +} + +static int mgmt_confirm_reply(int index, bdaddr_t *bdaddr, gboolean success) +{ + char buf[MGMT_HDR_SIZE + sizeof(struct mgmt_cp_user_confirm_reply)]; + struct mgmt_hdr *hdr = (void *) buf; + struct mgmt_cp_user_confirm_reply *cp; + char addr[18]; + + ba2str(bdaddr, addr); + DBG("index %d addr %s success %d", index, addr, success); + + memset(buf, 0, sizeof(buf)); + + if (success) + hdr->opcode = htobs(MGMT_OP_USER_CONFIRM_REPLY); + else + hdr->opcode = htobs(MGMT_OP_USER_CONFIRM_NEG_REPLY); + + hdr->len = htobs(sizeof(*cp)); + hdr->index = htobs(index); + + cp = (void *) &buf[sizeof(*hdr)]; + bacpy(&cp->bdaddr, bdaddr); + + if (write(mgmt_sock, buf, sizeof(buf)) < 0) + return -errno; + + return 0; +} + +static void mgmt_user_confirm_request(int sk, uint16_t index, void *buf, + size_t len) +{ + struct mgmt_ev_user_confirm_request *ev = buf; + struct controller_info *info; + char addr[18]; + int err; + + if (len < sizeof(*ev)) { + error("Too small user_confirm_request event"); + return; + } + + ba2str(&ev->bdaddr, addr); + + DBG("hci%u %s", index, addr); + + if (index > max_index) { + error("Unexpected index %u in user_confirm_request event", + index); + return; + } + + info = &controllers[index]; + + err = btd_event_user_confirm(&info->bdaddr, &ev->bdaddr, + btohl(ev->value)); + if (err < 0) { + error("btd_event_user_confirm: %s", strerror(-err)); + mgmt_confirm_reply(index, &ev->bdaddr, FALSE); + } +} + +static void uuid_to_uuid128(uuid_t *uuid128, const uuid_t *uuid) +{ + if (uuid->type == SDP_UUID16) + sdp_uuid16_to_uuid128(uuid128, uuid); + else if (uuid->type == SDP_UUID32) + sdp_uuid32_to_uuid128(uuid128, uuid); + else + memcpy(uuid128, uuid, sizeof(*uuid)); +} + +static int mgmt_add_uuid(int index, uuid_t *uuid, uint8_t svc_hint) +{ + char buf[MGMT_HDR_SIZE + sizeof(struct mgmt_cp_add_uuid)]; + struct mgmt_hdr *hdr = (void *) buf; + struct mgmt_cp_add_uuid *cp = (void *) &buf[sizeof(*hdr)]; + uuid_t uuid128; + uint128_t uint128; + + DBG("index %d", index); + + uuid_to_uuid128(&uuid128, uuid); + + memset(buf, 0, sizeof(buf)); + hdr->opcode = htobs(MGMT_OP_ADD_UUID); + hdr->len = htobs(sizeof(*cp)); + hdr->index = htobs(index); + + ntoh128((uint128_t *) uuid128.value.uuid128.data, &uint128); + htob128(&uint128, (uint128_t *) cp->uuid); + + cp->svc_hint = svc_hint; + + if (write(mgmt_sock, buf, sizeof(buf)) < 0) + return -errno; + + return 0; +} + +static int mgmt_remove_uuid(int index, uuid_t *uuid) +{ + char buf[MGMT_HDR_SIZE + sizeof(struct mgmt_cp_remove_uuid)]; + struct mgmt_hdr *hdr = (void *) buf; + struct mgmt_cp_remove_uuid *cp = (void *) &buf[sizeof(*hdr)]; + uuid_t uuid128; + uint128_t uint128; + + DBG("index %d", index); + + uuid_to_uuid128(&uuid128, uuid); + + memset(buf, 0, sizeof(buf)); + hdr->opcode = htobs(MGMT_OP_REMOVE_UUID); + hdr->len = htobs(sizeof(*cp)); + hdr->index = htobs(index); + + ntoh128((uint128_t *) uuid128.value.uuid128.data, &uint128); + htob128(&uint128, (uint128_t *) cp->uuid); + + if (write(mgmt_sock, buf, sizeof(buf)) < 0) + return -errno; + + return 0; +} + +static int clear_uuids(int index) +{ + uuid_t uuid_any; + + memset(&uuid_any, 0, sizeof(uuid_any)); + uuid_any.type = SDP_UUID128; + + return mgmt_remove_uuid(index, &uuid_any); +} + +static void read_index_list_complete(int sk, void *buf, size_t len) +{ + struct mgmt_rp_read_index_list *rp = buf; + uint16_t num; + int i; + + if (len < sizeof(*rp)) { + error("Too small read index list complete event"); + return; + } + + num = btohs(bt_get_unaligned(&rp->num_controllers)); + + if (num * sizeof(uint16_t) + sizeof(*rp) != len) { + error("Incorrect packet size for index list event"); + return; + } + + for (i = 0; i < num; i++) { + uint16_t index; + + index = btohs(bt_get_unaligned(&rp->index[i])); + + add_controller(index); + get_connections(sk, index); + clear_uuids(index); + } +} + +static int mgmt_set_powered(int index, gboolean powered) +{ + DBG("index %d powered %d", index, powered); + return mgmt_set_mode(index, MGMT_OP_SET_POWERED, powered); +} + +static void read_info_complete(int sk, uint16_t index, void *buf, size_t len) +{ + struct mgmt_rp_read_info *rp = buf; + struct controller_info *info; + struct btd_adapter *adapter; + uint8_t mode; + char addr[18]; + + if (len < sizeof(*rp)) { + error("Too small read info complete event"); + return; + } + + if (index > max_index) { + error("Unexpected index %u in read info complete", index); + return; + } + + mgmt_set_mode(index, MGMT_OP_SET_SERVICE_CACHE, 1); + + info = &controllers[index]; + info->type = rp->type; + info->enabled = rp->powered; + info->connectable = rp->connectable; + info->discoverable = rp->discoverable; + info->pairable = rp->pairable; + info->sec_mode = rp->sec_mode; + bacpy(&info->bdaddr, &rp->bdaddr); + memcpy(info->dev_class, rp->dev_class, 3); + memcpy(info->features, rp->features, 8); + info->manufacturer = btohs(bt_get_unaligned(&rp->manufacturer)); + info->hci_ver = rp->hci_ver; + info->hci_rev = btohs(bt_get_unaligned(&rp->hci_rev)); + + ba2str(&info->bdaddr, addr); + DBG("hci%u type %u addr %s", index, info->type, addr); + DBG("hci%u class 0x%02x%02x%02x", index, + info->dev_class[2], info->dev_class[1], info->dev_class[0]); + DBG("hci%u manufacturer %d HCI ver %d:%d", index, info->manufacturer, + info->hci_ver, info->hci_rev); + DBG("hci%u enabled %u discoverable %u pairable %u sec_mode %u", index, + info->enabled, info->discoverable, + info->pairable, info->sec_mode); + DBG("hci%u name %s", index, (char *) rp->name); + + adapter = btd_manager_register_adapter(index); + if (adapter == NULL) { + error("mgmtops: unable to register adapter"); + return; + } + + btd_adapter_get_mode(adapter, &mode, NULL, NULL); + if (mode == MODE_OFF) { + mgmt_set_powered(index, FALSE); + return; + } + + if (info->enabled) + mgmt_update_powered(index, TRUE); + else + mgmt_set_powered(index, TRUE); + + adapter_update_local_name(adapter, (char *) rp->name); + + btd_adapter_unref(adapter); +} + +static void set_powered_complete(int sk, uint16_t index, void *buf, size_t len) +{ + struct mgmt_mode *rp = buf; + + if (len < sizeof(*rp)) { + error("Too small set powered complete event"); + return; + } + + DBG("hci%d powered %u", index, rp->val); + + mgmt_update_powered(index, rp->val); +} + +static void set_discoverable_complete(int sk, uint16_t index, void *buf, + size_t len) +{ + struct mgmt_mode *rp = buf; + struct controller_info *info; + struct btd_adapter *adapter; + uint8_t mode; + + if (len < sizeof(*rp)) { + error("Too small set discoverable complete event"); + return; + } + + DBG("hci%d discoverable %u", index, rp->val); + + if (index > max_index) { + error("Unexpected index %u in discoverable complete", index); + return; + } + + info = &controllers[index]; + + info->discoverable = rp->val ? TRUE : FALSE; + + adapter = manager_find_adapter(&info->bdaddr); + if (!adapter) + return; + + /* set_discoverable will always also change page scanning */ + mode = SCAN_PAGE; + + if (info->discoverable) + mode |= SCAN_INQUIRY; + + adapter_mode_changed(adapter, mode); +} + +static void set_connectable_complete(int sk, uint16_t index, void *buf, + size_t len) +{ + struct mgmt_mode *rp = buf; + struct controller_info *info; + struct btd_adapter *adapter; + + if (len < sizeof(*rp)) { + error("Too small set connectable complete event"); + return; + } + + DBG("hci%d connectable %u", index, rp->val); + + if (index > max_index) { + error("Unexpected index %u in connectable complete", index); + return; + } + + info = &controllers[index]; + + info->connectable = rp->val ? TRUE : FALSE; + + adapter = manager_find_adapter(&info->bdaddr); + if (adapter) + adapter_mode_changed(adapter, rp->val ? SCAN_PAGE : 0); +} + +static void set_pairable_complete(int sk, uint16_t index, void *buf, + size_t len) +{ + struct mgmt_mode *rp = buf; + struct controller_info *info; + struct btd_adapter *adapter; + + if (len < sizeof(*rp)) { + error("Too small set pairable complete event"); + return; + } + + DBG("hci%d pairable %u", index, rp->val); + + if (index > max_index) { + error("Unexpected index %u in pairable complete", index); + return; + } + + info = &controllers[index]; + + info->pairable = rp->val ? TRUE : FALSE; + + adapter = manager_find_adapter(&info->bdaddr); + if (!adapter) + return; + + btd_adapter_pairable_changed(adapter, info->pairable); +} + +static void disconnect_complete(int sk, uint16_t index, void *buf, size_t len) +{ + struct mgmt_rp_disconnect *rp = buf; + struct controller_info *info; + char addr[18]; + + if (len < sizeof(*rp)) { + error("Too small disconnect complete event"); + return; + } + + ba2str(&rp->bdaddr, addr); + + DBG("hci%d %s disconnected", index, addr); + + if (index > max_index) { + error("Unexpected index %u in disconnect complete", index); + return; + } + + info = &controllers[index]; + + btd_event_disconn_complete(&info->bdaddr, &rp->bdaddr); + + btd_event_bonding_complete(&info->bdaddr, &rp->bdaddr, + HCI_CONNECTION_TERMINATED); +} + +static void pair_device_complete(int sk, uint16_t index, void *buf, size_t len) +{ + struct mgmt_rp_pair_device *rp = buf; + struct controller_info *info; + char addr[18]; + + if (len < sizeof(*rp)) { + error("Too small pair_device complete event"); + return; + } + + ba2str(&rp->bdaddr, addr); + + DBG("hci%d %s pairing complete status %u", index, addr, rp->status); + + if (index > max_index) { + error("Unexpected index %u in pair_device complete", index); + return; + } + + info = &controllers[index]; + + btd_event_bonding_complete(&info->bdaddr, &rp->bdaddr, rp->status); +} + +static void get_connections_complete(int sk, uint16_t index, void *buf, + size_t len) +{ + struct mgmt_rp_get_connections *rp = buf; + struct controller_info *info; + int i; + + if (len < sizeof(*rp)) { + error("Too small get_connections complete event"); + return; + } + + if (len < (sizeof(*rp) + (rp->conn_count * sizeof(bdaddr_t)))) { + error("Too small get_connections complete event"); + return; + } + + if (index > max_index) { + error("Unexpected index %u in get_connections complete", + index); + return; + } + + info = &controllers[index]; + + for (i = 0; i < rp->conn_count; i++) { + bdaddr_t *bdaddr = g_memdup(&rp->conn[i], sizeof(bdaddr_t)); + info->connections = g_slist_append(info->connections, bdaddr); + } + + read_info(sk, index); +} + +static void set_local_name_complete(int sk, uint16_t index, void *buf, + size_t len) +{ + struct mgmt_cp_set_local_name *rp = buf; + struct controller_info *info; + struct btd_adapter *adapter; + + if (len < sizeof(*rp)) { + error("Too small set_local_name complete event"); + return; + } + + DBG("hci%d name %s", index, (char *) rp->name); + + if (index > max_index) { + error("Unexpected index %u in set_local_name complete", index); + return; + } + + info = &controllers[index]; + + adapter = manager_find_adapter(&info->bdaddr); + if (adapter == NULL) { + DBG("Adapter not found"); + return; + } + + adapter_update_local_name(adapter, (char *) rp->name); +} + +static void read_local_oob_data_complete(int sk, uint16_t index, void *buf, + size_t len) +{ + struct mgmt_rp_read_local_oob_data *rp = buf; + struct btd_adapter *adapter; + + if (len != sizeof(*rp)) { + error("Wrong read_local_oob_data_complete event size"); + return; + } + + if (index > max_index) { + error("Unexpected index %u in read_local_oob_data_complete", + index); + return; + } + + DBG("hci%u", index); + + adapter = manager_find_adapter_by_id(index); + + if (adapter) + oob_read_local_data_complete(adapter, rp->hash, rp->randomizer); +} + +static void read_local_oob_data_failed(int sk, uint16_t index) +{ + struct btd_adapter *adapter; + + if (index > max_index) { + error("Unexpected index %u in read_local_oob_data_failed", + index); + return; + } + + DBG("hci%u", index); + + adapter = manager_find_adapter_by_id(index); + + if (adapter) + oob_read_local_data_complete(adapter, NULL, NULL); +} + +static void mgmt_cmd_complete(int sk, uint16_t index, void *buf, size_t len) +{ + struct mgmt_ev_cmd_complete *ev = buf; + uint16_t opcode; + + DBG(""); + + if (len < sizeof(*ev)) { + error("Too small management command complete event packet"); + return; + } + + opcode = btohs(bt_get_unaligned(&ev->opcode)); + + len -= sizeof(*ev); + + switch (opcode) { + case MGMT_OP_READ_VERSION: + read_version_complete(sk, ev->data, len); + break; + case MGMT_OP_READ_INDEX_LIST: + read_index_list_complete(sk, ev->data, len); + break; + case MGMT_OP_READ_INFO: + read_info_complete(sk, index, ev->data, len); + break; + case MGMT_OP_SET_POWERED: + set_powered_complete(sk, index, ev->data, len); + break; + case MGMT_OP_SET_DISCOVERABLE: + set_discoverable_complete(sk, index, ev->data, len); + break; + case MGMT_OP_SET_CONNECTABLE: + set_connectable_complete(sk, index, ev->data, len); + break; + case MGMT_OP_SET_PAIRABLE: + set_pairable_complete(sk, index, ev->data, len); + break; + case MGMT_OP_ADD_UUID: + DBG("add_uuid complete"); + break; + case MGMT_OP_REMOVE_UUID: + DBG("remove_uuid complete"); + break; + case MGMT_OP_SET_DEV_CLASS: + DBG("set_dev_class complete"); + break; + case MGMT_OP_SET_SERVICE_CACHE: + DBG("set_service_cache complete"); + break; + case MGMT_OP_LOAD_KEYS: + DBG("load_keys complete"); + break; + case MGMT_OP_REMOVE_KEY: + DBG("remove_key complete"); + break; + case MGMT_OP_DISCONNECT: + DBG("disconnect complete"); + disconnect_complete(sk, index, ev->data, len); + break; + case MGMT_OP_GET_CONNECTIONS: + get_connections_complete(sk, index, ev->data, len); + break; + case MGMT_OP_PIN_CODE_REPLY: + DBG("pin_code_reply complete"); + break; + case MGMT_OP_PIN_CODE_NEG_REPLY: + DBG("pin_code_neg_reply complete"); + break; + case MGMT_OP_SET_IO_CAPABILITY: + DBG("set_io_capability complete"); + break; + case MGMT_OP_PAIR_DEVICE: + pair_device_complete(sk, index, ev->data, len); + break; + case MGMT_OP_USER_CONFIRM_REPLY: + DBG("user_confirm_reply complete"); + break; + case MGMT_OP_USER_CONFIRM_NEG_REPLY: + DBG("user_confirm_net_reply complete"); + break; + case MGMT_OP_SET_LOCAL_NAME: + set_local_name_complete(sk, index, ev->data, len); + break; + case MGMT_OP_READ_LOCAL_OOB_DATA: + read_local_oob_data_complete(sk, index, ev->data, len); + break; + case MGMT_OP_ADD_REMOTE_OOB_DATA: + DBG("add_remote_oob_data complete"); + break; + case MGMT_OP_REMOVE_REMOTE_OOB_DATA: + DBG("remove_remote_oob_data complete"); + break; + default: + error("Unknown command complete for opcode %u", opcode); + break; + } +} + +static void mgmt_cmd_status(int sk, uint16_t index, void *buf, size_t len) +{ + struct mgmt_ev_cmd_status *ev = buf; + uint16_t opcode; + + if (len < sizeof(*ev)) { + error("Too small management command status event packet"); + return; + } + + opcode = btohs(bt_get_unaligned(&ev->opcode)); + + DBG("status %u opcode %u (index %u)", ev->status, opcode, index); + + switch (opcode) { + case MGMT_OP_READ_LOCAL_OOB_DATA: + read_local_oob_data_failed(sk, index); + break; + } +} + +static void mgmt_controller_error(int sk, uint16_t index, void *buf, size_t len) +{ + struct mgmt_ev_controller_error *ev = buf; + + if (len < sizeof(*ev)) { + error("Too small management controller error event packet"); + return; + } + + DBG("index %u error_code %u", index, ev->error_code); +} + +static void mgmt_auth_failed(int sk, uint16_t index, void *buf, size_t len) +{ + struct controller_info *info; + struct mgmt_ev_auth_failed *ev = buf; + + if (len < sizeof(*ev)) { + error("Too small mgmt_auth_failed event packet"); + return; + } + + DBG("hci%u auth failed status %u", index, ev->status); + + if (index > max_index) { + error("Unexpected index %u in auth_failed event", index); + return; + } + + info = &controllers[index]; + + btd_event_bonding_complete(&info->bdaddr, &ev->bdaddr, ev->status); +} + +static void mgmt_local_name_changed(int sk, uint16_t index, void *buf, size_t len) +{ + struct mgmt_cp_set_local_name *ev = buf; + struct controller_info *info; + struct btd_adapter *adapter; + + if (len < sizeof(*ev)) { + error("Too small mgmt_local_name_changed event packet"); + return; + } + + DBG("hci%u local name changed: %s", index, (char *) ev->name); + + if (index > max_index) { + error("Unexpected index %u in name_changed event", index); + return; + } + + info = &controllers[index]; + + adapter = manager_find_adapter(&info->bdaddr); + if (adapter) + adapter_update_local_name(adapter, (char *) ev->name); +} + +static gboolean mgmt_event(GIOChannel *io, GIOCondition cond, gpointer user_data) +{ + char buf[MGMT_BUF_SIZE]; + struct mgmt_hdr *hdr = (void *) buf; + int sk; + ssize_t ret; + uint16_t len, opcode, index; + + DBG("cond %d", cond); + + if (cond & G_IO_NVAL) + return FALSE; + + sk = g_io_channel_unix_get_fd(io); + + if (cond & (G_IO_ERR | G_IO_HUP)) { + error("Error on management socket"); + return FALSE; + } + + ret = read(sk, buf, sizeof(buf)); + if (ret < 0) { + error("Unable to read from management socket: %s (%d)", + strerror(errno), errno); + return TRUE; + } + + DBG("Received %zd bytes from management socket", ret); + + if (ret < MGMT_HDR_SIZE) { + error("Too small Management packet"); + return TRUE; + } + + opcode = btohs(bt_get_unaligned(&hdr->opcode)); + len = btohs(bt_get_unaligned(&hdr->len)); + index = btohs(bt_get_unaligned(&hdr->index)); + + if (ret != MGMT_HDR_SIZE + len) { + error("Packet length mismatch. ret %zd len %u", ret, len); + return TRUE; + } + + switch (opcode) { + case MGMT_EV_CMD_COMPLETE: + mgmt_cmd_complete(sk, index, buf + MGMT_HDR_SIZE, len); + break; + case MGMT_EV_CMD_STATUS: + mgmt_cmd_status(sk, index, buf + MGMT_HDR_SIZE, len); + break; + case MGMT_EV_CONTROLLER_ERROR: + mgmt_controller_error(sk, index, buf + MGMT_HDR_SIZE, len); + break; + case MGMT_EV_INDEX_ADDED: + mgmt_index_added(sk, index); + break; + case MGMT_EV_INDEX_REMOVED: + mgmt_index_removed(sk, index); + break; + case MGMT_EV_POWERED: + mgmt_powered(sk, index, buf + MGMT_HDR_SIZE, len); + break; + case MGMT_EV_DISCOVERABLE: + mgmt_discoverable(sk, index, buf + MGMT_HDR_SIZE, len); + break; + case MGMT_EV_CONNECTABLE: + mgmt_connectable(sk, index, buf + MGMT_HDR_SIZE, len); + break; + case MGMT_EV_PAIRABLE: + mgmt_pairable(sk, index, buf + MGMT_HDR_SIZE, len); + break; + case MGMT_EV_NEW_KEY: + mgmt_new_key(sk, index, buf + MGMT_HDR_SIZE, len); + break; + case MGMT_EV_DEVICE_CONNECTED: + mgmt_device_connected(sk, index, buf + MGMT_HDR_SIZE, len); + break; + case MGMT_EV_DEVICE_DISCONNECTED: + mgmt_device_disconnected(sk, index, buf + MGMT_HDR_SIZE, len); + break; + case MGMT_EV_CONNECT_FAILED: + mgmt_connect_failed(sk, index, buf + MGMT_HDR_SIZE, len); + break; + case MGMT_EV_PIN_CODE_REQUEST: + mgmt_pin_code_request(sk, index, buf + MGMT_HDR_SIZE, len); + break; + case MGMT_EV_USER_CONFIRM_REQUEST: + mgmt_user_confirm_request(sk, index, buf + MGMT_HDR_SIZE, len); + break; + case MGMT_EV_AUTH_FAILED: + mgmt_auth_failed(sk, index, buf + MGMT_HDR_SIZE, len); + break; + case MGMT_EV_LOCAL_NAME_CHANGED: + mgmt_local_name_changed(sk, index, buf + MGMT_HDR_SIZE, len); + break; + default: + error("Unknown Management opcode %u (index %u)", opcode, index); + break; + } + + return TRUE; +} + +static int mgmt_setup(void) +{ + struct mgmt_hdr hdr; + struct sockaddr_hci addr; + GIOChannel *io; + GIOCondition condition; + int dd, err; + + dd = socket(AF_BLUETOOTH, SOCK_RAW, BTPROTO_HCI); + if (dd < 0) + return -errno; + + memset(&addr, 0, sizeof(addr)); + addr.hci_family = AF_BLUETOOTH; + addr.hci_dev = HCI_DEV_NONE; + addr.hci_channel = HCI_CHANNEL_CONTROL; + + if (bind(dd, (struct sockaddr *) &addr, sizeof(addr)) < 0) { + err = -errno; + goto fail; + } + + memset(&hdr, 0, sizeof(hdr)); + hdr.opcode = htobs(MGMT_OP_READ_VERSION); + hdr.index = htobs(MGMT_INDEX_NONE); + if (write(dd, &hdr, sizeof(hdr)) < 0) { + err = -errno; + goto fail; + } + + io = g_io_channel_unix_new(dd); + condition = G_IO_IN | G_IO_ERR | G_IO_HUP | G_IO_NVAL; + mgmt_watch = g_io_add_watch(io, condition, mgmt_event, NULL); + g_io_channel_unref(io); + + mgmt_sock = dd; + + info("Bluetooth Management interface initialized"); + + return 0; + +fail: + close(dd); + return err; +} + +static void mgmt_cleanup(void) +{ + g_free(controllers); + controllers = NULL; + max_index = -1; + + if (mgmt_sock >= 0) { + close(mgmt_sock); + mgmt_sock = -1; + } + + if (mgmt_watch > 0) { + g_source_remove(mgmt_watch); + mgmt_watch = 0; + } +} + +static int mgmt_set_dev_class(int index, uint8_t major, uint8_t minor) +{ + char buf[MGMT_HDR_SIZE + sizeof(struct mgmt_cp_set_dev_class)]; + struct mgmt_hdr *hdr = (void *) buf; + struct mgmt_cp_set_dev_class *cp = (void *) &buf[sizeof(*hdr)]; + + DBG("index %d major %u minor %u", index, major, minor); + + memset(buf, 0, sizeof(buf)); + hdr->opcode = htobs(MGMT_OP_SET_DEV_CLASS); + hdr->len = htobs(sizeof(*cp)); + hdr->index = htobs(index); + + cp->major = major; + cp->minor = minor; + + if (write(mgmt_sock, buf, sizeof(buf)) < 0) + return -errno; + + return 0; +} + +static int mgmt_set_limited_discoverable(int index, gboolean limited) +{ + DBG("index %d limited %d", index, limited); + return -ENOSYS; +} + +static int mgmt_start_inquiry(int index, uint8_t length, gboolean periodic) +{ + DBG("index %d length %u periodic %d", index, length, periodic); + return -ENOSYS; +} + +static int mgmt_stop_inquiry(int index) +{ + DBG("index %d", index); + return -ENOSYS; +} + +static int mgmt_start_scanning(int index) +{ + DBG("index %d", index); + return -ENOSYS; +} + +static int mgmt_stop_scanning(int index) +{ + DBG("index %d", index); + return -ENOSYS; +} + +static int mgmt_resolve_name(int index, bdaddr_t *bdaddr) +{ + char addr[18]; + + ba2str(bdaddr, addr); + DBG("index %d addr %s", index, addr); + + return -ENOSYS; +} + +static int mgmt_set_name(int index, const char *name) +{ + char buf[MGMT_HDR_SIZE + sizeof(struct mgmt_cp_set_local_name)]; + struct mgmt_hdr *hdr = (void *) buf; + struct mgmt_cp_set_local_name *cp = (void *) &buf[sizeof(*hdr)]; + + DBG("index %d, name %s", index, name); + + memset(buf, 0, sizeof(buf)); + hdr->opcode = htobs(MGMT_OP_SET_LOCAL_NAME); + hdr->len = htobs(sizeof(*cp)); + hdr->index = htobs(index); + + strncpy((char *) cp->name, name, sizeof(cp->name) - 1); + + if (write(mgmt_sock, buf, sizeof(buf)) < 0) + return -errno; + + return 0; +} + +static int mgmt_cancel_resolve_name(int index, bdaddr_t *bdaddr) +{ + char addr[18]; + + ba2str(bdaddr, addr); + DBG("index %d addr %s", index, addr); + + return -ENOSYS; +} + +static int mgmt_fast_connectable(int index, gboolean enable) +{ + DBG("index %d enable %d", index, enable); + return -ENOSYS; +} + +static int mgmt_read_clock(int index, bdaddr_t *bdaddr, int which, int timeout, + uint32_t *clock, uint16_t *accuracy) +{ + char addr[18]; + + ba2str(bdaddr, addr); + DBG("index %d addr %s which %d timeout %d", index, addr, which, + timeout); + + return -ENOSYS; +} + +static int mgmt_read_bdaddr(int index, bdaddr_t *bdaddr) +{ + char addr[18]; + struct controller_info *info = &controllers[index]; + + ba2str(&info->bdaddr, addr); + DBG("index %d addr %s", index, addr); + + if (!info->valid) + return -ENODEV; + + bacpy(bdaddr, &info->bdaddr); + + return 0; +} + +static int mgmt_block_device(int index, bdaddr_t *bdaddr) +{ + char addr[18]; + + ba2str(bdaddr, addr); + DBG("index %d addr %s", index, addr); + + return -ENOSYS; +} + +static int mgmt_unblock_device(int index, bdaddr_t *bdaddr) +{ + char addr[18]; + + ba2str(bdaddr, addr); + DBG("index %d addr %s", index, addr); + + return -ENOSYS; +} + +static int mgmt_get_conn_list(int index, GSList **conns) +{ + struct controller_info *info = &controllers[index]; + + DBG("index %d", index); + + *conns = info->connections; + info->connections = NULL; + + return 0; +} + +static int mgmt_read_local_version(int index, struct hci_version *ver) +{ + struct controller_info *info = &controllers[index]; + + DBG("index %d", index); + + if (!info->valid) + return -ENODEV; + + memset(ver, 0, sizeof(*ver)); + ver->manufacturer = info->manufacturer; + ver->hci_ver = info->hci_ver; + ver->hci_rev = info->hci_rev; + + return 0; +} + +static int mgmt_read_local_features(int index, uint8_t *features) +{ + struct controller_info *info = &controllers[index]; + + DBG("index %d", index); + + if (!info->valid) + return -ENODEV; + + memcpy(features, info->features, 8); + + return 0; +} + +static int mgmt_disconnect(int index, bdaddr_t *bdaddr) +{ + char buf[MGMT_HDR_SIZE + sizeof(struct mgmt_cp_disconnect)]; + struct mgmt_hdr *hdr = (void *) buf; + struct mgmt_cp_disconnect *cp = (void *) &buf[sizeof(*hdr)]; + char addr[18]; + + ba2str(bdaddr, addr); + DBG("index %d %s", index, addr); + + memset(buf, 0, sizeof(buf)); + hdr->opcode = htobs(MGMT_OP_DISCONNECT); + hdr->len = htobs(sizeof(*cp)); + hdr->index = htobs(index); + + bacpy(&cp->bdaddr, bdaddr); + + if (write(mgmt_sock, buf, sizeof(buf)) < 0) + error("write: %s (%d)", strerror(errno), errno); + + return 0; +} + +static int mgmt_remove_bonding(int index, bdaddr_t *bdaddr) +{ + char buf[MGMT_HDR_SIZE + sizeof(struct mgmt_cp_remove_key)]; + struct mgmt_hdr *hdr = (void *) buf; + struct mgmt_cp_remove_key *cp = (void *) &buf[sizeof(*hdr)]; + char addr[18]; + + ba2str(bdaddr, addr); + DBG("index %d addr %s", index, addr); + + memset(buf, 0, sizeof(buf)); + hdr->opcode = htobs(MGMT_OP_REMOVE_KEY); + hdr->len = htobs(sizeof(*cp)); + hdr->index = htobs(index); + + bacpy(&cp->bdaddr, bdaddr); + cp->disconnect = 1; + + if (write(mgmt_sock, buf, sizeof(buf)) < 0) + return -errno; + + return 0; +} + +static int mgmt_passkey_reply(int index, bdaddr_t *bdaddr, uint32_t passkey) +{ + char addr[18]; + + ba2str(bdaddr, addr); + DBG("index %d addr %s passkey %06u", index, addr, passkey); + + return -ENOSYS; +} + +static int mgmt_enable_le(int index) +{ + DBG("index %d", index); + return -ENOSYS; +} + +static int mgmt_encrypt_link(int index, bdaddr_t *dst, bt_hci_result_t cb, + gpointer user_data) +{ + char addr[18]; + + ba2str(dst, addr); + DBG("index %d addr %s", index, addr); + + return -ENOSYS; +} + +static int mgmt_set_did(int index, uint16_t vendor, uint16_t product, + uint16_t version) +{ + DBG("index %d vendor %u product %u version %u", + index, vendor, product, version); + return -ENOSYS; +} + +static int mgmt_disable_cod_cache(int index) +{ + DBG("index %d", index); + return mgmt_set_mode(index, MGMT_OP_SET_SERVICE_CACHE, 0); +} + +static int mgmt_restore_powered(int index) +{ + DBG("index %d", index); + return -ENOSYS; +} + +static int mgmt_load_keys(int index, GSList *keys, gboolean debug_keys) +{ + char *buf; + struct mgmt_hdr *hdr; + struct mgmt_cp_load_keys *cp; + struct mgmt_key_info *key; + size_t key_count, cp_size; + GSList *l; + int err; + + key_count = g_slist_length(keys); + + DBG("index %d keys %zu debug_keys %d", index, key_count, debug_keys); + + cp_size = sizeof(*cp) + (key_count * sizeof(*key)); + + buf = g_try_malloc0(sizeof(*hdr) + cp_size); + if (buf == NULL) + return -ENOMEM; + + memset(buf, 0, sizeof(buf)); + + hdr = (void *) buf; + hdr->opcode = htobs(MGMT_OP_LOAD_KEYS); + hdr->len = htobs(cp_size); + hdr->index = htobs(index); + + cp = (void *) (buf + sizeof(*hdr)); + cp->debug_keys = debug_keys; + cp->key_count = htobs(key_count); + + for (l = keys, key = cp->keys; l != NULL; l = g_slist_next(l), key++) { + struct link_key_info *info = l->data; + + bacpy(&key->bdaddr, &info->bdaddr); + key->type = info->type; + memcpy(key->val, info->key, 16); + key->pin_len = info->pin_len; + } + + if (write(mgmt_sock, buf, sizeof(*hdr) + cp_size) < 0) + err = -errno; + else + err = 0; + + g_free(buf); + + return err; +} + +static int mgmt_set_io_capability(int index, uint8_t io_capability) +{ + char buf[MGMT_HDR_SIZE + sizeof(struct mgmt_cp_set_io_capability)]; + struct mgmt_hdr *hdr = (void *) buf; + struct mgmt_cp_set_io_capability *cp = (void *) &buf[sizeof(*hdr)]; + + DBG("hci%d io_capability 0x%02x", index, io_capability); + + memset(buf, 0, sizeof(buf)); + hdr->opcode = htobs(MGMT_OP_SET_IO_CAPABILITY); + hdr->len = htobs(sizeof(*cp)); + hdr->index = htobs(index); + + cp->io_capability = io_capability; + + if (write(mgmt_sock, buf, sizeof(buf)) < 0) + return -errno; + + return 0; +} + +static int mgmt_create_bonding(int index, bdaddr_t *bdaddr, uint8_t io_cap) +{ + char buf[MGMT_HDR_SIZE + sizeof(struct mgmt_cp_pair_device)]; + struct mgmt_hdr *hdr = (void *) buf; + struct mgmt_cp_pair_device *cp = (void *) &buf[sizeof(*hdr)]; + char addr[18]; + + ba2str(bdaddr, addr); + DBG("hci%d bdaddr %s io_cap 0x%02x", index, addr, io_cap); + + memset(buf, 0, sizeof(buf)); + hdr->opcode = htobs(MGMT_OP_PAIR_DEVICE); + hdr->len = htobs(sizeof(*cp)); + hdr->index = htobs(index); + + bacpy(&cp->bdaddr, bdaddr); + cp->io_cap = io_cap; + + if (write(mgmt_sock, &buf, sizeof(buf)) < 0) + return -errno; + + return 0; +} + +static int mgmt_cancel_bonding(int index, bdaddr_t *bdaddr) +{ + char addr[18]; + + ba2str(bdaddr, addr); + DBG("hci%d bdaddr %s", index, addr); + + return -ENOSYS; +} + +static int mgmt_read_local_oob_data(int index) +{ + struct mgmt_hdr hdr; + + DBG("hci%d", index); + + hdr.opcode = htobs(MGMT_OP_READ_LOCAL_OOB_DATA); + hdr.len = 0; + hdr.index = htobs(index); + + if (write(mgmt_sock, &hdr, sizeof(hdr)) < 0) + return -errno; + + return 0; +} + +static int mgmt_add_remote_oob_data(int index, bdaddr_t *bdaddr, + uint8_t *hash, uint8_t *randomizer) +{ + char buf[MGMT_HDR_SIZE + sizeof(struct mgmt_cp_add_remote_oob_data)]; + struct mgmt_hdr *hdr = (void *) buf; + struct mgmt_cp_add_remote_oob_data *cp = (void *) &buf[sizeof(*hdr)]; + char addr[18]; + + ba2str(bdaddr, addr); + DBG("hci%d bdaddr %s", index, addr); + + memset(buf, 0, sizeof(buf)); + + hdr->opcode = htobs(MGMT_OP_ADD_REMOTE_OOB_DATA); + hdr->index = htobs(index); + hdr->len = htobs(sizeof(*cp)); + + bacpy(&cp->bdaddr, bdaddr); + memcpy(cp->hash, hash, 16); + memcpy(cp->randomizer, randomizer, 16); + + if (write(mgmt_sock, &buf, sizeof(buf)) < 0) + return -errno; + + return 0; +} + +static int mgmt_remove_remote_oob_data(int index, bdaddr_t *bdaddr) +{ + char buf[MGMT_HDR_SIZE + sizeof(struct mgmt_cp_remove_remote_oob_data)]; + struct mgmt_hdr *hdr = (void *) buf; + struct mgmt_cp_remove_remote_oob_data *cp = (void *) &buf[sizeof(*hdr)]; + char addr[18]; + + ba2str(bdaddr, addr); + DBG("hci%d bdaddr %s", index, addr); + + memset(buf, 0, sizeof(buf)); + + hdr->opcode = htobs(MGMT_OP_REMOVE_REMOTE_OOB_DATA); + hdr->index = htobs(index); + hdr->len = htobs(sizeof(*cp)); + + bacpy(&cp->bdaddr, bdaddr); + + if (write(mgmt_sock, &buf, sizeof(buf)) < 0) + return -errno; + + return 0; +} + +static struct btd_adapter_ops mgmt_ops = { + .setup = mgmt_setup, + .cleanup = mgmt_cleanup, + .set_powered = mgmt_set_powered, + .set_discoverable = mgmt_set_discoverable, + .set_pairable = mgmt_set_pairable, + .set_limited_discoverable = mgmt_set_limited_discoverable, + .start_inquiry = mgmt_start_inquiry, + .stop_inquiry = mgmt_stop_inquiry, + .start_scanning = mgmt_start_scanning, + .stop_scanning = mgmt_stop_scanning, + .resolve_name = mgmt_resolve_name, + .cancel_resolve_name = mgmt_cancel_resolve_name, + .set_name = mgmt_set_name, + .set_dev_class = mgmt_set_dev_class, + .set_fast_connectable = mgmt_fast_connectable, + .read_clock = mgmt_read_clock, + .read_bdaddr = mgmt_read_bdaddr, + .block_device = mgmt_block_device, + .unblock_device = mgmt_unblock_device, + .get_conn_list = mgmt_get_conn_list, + .read_local_version = mgmt_read_local_version, + .read_local_features = mgmt_read_local_features, + .disconnect = mgmt_disconnect, + .remove_bonding = mgmt_remove_bonding, + .pincode_reply = mgmt_pincode_reply, + .confirm_reply = mgmt_confirm_reply, + .passkey_reply = mgmt_passkey_reply, + .enable_le = mgmt_enable_le, + .encrypt_link = mgmt_encrypt_link, + .set_did = mgmt_set_did, + .add_uuid = mgmt_add_uuid, + .remove_uuid = mgmt_remove_uuid, + .disable_cod_cache = mgmt_disable_cod_cache, + .restore_powered = mgmt_restore_powered, + .load_keys = mgmt_load_keys, + .set_io_capability = mgmt_set_io_capability, + .create_bonding = mgmt_create_bonding, + .cancel_bonding = mgmt_cancel_bonding, + .read_local_oob_data = mgmt_read_local_oob_data, + .add_remote_oob_data = mgmt_add_remote_oob_data, + .remove_remote_oob_data = mgmt_remove_remote_oob_data, +}; + +static int mgmt_init(void) +{ + return btd_register_adapter_ops(&mgmt_ops, TRUE); +} + +static void mgmt_exit(void) +{ + btd_adapter_cleanup_ops(&mgmt_ops); +} + +BLUETOOTH_PLUGIN_DEFINE(mgmtops, VERSION, + BLUETOOTH_PLUGIN_PRIORITY_LOW, mgmt_init, mgmt_exit) diff --git a/plugins/pnat.c b/plugins/pnat.c new file mode 100644 index 0000000..2d73910 --- /dev/null +++ b/plugins/pnat.c @@ -0,0 +1,526 @@ +/* + * + * BlueZ - Bluetooth protocol stack for Linux + * + * Copyright (C) 2010 Nokia Corporation + * Copyright (C) 2010 Marcel Holtmann <marcel@holtmann.org> + * + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + * + */ + +#ifdef HAVE_CONFIG_H +#include <config.h> +#endif + +#include <errno.h> +#include <unistd.h> +#include <sys/socket.h> +#include <sys/ioctl.h> +#include <sys/types.h> +#include <sys/stat.h> +#include <sys/wait.h> +#include <fcntl.h> + +#include <bluetooth/bluetooth.h> +#include <bluetooth/rfcomm.h> +#include <bluetooth/sdp.h> +#include <bluetooth/sdp_lib.h> + +#include <glib.h> + +#include <gdbus.h> + +#include "plugin.h" +#include "sdpd.h" +#include "btio.h" +#include "adapter.h" +#include "log.h" + +/* FIXME: This location should be build-time configurable */ +#define PNATD "/usr/bin/phonet-at" + +#define DUN_CHANNEL 1 +#define DUN_UUID "00001103-0000-1000-8000-00805F9B34FB" + +#define TTY_TIMEOUT 100 +#define TTY_TRIES 10 + +struct dun_client { + bdaddr_t bda; + + GIOChannel *io; /* Client socket */ + guint io_watch; /* Client IO watch id */ + + guint tty_timer; + int tty_tries; + gboolean tty_open; + int tty_id; + char tty_name[PATH_MAX]; + + GPid pnatd_pid; +}; + +struct dun_server { + bdaddr_t bda; /* Local adapter address */ + + uint32_t record_handle; /* Local SDP record handle */ + GIOChannel *server; /* Server socket */ + + int rfcomm_ctl; + + struct dun_client client; +}; + +static GSList *servers = NULL; + +static void disconnect(struct dun_server *server) +{ + struct dun_client *client = &server->client; + + if (!client->io) + return; + + if (client->io_watch > 0) { + g_source_remove(client->io_watch); + client->io_watch = 0; + } + + g_io_channel_shutdown(client->io, TRUE, NULL); + g_io_channel_unref(client->io); + client->io = NULL; + + if (client->pnatd_pid > 0) { + kill(client->pnatd_pid, SIGTERM); + client->pnatd_pid = 0; + } + + if (client->tty_timer > 0) { + g_source_remove(client->tty_timer); + client->tty_timer = 0; + } + + if (client->tty_id >= 0) { + struct rfcomm_dev_req req; + + memset(&req, 0, sizeof(req)); + req.dev_id = client->tty_id; + req.flags = (1 << RFCOMM_HANGUP_NOW); + ioctl(server->rfcomm_ctl, RFCOMMRELEASEDEV, &req); + + client->tty_name[0] = '\0'; + client->tty_open = FALSE; + client->tty_id = -1; + } +} + +static gboolean client_event(GIOChannel *chan, + GIOCondition cond, gpointer data) +{ + struct dun_server *server = data; + struct dun_client *client = &server->client; + char addr[18]; + + ba2str(&client->bda, addr); + + DBG("Disconnected DUN from %s (%s)", addr, client->tty_name); + + client->io_watch = 0; + disconnect(server); + + return FALSE; +} + +static void pnatd_exit(GPid pid, gint status, gpointer user_data) +{ + struct dun_server *server = user_data; + struct dun_client *client = &server->client; + + if (WIFEXITED(status)) + DBG("pnatd (%d) exited with status %d", pid, + WEXITSTATUS(status)); + else + DBG("pnatd (%d) was killed by signal %d", pid, + WTERMSIG(status)); + g_spawn_close_pid(pid); + + if (pid != client->pnatd_pid) + return; + + /* So disconnect() doesn't send SIGTERM to a non-existing process */ + client->pnatd_pid = 0; + + disconnect(server); +} + +static gboolean start_pnatd(struct dun_server *server) +{ + struct dun_client *client = &server->client; + GSpawnFlags flags = G_SPAWN_DO_NOT_REAP_CHILD | G_SPAWN_SEARCH_PATH; + char *argv[] = { PNATD, client->tty_name, NULL }; + GError *err = NULL; + GPid pid; + + g_spawn_async(NULL, argv, NULL, flags, NULL, NULL, &pid, &err); + if (err != NULL) { + error("Unable to spawn pnatd: %s", err->message); + g_error_free(err); + return FALSE; + } + + DBG("pnatd started for %s with pid %d", client->tty_name, pid); + + client->pnatd_pid = pid; + + /* We do not store the GSource id since g_remove_source doesn't + * make sense for a child watch. If the callback gets removed + * waitpid won't be called and the child remains as a zombie) + */ + g_child_watch_add(pid, pnatd_exit, server); + + return TRUE; +} + +static gboolean tty_try_open(gpointer user_data) +{ + struct dun_server *server = user_data; + struct dun_client *client = &server->client; + int tty_fd; + + tty_fd = open(client->tty_name, O_RDONLY | O_NOCTTY); + if (tty_fd < 0) { + if (errno == EACCES) + goto disconnect; + + client->tty_tries--; + + if (client->tty_tries <= 0) + goto disconnect; + + return TRUE; + } + + DBG("%s created for DUN", client->tty_name); + + client->tty_open = TRUE; + client->tty_timer = 0; + + g_io_channel_unref(client->io); + g_source_remove(client->io_watch); + + client->io = g_io_channel_unix_new(tty_fd); + client->io_watch = g_io_add_watch(client->io, + G_IO_HUP | G_IO_ERR | G_IO_NVAL, + client_event, server); + + if (!start_pnatd(server)) + goto disconnect; + + return FALSE; + +disconnect: + client->tty_timer = 0; + disconnect(server); + return FALSE; +} + +static gboolean create_tty(struct dun_server *server) +{ + struct dun_client *client = &server->client; + struct rfcomm_dev_req req; + int sk = g_io_channel_unix_get_fd(client->io); + + memset(&req, 0, sizeof(req)); + req.dev_id = -1; + req.flags = (1 << RFCOMM_REUSE_DLC) | (1 << RFCOMM_RELEASE_ONHUP); + + bacpy(&req.src, &server->bda); + bacpy(&req.dst, &client->bda); + + bt_io_get(client->io, BT_IO_RFCOMM, NULL, + BT_IO_OPT_DEST_CHANNEL, &req.channel, + BT_IO_OPT_INVALID); + + client->tty_id = ioctl(sk, RFCOMMCREATEDEV, &req); + if (client->tty_id < 0) { + error("Can't create RFCOMM TTY: %s", strerror(errno)); + return FALSE; + } + + snprintf(client->tty_name, PATH_MAX - 1, "/dev/rfcomm%d", + client->tty_id); + + client->tty_tries = TTY_TRIES; + + tty_try_open(server); + if (!client->tty_open && client->tty_tries > 0) + client->tty_timer = g_timeout_add(TTY_TIMEOUT, + tty_try_open, server); + + return TRUE; +} + +static void connect_cb(GIOChannel *io, GError *err, gpointer user_data) +{ + struct dun_server *server = user_data; + + if (err) { + error("Accepting DUN connection failed: %s", err->message); + disconnect(server); + return; + } + + if (!create_tty(server)) { + error("Device creation failed"); + disconnect(server); + } +} + +static void auth_cb(DBusError *derr, void *user_data) +{ + struct dun_server *server = user_data; + struct dun_client *client = &server->client; + GError *err = NULL; + + if (derr && dbus_error_is_set(derr)) { + error("DUN access denied: %s", derr->message); + goto drop; + } + + if (!bt_io_accept(client->io, connect_cb, server, NULL, &err)) { + error("bt_io_accept: %s", err->message); + g_error_free(err); + goto drop; + } + + return; + +drop: + disconnect(server); +} + +static gboolean auth_watch(GIOChannel *chan, GIOCondition cond, gpointer data) +{ + struct dun_server *server = data; + struct dun_client *client = &server->client; + + error("DUN client disconnected while waiting for authorization"); + + btd_cancel_authorization(&server->bda, &client->bda); + + disconnect(server); + + return FALSE; +} + +static void confirm_cb(GIOChannel *io, gpointer user_data) +{ + struct dun_server *server = user_data; + struct dun_client *client = &server->client; + GError *err = NULL; + + if (client->io) { + error("Rejecting DUN connection since one already exists"); + return; + } + + bt_io_get(io, BT_IO_RFCOMM, &err, + BT_IO_OPT_DEST_BDADDR, &client->bda, + BT_IO_OPT_INVALID); + if (err != NULL) { + error("Unable to get DUN source and dest address: %s", + err->message); + g_error_free(err); + return; + } + + if (btd_request_authorization(&server->bda, &client->bda, DUN_UUID, + auth_cb, user_data) < 0) { + error("Requesting DUN authorization failed"); + return; + } + + client->io_watch = g_io_add_watch(io, G_IO_ERR | G_IO_HUP | G_IO_NVAL, + (GIOFunc) auth_watch, server); + client->io = g_io_channel_ref(io); +} + +static sdp_record_t *dun_record(uint8_t ch) +{ + sdp_list_t *svclass_id, *pfseq, *apseq, *root, *aproto; + uuid_t root_uuid, dun, gn, l2cap, rfcomm; + sdp_profile_desc_t profile; + sdp_list_t *proto[2]; + sdp_record_t *record; + sdp_data_t *channel; + + record = sdp_record_alloc(); + if (!record) + return NULL; + + sdp_uuid16_create(&root_uuid, PUBLIC_BROWSE_GROUP); + root = sdp_list_append(NULL, &root_uuid); + sdp_set_browse_groups(record, root); + + sdp_uuid16_create(&dun, DIALUP_NET_SVCLASS_ID); + svclass_id = sdp_list_append(NULL, &dun); + sdp_uuid16_create(&gn, GENERIC_NETWORKING_SVCLASS_ID); + svclass_id = sdp_list_append(svclass_id, &gn); + sdp_set_service_classes(record, svclass_id); + + sdp_uuid16_create(&profile.uuid, DIALUP_NET_PROFILE_ID); + profile.version = 0x0100; + pfseq = sdp_list_append(NULL, &profile); + sdp_set_profile_descs(record, pfseq); + + sdp_uuid16_create(&l2cap, L2CAP_UUID); + proto[0] = sdp_list_append(NULL, &l2cap); + apseq = sdp_list_append(NULL, proto[0]); + + sdp_uuid16_create(&rfcomm, RFCOMM_UUID); + proto[1] = sdp_list_append(NULL, &rfcomm); + channel = sdp_data_alloc(SDP_UINT8, &ch); + proto[1] = sdp_list_append(proto[1], channel); + apseq = sdp_list_append(apseq, proto[1]); + + aproto = sdp_list_append(0, apseq); + sdp_set_access_protos(record, aproto); + + sdp_set_info_attr(record, "Dial-Up Networking", 0, 0); + + sdp_data_free(channel); + sdp_list_free(root, NULL); + sdp_list_free(svclass_id, NULL); + sdp_list_free(proto[0], NULL); + sdp_list_free(proto[1], NULL); + sdp_list_free(pfseq, NULL); + sdp_list_free(apseq, NULL); + sdp_list_free(aproto, NULL); + + return record; +} + +static gint server_cmp(gconstpointer a, gconstpointer b) +{ + const struct dun_server *server = a; + const bdaddr_t *src = b; + + return bacmp(src, &server->bda); +} + +static int pnat_probe(struct btd_adapter *adapter) +{ + struct dun_server *server; + GIOChannel *io; + GError *err = NULL; + sdp_record_t *record; + bdaddr_t src; + + adapter_get_address(adapter, &src); + + server = g_new0(struct dun_server, 1); + + io = bt_io_listen(BT_IO_RFCOMM, NULL, confirm_cb, server, NULL, &err, + BT_IO_OPT_SOURCE_BDADDR, &src, + BT_IO_OPT_CHANNEL, DUN_CHANNEL, + BT_IO_OPT_INVALID); + if (err != NULL) { + error("Failed to start DUN server: %s", err->message); + g_error_free(err); + goto fail; + } + + record = dun_record(DUN_CHANNEL); + if (!record) { + error("Unable to allocate new service record"); + goto fail; + } + + if (add_record_to_server(&src, record) < 0) { + error("Unable to register DUN service record"); + goto fail; + } + + server->rfcomm_ctl = socket(AF_BLUETOOTH, SOCK_RAW, BTPROTO_RFCOMM); + if (server->rfcomm_ctl < 0) { + error("Unable to create RFCOMM control socket: %s (%d)", + strerror(errno), errno); + goto fail; + } + + server->server = io; + server->record_handle = record->handle; + bacpy(&server->bda, &src); + + servers = g_slist_append(servers, server); + + return 0; + +fail: + if (io != NULL) + g_io_channel_unref(io); + g_free(server); + return -EIO; +} + +static void pnat_remove(struct btd_adapter *adapter) +{ + struct dun_server *server; + GSList *match; + bdaddr_t src; + + adapter_get_address(adapter, &src); + + match = g_slist_find_custom(servers, &src, server_cmp); + if (match == NULL) + return; + + server = match->data; + + servers = g_slist_delete_link(servers, match); + + disconnect(server); + + remove_record_from_server(server->record_handle); + close(server->rfcomm_ctl); + g_io_channel_shutdown(server->server, TRUE, NULL); + g_io_channel_unref(server->server); + g_free(server); +} + +static struct btd_adapter_driver pnat_server = { + .name = "pnat-server", + .probe = pnat_probe, + .remove = pnat_remove, +}; + +static int pnat_init(void) +{ + DBG("Setup Phonet AT (DUN) plugin"); + + return btd_register_adapter_driver(&pnat_server); +} + +static void pnat_exit(void) +{ + DBG("Cleanup Phonet AT (DUN) plugin"); + + btd_unregister_adapter_driver(&pnat_server); +} + +BLUETOOTH_PLUGIN_DEFINE(pnat, VERSION, + BLUETOOTH_PLUGIN_PRIORITY_DEFAULT, + pnat_init, pnat_exit) diff --git a/plugins/service.c b/plugins/service.c new file mode 100644 index 0000000..d73cdea --- /dev/null +++ b/plugins/service.c @@ -0,0 +1,824 @@ +/* + * + * BlueZ - Bluetooth protocol stack for Linux + * + * Copyright (C) 2006-2010 Nokia Corporation + * Copyright (C) 2004-2010 Marcel Holtmann <marcel@holtmann.org> + * + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + * + */ + +#ifdef HAVE_CONFIG_H +#include <config.h> +#endif + +#include <errno.h> +#include <stdlib.h> +#include <string.h> + +#include <bluetooth/bluetooth.h> +#include <bluetooth/sdp.h> +#include <bluetooth/sdp_lib.h> + +#include <gdbus.h> + +#include "sdpd.h" +#include "sdp-xml.h" +#include "plugin.h" +#include "adapter.h" +#include "error.h" +#include "log.h" + +#define SERVICE_INTERFACE "org.bluez.Service" + +static DBusConnection *connection; + +struct record_data { + uint32_t handle; + char *sender; + guint listener_id; + struct service_adapter *serv_adapter; +}; + +struct context_data { + sdp_record_t *record; + sdp_data_t attr_data; + struct sdp_xml_data *stack_head; + uint16_t attr_id; +}; + +struct pending_auth { + DBusConnection *conn; + DBusMessage *msg; + char *sender; + bdaddr_t dst; + char uuid[MAX_LEN_UUID_STR]; +}; + +struct service_adapter { + struct btd_adapter *adapter; + GSList *pending_list; + GSList *records; +}; + +static struct service_adapter *serv_adapter_any = NULL; + +static int compute_seq_size(sdp_data_t *data) +{ + int unit_size = data->unitSize; + sdp_data_t *seq = data->val.dataseq; + + for (; seq; seq = seq->next) + unit_size += seq->unitSize; + + return unit_size; +} + +static void element_start(GMarkupParseContext *context, + const gchar *element_name, const gchar **attribute_names, + const gchar **attribute_values, gpointer user_data, GError **err) +{ + struct context_data *ctx_data = user_data; + + if (!strcmp(element_name, "record")) + return; + + if (!strcmp(element_name, "attribute")) { + int i; + for (i = 0; attribute_names[i]; i++) { + if (!strcmp(attribute_names[i], "id")) { + ctx_data->attr_id = strtol(attribute_values[i], 0, 0); + break; + } + } + DBG("New attribute 0x%04x", ctx_data->attr_id); + return; + } + + if (ctx_data->stack_head) { + struct sdp_xml_data *newelem = sdp_xml_data_alloc(); + newelem->next = ctx_data->stack_head; + ctx_data->stack_head = newelem; + } else { + ctx_data->stack_head = sdp_xml_data_alloc(); + ctx_data->stack_head->next = NULL; + } + + if (!strcmp(element_name, "sequence")) + ctx_data->stack_head->data = sdp_data_alloc(SDP_SEQ8, NULL); + else if (!strcmp(element_name, "alternate")) + ctx_data->stack_head->data = sdp_data_alloc(SDP_ALT8, NULL); + else { + int i; + /* Parse value, name, encoding */ + for (i = 0; attribute_names[i]; i++) { + if (!strcmp(attribute_names[i], "value")) { + int curlen = strlen(ctx_data->stack_head->text); + int attrlen = strlen(attribute_values[i]); + + /* Ensure we're big enough */ + while ((curlen + 1 + attrlen) > ctx_data->stack_head->size) { + sdp_xml_data_expand(ctx_data->stack_head); + } + + memcpy(ctx_data->stack_head->text + curlen, + attribute_values[i], attrlen); + ctx_data->stack_head->text[curlen + attrlen] = '\0'; + } + + if (!strcmp(attribute_names[i], "encoding")) { + if (!strcmp(attribute_values[i], "hex")) + ctx_data->stack_head->type = 1; + } + + if (!strcmp(attribute_names[i], "name")) { + ctx_data->stack_head->name = strdup(attribute_values[i]); + } + } + + ctx_data->stack_head->data = sdp_xml_parse_datatype(element_name, + ctx_data->stack_head, ctx_data->record); + + if (ctx_data->stack_head->data == NULL) + error("Can't parse element %s", element_name); + } +} + +static void element_end(GMarkupParseContext *context, + const gchar *element_name, gpointer user_data, GError **err) +{ + struct context_data *ctx_data = user_data; + struct sdp_xml_data *elem; + + if (!strcmp(element_name, "record")) + return; + + if (!strcmp(element_name, "attribute")) { + if (ctx_data->stack_head && ctx_data->stack_head->data) { + int ret = sdp_attr_add(ctx_data->record, ctx_data->attr_id, + ctx_data->stack_head->data); + if (ret == -1) + DBG("Could not add attribute 0x%04x", + ctx_data->attr_id); + + ctx_data->stack_head->data = NULL; + sdp_xml_data_free(ctx_data->stack_head); + ctx_data->stack_head = NULL; + } else { + DBG("No data for attribute 0x%04x", ctx_data->attr_id); + } + return; + } + + if (!strcmp(element_name, "sequence")) { + ctx_data->stack_head->data->unitSize = compute_seq_size(ctx_data->stack_head->data); + + if (ctx_data->stack_head->data->unitSize > USHRT_MAX) { + ctx_data->stack_head->data->unitSize += sizeof(uint32_t); + ctx_data->stack_head->data->dtd = SDP_SEQ32; + } else if (ctx_data->stack_head->data->unitSize > UCHAR_MAX) { + ctx_data->stack_head->data->unitSize += sizeof(uint16_t); + ctx_data->stack_head->data->dtd = SDP_SEQ16; + } else { + ctx_data->stack_head->data->unitSize += sizeof(uint8_t); + } + } else if (!strcmp(element_name, "alternate")) { + ctx_data->stack_head->data->unitSize = compute_seq_size(ctx_data->stack_head->data); + + if (ctx_data->stack_head->data->unitSize > USHRT_MAX) { + ctx_data->stack_head->data->unitSize += sizeof(uint32_t); + ctx_data->stack_head->data->dtd = SDP_ALT32; + } else if (ctx_data->stack_head->data->unitSize > UCHAR_MAX) { + ctx_data->stack_head->data->unitSize += sizeof(uint16_t); + ctx_data->stack_head->data->dtd = SDP_ALT16; + } else { + ctx_data->stack_head->data->unitSize += sizeof(uint8_t); + } + } + + if (ctx_data->stack_head->next && ctx_data->stack_head->data && + ctx_data->stack_head->next->data) { + switch (ctx_data->stack_head->next->data->dtd) { + case SDP_SEQ8: + case SDP_SEQ16: + case SDP_SEQ32: + case SDP_ALT8: + case SDP_ALT16: + case SDP_ALT32: + ctx_data->stack_head->next->data->val.dataseq = + sdp_seq_append(ctx_data->stack_head->next->data->val.dataseq, + ctx_data->stack_head->data); + ctx_data->stack_head->data = NULL; + break; + } + + elem = ctx_data->stack_head; + ctx_data->stack_head = ctx_data->stack_head->next; + + sdp_xml_data_free(elem); + } +} + +static GMarkupParser parser = { + element_start, element_end, NULL, NULL, NULL +}; + +static sdp_record_t *sdp_xml_parse_record(const char *data, int size) +{ + GMarkupParseContext *ctx; + struct context_data *ctx_data; + sdp_record_t *record; + + ctx_data = malloc(sizeof(*ctx_data)); + if (!ctx_data) + return NULL; + + record = sdp_record_alloc(); + if (!record) { + free(ctx_data); + return NULL; + } + + memset(ctx_data, 0, sizeof(*ctx_data)); + ctx_data->record = record; + + ctx = g_markup_parse_context_new(&parser, 0, ctx_data, NULL); + + if (g_markup_parse_context_parse(ctx, data, size, NULL) == FALSE) { + error("XML parsing error"); + g_markup_parse_context_free(ctx); + sdp_record_free(record); + free(ctx_data); + return NULL; + } + + g_markup_parse_context_free(ctx); + + free(ctx_data); + + return record; +} + +static struct record_data *find_record(struct service_adapter *serv_adapter, + uint32_t handle, const char *sender) +{ + GSList *list; + + for (list = serv_adapter->records; list; list = list->next) { + struct record_data *data = list->data; + if (handle == data->handle && !strcmp(sender, data->sender)) + return data; + } + + return NULL; +} + +static struct pending_auth *next_pending(struct service_adapter *serv_adapter) +{ + GSList *l = serv_adapter->pending_list; + + if (l) { + struct pending_auth *auth = l->data; + return auth; + } + + return NULL; +} + +static struct pending_auth *find_pending_by_sender( + struct service_adapter *serv_adapter, + const char *sender) +{ + GSList *l = serv_adapter->pending_list; + + for (; l; l = l->next) { + struct pending_auth *auth = l->data; + if (g_str_equal(auth->sender, sender)) + return auth; + } + + return NULL; +} + +static void exit_callback(DBusConnection *conn, void *user_data) +{ + struct record_data *user_record = user_data; + struct service_adapter *serv_adapter = user_record->serv_adapter; + struct pending_auth *auth; + + DBG("remove record"); + + serv_adapter->records = g_slist_remove(serv_adapter->records, + user_record); + + auth = find_pending_by_sender(serv_adapter, user_record->sender); + if (auth) { + serv_adapter->pending_list = g_slist_remove(serv_adapter->pending_list, + auth); + g_free(auth); + } + + remove_record_from_server(user_record->handle); + + g_free(user_record->sender); + g_free(user_record); +} + +static int add_xml_record(DBusConnection *conn, const char *sender, + struct service_adapter *serv_adapter, + const char *record, dbus_uint32_t *handle) +{ + struct record_data *user_record; + sdp_record_t *sdp_record; + bdaddr_t src; + + sdp_record = sdp_xml_parse_record(record, strlen(record)); + if (!sdp_record) { + error("Parsing of XML service record failed"); + return -EIO; + } + + if (serv_adapter->adapter) + adapter_get_address(serv_adapter->adapter, &src); + else + bacpy(&src, BDADDR_ANY); + + if (add_record_to_server(&src, sdp_record) < 0) { + error("Failed to register service record"); + sdp_record_free(sdp_record); + return -EIO; + } + + user_record = g_new0(struct record_data, 1); + user_record->handle = sdp_record->handle; + user_record->sender = g_strdup(sender); + user_record->serv_adapter = serv_adapter; + user_record->listener_id = g_dbus_add_disconnect_watch(conn, sender, + exit_callback, user_record, NULL); + + serv_adapter->records = g_slist_append(serv_adapter->records, + user_record); + + DBG("listener_id %d", user_record->listener_id); + + *handle = user_record->handle; + + return 0; +} + +static DBusMessage *update_record(DBusConnection *conn, DBusMessage *msg, + struct service_adapter *serv_adapter, + dbus_uint32_t handle, sdp_record_t *sdp_record) +{ + bdaddr_t src; + int err; + + if (remove_record_from_server(handle) < 0) { + sdp_record_free(sdp_record); + return btd_error_not_available(msg); + } + + if (serv_adapter->adapter) + adapter_get_address(serv_adapter->adapter, &src); + else + bacpy(&src, BDADDR_ANY); + + sdp_record->handle = handle; + err = add_record_to_server(&src, sdp_record); + if (err < 0) { + sdp_record_free(sdp_record); + error("Failed to update the service record"); + return btd_error_failed(msg, strerror(-err)); + } + + return dbus_message_new_method_return(msg); +} + +static DBusMessage *update_xml_record(DBusConnection *conn, + DBusMessage *msg, + struct service_adapter *serv_adapter) +{ + struct record_data *user_record; + sdp_record_t *sdp_record; + const char *record; + dbus_uint32_t handle; + int len; + + if (dbus_message_get_args(msg, NULL, + DBUS_TYPE_UINT32, &handle, + DBUS_TYPE_STRING, &record, + DBUS_TYPE_INVALID) == FALSE) + return NULL; + + len = (record ? strlen(record) : 0); + if (len == 0) + return btd_error_invalid_args(msg); + + user_record = find_record(serv_adapter, handle, + dbus_message_get_sender(msg)); + if (!user_record) + return btd_error_not_available(msg); + + sdp_record = sdp_xml_parse_record(record, len); + if (!sdp_record) { + error("Parsing of XML service record failed"); + sdp_record_free(sdp_record); + return btd_error_failed(msg, + "Parsing of XML service record failed"); + } + + return update_record(conn, msg, serv_adapter, handle, sdp_record); +} + +static int remove_record(DBusConnection *conn, const char *sender, + struct service_adapter *serv_adapter, + dbus_uint32_t handle) +{ + struct record_data *user_record; + + DBG("remove record 0x%x", handle); + + user_record = find_record(serv_adapter, handle, sender); + if (!user_record) + return -1; + + DBG("listner_id %d", user_record->listener_id); + + g_dbus_remove_watch(conn, user_record->listener_id); + + exit_callback(conn, user_record); + + return 0; +} + +static DBusMessage *add_service_record(DBusConnection *conn, + DBusMessage *msg, void *data) +{ + struct service_adapter *serv_adapter = data; + DBusMessage *reply; + const char *sender, *record; + dbus_uint32_t handle; + int err; + + if (dbus_message_get_args(msg, NULL, + DBUS_TYPE_STRING, &record, DBUS_TYPE_INVALID) == FALSE) + return NULL; + + sender = dbus_message_get_sender(msg); + err = add_xml_record(conn, sender, serv_adapter, record, &handle); + if (err < 0) + return btd_error_failed(msg, strerror(-err)); + + reply = dbus_message_new_method_return(msg); + if (!reply) + return NULL; + + dbus_message_append_args(reply, DBUS_TYPE_UINT32, &handle, + DBUS_TYPE_INVALID); + + return reply; +} + +static DBusMessage *update_service_record(DBusConnection *conn, + DBusMessage *msg, void *data) +{ + struct service_adapter *serv_adapter = data; + + return update_xml_record(conn, msg, serv_adapter); +} + +static DBusMessage *remove_service_record(DBusConnection *conn, + DBusMessage *msg, void *data) +{ + struct service_adapter *serv_adapter = data; + dbus_uint32_t handle; + const char *sender; + + if (dbus_message_get_args(msg, NULL, DBUS_TYPE_UINT32, &handle, + DBUS_TYPE_INVALID) == FALSE) + return NULL; + + sender = dbus_message_get_sender(msg); + + if (remove_record(conn, sender, serv_adapter, handle) < 0) + return btd_error_not_available(msg); + + return dbus_message_new_method_return(msg); +} + +static void auth_cb(DBusError *derr, void *user_data) +{ + struct service_adapter *serv_adapter = user_data; + DBusMessage *reply; + struct pending_auth *auth; + bdaddr_t src; + + auth = next_pending(serv_adapter); + if (auth == NULL) { + info("Authorization cancelled: Client exited"); + return; + } + + if (derr) { + error("Access denied: %s", derr->message); + + reply = btd_error_not_authorized(auth->msg); + dbus_message_unref(auth->msg); + g_dbus_send_message(auth->conn, reply); + goto done; + } + + g_dbus_send_reply(auth->conn, auth->msg, + DBUS_TYPE_INVALID); + +done: + dbus_connection_unref(auth->conn); + + serv_adapter->pending_list = g_slist_remove(serv_adapter->pending_list, + auth); + g_free(auth); + + auth = next_pending(serv_adapter); + if (auth == NULL) + return; + + if (serv_adapter->adapter) + adapter_get_address(serv_adapter->adapter, &src); + else + bacpy(&src, BDADDR_ANY); + + btd_request_authorization(&src, &auth->dst, + auth->uuid, auth_cb, serv_adapter); +} + +static DBusMessage *request_authorization(DBusConnection *conn, + DBusMessage *msg, void *data) +{ + struct record_data *user_record; + struct service_adapter *serv_adapter = data; + sdp_record_t *record; + sdp_list_t *services; + const char *sender; + dbus_uint32_t handle; + const char *address; + struct pending_auth *auth; + char uuid_str[MAX_LEN_UUID_STR]; + uuid_t *uuid, *uuid128; + bdaddr_t src; + + if (dbus_message_get_args(msg, NULL, DBUS_TYPE_STRING, &address, + DBUS_TYPE_UINT32, &handle, + DBUS_TYPE_INVALID) == FALSE) + return NULL; + + sender = dbus_message_get_sender(msg); + if (find_pending_by_sender(serv_adapter, sender)) + return btd_error_does_not_exist(msg); + + user_record = find_record(serv_adapter, handle, sender); + if (!user_record) { + user_record = find_record(serv_adapter_any, handle, sender); + if (!user_record) + return btd_error_not_authorized(msg); + } + + record = sdp_record_find(user_record->handle); + if (record == NULL) + return btd_error_not_authorized(msg); + + if (sdp_get_service_classes(record, &services) < 0) { + sdp_record_free(record); + return btd_error_not_authorized(msg); + } + + if (services == NULL) + return btd_error_not_authorized(msg); + + uuid = services->data; + uuid128 = sdp_uuid_to_uuid128(uuid); + + sdp_list_free(services, bt_free); + + if (sdp_uuid2strn(uuid128, uuid_str, MAX_LEN_UUID_STR) < 0) { + bt_free(uuid128); + return btd_error_not_authorized(msg); + } + bt_free(uuid128); + + auth = g_new0(struct pending_auth, 1); + auth->msg = dbus_message_ref(msg); + auth->conn = dbus_connection_ref(connection); + auth->sender = user_record->sender; + memcpy(auth->uuid, uuid_str, MAX_LEN_UUID_STR); + str2ba(address, &auth->dst); + + serv_adapter->pending_list = g_slist_append(serv_adapter->pending_list, + auth); + + auth = next_pending(serv_adapter); + if (auth == NULL) + return btd_error_does_not_exist(msg); + + if (serv_adapter->adapter) + adapter_get_address(serv_adapter->adapter, &src); + else + bacpy(&src, BDADDR_ANY); + + if (btd_request_authorization(&src, &auth->dst, auth->uuid, auth_cb, + serv_adapter) < 0) { + serv_adapter->pending_list = g_slist_remove(serv_adapter->pending_list, + auth); + g_free(auth); + return btd_error_not_authorized(msg); + } + + return NULL; +} + +static DBusMessage *cancel_authorization(DBusConnection *conn, + DBusMessage *msg, void *data) +{ + DBusMessage *reply; + struct service_adapter *serv_adapter = data; + struct pending_auth *auth; + const gchar *sender; + bdaddr_t src; + + sender = dbus_message_get_sender(msg); + + auth = find_pending_by_sender(serv_adapter, sender); + if (auth == NULL) + return btd_error_does_not_exist(msg); + + if (serv_adapter->adapter) + adapter_get_address(serv_adapter->adapter, &src); + else + bacpy(&src, BDADDR_ANY); + + btd_cancel_authorization(&src, &auth->dst); + + reply = btd_error_not_authorized(auth->msg); + dbus_message_unref(auth->msg); + g_dbus_send_message(auth->conn, reply); + + dbus_connection_unref(auth->conn); + + serv_adapter->pending_list = g_slist_remove(serv_adapter->pending_list, + auth); + g_free(auth); + + auth = next_pending(serv_adapter); + if (auth == NULL) + goto done; + + if (serv_adapter->adapter) + adapter_get_address(serv_adapter->adapter, &src); + else + bacpy(&src, BDADDR_ANY); + + btd_request_authorization(&src, &auth->dst, + auth->uuid, auth_cb, serv_adapter); + +done: + return dbus_message_new_method_return(msg); +} + +static GDBusMethodTable service_methods[] = { + { "AddRecord", "s", "u", add_service_record }, + { "UpdateRecord", "us", "", update_service_record }, + { "RemoveRecord", "u", "", remove_service_record }, + { "RequestAuthorization","su", "", request_authorization, + G_DBUS_METHOD_FLAG_ASYNC}, + { "CancelAuthorization", "", "", cancel_authorization }, + { } +}; + +static void path_unregister(void *data) +{ + struct service_adapter *serv_adapter = data; + GSList *l, *next = NULL; + + for (l = serv_adapter->records; l != NULL; l = next) { + struct record_data *user_record = l->data; + + next = l->next; + + g_dbus_remove_watch(connection, user_record->listener_id); + exit_callback(connection, user_record); + } + + g_free(serv_adapter); +} + +static int register_interface(const char *path, struct btd_adapter *adapter) +{ + struct service_adapter *serv_adapter; + + DBG("path %s", path); + + serv_adapter = g_try_new0(struct service_adapter, 1); + if (serv_adapter == NULL) + return -ENOMEM; + + serv_adapter->adapter = adapter; + serv_adapter->pending_list = NULL; + + if (g_dbus_register_interface(connection, path, SERVICE_INTERFACE, + service_methods, NULL, NULL, serv_adapter, + path_unregister) == FALSE) { + error("D-Bus failed to register %s interface", + SERVICE_INTERFACE); + g_free(serv_adapter); + return -EIO; + } + + DBG("Registered interface %s on path %s", SERVICE_INTERFACE, path); + + if (serv_adapter->adapter == NULL) + serv_adapter_any = serv_adapter; + + return 0; +} + +static void unregister_interface(const char *path) +{ + DBG("path %s", path); + + g_dbus_unregister_interface(connection, path, SERVICE_INTERFACE); +} + +static int service_probe(struct btd_adapter *adapter) +{ + register_interface(adapter_get_path(adapter), adapter); + + return 0; +} + +static void service_remove(struct btd_adapter *adapter) +{ + unregister_interface(adapter_get_path(adapter)); +} + +static struct btd_adapter_driver service_driver = { + .name = "service", + .probe = service_probe, + .remove = service_remove, +}; + +static const char *any_path; + +static int service_init(void) +{ + int err; + + connection = dbus_bus_get(DBUS_BUS_SYSTEM, NULL); + if (connection == NULL) + return -EIO; + + any_path = btd_adapter_any_request_path(); + if (any_path != NULL) { + if (register_interface(any_path, NULL) < 0) { + btd_adapter_any_release_path(); + any_path = NULL; + } + } + + err = btd_register_adapter_driver(&service_driver); + if (err < 0) { + dbus_connection_unref(connection); + return err; + } + + return 0; +} + +static void service_exit(void) +{ + btd_unregister_adapter_driver(&service_driver); + + if (any_path != NULL) { + unregister_interface(any_path); + + btd_adapter_any_release_path(); + any_path = NULL; + } + + dbus_connection_unref(connection); +} + +BLUETOOTH_PLUGIN_DEFINE(service, VERSION, + BLUETOOTH_PLUGIN_PRIORITY_HIGH, service_init, service_exit) diff --git a/plugins/storage.c b/plugins/storage.c new file mode 100644 index 0000000..04a02c7 --- /dev/null +++ b/plugins/storage.c @@ -0,0 +1,43 @@ +/* + * + * BlueZ - Bluetooth protocol stack for Linux + * + * Copyright (C) 2004-2010 Marcel Holtmann <marcel@holtmann.org> + * + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + * + */ + +#ifdef HAVE_CONFIG_H +#include <config.h> +#endif + +#include <bluetooth/bluetooth.h> + +#include "plugin.h" +#include "log.h" + +static int storage_init(void) +{ + return 0; +} + +static void storage_exit(void) +{ +} + +BLUETOOTH_PLUGIN_DEFINE(storage, VERSION, + BLUETOOTH_PLUGIN_PRIORITY_DEFAULT, storage_init, storage_exit) |