From d911528cfb367fac34a5764ad6bce339a12f56d0 Mon Sep 17 00:00:00 2001 From: Charles Kerr Date: Sun, 6 Mar 2016 23:00:42 -0600 Subject: add ADB server/client + tests --- src/main.cpp | 11 +++++++++++ 1 file changed, 11 insertions(+) (limited to 'src/main.cpp') diff --git a/src/main.cpp b/src/main.cpp index 86bdeb3..0c56bd6 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -17,6 +17,7 @@ * Charles Kerr */ +#include #include #include @@ -54,6 +55,16 @@ main(int /*argc*/, char** /*argv*/) exporters.push_back(exporter); } + // We need the ADBD handler running, + // even though it doesn't have an indicator component yet + static constexpr char const * ADB_SOCKET_PATH {"/dev/socket/adb"}; + GAdbdClient adbd_client{ADB_SOCKET_PATH}; + adbd_client.on_pk_request().connect([](const AdbdClient::PKRequest& req){ + g_debug("%s got pk_request [%s]", G_STRLOC, req.public_key.c_str()); + // FIXME: actually decide what response to send back + req.respond(AdbdClient::PKResponse::ALLOW); + }); + g_main_loop_run(loop); // cleanup -- cgit v1.2.3 From 68b671ce04b8b5d6b37025ad093c73a3e14d4d64 Mon Sep 17 00:00:00 2001 From: Charles Kerr Date: Tue, 8 Mar 2016 22:04:56 -0600 Subject: add fingerprint snap decisions; test with notification dbusmock --- CMakeLists.txt | 13 +-- cmake/FindGMock.cmake | 10 -- debian/control | 5 + src/main.cpp | 9 +- src/usb-snap.cpp | 254 ++++++++++++++++++++++++++++++++++++++++++++++++ src/usb-snap.h | 39 ++++++++ tests/CMakeLists.txt | 56 ++++++++--- tests/dbus-types.h | 47 +++++++++ tests/usb-snap-test.cpp | 216 ++++++++++++++++++++++++++++++++++++++++ 9 files changed, 611 insertions(+), 38 deletions(-) delete mode 100644 cmake/FindGMock.cmake create mode 100644 src/usb-snap.cpp create mode 100644 src/usb-snap.h create mode 100644 tests/dbus-types.h create mode 100644 tests/usb-snap-test.cpp (limited to 'src/main.cpp') diff --git a/CMakeLists.txt b/CMakeLists.txt index 9fa4d10..8b8ef65 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1,5 +1,5 @@ -project (indicator-display) -cmake_minimum_required (VERSION 2.8.9) +project(indicator-display LANGUAGES C CXX) +cmake_minimum_required(VERSION 2.8.9) list (APPEND CMAKE_MODULE_PATH ${CMAKE_SOURCE_DIR}/cmake) @@ -15,9 +15,6 @@ set (SERVICE_EXEC "${PACKAGE}-service") option (enable_tests "Build the package's automatic tests." ON) option (enable_lcov "Generate lcov code coverage reports." ON) -set(THREADS_PREFER_PTHREAD_FLAG ON) -find_package(Threads REQUIRED) - ## ## GNU standard paths ## @@ -33,9 +30,10 @@ set (CMAKE_INSTALL_FULL_PKGLIBEXECDIR "${CMAKE_INSTALL_FULL_LIBEXECDIR}/${CMAKE_ ## Check for prerequisites ## +set(THREADS_PREFER_PTHREAD_FLAG ON) +find_package(Threads REQUIRED) find_package (PkgConfig REQUIRED) -include (FindPkgConfig) pkg_check_modules (SERVICE_DEPS REQUIRED gio-unix-2.0>=2.36 glib-2.0>=2.36) @@ -58,9 +56,6 @@ set (CXX_WARNING_ARGS "${CXX_WARNING_ARGS} -Wno-missing-field-initializers") # G # testing & coverage if (${enable_tests}) - set (GTEST_SOURCE_DIR /usr/src/gtest/src) - set (GTEST_INCLUDE_DIR ${GTEST_SOURCE_DIR}/..) - set (GTEST_LIBS -lpthread) enable_testing () if (${enable_lcov}) include(GCov) diff --git a/cmake/FindGMock.cmake b/cmake/FindGMock.cmake deleted file mode 100644 index 74a1c15..0000000 --- a/cmake/FindGMock.cmake +++ /dev/null @@ -1,10 +0,0 @@ -# Build with system gmock and embedded gtest -set (GMOCK_INCLUDE_DIRS "/usr/include/gmock/include" CACHE PATH "gmock source include directory") -set (GMOCK_SOURCE_DIR "/usr/src/gmock" CACHE PATH "gmock source directory") -set (GTEST_INCLUDE_DIRS "${GMOCK_SOURCE_DIR}/gtest/include" CACHE PATH "gtest source include directory") - -add_subdirectory(${GMOCK_SOURCE_DIR} "${CMAKE_CURRENT_BINARY_DIR}/gmock") - -set(GTEST_LIBRARIES gtest) -set(GTEST_MAIN_LIBRARIES gtest_main) -set(GMOCK_LIBRARIES gmock gmock_main) diff --git a/debian/control b/debian/control index 4f05f74..5088af5 100644 --- a/debian/control +++ b/debian/control @@ -3,12 +3,17 @@ Section: misc Priority: optional Maintainer: Charles Kerr Build-Depends: cmake, + cmake-extras (>= 0.4), dbus, libglib2.0-dev (>= 2.36), libproperties-cpp-dev, # for coverage reports lcov, # for tests + qt5-default, + qtbase5-dev, + libqtdbusmock1-dev (>= 0.4), + libqtdbustest1-dev, cppcheck, libgtest-dev, google-mock (>= 1.6.0+svn437), diff --git a/src/main.cpp b/src/main.cpp index 0c56bd6..62eca62 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -20,6 +20,7 @@ #include #include #include +#include #include // bindtextdomain() #include @@ -60,9 +61,11 @@ main(int /*argc*/, char** /*argv*/) static constexpr char const * ADB_SOCKET_PATH {"/dev/socket/adb"}; GAdbdClient adbd_client{ADB_SOCKET_PATH}; adbd_client.on_pk_request().connect([](const AdbdClient::PKRequest& req){ - g_debug("%s got pk_request [%s]", G_STRLOC, req.public_key.c_str()); - // FIXME: actually decide what response to send back - req.respond(AdbdClient::PKResponse::ALLOW); + auto snap = new UsbSnap(req.public_key); + snap->on_user_response().connect([req,snap](AdbdClient::PKResponse response, bool /*FIXME: remember_choice*/){ + req.respond(response); + g_idle_add([](gpointer gsnap){delete static_cast(gsnap); return G_SOURCE_REMOVE;}, snap); // delete-later + }); }); g_main_loop_run(loop); diff --git a/src/usb-snap.cpp b/src/usb-snap.cpp new file mode 100644 index 0000000..40f02a2 --- /dev/null +++ b/src/usb-snap.cpp @@ -0,0 +1,254 @@ +/* + * Copyright 2016 Canonical Ltd. + * + * This program is free software: you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 3, as published + * by the Free Software Foundation. + * + * This program is distributed in the hope that it will be useful, but + * WITHOUT ANY WARRANTY; without even the implied warranties of + * MERCHANTABILITY, SATISFACTORY QUALITY, 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, see . + * + * Authors: + * Charles Kerr + */ + +#include + +#include +#include + +/*** +**** +***/ + +class UsbSnap::Impl +{ +public: + + explicit Impl(const std::string& fingerprint): + m_fingerprint{fingerprint}, + m_cancellable{g_cancellable_new()} + { + g_bus_get (G_BUS_TYPE_SESSION, m_cancellable, on_bus_ready_static, this); + } + + ~Impl() + { + g_cancellable_cancel(m_cancellable); + g_clear_object(&m_cancellable); + + if (m_subscription_id != 0) + g_dbus_connection_signal_unsubscribe (m_bus, m_subscription_id); + + if (m_notification_id != 0) { + GError* error {}; + g_dbus_connection_call_sync(m_bus, + BUS_NAME, + OBJECT_PATH, + IFACE_NAME, + "CloseNotification", + g_variant_new("(u)", m_notification_id), + nullptr, + G_DBUS_CALL_FLAGS_NONE, + -1, + nullptr, + &error); + if (error != nullptr) { + g_warning("Error closing notification: %s", error->message); + g_clear_error(&error); + } + } + + g_clear_object(&m_bus); + } + + core::Signal& on_user_response() + { + return m_on_user_response; + } + +private: + + static void on_bus_ready_static(GObject* /*source*/, GAsyncResult* res, gpointer gself) + { + GError* error {}; + auto bus = g_bus_get_finish (res, &error); + if (error != nullptr) { + if (!g_error_matches(error, G_IO_ERROR, G_IO_ERROR_CANCELLED)) + g_warning("UsbSnap: Error getting session bus: %s", error->message); + g_clear_error(&error); + } else { + static_cast(gself)->on_bus_ready(bus); + } + g_clear_object(&bus); + } + + void on_bus_ready(GDBusConnection* bus) + { + m_bus = G_DBUS_CONNECTION(g_object_ref(G_OBJECT(bus))); + + auto body = g_strdup_printf(_("The computer's RSA key fingerprint is: %s"), m_fingerprint.c_str()); + + GVariantBuilder actions_builder; + g_variant_builder_init(&actions_builder, G_VARIANT_TYPE_STRING_ARRAY); + g_variant_builder_add(&actions_builder, "s", ACTION_ALLOW); + g_variant_builder_add(&actions_builder, "s", _("Allow")); + g_variant_builder_add(&actions_builder, "s", ACTION_DENY); + g_variant_builder_add(&actions_builder, "s", _("Deny")); + + GVariantBuilder hints_builder; + g_variant_builder_init(&hints_builder, G_VARIANT_TYPE_VARDICT); + g_variant_builder_add(&hints_builder, "{sv}", "x-canonical-non-shaped-icon", g_variant_new_string("true")); + g_variant_builder_add(&hints_builder, "{sv}", "x-canonical-snap-decisions", g_variant_new_string("true")); + g_variant_builder_add(&hints_builder, "{sv}", "x-canonical-private-affirmative-tint", g_variant_new_string("true")); + + auto args = g_variant_new("(susssasa{sv}i)", + "", + uint32_t(0), + "computer-symbolic", + _("Allow USB Debugging?"), + body, + &actions_builder, + &hints_builder, + -1); + g_dbus_connection_call(m_bus, + BUS_NAME, + OBJECT_PATH, + IFACE_NAME, + "Notify", + args, + G_VARIANT_TYPE("(u)"), + G_DBUS_CALL_FLAGS_NONE, + -1, // timeout + m_cancellable, + on_notify_reply_static, + this); + + g_clear_pointer(&body, g_free); + } + + static void on_notify_reply_static(GObject* obus, GAsyncResult* res, gpointer gself) + { + GError* error {}; + auto reply = g_dbus_connection_call_finish (G_DBUS_CONNECTION(obus), res, &error); + if (error != nullptr) { + if (!g_error_matches(error, G_IO_ERROR, G_IO_ERROR_CANCELLED)) + g_warning("UsbSnap: Error calling Notify: %s", error->message); + g_clear_error(&error); + } else { + uint32_t id {}; + g_variant_get(reply, "(u)", &id); + static_cast(gself)->on_notify_reply(id); + } + g_clear_pointer(&reply, g_variant_unref); + } + + void on_notify_reply(uint32_t id) + { + m_notification_id = id; + + m_subscription_id = g_dbus_connection_signal_subscribe(m_bus, + BUS_NAME, + IFACE_NAME, + nullptr, + OBJECT_PATH, + nullptr, + G_DBUS_SIGNAL_FLAGS_NONE, + on_notification_signal_static, + this, + nullptr); + } + + static void on_notification_signal_static(GDBusConnection* /*connection*/, + const gchar* /*sender_name*/, + const gchar* object_path, + const gchar* interface_name, + const gchar* signal_name, + GVariant* parameters, + gpointer gself) + { + g_return_if_fail(!g_strcmp0(object_path, OBJECT_PATH)); + g_return_if_fail(!g_strcmp0(interface_name, IFACE_NAME)); + + auto self = static_cast(gself); + + if (!g_strcmp0(signal_name, "ActionInvoked")) + { + uint32_t id {}; + const char* action_name {}; + g_variant_get(parameters, "(u&s)", &id, &action_name); + if (id == self->m_notification_id) + self->on_action_invoked(action_name); + } + else if (!g_strcmp0(signal_name, "NotificationClosed")) + { + uint32_t id {}; + uint32_t close_reason {}; + g_variant_get(parameters, "(uu)", &id, &close_reason); + if (id == self->m_notification_id) + self->on_notification_closed(close_reason); + } + } + + void on_action_invoked(const char* action_name) + { + const auto response = !g_strcmp0(action_name, ACTION_ALLOW) + ? AdbdClient::PKResponse::ALLOW + : AdbdClient::PKResponse::DENY; + + // FIXME: the current default is to cover the most common use case. + // We need to get the notification ui's checkbox working ASAP so + // that the user can provide this flag + const bool remember_this_choice = response == AdbdClient::PKResponse::ALLOW; + + m_on_user_response(response, remember_this_choice); + } + + void on_notification_closed(uint32_t close_reason) + { + if (close_reason == CloseReason::EXPIRED) + m_on_user_response(AdbdClient::PKResponse::DENY, false); + + m_notification_id = 0; + } + + static constexpr char const * ACTION_ALLOW{"allow"}; + static constexpr char const * ACTION_DENY{"deny"}; + + static constexpr char const * BUS_NAME {"org.freedesktop.Notifications" }; + static constexpr char const * IFACE_NAME {"org.freedesktop.Notifications" }; + static constexpr char const * OBJECT_PATH {"/org/freedesktop/Notifications" }; + enum CloseReason { EXPIRED=1, DISMISSED=2, API=3, UNDEFINED=4 }; + + const std::string m_fingerprint; + core::Signal m_on_user_response; + GCancellable* m_cancellable {}; + GDBusConnection* m_bus {}; + uint32_t m_notification_id {}; + unsigned int m_subscription_id {}; +}; + +/*** +**** +***/ + +UsbSnap::UsbSnap(const std::string& public_key): + impl{new Impl{public_key}} +{ +} + +UsbSnap::~UsbSnap() +{ +} + +core::Signal& +UsbSnap::on_user_response() +{ + return impl->on_user_response(); +} + diff --git a/src/usb-snap.h b/src/usb-snap.h new file mode 100644 index 0000000..6ad3a4c --- /dev/null +++ b/src/usb-snap.h @@ -0,0 +1,39 @@ +/* + * Copyright 2016 Canonical Ltd. + * + * This program is free software: you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 3, as published + * by the Free Software Foundation. + * + * This program is distributed in the hope that it will be useful, but + * WITHOUT ANY WARRANTY; without even the implied warranties of + * MERCHANTABILITY, SATISFACTORY QUALITY, 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, see . + * + * Authors: + * Charles Kerr + */ + +#pragma once + +#include // AdbdClient::PKResponse + +#include + +#include +#include + +class UsbSnap +{ +public: + explicit UsbSnap(const std::string& public_key); + ~UsbSnap(); + core::Signal& on_user_response(); + +protected: + class Impl; + std::unique_ptr impl; +}; diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt index 706e35b..1fbe407 100644 --- a/tests/CMakeLists.txt +++ b/tests/CMakeLists.txt @@ -1,33 +1,57 @@ -include(FindGMock) -include_directories(${CMAKE_CURRENT_SOURCE_DIR}) -include_directories(${GMOCK_INCLUDE_DIRS}) -include_directories(${GTEST_INCLUDE_DIRS}) + +set(CMAKE_AUTOMOC ON) + +find_package(GMock REQUIRED) +find_package(Qt5Core REQUIRED) +find_package(Qt5Test REQUIRED) +find_package(Qt5DBus COMPONENTS Qt5DBusMacros REQUIRED) + +pkg_check_modules(TEST_DEPS + libqtdbustest-1 REQUIRED + libqtdbusmock-1 REQUIRED +) + +include_directories( + ${CMAKE_SOURCE_DIR} + ${CMAKE_CURRENT_BINARY_DIR} + ${CMAKE_CURRENT_SOURCE_DIR} +) +include_directories(SYSTEM + ${DBUSTEST_INCLUDE_DIRS} + ${TEST_DEPS_INCLUDE_DIRS} + ${GTEST_INCLUDE_DIRS} + ${GMOCK_INCLUDE_DIRS} +) set(CTEST_ENVIRONMENT "${CTEST_ENVIRONMENT};G_MESSAGES_DEBUG=all") if ("${CMAKE_CXX_COMPILER_ID}" STREQUAL "Clang") # turn off the warnings that break Google Test - set (CXX_WARNING_ARGS "${CXX_WARNING_ARGS} -Wno-global-constructors -Wno-weak-vtables -Wno-undef -Wno-c++98-compat-pedantic -Wno-missing-noreturn -Wno-used-but-marked-unused -Wno-padded -Wno-deprecated -Wno-sign-compare -Wno-shift-sign-overflow") + set (CXX_WARNING_ARGS "${CXX_WARNING_ARGS} -Wno-global-constructors -Wno-weak-vtables") endif() -SET (CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11 -g -pthread ${CXX_WARNING_ARGS}") - -# look for headers in our src dir, and also in the directories where we autogenerate files... -include_directories (${CMAKE_SOURCE_DIR}/src) -include_directories (${CMAKE_CURRENT_BINARY_DIR}) -include_directories (${DBUSTEST_INCLUDE_DIRS}) +SET (CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -fPIC -std=c++11 -g ${CXX_WARNING_ARGS}") function(add_test_by_name name) set (TEST_NAME ${name}) add_executable (${TEST_NAME} ${TEST_NAME}.cpp) add_test (${TEST_NAME} ${TEST_NAME}) - set_property(TEST ${TEST_NAME} PROPERTY ENVIRONMENT "${CTEST_ENVIRONMENT}") - - add_dependencies (${TEST_NAME} libindicatordisplayservice) - target_link_libraries (${TEST_NAME} indicatordisplayservice ${SERVICE_DEPS_LIBRARIES} ${GTEST_LIBRARIES} ${GMOCK_LIBRARIES}) + set_property(TEST ${TEST_NAME} PROPERTY ENVIRONMENT "${CTEST_ENVIRONMENT}") + add_dependencies (${TEST_NAME} indicatordisplayservice) + target_link_libraries (${TEST_NAME} indicatordisplayservice ${SERVICE_DEPS_LIBRARIES} ${TEST_DEPS_LIBRARIES} ${GTEST_LIBRARIES} ${GMOCK_LIBRARIES}) endfunction() add_test_by_name(rotation-lock-test) add_test_by_name(adbd-client-test) -add_test (cppcheck cppcheck --enable=all -USCHEMA_DIR --error-exitcode=2 --inline-suppr -I${CMAKE_SOURCE_DIR} ${CMAKE_SOURCE_DIR}/src ${CMAKE_SOURCE_DIR}/tests) +function(add_qt_test_by_name name) + set (TEST_NAME ${name}) + add_executable (${TEST_NAME} ${TEST_NAME}.cpp qmain.cpp) + add_test (${TEST_NAME} ${TEST_NAME}) + set_property(TEST ${TEST_NAME} PROPERTY ENVIRONMENT "${CTEST_ENVIRONMENT}") + add_dependencies (${TEST_NAME} indicatordisplayservice) + target_link_libraries (${TEST_NAME} indicatordisplayservice ${SERVICE_DEPS_LIBRARIES} Qt5::Core Qt5::Test Qt5::DBus ${TEST_DEPS_LIBRARIES} ${GTEST_LIBRARIES} ${GMOCK_LIBRARIES}) +endfunction() +add_qt_test_by_name(usb-snap-test) + +add_test(cppcheck cppcheck --enable=all -USCHEMA_DIR --error-exitcode=2 --inline-suppr -I${CMAKE_SOURCE_DIR} ${CMAKE_SOURCE_DIR}/src ${CMAKE_SOURCE_DIR}/tests) diff --git a/tests/dbus-types.h b/tests/dbus-types.h new file mode 100644 index 0000000..c2dfb81 --- /dev/null +++ b/tests/dbus-types.h @@ -0,0 +1,47 @@ +/* + * Copyright (C) 2013-2016 Canonical, Ltd. + * + * This program is free software: you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 3, as published + * by the Free Software Foundation. + * + * This program is distributed in the hope that it will be useful, but + * WITHOUT ANY WARRANTY; without even the implied warranties of + * MERCHANTABILITY, SATISFACTORY QUALITY, 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, see . + * + * Author: Pete Woods + */ + +#pragma once + +#include +#include +#include +#include + +typedef QMap QVariantDictMap; +Q_DECLARE_METATYPE(QVariantDictMap) + +typedef QMap QStringMap; +Q_DECLARE_METATYPE(QStringMap) + +namespace DBusTypes +{ + inline void registerMetaTypes() + { + qRegisterMetaType("QVariantDictMap"); + qRegisterMetaType("QStringMap"); + + qDBusRegisterMetaType(); + qDBusRegisterMetaType(); + } + static constexpr char const* NOTIFY_DBUS_NAME = "org.freedesktop.Notifications"; + + static constexpr char const* NOTIFY_DBUS_INTERFACE = "org.freedesktop.Notifications"; + + static constexpr char const* NOTIFY_DBUS_PATH = "/org/freedesktop/Notifications"; +} diff --git a/tests/usb-snap-test.cpp b/tests/usb-snap-test.cpp new file mode 100644 index 0000000..309980a --- /dev/null +++ b/tests/usb-snap-test.cpp @@ -0,0 +1,216 @@ +/* + * Copyright 2016 Canonical Ltd. + * + * This program is free software: you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 3, as published + * by the Free Software Foundation. + * + * This program is distributed in the hope that it will be useful, but + * WITHOUT ANY WARRANTY; without even the implied warranties of + * MERCHANTABILITY, SATISFACTORY QUALITY, 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, see . + * + * Authors: + * Charles Kerr + */ + +#define QT_NO_KEYWORDS +#include +#include + +#include + +#include + +#include +#include +#include + +#include + +#include + +using namespace QtDBusTest; +using namespace QtDBusMock; + +inline QString qVariantToString(const QVariant& variant) { + QString output; + QDebug dbg(&output); + dbg << variant; + return output; +} + +inline void PrintTo(const QVariant& variant, std::ostream* os) { + QString output; + QDebug dbg(&output); + dbg << variant; + + *os << "QVariant(" << output.toStdString() << ")"; +} + +inline void PrintTo(const QString& s, std::ostream* os) { + *os << "\"" << s.toStdString() << "\""; +} + +inline void PrintTo(const QStringList& list, std::ostream* os) { + QString output; + QDebug dbg(&output); + dbg << list; + + *os << "QStringList(" << output.toStdString() << ")"; +} + +inline void PrintTo(const QList& list, std::ostream* os) { + QString output; + for (const auto& path: list) + { + output.append("\"" + path.path() + "\","); + } + + *os << "QList(" << output.toStdString() << ")"; +} + +#define WAIT_FOR_SIGNALS(signalSpy, signalsExpected)\ +{\ + while (signalSpy.size() < signalsExpected)\ + {\ + ASSERT_TRUE(signalSpy.wait());\ + }\ + ASSERT_EQ(signalsExpected, signalSpy.size());\ +} + +class UsbSnapFixture: public GlibFixture +{ + using super = GlibFixture; + +public: + + UsbSnapFixture(): + dbusMock{dbusTestRunner} + { + DBusTypes::registerMetaTypes(); + + dbusTestRunner.startServices(); + } + + ~UsbSnapFixture() =default; + +protected: + + bool qDBusArgumentToMap(QVariant const& variant, QVariantMap& map) + { + if (variant.canConvert()) + { + QDBusArgument value(variant.value()); + if (value.currentType() == QDBusArgument::MapType) + { + value >> map; + return true; + } + } + return false; + } + + void SetUp() override + { + super::SetUp(); + + dbusMock.registerNotificationDaemon(); + dbusTestRunner.startServices(); + } + + OrgFreedesktopDBusMockInterface& notificationsMockInterface() + { + return dbusMock.mockInterface("org.freedesktop.Notifications", + "/org/freedesktop/Notifications", + "org.freedesktop.Notifications", + QDBusConnection::SessionBus); + } + + QtDBusTest::DBusTestRunner dbusTestRunner; + QtDBusMock::DBusMock dbusMock; + QtDBusTest::DBusServicePtr indicator; +}; + +TEST_F(UsbSnapFixture, TestRoundTrip) +{ + struct { + const char* fingerprint; + const char* action_to_invoke; + const AdbdClient::PKResponse expected_response; + } tests[] = { + { "Fingerprint", "allow", AdbdClient::PKResponse::ALLOW }, + { "Fingerprint", "deny", AdbdClient::PKResponse::DENY } + }; + + uint32_t next_id = 1; + for(const auto& test : tests) + { + // Minor wart: we don't have a way of getting the fdo notification id + // from dbusmock so instead we copy its (simple) id generation here + const auto id = next_id++; + + QSignalSpy notificationsSpy( + ¬ificationsMockInterface(), + SIGNAL(MethodCalled(const QString &, const QVariantList &))); + + // start up a UsbSnap to ask about a fingerprint + auto snap = std::make_shared(test.fingerprint); + AdbdClient::PKResponse user_response {}; + bool user_response_set = false; + snap->on_user_response().connect([&user_response,&user_response_set](AdbdClient::PKResponse response, bool /*remember*/){ + user_response = response; + user_response_set = true; + }); + + // test that UsbSnap creates a fdo notification + WAIT_FOR_SIGNALS(notificationsSpy, 1); + { + QVariantList const& call(notificationsSpy.at(0)); + EXPECT_EQ("Notify", call.at(0)); + + QVariantList const& args(call.at(1).toList()); + ASSERT_EQ(8, args.size()); + EXPECT_EQ("", args.at(0)); // app name + EXPECT_EQ(0, args.at(1)); // replaces-id + EXPECT_EQ("computer-symbolic", args.at(2)); // icon name + EXPECT_EQ("Allow USB Debugging?", args.at(3)); // summary + EXPECT_EQ(QString::fromUtf8("The computer's RSA key fingerprint is: ") + test.fingerprint, args.at(4)); // body + EXPECT_EQ(QStringList({"allow", "Allow", "deny", "Deny"}), args.at(5)); // actions + EXPECT_EQ(-1, args.at(7)); + + QVariantMap hints; + ASSERT_TRUE(qDBusArgumentToMap(args.at(6), hints)); + ASSERT_EQ(3, hints.size()); + ASSERT_TRUE(hints.contains("x-canonical-private-affirmative-tint")); + ASSERT_TRUE(hints.contains("x-canonical-non-shaped-icon")); + ASSERT_TRUE(hints.contains("x-canonical-snap-decisions")); + } + notificationsSpy.clear(); + + // fake a user interaction with the fdo notification + notificationsMockInterface().EmitSignal( + DBusTypes::NOTIFY_DBUS_INTERFACE, + "ActionInvoked", + "us", + QVariantList() << id << test.action_to_invoke); + + // test that UsbSnap emits on_user_response() as a result + wait_for([&user_response_set](){return user_response_set;}); + EXPECT_TRUE(user_response_set); + ASSERT_EQ(test.expected_response, user_response); + + // confirm that the snap dtor cleans up the notification + snap.reset(); + WAIT_FOR_SIGNALS(notificationsSpy, 1); + { + QVariantList const& call(notificationsSpy.at(0)); + EXPECT_EQ("CloseNotification", call.at(0)); + QVariantList const& args(call.at(1).toList()); + EXPECT_EQ(id, args.at(0)); + } + } +} -- cgit v1.2.3 From 13a0b901492901638a7abc90bb2935a9c0387f75 Mon Sep 17 00:00:00 2001 From: Charles Kerr Date: Wed, 9 Mar 2016 17:19:23 -0600 Subject: add human-readable fingerprint extraction from the adb public keys --- src/adbd-client.cpp | 39 +++++++++++++++++++++++++++++++++++++++ src/adbd-client.h | 1 + src/main.cpp | 2 +- src/usb-snap.cpp | 4 ++-- 4 files changed, 43 insertions(+), 3 deletions(-) (limited to 'src/main.cpp') diff --git a/src/adbd-client.cpp b/src/adbd-client.cpp index 38f202f..edd403c 100644 --- a/src/adbd-client.cpp +++ b/src/adbd-client.cpp @@ -22,6 +22,9 @@ #include #include +#include +#include +#include #include #include #include @@ -89,6 +92,7 @@ private: auto self = data->self; struct PKRequest req; req.public_key = data->public_key; + req.fingerprint = get_fingerprint(req.public_key); req.respond = [self](PKResponse response){self->on_public_key_response(response);}; self->m_on_pk_request(req); } @@ -219,6 +223,37 @@ private: } } + static std::string get_fingerprint(const std::string& public_key) + { + // The first token is base64-encoded data, so cut on the first whitespace + const std::string base64 ( + public_key.begin(), + std::find_if( + public_key.begin(), public_key.end(), + [](const std::string::value_type& ch){return std::isspace(ch);} + ) + ); + + gsize digest_len {}; + auto digest = g_base64_decode(base64.c_str(), &digest_len); + + auto checksum = g_compute_checksum_for_data(G_CHECKSUM_MD5, digest, digest_len); + const gsize checksum_len = checksum ? strlen(checksum) : 0; + + // insert ':' between character pairs; eg "ff27b5f3" --> "ff:27:b5:f3" + std::string fingerprint; + for (gsize i=0; i respond; }; diff --git a/src/main.cpp b/src/main.cpp index 62eca62..151b642 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -61,7 +61,7 @@ main(int /*argc*/, char** /*argv*/) static constexpr char const * ADB_SOCKET_PATH {"/dev/socket/adb"}; GAdbdClient adbd_client{ADB_SOCKET_PATH}; adbd_client.on_pk_request().connect([](const AdbdClient::PKRequest& req){ - auto snap = new UsbSnap(req.public_key); + auto snap = new UsbSnap(req.fingerprint); snap->on_user_response().connect([req,snap](AdbdClient::PKResponse response, bool /*FIXME: remember_choice*/){ req.respond(response); g_idle_add([](gpointer gsnap){delete static_cast(gsnap); return G_SOURCE_REMOVE;}, snap); // delete-later diff --git a/src/usb-snap.cpp b/src/usb-snap.cpp index 40f02a2..87f4673 100644 --- a/src/usb-snap.cpp +++ b/src/usb-snap.cpp @@ -217,8 +217,8 @@ private: m_notification_id = 0; } - static constexpr char const * ACTION_ALLOW{"allow"}; - static constexpr char const * ACTION_DENY{"deny"}; + static constexpr char const * ACTION_ALLOW {"allow"}; + static constexpr char const * ACTION_DENY {"deny"}; static constexpr char const * BUS_NAME {"org.freedesktop.Notifications" }; static constexpr char const * IFACE_NAME {"org.freedesktop.Notifications" }; -- cgit v1.2.3 From d8ef8e68805ab7f53258427c79ee5aaafec916ba Mon Sep 17 00:00:00 2001 From: Charles Kerr Date: Thu, 10 Mar 2016 17:09:59 -0600 Subject: add UsbManager --- src/CMakeLists.txt | 1 + src/main.cpp | 14 +-- src/usb-manager.cpp | 109 +++++++++++++++++++ src/usb-manager.h | 34 ++++++ tests/CMakeLists.txt | 1 + tests/integration/CMakeLists.txt | 24 +++++ tests/integration/usb-manager-test.cpp | 186 +++++++++++++++++++++++++++++++++ tests/unit/adbd-client-test.cpp | 22 ++-- tests/unit/usb-snap-test.cpp | 38 +------ tests/utils/gtest-qt-print-helpers.h | 45 ++++++++ 10 files changed, 416 insertions(+), 58 deletions(-) create mode 100644 src/usb-manager.cpp create mode 100644 src/usb-manager.h create mode 100644 tests/integration/CMakeLists.txt create mode 100644 tests/integration/usb-manager-test.cpp create mode 100644 tests/utils/gtest-qt-print-helpers.h (limited to 'src/main.cpp') diff --git a/src/CMakeLists.txt b/src/CMakeLists.txt index 6cfda91..d0ab901 100644 --- a/src/CMakeLists.txt +++ b/src/CMakeLists.txt @@ -10,6 +10,7 @@ add_library( exporter.cpp indicator.cpp rotation-lock.cpp + usb-manager.cpp usb-snap.cpp ) diff --git a/src/main.cpp b/src/main.cpp index 151b642..eb1bb2c 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -17,10 +17,9 @@ * Charles Kerr */ -#include #include #include -#include +#include #include // bindtextdomain() #include @@ -59,15 +58,10 @@ main(int /*argc*/, char** /*argv*/) // We need the ADBD handler running, // even though it doesn't have an indicator component yet static constexpr char const * ADB_SOCKET_PATH {"/dev/socket/adb"}; - GAdbdClient adbd_client{ADB_SOCKET_PATH}; - adbd_client.on_pk_request().connect([](const AdbdClient::PKRequest& req){ - auto snap = new UsbSnap(req.fingerprint); - snap->on_user_response().connect([req,snap](AdbdClient::PKResponse response, bool /*FIXME: remember_choice*/){ - req.respond(response); - g_idle_add([](gpointer gsnap){delete static_cast(gsnap); return G_SOURCE_REMOVE;}, snap); // delete-later - }); - }); + static constexpr char const * PUBLIC_KEYS_FILENAME {"/data/misc/adb/adb_keys"}; + UsbManager usb_manager {ADB_SOCKET_PATH, PUBLIC_KEYS_FILENAME}; + // let's go! g_main_loop_run(loop); // cleanup diff --git a/src/usb-manager.cpp b/src/usb-manager.cpp new file mode 100644 index 0000000..6b40cea --- /dev/null +++ b/src/usb-manager.cpp @@ -0,0 +1,109 @@ +/* + * Copyright 2016 Canonical Ltd. + * + * This program is free software: you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 3, as published + * by the Free Software Foundation. + * + * This program is distributed in the hope that it will be useful, but + * WITHOUT ANY WARRANTY; without even the implied warranties of + * MERCHANTABILITY, SATISFACTORY QUALITY, 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, see . + * + * Authors: + * Charles Kerr + */ + +#include +#include +#include + +#include + +#include +#include +#include +#include + +class UsbManager::Impl +{ +public: + + explicit Impl( + const std::string& socket_path, + const std::string& public_keys_filename + ): + m_adbd_client{std::make_shared(socket_path)}, + m_public_keys_filename{public_keys_filename} + { + m_adbd_client->on_pk_request().connect([this](const AdbdClient::PKRequest& req){ + auto snap = new UsbSnap(req.fingerprint); + snap->on_user_response().connect([this,req,snap](AdbdClient::PKResponse response, bool /*FIXME: remember_choice*/){ + req.respond(response); + if (response == AdbdClient::PKResponse::ALLOW) + write_public_key(req.public_key); + + // delete later + g_idle_add([](gpointer gsnap){delete static_cast(gsnap); return G_SOURCE_REMOVE;}, snap); + }); + }); + } + + ~Impl() + { + } + +private: + + void write_public_key(const std::string& public_key) + { + // confirm the directory exists + auto dirname = g_path_get_dirname(m_public_keys_filename.c_str()); + const auto dir_exists = g_file_test(dirname, G_FILE_TEST_IS_DIR); + if (!dir_exists) + g_warning("ADB data directory '%s' does not exist", dirname); + g_clear_pointer(&dirname, g_free); + if (!dir_exists) + return; + + // open the file in append mode, with user rw and group r permissions + const auto fd = open( + m_public_keys_filename.c_str(), + O_APPEND|O_CREAT|O_WRONLY, + S_IRUSR|S_IWUSR|S_IRGRP + ); + if (fd == -1) { + g_warning("Error opening ADB datafile: %s", g_strerror(errno)); + return; + } + + // write the new public key on its own line + std::string buf {public_key + '\n'}; + if (write(fd, buf.c_str(), buf.size()) == -1) + g_warning("Error writing ADB datafile: %d %s", errno, g_strerror(errno)); + close(fd); + } + + std::shared_ptr m_adbd_client; + const std::string m_public_keys_filename; +}; + +/*** +**** +***/ + +UsbManager::UsbManager( + const std::string& socket_path, + const std::string& public_keys_filename +): + impl{new Impl{socket_path, public_keys_filename}} +{ +} + +UsbManager::~UsbManager() +{ +} + diff --git a/src/usb-manager.h b/src/usb-manager.h new file mode 100644 index 0000000..28a27f3 --- /dev/null +++ b/src/usb-manager.h @@ -0,0 +1,34 @@ +/* + * Copyright 2016 Canonical Ltd. + * + * This program is free software: you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 3, as published + * by the Free Software Foundation. + * + * This program is distributed in the hope that it will be useful, but + * WITHOUT ANY WARRANTY; without even the implied warranties of + * MERCHANTABILITY, SATISFACTORY QUALITY, 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, see . + * + * Authors: + * Charles Kerr + */ + +#pragma once + +#include +#include + +class UsbManager +{ +public: + UsbManager(const std::string& socket_path, const std::string& public_key_filename); + ~UsbManager(); + +protected: + class Impl; + std::unique_ptr impl; +}; diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt index 205792e..be0000d 100644 --- a/tests/CMakeLists.txt +++ b/tests/CMakeLists.txt @@ -27,5 +27,6 @@ set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} ${CXX_WARNING_ARGS}") add_test(cppcheck cppcheck --enable=all -USCHEMA_DIR --error-exitcode=2 --inline-suppr -I${CMAKE_SOURCE_DIR} ${CMAKE_SOURCE_DIR}/src ${CMAKE_SOURCE_DIR}/tests) +add_subdirectory(integration) add_subdirectory(unit) add_subdirectory(utils) diff --git a/tests/integration/CMakeLists.txt b/tests/integration/CMakeLists.txt new file mode 100644 index 0000000..c04ecc8 --- /dev/null +++ b/tests/integration/CMakeLists.txt @@ -0,0 +1,24 @@ +set(SERVICE_LINK_LIBRARIES + ${SERVICE_LIB} + ${SERVICE_DEPS_LIBRARIES} +) +set(QT_LINK_LIBRARIES + test-utils + Qt5::Core + Qt5::Test + Qt5::DBus +) +set(TEST_LINK_LIBRARIES + ${TEST_DEPS_LIBRARIES} + ${GTEST_LIBRARIES} + ${GMOCK_LIBRARIES} +) + +function(add_qt_test_by_name name) + set(TEST_NAME ${name}) + add_executable (${TEST_NAME} ${TEST_NAME}.cpp) + add_test(${TEST_NAME} ${TEST_NAME}) + set_property(TEST ${TEST_NAME} APPEND PROPERTY ENVIRONMENT "${CTEST_ENVIRONMENT}") + target_link_libraries(${TEST_NAME} ${SERVICE_LINK_LIBRARIES} ${QT_LINK_LIBRARIES} ${TEST_LINK_LIBRARIES}) +endfunction() +add_qt_test_by_name(usb-manager-test) diff --git a/tests/integration/usb-manager-test.cpp b/tests/integration/usb-manager-test.cpp new file mode 100644 index 0000000..aca5325 --- /dev/null +++ b/tests/integration/usb-manager-test.cpp @@ -0,0 +1,186 @@ +/* + * Copyright 2016 Canonical Ltd. + * + * This program is free software: you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 3, as published + * by the Free Software Foundation. + * + * This program is distributed in the hope that it will be useful, but + * WITHOUT ANY WARRANTY; without even the implied warranties of + * MERCHANTABILITY, SATISFACTORY QUALITY, 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, see . + * + * Authors: + * Charles Kerr + */ + +#define QT_NO_KEYWORDS + +#include +#include +#include +#include + +#include + +#include +#include +#include + +#include + +#include + +#include + +#include +#include +#include + +/*** +**** +***/ + +#define WAIT_FOR_SIGNALS(signalSpy, signalsExpected)\ +{\ + while (signalSpy.size() < signalsExpected)\ + {\ + ASSERT_TRUE(signalSpy.wait());\ + }\ + ASSERT_EQ(signalsExpected, signalSpy.size());\ +} + +class UsbManagerFixture: public GlibFixture +{ + using super = GlibFixture; + +public: + + UsbManagerFixture(): + dbusMock{dbusTestRunner} + { + DBusTypes::registerMetaTypes(); + + dbusTestRunner.startServices(); + } + + ~UsbManagerFixture() =default; + +protected: + + static void file_deleter (std::string* s) + { + fprintf(stderr, "remove \"%s\"\n", s->c_str()); + remove(s->c_str()); + delete s; + } + + bool qDBusArgumentToMap(QVariant const& variant, QVariantMap& map) + { + if (variant.canConvert()) + { + QDBusArgument value(variant.value()); + if (value.currentType() == QDBusArgument::MapType) + { + value >> map; + return true; + } + } + return false; + } + + void SetUp() override + { + super::SetUp(); + + char tmpl[] = {"usb-manager-test-XXXXXX"}; + m_tmpdir.reset(new std::string{g_mkdtemp(tmpl)}, file_deleter); + g_message("using tmpdir '%s'", m_tmpdir->c_str()); + + dbusMock.registerNotificationDaemon(); + dbusTestRunner.startServices(); + } + + OrgFreedesktopDBusMockInterface& notificationsMockInterface() + { + return dbusMock.mockInterface("org.freedesktop.Notifications", + "/org/freedesktop/Notifications", + "org.freedesktop.Notifications", + QDBusConnection::SessionBus); + } + + QtDBusTest::DBusTestRunner dbusTestRunner; + QtDBusMock::DBusMock dbusMock; + QtDBusTest::DBusServicePtr indicator; + std::shared_ptr m_tmpdir; +}; + +TEST_F(UsbManagerFixture, Allow) +{ + const std::shared_ptr socket_path {new std::string{*m_tmpdir+"/socket"}, file_deleter}; + const std::shared_ptr public_keys_path {new std::string{*m_tmpdir+"/adb_keys"}, file_deleter}; + + // add a signal spy to listen to the notification daemon + QSignalSpy notificationsSpy( + ¬ificationsMockInterface(), + SIGNAL(MethodCalled(const QString &, const QVariantList &)) + ); + + // start a mock AdbdServer ready to submit a request + const std::string public_key {"qAAAALUHllFjEZjl5jbS9ivjpQpaTNpibl28Re71D/S8sV3usNJTkbpvZYoVPfxtmHSNdCgLkWN6qcDZsHZqE/4myzmx/8Y/RqBy1oirudugi3YUUcJh7aWkY8lKQe9shCLTcrT7cFLZIJIidTvfmWTm0UcU+xmdPALze11I3lGo1Ty5KpCe9oP+qYM8suHbxhm78LKLlo0QJ2QqM8T5isr1pvoPHDgRb+mSESElG+xDIfPWA2BTu77/xk4EnXmOYfcuCr5akF3N4fRo/ACnYgXWDZFX2XdklBXyDj78lVlinF37xdMk7BMQh166X7UNkpH1uG2y5F6lUzyLg8SsFtRnJkw7eVe/gnJj3feQaFQbF5oVDhWhLMtWLtejhX6umvroVBVA4rynG4xEgs00K4u4ly8DUIIJYDO22Ml4myFR5CUm3lOlyitNdzYGh0utLXPq9oc8EbMVxM3i+O7PRxQw5Ul04X6K8GLiGUDV98DB+xYUqfEveq1BRnXi/ZrdPDhQ8Lfkg5xnLccPTFamAqutPtZXV6s7dXJInBTZf0NtBaWL0RdR2cOJBrpeBYkrc9yIyeqFLFdxr66rjaehjaa4pS4S+CD6PkGiIpPWSQtwNC4RlT10qTQ0/K9lRux2p0D8Z8ubUTFuh4kBScGUkN1OV3Z+7d7B+ghmBtZrrgleXsbehjRuKgEAAQA= foo@bar"}; + const std::string fingerprint {"12:23:5f:2d:8c:40:ae:1d:05:7b:ae:bd:88:8a:f0:80"}; + auto adbd_server = std::make_shared(*socket_path, std::vector{"PK"+public_key}); + + // set up a UsbManager to process the request + auto usb_manager = std::make_shared(*socket_path, *public_keys_path); + + // wait for the notification to show up, confirm it looks right + WAIT_FOR_SIGNALS(notificationsSpy, 1); + { + QVariantList const& call(notificationsSpy.at(0)); + EXPECT_EQ("Notify", call.at(0)); + + QVariantList const& args(call.at(1).toList()); + ASSERT_EQ(8, args.size()); + EXPECT_EQ("", args.at(0)); // app name + EXPECT_EQ(0, args.at(1)); // replaces-id + EXPECT_EQ("computer-symbolic", args.at(2)); // icon name + EXPECT_EQ("Allow USB Debugging?", args.at(3)); // summary + EXPECT_EQ(QString::fromUtf8("The computer's RSA key fingerprint is: ") + QString::fromUtf8(fingerprint.c_str()), args.at(4)); // body + EXPECT_EQ(QStringList({"allow", "Allow", "deny", "Deny"}), args.at(5)); // actions + EXPECT_EQ(-1, args.at(7)); + + QVariantMap hints; + ASSERT_TRUE(qDBusArgumentToMap(args.at(6), hints)); + ASSERT_EQ(3, hints.size()); + ASSERT_TRUE(hints.contains("x-canonical-private-affirmative-tint")); + ASSERT_TRUE(hints.contains("x-canonical-non-shaped-icon")); + ASSERT_TRUE(hints.contains("x-canonical-snap-decisions")); + } + notificationsSpy.clear(); + + // click on allow in the notification + notificationsMockInterface().EmitSignal( + DBusTypes::NOTIFY_DBUS_INTERFACE, + "ActionInvoked", + "us", + QVariantList() << uint32_t(1) << "allow" + ); + + // confirm that the AdbdServer got the right response + wait_for([adbd_server](){return !adbd_server->m_responses.empty();}, 2000); + ASSERT_EQ(1, adbd_server->m_responses.size()); + EXPECT_EQ("OK", adbd_server->m_responses.front()); + + // confirm that the public_keys file got the public key appended to it + std::ifstream ifkeys {*public_keys_path}; + std::vector lines; + std::string line; + while(getline(ifkeys, line)) + lines.emplace_back(std::move(line)); + ASSERT_EQ(1, lines.size()); + EXPECT_EQ(public_key, lines[0]); +} diff --git a/tests/unit/adbd-client-test.cpp b/tests/unit/adbd-client-test.cpp index 1e28cc9..6514456 100644 --- a/tests/unit/adbd-client-test.cpp +++ b/tests/unit/adbd-client-test.cpp @@ -31,22 +31,22 @@ private: protected: - std::string m_tmpdir; + static void file_deleter (std::string* s) + { + fprintf(stderr, "remove \"%s\"\n", s->c_str()); + remove(s->c_str()); + delete s; + } + + std::shared_ptr m_tmpdir; void SetUp() { super::SetUp(); char tmpl[] {"adb-client-test-XXXXXX"}; - m_tmpdir = mkdtemp(tmpl); - g_message("using tmpdir '%s'", m_tmpdir.c_str()); - } - - void TearDown() - { - g_rmdir(m_tmpdir.c_str()); - - super::TearDown(); + m_tmpdir.reset(new std::string{mkdtemp(tmpl)}, file_deleter); + g_message("using tmpdir '%s'", m_tmpdir->c_str()); } }; @@ -67,7 +67,7 @@ TEST_F(AdbdClientFixture, SocketPlumbing) const auto main_thread = g_thread_self(); - const auto socket_path = m_tmpdir + "/test-socket-plumbing"; + const auto socket_path = *m_tmpdir + "/test-socket-plumbing"; g_message("socket_path is %s", socket_path.c_str()); for (const auto& test : tests) diff --git a/tests/unit/usb-snap-test.cpp b/tests/unit/usb-snap-test.cpp index 70c9d97..84555cc 100644 --- a/tests/unit/usb-snap-test.cpp +++ b/tests/unit/usb-snap-test.cpp @@ -20,6 +20,7 @@ #define QT_NO_KEYWORDS #include #include +#include #include @@ -36,43 +37,6 @@ using namespace QtDBusTest; using namespace QtDBusMock; -inline QString qVariantToString(const QVariant& variant) { - QString output; - QDebug dbg(&output); - dbg << variant; - return output; -} - -inline void PrintTo(const QVariant& variant, std::ostream* os) { - QString output; - QDebug dbg(&output); - dbg << variant; - - *os << "QVariant(" << output.toStdString() << ")"; -} - -inline void PrintTo(const QString& s, std::ostream* os) { - *os << "\"" << s.toStdString() << "\""; -} - -inline void PrintTo(const QStringList& list, std::ostream* os) { - QString output; - QDebug dbg(&output); - dbg << list; - - *os << "QStringList(" << output.toStdString() << ")"; -} - -inline void PrintTo(const QList& list, std::ostream* os) { - QString output; - for (const auto& path: list) - { - output.append("\"" + path.path() + "\","); - } - - *os << "QList(" << output.toStdString() << ")"; -} - #define WAIT_FOR_SIGNALS(signalSpy, signalsExpected)\ {\ while (signalSpy.size() < signalsExpected)\ diff --git a/tests/utils/gtest-qt-print-helpers.h b/tests/utils/gtest-qt-print-helpers.h new file mode 100644 index 0000000..7a0897e --- /dev/null +++ b/tests/utils/gtest-qt-print-helpers.h @@ -0,0 +1,45 @@ + +#pragma once + +#include +#include +#include +#include + +inline QString qVariantToString(const QVariant& variant) { + QString output; + QDebug dbg(&output); + dbg << variant; + return output; +} + +inline void PrintTo(const QVariant& variant, std::ostream* os) { + QString output; + QDebug dbg(&output); + dbg << variant; + + *os << "QVariant(" << output.toStdString() << ")"; +} + +inline void PrintTo(const QString& s, std::ostream* os) { + *os << "\"" << s.toStdString() << "\""; +} + +inline void PrintTo(const QStringList& list, std::ostream* os) { + QString output; + QDebug dbg(&output); + dbg << list; + + *os << "QStringList(" << output.toStdString() << ")"; +} + +inline void PrintTo(const QList& list, std::ostream* os) { + QString output; + for (const auto& path: list) + { + output.append("\"" + path.path() + "\","); + } + + *os << "QList(" << output.toStdString() << ")"; +} + -- cgit v1.2.3 From df322a475939f3d30e4ff20213df1c01f7ff26d5 Mon Sep 17 00:00:00 2001 From: Charles Kerr Date: Tue, 15 Mar 2016 15:41:55 -0500 Subject: add some debug stubs --- src/adbd-client.cpp | 6 ++++-- src/main.cpp | 3 +++ 2 files changed, 7 insertions(+), 2 deletions(-) (limited to 'src/main.cpp') diff --git a/src/adbd-client.cpp b/src/adbd-client.cpp index 30929a7..4f7d28f 100644 --- a/src/adbd-client.cpp +++ b/src/adbd-client.cpp @@ -119,7 +119,7 @@ private: while (!g_cancellable_is_cancelled(m_cancellable)) { - g_debug("%s creating a client socket", G_STRLOC); + g_debug("%s creating a client socket to '%s'", G_STRLOC, socket_path.c_str()); auto socket = create_client_socket(socket_path); bool got_valid_req = false; @@ -179,9 +179,11 @@ private: } auto address = g_unix_socket_address_new(socket_path.c_str()); - const auto connected = g_socket_connect(socket, address, m_cancellable, nullptr); + const auto connected = g_socket_connect(socket, address, m_cancellable, &error); g_clear_object(&address); if (!connected) { + g_debug("unable to connect to '%s': %s", socket_path.c_str(), error->message); + g_clear_error(&error); g_clear_object(&socket); return nullptr; } diff --git a/src/main.cpp b/src/main.cpp index eb1bb2c..2e84afa 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -29,6 +29,9 @@ int main(int /*argc*/, char** /*argv*/) { +#warning temp +g_assert(g_setenv("G_MESSAGES_DEBUG", "all", true)); + // Work around a deadlock in glib's type initialization. // It can be removed when https://bugzilla.gnome.org/show_bug.cgi?id=674885 is fixed. g_type_ensure(G_TYPE_DBUS_CONNECTION); -- cgit v1.2.3 From 8ddb1713fa0816ea1c98ae039fea181d629acc7d Mon Sep 17 00:00:00 2001 From: Charles Kerr Date: Tue, 15 Mar 2016 17:09:47 -0500 Subject: listen on /dev/socket/adbd, not /dev/socket/adb --- src/main.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'src/main.cpp') diff --git a/src/main.cpp b/src/main.cpp index 2e84afa..f195bda 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -60,7 +60,7 @@ g_assert(g_setenv("G_MESSAGES_DEBUG", "all", true)); // We need the ADBD handler running, // even though it doesn't have an indicator component yet - static constexpr char const * ADB_SOCKET_PATH {"/dev/socket/adb"}; + static constexpr char const * ADB_SOCKET_PATH {"/dev/socket/adbd"}; static constexpr char const * PUBLIC_KEYS_FILENAME {"/data/misc/adb/adb_keys"}; UsbManager usb_manager {ADB_SOCKET_PATH, PUBLIC_KEYS_FILENAME}; -- cgit v1.2.3 From ff5be6a08a602e8a4454cbfcd8eeb38e28db3e1f Mon Sep 17 00:00:00 2001 From: Charles Kerr Date: Thu, 17 Mar 2016 13:29:09 -0500 Subject: fix warning message --- src/main.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'src/main.cpp') diff --git a/src/main.cpp b/src/main.cpp index f195bda..2e428f9 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -29,7 +29,7 @@ int main(int /*argc*/, char** /*argv*/) { -#warning temp +#warning NB the next line turns on verbose debug logging and is used for developement. Remove it before landing. g_assert(g_setenv("G_MESSAGES_DEBUG", "all", true)); // Work around a deadlock in glib's type initialization. -- cgit v1.2.3 From 45709c48f34e0909c1309dccac1dd3e047f518fb Mon Sep 17 00:00:00 2001 From: Charles Kerr Date: Fri, 18 Mar 2016 12:39:58 -0500 Subject: turn off verbose debugging --- src/main.cpp | 3 --- src/usb-manager.cpp | 6 +++--- 2 files changed, 3 insertions(+), 6 deletions(-) (limited to 'src/main.cpp') diff --git a/src/main.cpp b/src/main.cpp index 2e428f9..7d6eb5f 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -29,9 +29,6 @@ int main(int /*argc*/, char** /*argv*/) { -#warning NB the next line turns on verbose debug logging and is used for developement. Remove it before landing. -g_assert(g_setenv("G_MESSAGES_DEBUG", "all", true)); - // Work around a deadlock in glib's type initialization. // It can be removed when https://bugzilla.gnome.org/show_bug.cgi?id=674885 is fixed. g_type_ensure(G_TYPE_DBUS_CONNECTION); diff --git a/src/usb-manager.cpp b/src/usb-manager.cpp index 335db00..7f43520 100644 --- a/src/usb-manager.cpp +++ b/src/usb-manager.cpp @@ -42,7 +42,7 @@ public: m_adbd_client->on_pk_request().connect([this](const AdbdClient::PKRequest& req){ auto snap = new UsbSnap(req.fingerprint); snap->on_user_response().connect([this,req,snap](AdbdClient::PKResponse response, bool remember_choice){ - g_debug("user responded! response %d, remember %d", int(response), int(remember_choice)); + g_debug("%s user responded! response %d, remember %d", G_STRLOC, int(response), int(remember_choice)); req.respond(response); if (remember_choice && (response == AdbdClient::PKResponse::ALLOW)) write_public_key(req.public_key); @@ -78,12 +78,12 @@ private: S_IRUSR|S_IWUSR|S_IRGRP ); if (fd == -1) { - g_warning("Error opening ADB datafile: %s", g_strerror(errno)); + g_warning("Error opening ADB datafile '%s': %s", m_public_keys_filename.c_str(), g_strerror(errno)); return; } // write the new public key on its own line - std::string buf {public_key + '\n'}; + const std::string buf {public_key + '\n'}; if (write(fd, buf.c_str(), buf.size()) == -1) g_warning("Error writing ADB datafile: %d %s", errno, g_strerror(errno)); close(fd); -- cgit v1.2.3 From 7a25132c125f6e5e413ad26ea950ae22bee982f5 Mon Sep 17 00:00:00 2001 From: Charles Kerr Date: Mon, 21 Mar 2016 13:40:11 -0500 Subject: if our USB device is disconnected while prompting the user for ADBD, cancel the prompt. --- CMakeLists.txt | 1 + debian/control | 1 + src/CMakeLists.txt | 1 + src/adbd-client.cpp | 1 + src/main.cpp | 4 +- src/usb-manager.cpp | 63 +++++++++++++++++--------- src/usb-manager.h | 11 ++++- src/usb-monitor.cpp | 81 ++++++++++++++++++++++++++++++++++ src/usb-monitor.h | 52 ++++++++++++++++++++++ src/usb-snap.cpp | 1 + tests/integration/usb-manager-test.cpp | 44 ++++++++++++++++-- tests/unit/usb-snap-test.cpp | 1 - tests/utils/mock-usb-monitor.h | 32 ++++++++++++++ tests/utils/qdbus-helpers.h | 21 --------- tests/utils/qt-fixture.h | 18 +++++++- 15 files changed, 284 insertions(+), 48 deletions(-) create mode 100644 src/usb-monitor.cpp create mode 100644 src/usb-monitor.h create mode 100644 tests/utils/mock-usb-monitor.h delete mode 100644 tests/utils/qdbus-helpers.h (limited to 'src/main.cpp') diff --git a/CMakeLists.txt b/CMakeLists.txt index bb7568e..8a1a6aa 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -48,6 +48,7 @@ set(GLIB_MINIMUM 2.36) pkg_check_modules(SERVICE_DEPS REQUIRED gio-unix-2.0>=${GLIB_MINIMUM} glib-2.0>=${GLIB_MINIMUM} + gudev-1.0 ) include_directories (SYSTEM ${SERVICE_DEPS_INCLUDE_DIRS} diff --git a/debian/control b/debian/control index 529fa37..90e2590 100644 --- a/debian/control +++ b/debian/control @@ -7,6 +7,7 @@ Build-Depends: cmake, cmake-extras (>= 0.4), dbus, libglib2.0-dev (>= 2.36), + libgudev-1.0-dev, libproperties-cpp-dev, # for coverage reports lcov, diff --git a/src/CMakeLists.txt b/src/CMakeLists.txt index d3a021b..cdd2384 100644 --- a/src/CMakeLists.txt +++ b/src/CMakeLists.txt @@ -13,6 +13,7 @@ add_library( indicator.cpp rotation-lock.cpp usb-manager.cpp + usb-monitor.cpp usb-snap.cpp ) diff --git a/src/adbd-client.cpp b/src/adbd-client.cpp index 4f7d28f..937215e 100644 --- a/src/adbd-client.cpp +++ b/src/adbd-client.cpp @@ -45,6 +45,7 @@ public: { // tell the worker thread to stop whatever it's doing and exit. g_cancellable_cancel(m_cancellable); + m_pkresponse_cv.notify_one(); m_sleep_cv.notify_one(); m_worker_thread.join(); g_clear_object(&m_cancellable); diff --git a/src/main.cpp b/src/main.cpp index 7d6eb5f..27e6bcc 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -20,6 +20,7 @@ #include #include #include +#include #include // bindtextdomain() #include @@ -59,7 +60,8 @@ main(int /*argc*/, char** /*argv*/) // even though it doesn't have an indicator component yet static constexpr char const * ADB_SOCKET_PATH {"/dev/socket/adbd"}; static constexpr char const * PUBLIC_KEYS_FILENAME {"/data/misc/adb/adb_keys"}; - UsbManager usb_manager {ADB_SOCKET_PATH, PUBLIC_KEYS_FILENAME}; + auto usb_monitor = std::make_shared(); + UsbManager usb_manager {ADB_SOCKET_PATH, PUBLIC_KEYS_FILENAME, usb_monitor}; // let's go! g_main_loop_run(loop); diff --git a/src/usb-manager.cpp b/src/usb-manager.cpp index 7f43520..840a04b 100644 --- a/src/usb-manager.cpp +++ b/src/usb-manager.cpp @@ -28,39 +28,57 @@ #include #include +#include + class UsbManager::Impl { public: explicit Impl( const std::string& socket_path, - const std::string& public_keys_filename + const std::string& public_keys_filename, + const std::shared_ptr& usb_monitor ): m_adbd_client{std::make_shared(socket_path)}, - m_public_keys_filename{public_keys_filename} + m_public_keys_filename{public_keys_filename}, + m_usb_monitor{usb_monitor} { - m_adbd_client->on_pk_request().connect([this](const AdbdClient::PKRequest& req){ - auto snap = new UsbSnap(req.fingerprint); - snap->on_user_response().connect([this,req,snap](AdbdClient::PKResponse response, bool remember_choice){ - g_debug("%s user responded! response %d, remember %d", G_STRLOC, int(response), int(remember_choice)); - req.respond(response); - if (remember_choice && (response == AdbdClient::PKResponse::ALLOW)) - write_public_key(req.public_key); - // delete_later - g_idle_add([](gpointer gsnap){delete static_cast(gsnap); return G_SOURCE_REMOVE;}, snap); - }); + m_usb_monitor->on_usb_disconnected().connect([this](const std::string& /*usb_name*/) { + m_snap.reset(); }); - } - ~Impl() - { + m_adbd_client->on_pk_request().connect( + [this](const AdbdClient::PKRequest& req){ + + m_snap.reset(new UsbSnap(req.fingerprint), + [this](UsbSnap* snap){ + m_snap_connections.clear(); + delete snap; + } + ); + + m_snap_connections.insert((*m_snap).on_user_response().connect( + [this,req](AdbdClient::PKResponse response, bool remember_choice){ + g_message("%s user responded! response %d, remember %d", G_STRLOC, int(response), int(remember_choice)); + req.respond(response); + g_message("%s", G_STRLOC); + if (remember_choice && (response == AdbdClient::PKResponse::ALLOW)) + write_public_key(req.public_key); + g_idle_add([](gpointer gself){static_cast(gself)->m_snap.reset(); return G_SOURCE_REMOVE;}, this); + } + )); + } + ); + } + ~Impl() =default; + private: void write_public_key(const std::string& public_key) { - g_debug("writing public key '%s' to '%s'", public_key.c_str(), m_public_keys_filename.c_str()); + g_message("%s writing public key '%s' to '%s'", G_STRLOC, public_key.c_str(), m_public_keys_filename.c_str()); // confirm the directory exists auto dirname = g_path_get_dirname(m_public_keys_filename.c_str()); @@ -78,12 +96,12 @@ private: S_IRUSR|S_IWUSR|S_IRGRP ); if (fd == -1) { - g_warning("Error opening ADB datafile '%s': %s", m_public_keys_filename.c_str(), g_strerror(errno)); + g_warning("Error opening ADB datafile: %s", g_strerror(errno)); return; } // write the new public key on its own line - const std::string buf {public_key + '\n'}; + std::string buf {public_key + '\n'}; if (write(fd, buf.c_str(), buf.size()) == -1) g_warning("Error writing ADB datafile: %d %s", errno, g_strerror(errno)); close(fd); @@ -91,6 +109,10 @@ private: std::shared_ptr m_adbd_client; const std::string m_public_keys_filename; + std::shared_ptr m_usb_monitor; + + std::shared_ptr m_snap; + std::set m_snap_connections; }; /*** @@ -99,9 +121,10 @@ private: UsbManager::UsbManager( const std::string& socket_path, - const std::string& public_keys_filename + const std::string& public_keys_filename, + const std::shared_ptr& usb_monitor ): - impl{new Impl{socket_path, public_keys_filename}} + impl{new Impl{socket_path, public_keys_filename, usb_monitor}} { } diff --git a/src/usb-manager.h b/src/usb-manager.h index ec405c0..960d634 100644 --- a/src/usb-manager.h +++ b/src/usb-manager.h @@ -19,6 +19,8 @@ #pragma once +#include + #include #include @@ -28,10 +30,17 @@ class UsbManager { public: - UsbManager(const std::string& socket_path, const std::string& public_key_filename); + + UsbManager( + const std::string& socket_path, + const std::string& public_key_filename, + const std::shared_ptr& + ); + ~UsbManager(); protected: + class Impl; std::unique_ptr impl; }; diff --git a/src/usb-monitor.cpp b/src/usb-monitor.cpp new file mode 100644 index 0000000..5fc5a6d --- /dev/null +++ b/src/usb-monitor.cpp @@ -0,0 +1,81 @@ +/* + * Copyright 2016 Canonical Ltd. + * + * This program is free software: you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 3, as published + * by the Free Software Foundation. + * + * This program is distributed in the hope that it will be useful, but + * WITHOUT ANY WARRANTY; without even the implied warranties of + * MERCHANTABILITY, SATISFACTORY QUALITY, 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, see . + * + * Authors: + * Charles Kerr + */ + +#include + +#include +#include + +class GUDevUsbMonitor::Impl +{ +public: + + Impl() + { + const char* subsystems[] = {"android_usb", nullptr}; + m_udev_client = g_udev_client_new(subsystems); + g_signal_connect(m_udev_client, "uevent", G_CALLBACK(on_android_usb_event), this); + } + + ~Impl() + { + g_signal_handlers_disconnect_by_data(m_udev_client, this); + g_clear_object(&m_udev_client); + } + + core::Signal& on_usb_disconnected() + { + return m_on_usb_disconnected; + } + +private: + + static void on_android_usb_event(GUdevClient*, gchar* action, GUdevDevice* device, gpointer gself) + { + if (!g_strcmp0(action, "change")) + if (!g_strcmp0(g_udev_device_get_property(device, "USB_STATE"), "DISCONNECTED")) + static_cast(gself)->m_on_usb_disconnected(g_udev_device_get_name(device)); + } + + core::Signal m_on_usb_disconnected; + + GUdevClient* m_udev_client = nullptr; +}; + +/*** +**** +***/ + +UsbMonitor::UsbMonitor() =default; + +UsbMonitor::~UsbMonitor() =default; + +GUDevUsbMonitor::GUDevUsbMonitor(): + impl{new Impl{}} +{ +} + +GUDevUsbMonitor::~GUDevUsbMonitor() =default; + +core::Signal& +GUDevUsbMonitor::on_usb_disconnected() +{ + return impl->on_usb_disconnected(); +} + diff --git a/src/usb-monitor.h b/src/usb-monitor.h new file mode 100644 index 0000000..d9be539 --- /dev/null +++ b/src/usb-monitor.h @@ -0,0 +1,52 @@ +/* + * Copyright 2016 Canonical Ltd. + * + * This program is free software: you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 3, as published + * by the Free Software Foundation. + * + * This program is distributed in the hope that it will be useful, but + * WITHOUT ANY WARRANTY; without even the implied warranties of + * MERCHANTABILITY, SATISFACTORY QUALITY, 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, see . + * + * Authors: + * Charles Kerr + */ + +#pragma once + +#include + +#include +#include + +/** + * Simple interface that emits signals on USB device state changes + */ +class UsbMonitor +{ +public: + UsbMonitor(); + virtual ~UsbMonitor(); + virtual core::Signal& on_usb_disconnected() =0; +}; + +/** + * Simple GUDev wrapper that notifies on android_usb device state changes + */ +class GUDevUsbMonitor: public UsbMonitor +{ +public: + GUDevUsbMonitor(); + virtual ~GUDevUsbMonitor(); + core::Signal& on_usb_disconnected() override; + +protected: + class Impl; + std::unique_ptr impl; +}; + diff --git a/src/usb-snap.cpp b/src/usb-snap.cpp index 41c78c6..349d80e 100644 --- a/src/usb-snap.cpp +++ b/src/usb-snap.cpp @@ -148,6 +148,7 @@ private: { GError* error {}; auto reply = g_dbus_connection_call_finish (G_DBUS_CONNECTION(obus), res, &error); +g_message("%s got notify response %s", G_STRLOC, g_variant_print(reply, true)); if (error != nullptr) { if (!g_error_matches(error, G_IO_ERROR, G_IO_ERROR_CANCELLED)) g_warning("UsbSnap: Error calling Notify: %s", error->message); diff --git a/tests/integration/usb-manager-test.cpp b/tests/integration/usb-manager-test.cpp index 21fdc97..19c0401 100644 --- a/tests/integration/usb-manager-test.cpp +++ b/tests/integration/usb-manager-test.cpp @@ -17,10 +17,9 @@ * Charles Kerr */ -#define QT_NO_KEYWORDS - #include #include +#include #include #include @@ -64,6 +63,8 @@ protected: { super::SetUp(); + m_usb_monitor.reset(new MockUsbMonitor{}); + char tmpl[] = {"usb-manager-test-XXXXXX"}; m_tmpdir.reset(new std::string{g_mkdtemp(tmpl)}, file_deleter); g_message("using tmpdir '%s'", m_tmpdir->c_str()); @@ -83,6 +84,7 @@ protected: QtDBusTest::DBusTestRunner dbusTestRunner; QtDBusMock::DBusMock dbusMock; std::shared_ptr m_tmpdir; + std::shared_ptr m_usb_monitor; }; TEST_F(UsbManagerFixture, Allow) @@ -102,7 +104,7 @@ TEST_F(UsbManagerFixture, Allow) auto adbd_server = std::make_shared(*socket_path, std::vector{"PK"+public_key}); // set up a UsbManager to process the request - auto usb_manager = std::make_shared(*socket_path, *public_keys_path); + auto usb_manager = std::make_shared(*socket_path, *public_keys_path, m_usb_monitor); // wait for the notification to show up, confirm it looks right wait_for_signals(notificationsSpy, 1); @@ -151,3 +153,39 @@ TEST_F(UsbManagerFixture, Allow) ASSERT_EQ(1, lines.size()); EXPECT_EQ(public_key, lines[0]); } + +TEST_F(UsbManagerFixture, Cancel) +{ + const std::shared_ptr socket_path {new std::string{*m_tmpdir+"/socket"}, file_deleter}; + const std::shared_ptr public_keys_path {new std::string{*m_tmpdir+"/adb_keys"}, file_deleter}; + + // add a signal spy to listen to the notification daemon + QSignalSpy notificationsSpy( + ¬ificationsMockInterface(), + SIGNAL(MethodCalled(const QString &, const QVariantList &)) + ); + + // start a mock AdbdServer ready to submit a request + const std::string public_key {"public_key"}; + auto adbd_server = std::make_shared(*socket_path, std::vector{"PK"+public_key}); + + // set up a UsbManager to process the request + auto usb_manager = std::make_shared(*socket_path, *public_keys_path, m_usb_monitor); + + // wait for a notification to show up + wait_for_signals(notificationsSpy, 1); + EXPECT_EQ("Notify", notificationsSpy.at(0).at(0)); + notificationsSpy.clear(); + + // wait for UsbSnap to receive dbusmock's response to the Notify request. + // there's no event to key off of for this, so just wait for a moment + wait_msec(); + + // disconnect the USB before the user has a chance to allow/deny + m_usb_monitor->m_on_usb_disconnected("android0"); + + // confirm that we requested the notification to be pulled down + wait_for_signals(notificationsSpy, 1); + EXPECT_EQ("CloseNotification", notificationsSpy.at(0).at(0)); + notificationsSpy.clear(); +} diff --git a/tests/unit/usb-snap-test.cpp b/tests/unit/usb-snap-test.cpp index 663f9e6..40de94a 100644 --- a/tests/unit/usb-snap-test.cpp +++ b/tests/unit/usb-snap-test.cpp @@ -17,7 +17,6 @@ * Charles Kerr */ -#define QT_NO_KEYWORDS #include #include diff --git a/tests/utils/mock-usb-monitor.h b/tests/utils/mock-usb-monitor.h new file mode 100644 index 0000000..92b89db --- /dev/null +++ b/tests/utils/mock-usb-monitor.h @@ -0,0 +1,32 @@ +/* + * Copyright 2016 Canonical Ltd. + * + * This program is free software: you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 3, as published + * by the Free Software Foundation. + * + * This program is distributed in the hope that it will be useful, but + * WITHOUT ANY WARRANTY; without even the implied warranties of + * MERCHANTABILITY, SATISFACTORY QUALITY, 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, see . + * + * Authors: + * Charles Kerr + */ + +#pragma once + +#include + +class MockUsbMonitor: public UsbMonitor +{ +public: + MockUsbMonitor() =default; + virtual ~MockUsbMonitor() =default; + core::Signal& on_usb_disconnected() override {return m_on_usb_disconnected;} + core::Signal m_on_usb_disconnected; +}; + diff --git a/tests/utils/qdbus-helpers.h b/tests/utils/qdbus-helpers.h deleted file mode 100644 index f873e23..0000000 --- a/tests/utils/qdbus-helpers.h +++ /dev/null @@ -1,21 +0,0 @@ -#pragma once - -#define QT_NO_KEYWORDS -#include -#include - -bool qDBusArgumentToMap(QVariant const& variant, QVariantMap& map) -{ - if (variant.canConvert()) - { - QDBusArgument value(variant.value()); - if (value.currentType() == QDBusArgument::MapType) - { - value >> map; - return true; - } - } - - return false; -} - diff --git a/tests/utils/qt-fixture.h b/tests/utils/qt-fixture.h index 321d56e..0f5722b 100644 --- a/tests/utils/qt-fixture.h +++ b/tests/utils/qt-fixture.h @@ -22,12 +22,13 @@ #define QT_NO_KEYWORDS #include -#include #include #include #include +#include +#include #include class QtFixture: public GlibFixture @@ -54,5 +55,20 @@ protected: ASSERT_EQ(signalsExpected, signalSpy.size()); } + + bool qDBusArgumentToMap(QVariant const& variant, QVariantMap& map) + { + if (variant.canConvert()) + { + QDBusArgument value(variant.value()); + if (value.currentType() == QDBusArgument::MapType) + { + value >> map; + return true; + } + } + + return false; + } }; -- cgit v1.2.3 From 70209f30bc6907ad545e33dc6e7de78cf63b9e9a Mon Sep 17 00:00:00 2001 From: Charles Kerr Date: Mon, 21 Mar 2016 19:33:35 -0500 Subject: get greeter's IsActive property working --- src/dbus-names.h | 11 ++++++++ src/greeter.cpp | 80 +++++++++++++++++++++++++++++++++++++++++--------------- src/main.cpp | 3 +++ 3 files changed, 73 insertions(+), 21 deletions(-) (limited to 'src/main.cpp') diff --git a/src/dbus-names.h b/src/dbus-names.h index 3127b9f..b31098a 100644 --- a/src/dbus-names.h +++ b/src/dbus-names.h @@ -45,5 +45,16 @@ namespace DBusNames static constexpr char const * PATH = "/"; static constexpr char const * INTERFACE = "com.canonical.UnityGreeter"; } + + namespace Properties + { + static constexpr char const * INTERFACE = "org.freedesktop.DBus.Properties"; + + namespace PropertiesChanged + { + static constexpr char const* NAME = "PropertiesChanged"; + static constexpr char const* ARGS_VARIANT_TYPE = "(sa{sv}as)"; + } + } } diff --git a/src/greeter.cpp b/src/greeter.cpp index 351b870..cffa376 100644 --- a/src/greeter.cpp +++ b/src/greeter.cpp @@ -68,37 +68,69 @@ private: { m_bus = G_DBUS_CONNECTION(g_object_ref(G_OBJECT(bus))); + g_dbus_connection_call(m_bus, + DBusNames::UnityGreeter::NAME, + DBusNames::UnityGreeter::PATH, + DBusNames::Properties::INTERFACE, + "Get", + g_variant_new("(ss)", DBusNames::UnityGreeter::INTERFACE, "IsActive"), + G_VARIANT_TYPE("(v)"), + G_DBUS_CALL_FLAGS_NONE, + -1, + m_cancellable, + on_get_is_active_ready, + this); + m_subscription_id = g_dbus_connection_signal_subscribe(m_bus, DBusNames::UnityGreeter::NAME, - "org.freedesktop.DBus.Properties", - "PropertiesChanged", + DBusNames::Properties::INTERFACE, + DBusNames::Properties::PropertiesChanged::NAME, DBusNames::UnityGreeter::PATH, - nullptr, + DBusNames::UnityGreeter::INTERFACE, G_DBUS_SIGNAL_FLAGS_NONE, - on_properties_changed_signal_static, + on_properties_changed_signal, this, nullptr); } - static void on_properties_changed_signal_static(GDBusConnection* /*connection*/, - const gchar* sender_name, - const gchar* object_path, - const gchar* interface_name, - const gchar* signal_name, - GVariant* parameters, - gpointer gself) + static void on_get_is_active_ready(GObject* source, GAsyncResult* res, gpointer gself) { - g_return_if_fail(!g_strcmp0(sender_name, DBusNames::UnityGreeter::NAME)); - g_return_if_fail(!g_strcmp0(object_path, DBusNames::UnityGreeter::PATH)); - g_return_if_fail(!g_strcmp0(interface_name, "org.freedesktop.DBus.Properties")); - g_return_if_fail(!g_strcmp0(signal_name, "PropertiesChanged")); - - static_cast(gself)->on_properties_changed_signal(parameters); + GError* error {}; + auto v = g_dbus_connection_call_finish(G_DBUS_CONNECTION(source), res, &error); + if (error != nullptr) { + if (!g_error_matches(error, G_IO_ERROR, G_IO_ERROR_CANCELLED)) + g_warning("UsbSnap: Error getting session bus: %s", error->message); + g_clear_error(&error); + } else { + GVariant* is_active {}; + g_variant_get_child(v, 0, "v", &is_active_v); + static_cast(gself)->m_is_active.set(g_variant_get_boolean(is_active); + g_clear_pointer(&is_active, g_variant_unref); + } + g_clear_pointer(&v, g_variant_unref); } - void on_properties_changed_signal(GVariant* parameters) + static void on_properties_changed_signal(GDBusConnection* /*connection*/, + const gchar* /*sender_name*/, + const gchar* object_path, + const gchar* interface_name, + const gchar* signal_name, + GVariant* parameters, + gpointer gself) { - g_message("%s %s", G_STRLOC, g_variant_print(parameters, true)); + g_return_if_fail(!g_strcmp0(object_path, DBusNames::UnityGreeter::PATH)); + g_return_if_fail(!g_strcmp0(interface_name, DBusNames::Properties::INTERFACE)); + g_return_if_fail(!g_strcmp0(signal_name, DBusNames::Properties::PropertiesChanged::NAME)); + g_return_if_fail(g_variant_is_of_type(parameters, G_VARIANT_TYPE(DBusNames::Properties::PropertiesChanged::ARGS_VARIANT_TYPE))); + + auto v = g_variant_get_child_value (parameters, 1); + gboolean is_active {}; + if (g_variant_lookup(v, "IsActive", "b", &is_active)) + { + g_debug("%s is_active changed to %d", G_STRLOC, int(is_active)); + static_cast(gself)->m_is_active.set(is_active); + } + g_clear_pointer(&v, g_variant_unref); } core::Property m_is_active; @@ -115,9 +147,15 @@ Greeter::Greeter() =default; Greeter::~Greeter() =default; -UnityGreeter::~UnityGreeter() =default; - UnityGreeter::UnityGreeter(): impl{new Impl{}} { } + +UnityGreeter::~UnityGreeter() =default; + +core::Property& +UnityGreeter::is_active() +{ + return impl->is_active(); +} diff --git a/src/main.cpp b/src/main.cpp index 27e6bcc..6c111f1 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -19,6 +19,8 @@ #include #include + +#include #include #include @@ -61,6 +63,7 @@ main(int /*argc*/, char** /*argv*/) static constexpr char const * ADB_SOCKET_PATH {"/dev/socket/adbd"}; static constexpr char const * PUBLIC_KEYS_FILENAME {"/data/misc/adb/adb_keys"}; auto usb_monitor = std::make_shared(); + auto greeter = std::make_shared(); UsbManager usb_manager {ADB_SOCKET_PATH, PUBLIC_KEYS_FILENAME, usb_monitor}; // let's go! -- cgit v1.2.3 From a5f330f6b73101d7bbdeadc6a5f53b8da3349999 Mon Sep 17 00:00:00 2001 From: Charles Kerr Date: Tue, 22 Mar 2016 15:39:36 -0500 Subject: don't show the snap decision until we're out of the greeter --- src/main.cpp | 2 +- src/usb-manager.cpp | 76 +++++++++++++++++++++++++++++++++------------- src/usb-manager.h | 4 ++- tests/utils/mock-greeter.h | 32 +++++++++++++++++++ 4 files changed, 91 insertions(+), 23 deletions(-) create mode 100644 tests/utils/mock-greeter.h (limited to 'src/main.cpp') diff --git a/src/main.cpp b/src/main.cpp index 6c111f1..52cdd58 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -64,7 +64,7 @@ main(int /*argc*/, char** /*argv*/) static constexpr char const * PUBLIC_KEYS_FILENAME {"/data/misc/adb/adb_keys"}; auto usb_monitor = std::make_shared(); auto greeter = std::make_shared(); - UsbManager usb_manager {ADB_SOCKET_PATH, PUBLIC_KEYS_FILENAME, usb_monitor}; + UsbManager usb_manager {ADB_SOCKET_PATH, PUBLIC_KEYS_FILENAME, usb_monitor, greeter}; // let's go! g_main_loop_run(loop); diff --git a/src/usb-manager.cpp b/src/usb-manager.cpp index f5957d9..0e59ca2 100644 --- a/src/usb-manager.cpp +++ b/src/usb-manager.cpp @@ -37,51 +37,83 @@ public: explicit Impl( const std::string& socket_path, const std::string& public_keys_filename, - const std::shared_ptr& usb_monitor + const std::shared_ptr& usb_monitor, + const std::shared_ptr& greeter ): m_socket_path{socket_path}, m_public_keys_filename{public_keys_filename}, - m_usb_monitor{usb_monitor} + m_usb_monitor{usb_monitor}, + m_greeter{greeter} { m_usb_monitor->on_usb_disconnected().connect([this](const std::string& /*usb_name*/) { restart(); }); + m_greeter->is_active().changed().connect([this](bool /*is_active*/) { + maybe_snap_now(); + }); + restart(); } - ~Impl() =default; + ~Impl() + { + clear(); + } private: - void restart() + void clear() { // clear out old state m_snap_connections.clear(); m_snap.reset(); + m_req = AdbdClient::PKRequest{}; m_adbd_client.reset(); + } - // add a new client + void restart() + { + clear(); + + // set a new client m_adbd_client.reset(new GAdbdClient{m_socket_path}); m_adbd_client->on_pk_request().connect( [this](const AdbdClient::PKRequest& req) { - g_debug("%s got pk request", G_STRLOC); - - m_snap = std::make_shared(req.fingerprint); - m_snap_connections.insert((*m_snap).on_user_response().connect( - [this,req](AdbdClient::PKResponse response, bool remember_choice){ - g_debug("%s user responded! response %d, remember %d", G_STRLOC, int(response), int(remember_choice)); - req.respond(response); - if (remember_choice && (response == AdbdClient::PKResponse::ALLOW)) - write_public_key(req.public_key); - g_idle_add([](gpointer gself){static_cast(gself)->m_snap.reset(); return G_SOURCE_REMOVE;}, this); - } - )); + m_req = req; + maybe_snap_now(); } ); } + bool ready_to_snap() + { + return !m_greeter->is_active().get() && !m_req.public_key.empty(); + } + + void maybe_snap_now() + { + if (ready_to_snap()) + snap_now(); + } + + void snap_now() + { + g_return_if_fail(ready_to_snap()); + + m_snap = std::make_shared(m_req.fingerprint); + m_snap_connections.insert((*m_snap).on_user_response().connect( + [this](AdbdClient::PKResponse response, bool remember_choice){ + g_debug("%s user responded! response %d, remember %d", G_STRLOC, int(response), int(remember_choice)); + m_req.respond(response); + if (remember_choice && (response == AdbdClient::PKResponse::ALLOW)) + write_public_key(m_req.public_key); + g_idle_add([](gpointer gself){static_cast(gself)->restart(); return G_SOURCE_REMOVE;}, this); + } + )); + } + void write_public_key(const std::string& public_key) { g_debug("%s writing public key '%s' to '%s'", G_STRLOC, public_key.c_str(), m_public_keys_filename.c_str()); @@ -115,10 +147,11 @@ private: const std::string m_socket_path; const std::string m_public_keys_filename; - - std::shared_ptr m_usb_monitor; + const std::shared_ptr m_usb_monitor; + const std::shared_ptr m_greeter; std::shared_ptr m_adbd_client; + AdbdClient::PKRequest m_req; std::shared_ptr m_snap; std::set m_snap_connections; }; @@ -130,9 +163,10 @@ private: UsbManager::UsbManager( const std::string& socket_path, const std::string& public_keys_filename, - const std::shared_ptr& usb_monitor + const std::shared_ptr& usb_monitor, + const std::shared_ptr& greeter ): - impl{new Impl{socket_path, public_keys_filename, usb_monitor}} + impl{new Impl{socket_path, public_keys_filename, usb_monitor, greeter}} { } diff --git a/src/usb-manager.h b/src/usb-manager.h index 960d634..b93992f 100644 --- a/src/usb-manager.h +++ b/src/usb-manager.h @@ -19,6 +19,7 @@ #pragma once +#include #include #include @@ -34,7 +35,8 @@ public: UsbManager( const std::string& socket_path, const std::string& public_key_filename, - const std::shared_ptr& + const std::shared_ptr&, + const std::shared_ptr& ); ~UsbManager(); diff --git a/tests/utils/mock-greeter.h b/tests/utils/mock-greeter.h new file mode 100644 index 0000000..5ac85a0 --- /dev/null +++ b/tests/utils/mock-greeter.h @@ -0,0 +1,32 @@ +/* + * Copyright 2016 Canonical Ltd. + * + * This program is free software: you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 3, as published + * by the Free Software Foundation. + * + * This program is distributed in the hope that it will be useful, but + * WITHOUT ANY WARRANTY; without even the implied warranties of + * MERCHANTABILITY, SATISFACTORY QUALITY, 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, see . + * + * Authors: + * Charles Kerr + */ + +#pragma once + +#include + +class MockGreeter: public Greeter +{ +public: + MockGreeter() =default; + virtual ~MockGreeter() =default; + core::Property& is_active() override {return m_is_active;} + core::Property m_is_active {false}; +}; + -- cgit v1.2.3