Separate native API code from capmgr repository
authorSangyoon Jang <jeremy.jang@samsung.com>
Thu, 23 Aug 2018 07:58:30 +0000 (16:58 +0900)
committerSangyoon Jang <jeremy.jang@samsung.com>
Thu, 23 Aug 2018 08:21:42 +0000 (17:21 +0900)
Change-Id: I48bbba39bcfb19cef61b2e6ed090ea9d4b918f90
Signed-off-by: Sangyoon Jang <jeremy.jang@samsung.com>
25 files changed:
CMakeLists.txt [new file with mode: 0644]
LICENSE [new file with mode: 0644]
cmake/Modules/ApplyPkgConfig.cmake [new file with mode: 0644]
include/capmgr.h [new file with mode: 0644]
packaging/capi-appfw-capmgr.manifest [new file with mode: 0644]
packaging/capi-appfw-capmgr.spec [new file with mode: 0644]
src/CMakeLists.txt [new file with mode: 0644]
src/capi-appfw-capmgr.pc.in [new file with mode: 0644]
src/client.cc [new file with mode: 0644]
src/dbus.cc [new file with mode: 0644]
src/dbus.h [new file with mode: 0644]
src/sql_connection.h [new file with mode: 0644]
src/sql_statement.h [new file with mode: 0644]
src/sql_transaction.cc [new file with mode: 0644]
src/sql_transaction.h [new file with mode: 0644]
src/sqlite_connection.cc [new file with mode: 0644]
src/sqlite_connection.h [new file with mode: 0644]
src/sqlite_statement.cc [new file with mode: 0644]
src/sqlite_statement.h [new file with mode: 0644]
src/utils/glist_range.h [new file with mode: 0644]
src/utils/logging.cc [new file with mode: 0644]
src/utils/logging.h [new file with mode: 0644]
tools/CMakeLists.txt [new file with mode: 0644]
tools/capmgr_test.cc [new file with mode: 0644]
tools/check-coding-style [new file with mode: 0755]

diff --git a/CMakeLists.txt b/CMakeLists.txt
new file mode 100644 (file)
index 0000000..69272ee
--- /dev/null
@@ -0,0 +1,38 @@
+CMAKE_MINIMUM_REQUIRED(VERSION 2.8.12)
+
+PROJECT(capi-appfw-capmgr)
+
+SET(PREFIX ${CMAKE_INSTALL_PREFIX})
+SET(EXEC_PREFIX "\${prefix}")
+SET(LIBDIR ${LIB_INSTALL_DIR})
+SET(INCLUDEDIR "\${prefix}/include")
+
+## Compiler flags
+SET(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11 -Wall -Werror -ffunction-sections -fdata-sections -fmerge-all-constants")
+
+## Linker flags
+SET(CMAKE_EXE_LINKER_FLAGS "-Wl,--as-needed,--gc-sections")
+
+SET(CMAKE_MODULE_PATH ${CMAKE_MODULE_PATH} "${CMAKE_CURRENT_SOURCE_DIR}/cmake/Modules/")
+
+## Targets
+SET(TARGET_LIB_CAPMGR "capi-appfw-capmgr")
+
+INCLUDE(FindPkgConfig)
+INCLUDE(ApplyPkgConfig)
+
+ADD_DEFINITIONS("-DPROJECT_TAG=\"CAPI_APPFW_CAPMGR\"")
+
+## Find all needed packages once
+PKG_CHECK_MODULES(AUL_DEPS REQUIRED aul)
+PKG_CHECK_MODULES(BUNDLE_DEPS REQUIRED bundle)
+PKG_CHECK_MODULES(DLOG_DEPS REQUIRED dlog)
+PKG_CHECK_MODULES(GIO_DEPS REQUIRED gio-2.0)
+PKG_CHECK_MODULES(GLIB_DEPS REQUIRED glib-2.0)
+PKG_CHECK_MODULES(SQLITE_DEPS REQUIRED sqlite3)
+
+FIND_PACKAGE(Boost REQUIRED COMPONENTS filesystem program_options system)
+INSTALL(DIRECTORY include/ DESTINATION ${INCLUDEDIR} FILES_MATCHING PATTERN "*.h")
+
+ADD_SUBDIRECTORY(src)
+ADD_SUBDIRECTORY(tools)
diff --git a/LICENSE b/LICENSE
new file mode 100644 (file)
index 0000000..a06208b
--- /dev/null
+++ b/LICENSE
@@ -0,0 +1,204 @@
+Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd. All rights reserved.
+
+                                 Apache License
+                           Version 2.0, January 2004
+                        http://www.apache.org/licenses/
+
+   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+   1. Definitions.
+
+      "License" shall mean the terms and conditions for use, reproduction,
+      and distribution as defined by Sections 1 through 9 of this document.
+
+      "Licensor" shall mean the copyright owner or entity authorized by
+      the copyright owner that is granting the License.
+
+      "Legal Entity" shall mean the union of the acting entity and all
+      other entities that control, are controlled by, or are under common
+      control with that entity. For the purposes of this definition,
+      "control" means (i) the power, direct or indirect, to cause the
+      direction or management of such entity, whether by contract or
+      otherwise, or (ii) ownership of fifty percent (50%) or more of the
+      outstanding shares, or (iii) beneficial ownership of such entity.
+
+      "You" (or "Your") shall mean an individual or Legal Entity
+      exercising permissions granted by this License.
+
+      "Source" form shall mean the preferred form for making modifications,
+      including but not limited to software source code, documentation
+      source, and configuration files.
+
+      "Object" form shall mean any form resulting from mechanical
+      transformation or translation of a Source form, including but
+      not limited to compiled object code, generated documentation,
+      and conversions to other media types.
+
+      "Work" shall mean the work of authorship, whether in Source or
+      Object form, made available under the License, as indicated by a
+      copyright notice that is included in or attached to the work
+      (an example is provided in the Appendix below).
+
+      "Derivative Works" shall mean any work, whether in Source or Object
+      form, that is based on (or derived from) the Work and for which the
+      editorial revisions, annotations, elaborations, or other modifications
+      represent, as a whole, an original work of authorship. For the purposes
+      of this License, Derivative Works shall not include works that remain
+      separable from, or merely link (or bind by name) to the interfaces of,
+      the Work and Derivative Works thereof.
+
+      "Contribution" shall mean any work of authorship, including
+      the original version of the Work and any modifications or additions
+      to that Work or Derivative Works thereof, that is intentionally
+      submitted to Licensor for inclusion in the Work by the copyright owner
+      or by an individual or Legal Entity authorized to submit on behalf of
+      the copyright owner. For the purposes of this definition, "submitted"
+      means any form of electronic, verbal, or written communication sent
+      to the Licensor or its representatives, including but not limited to
+      communication on electronic mailing lists, source code control systems,
+      and issue tracking systems that are managed by, or on behalf of, the
+      Licensor for the purpose of discussing and improving the Work, but
+      excluding communication that is conspicuously marked or otherwise
+      designated in writing by the copyright owner as "Not a Contribution."
+
+      "Contributor" shall mean Licensor and any individual or Legal Entity
+      on behalf of whom a Contribution has been received by Licensor and
+      subsequently incorporated within the Work.
+
+   2. Grant of Copyright License. Subject to the terms and conditions of
+      this License, each Contributor hereby grants to You a perpetual,
+      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+      copyright license to reproduce, prepare Derivative Works of,
+      publicly display, publicly perform, sublicense, and distribute the
+      Work and such Derivative Works in Source or Object form.
+
+   3. Grant of Patent License. Subject to the terms and conditions of
+      this License, each Contributor hereby grants to You a perpetual,
+      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+      (except as stated in this section) patent license to make, have made,
+      use, offer to sell, sell, import, and otherwise transfer the Work,
+      where such license applies only to those patent claims licensable
+      by such Contributor that are necessarily infringed by their
+      Contribution(s) alone or by combination of their Contribution(s)
+      with the Work to which such Contribution(s) was submitted. If You
+      institute patent litigation against any entity (including a
+      cross-claim or counterclaim in a lawsuit) alleging that the Work
+      or a Contribution incorporated within the Work constitutes direct
+      or contributory patent infringement, then any patent licenses
+      granted to You under this License for that Work shall terminate
+      as of the date such litigation is filed.
+
+   4. Redistribution. You may reproduce and distribute copies of the
+      Work or Derivative Works thereof in any medium, with or without
+      modifications, and in Source or Object form, provided that You
+      meet the following conditions:
+
+      (a) You must give any other recipients of the Work or
+          Derivative Works a copy of this License; and
+
+      (b) You must cause any modified files to carry prominent notices
+          stating that You changed the files; and
+
+      (c) You must retain, in the Source form of any Derivative Works
+          that You distribute, all copyright, patent, trademark, and
+          attribution notices from the Source form of the Work,
+          excluding those notices that do not pertain to any part of
+          the Derivative Works; and
+
+      (d) If the Work includes a "NOTICE" text file as part of its
+          distribution, then any Derivative Works that You distribute must
+          include a readable copy of the attribution notices contained
+          within such NOTICE file, excluding those notices that do not
+          pertain to any part of the Derivative Works, in at least one
+          of the following places: within a NOTICE text file distributed
+          as part of the Derivative Works; within the Source form or
+          documentation, if provided along with the Derivative Works; or,
+          within a display generated by the Derivative Works, if and
+          wherever such third-party notices normally appear. The contents
+          of the NOTICE file are for informational purposes only and
+          do not modify the License. You may add Your own attribution
+          notices within Derivative Works that You distribute, alongside
+          or as an addendum to the NOTICE text from the Work, provided
+          that such additional attribution notices cannot be construed
+          as modifying the License.
+
+      You may add Your own copyright statement to Your modifications and
+      may provide additional or different license terms and conditions
+      for use, reproduction, or distribution of Your modifications, or
+      for any such Derivative Works as a whole, provided Your use,
+      reproduction, and distribution of the Work otherwise complies with
+      the conditions stated in this License.
+
+   5. Submission of Contributions. Unless You explicitly state otherwise,
+      any Contribution intentionally submitted for inclusion in the Work
+      by You to the Licensor shall be under the terms and conditions of
+      this License, without any additional terms or conditions.
+      Notwithstanding the above, nothing herein shall supersede or modify
+      the terms of any separate license agreement you may have executed
+      with Licensor regarding such Contributions.
+
+   6. Trademarks. This License does not grant permission to use the trade
+      names, trademarks, service marks, or product names of the Licensor,
+      except as required for reasonable and customary use in describing the
+      origin of the Work and reproducing the content of the NOTICE file.
+
+   7. Disclaimer of Warranty. Unless required by applicable law or
+      agreed to in writing, Licensor provides the Work (and each
+      Contributor provides its Contributions) on an "AS IS" BASIS,
+      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+      implied, including, without limitation, any warranties or conditions
+      of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
+      PARTICULAR PURPOSE. You are solely responsible for determining the
+      appropriateness of using or redistributing the Work and assume any
+      risks associated with Your exercise of permissions under this License.
+
+   8. Limitation of Liability. In no event and under no legal theory,
+      whether in tort (including negligence), contract, or otherwise,
+      unless required by applicable law (such as deliberate and grossly
+      negligent acts) or agreed to in writing, shall any Contributor be
+      liable to You for damages, including any direct, indirect, special,
+      incidental, or consequential damages of any character arising as a
+      result of this License or out of the use or inability to use the
+      Work (including but not limited to damages for loss of goodwill,
+      work stoppage, computer failure or malfunction, or any and all
+      other commercial damages or losses), even if such Contributor
+      has been advised of the possibility of such damages.
+
+   9. Accepting Warranty or Additional Liability. While redistributing
+      the Work or Derivative Works thereof, You may choose to offer,
+      and charge a fee for, acceptance of support, warranty, indemnity,
+      or other liability obligations and/or rights consistent with this
+      License. However, in accepting such obligations, You may act only
+      on Your own behalf and on Your sole responsibility, not on behalf
+      of any other Contributor, and only if You agree to indemnify,
+      defend, and hold each Contributor harmless for any liability
+      incurred by, or claims asserted against, such Contributor by reason
+      of your accepting any such warranty or additional liability.
+
+   END OF TERMS AND CONDITIONS
+
+   APPENDIX: How to apply the Apache License to your work.
+
+      To apply the Apache License to your work, attach the following
+      boilerplate notice, with the fields enclosed by brackets "[]"
+      replaced with your own identifying information. (Don't include
+      the brackets!)  The text should be enclosed in the appropriate
+      comment syntax for the file format. We also recommend that a
+      file or class name and description of purpose be included on the
+      same "printed page" as the copyright notice for easier
+      identification within third-party archives.
+
+   Copyright [yyyy] [name of copyright owner]
+
+   Licensed under the Apache License, Version 2.0 (the "License");
+   you may not use this file except in compliance with the License.
+   You may obtain a copy of the License at
+
+       http://www.apache.org/licenses/LICENSE-2.0
+
+   Unless required by applicable law or agreed to in writing, software
+   distributed under the License is distributed on an "AS IS" BASIS,
+   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+   See the License for the specific language governing permissions and
+   limitations under the License.
+
diff --git a/cmake/Modules/ApplyPkgConfig.cmake b/cmake/Modules/ApplyPkgConfig.cmake
new file mode 100644 (file)
index 0000000..97679d7
--- /dev/null
@@ -0,0 +1,35 @@
+# Copyright (c) 2014 Samsung Electronics Co., Ltd All Rights Reserved
+# Use of this source code is governed by a BSD-style license that can be
+# found in the LICENSE file.
+
+#
+# This function applies external (out of source tree) dependencies
+# to given target. Arguments are:
+#   TARGET - valid cmake target
+#   PRIVACY - dependency can be inherited by dependent targets or not:
+#     PUBLIC - this should be used by default, cause compile/link flags passing
+#     PRIVATE - do not passes any settings to dependent targets,
+#               may be usefull for static libraries from the inside of the project
+# Argument ARGV2 and following are supposed to be names of checked pkg config
+# packages. This function will use variables created by check_pkg_modules().
+#  - ${DEP_NAME}_LIBRARIES
+#  - ${DEP_NAME}_INCLUDE_DIRS
+#  - ${DEP_NAME}_CFLAGS
+#
+FUNCTION(APPLY_PKG_CONFIG TARGET PRIVACY)
+  MATH(EXPR DEST_INDEX "${ARGC}-1")
+  FOREACH(I RANGE 2 ${DEST_INDEX})
+    IF(NOT ${ARGV${I}}_FOUND)
+      MESSAGE(FATAL_ERROR "Not found dependency - ${ARGV${I}}_FOUND")
+    ENDIF(NOT ${ARGV${I}}_FOUND)
+    TARGET_LINK_LIBRARIES(${TARGET} ${PRIVACY} "${${ARGV${I}}_LIBRARIES}")
+    TARGET_INCLUDE_DIRECTORIES(${TARGET} ${PRIVACY} SYSTEM "${${ARGV${I}}_INCLUDE_DIRS}")
+    STRING(REPLACE ";" " " CFLAGS_STR "${${ARGV${I}}_CFLAGS}")
+    SET(CFLAGS_LIST ${CFLAGS_STR})
+    SEPARATE_ARGUMENTS(CFLAGS_LIST)
+    FOREACH(OPTION ${CFLAGS_LIST})
+      TARGET_COMPILE_OPTIONS(${TARGET} ${PRIVACY} ${OPTION})
+    ENDFOREACH(OPTION)
+    SET_TARGET_PROPERTIES(${TARGET} PROPERTIES SKIP_BUILD_RPATH true)
+  ENDFOREACH(I RANGE 2 ${DEST_INDEX})
+ENDFUNCTION(APPLY_PKG_CONFIG TARGET PRIVACY)
diff --git a/include/capmgr.h b/include/capmgr.h
new file mode 100644 (file)
index 0000000..daaf3b6
--- /dev/null
@@ -0,0 +1,258 @@
+// Copyright (c) 2018 Samsung Electronics Co., Ltd All Rights Reserved
+// Use of this source code is governed by a apache 2.0 license that can be
+// found in the LICENSE file.
+
+#ifndef INCLUDE_CAPMGR_H_
+#define INCLUDE_CAPMGR_H_
+
+#include <tizen.h>
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+
+/**
+ * @brief
+ */
+typedef enum {
+  CAPMGR_ERROR_NONE = TIZEN_ERROR_NONE,
+  CAPMGR_ERROR_INVALID_PARAMETER = TIZEN_ERROR_INVALID_PARAMETER,
+  CAPMGR_ERROR_OUT_OF_MEMORY = TIZEN_ERROR_OUT_OF_MEMORY,
+  CAPMGR_ERROR_IO_ERROR = TIZEN_ERROR_IO_ERROR,
+} capmgr_error_e;
+
+typedef enum {
+  CAPMGR_APP_CONTROL_RESULT_OK,
+} capmgr_app_control_result_e;
+
+/**
+ * @brief
+ */
+typedef struct capmgr_device_s* capmgr_device_h;
+
+/**
+ * @brief
+ */
+typedef struct capmgr_app_control_s* capmgr_app_control_h;
+
+/**
+ * @brief
+ */
+typedef struct capmgr_package_info_s* capmgr_package_info_h;
+
+/**
+ * @brief
+ */
+typedef int (*capmgr_device_foreach_cb)(const capmgr_device_h device,
+    void* user_data);
+
+/**
+ * @brief
+ */
+typedef int (*capmgr_app_control_reply_cb)(const capmgr_app_control_h request,
+    const capmgr_app_control_h reply, capmgr_app_control_result_e result,
+    void* user_data);
+
+/**
+ * @brief
+ */
+typedef int (*capmgr_package_info_foreach_package_cb)(
+    const capmgr_package_info_h remote_package_info, void* user_data);
+
+/**
+ * @brief
+ */
+typedef int (*capmgr_package_info_foreach_app_cb)(
+    const char* appid, void* user_data);
+
+/**
+ * @brief
+ */
+int capmgr_device_foreach_devices(capmgr_device_foreach_cb cb,
+    void* user_data);
+
+/**
+ * @brief
+ */
+int capmgr_device_clone(const capmgr_device_h device,
+    capmgr_device_h* device_clone);
+
+/**
+ * @brief
+ */
+int capmgr_device_destroy(capmgr_device_h device);
+
+/**
+ * @brief
+ */
+int capmgr_device_get_device_id(capmgr_device_h device, char** device_id);
+
+/**
+ * @brief
+ */
+int capmgr_device_get_model_name(capmgr_device_h device, char** model_name);
+
+/**
+ * @brief
+ */
+int capmgr_device_get_device_name(capmgr_device_h device, char** device_name);
+
+/**
+ * @brief
+ */
+int capmgr_device_get_platform_ver(capmgr_device_h device, char** platform_ver);
+
+/**
+ * @brief
+ */
+int capmgr_device_get_profile(capmgr_device_h device, char** profile);
+
+/**
+ * @brief
+ */
+int capmgr_device_get_sw_ver(capmgr_device_h device, char** sw_ver);
+
+/**
+ * @brief
+ */
+int capmgr_device_get_platform_version(capmgr_device_h device,
+    char** platform_version);
+
+/**
+ * @brief
+ */
+int capmgr_app_control_create(capmgr_app_control_h* app_control);
+
+/**
+ * @brief
+ */
+int capmgr_app_control_clone(const capmgr_app_control_h app_control,
+    capmgr_app_control_h* app_control_clone);
+
+/**
+ * @brief
+ */
+int capmgr_app_control_destroy(capmgr_app_control_h app_control);
+
+/**
+ * @brief
+ */
+int capmgr_app_control_get_device(capmgr_app_control_h app_control,
+    capmgr_device_h* device);
+
+/**
+ * @brief
+ */
+int capmgr_app_control_get_operation(capmgr_app_control_h app_control,
+    char** operation);
+
+/**
+ * @brief
+ */
+int capmgr_app_control_get_uri(capmgr_app_control_h app_control,
+    char** uri);
+
+/**
+ * @brief
+ */
+int capmgr_app_control_get_mime(capmgr_app_control_h app_control,
+    char** mime);
+
+/**
+ * @brief
+ */
+int capmgr_app_control_get_appid(capmgr_app_control_h app_control,
+    char** appid);
+
+/**
+ * @brief
+ */
+int capmgr_app_control_get_extra_data(capmgr_app_control_h app_control,
+    const char* key, char** value);
+
+/**
+ * @brief
+ */
+int capmgr_app_control_set_device(capmgr_app_control_h app_control,
+    const capmgr_device_h device);
+
+/**
+ * @brief
+ */
+int capmgr_app_control_set_operation(capmgr_app_control_h app_control,
+    const char* operation);
+
+/**
+ * @brief
+ */
+int capmgr_app_control_set_uri(capmgr_app_control_h app_control,
+    const char* uri);
+
+/**
+ * @brief
+ */
+int capmgr_app_control_set_mime(capmgr_app_control_h app_control,
+    const char* mime);
+
+/**
+ * @brief
+ */
+int capmgr_app_control_set_appid(capmgr_app_control_h app_control,
+    const char* appid);
+
+/**
+ * @brief
+ */
+int capmgr_app_control_add_extra_data(capmgr_app_control_h app_control,
+    const char* key, const char* value);
+
+/**
+ * @brief
+ */
+int capmgr_app_control_remove_extra_data(capmgr_app_control_h app_control,
+    const char* key);
+
+/**
+ * @brief
+ */
+int capmgr_app_control_send(capmgr_app_control_h app_control,
+    capmgr_app_control_reply_cb cb, void* user_data);
+
+/**
+ * @brief
+ */
+int capmgr_package_info_foreach_packages(const capmgr_device_h device,
+    capmgr_package_info_foreach_package_cb cb, void* user_data);
+
+/**
+ * @brief
+ */
+int capmgr_package_info_foreach_applications(
+    const capmgr_package_info_h remote_package_info,
+    capmgr_package_info_foreach_app_cb cb, void* user_data);
+
+/**
+ * @brief
+ */
+int capmgr_package_info_get_pkgid(capmgr_package_info_h remote_package_info,
+    char** pkgid);
+
+/**
+ * @brief
+ */
+int capmgr_package_info_get_label(capmgr_package_info_h remote_package_info,
+    char** label);
+
+
+/**
+ * @brief
+ */
+int capmgr_package_info_get_version(capmgr_package_info_h remote_package_info,
+    char** version);
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif  // INCLUDE_CAPMGR_H_
diff --git a/packaging/capi-appfw-capmgr.manifest b/packaging/capi-appfw-capmgr.manifest
new file mode 100644 (file)
index 0000000..a76fdba
--- /dev/null
@@ -0,0 +1,5 @@
+<manifest>
+       <request>
+               <domain name="_" />
+       </request>
+</manifest>
diff --git a/packaging/capi-appfw-capmgr.spec b/packaging/capi-appfw-capmgr.spec
new file mode 100644 (file)
index 0000000..4f1a186
--- /dev/null
@@ -0,0 +1,58 @@
+Name:       capi-appfw-capmgr
+Summary:    Capability Manager Native API
+Version:    0.0.1
+Release:    1
+Group:      Application Framework/Application Communication
+License:    Apache-2.0
+Source0:    %{name}-%{version}.tar.gz
+Source1001: %{name}.manifest
+BuildRequires:  boost-devel
+BuildRequires:  cmake
+BuildRequires:  pkgconfig(aul)
+BuildRequires:  pkgconfig(bundle)
+BuildRequires:  pkgconfig(capi-base-common)
+BuildRequires:  pkgconfig(dlog)
+BuildRequires:  pkgconfig(gio-2.0)
+BuildRequires:  pkgconfig(glib-2.0)
+BuildRequires:  pkgconfig(sqlite3)
+
+%description
+Tizen Capability Manager Native API
+
+%package devel
+Summary:   Capability Manager development files
+Group:     Application Framework/Package Management
+Requires:  %{name} = %{version}
+
+%description devel
+This package contains header files of capability manager native API
+
+%prep
+%setup -q
+cp %{SOURCE1001} .
+
+%build
+MAJORVER=`echo %{version} | awk 'BEGIN {FS="."}{print $1}'`
+%cmake . -DUNITDIR=%{_unitdir} \
+         -DFULLVER=%{version} \
+         -DMAJORVER=${MAJORVER}
+
+%__make %{?_smp_mflags}
+
+%install
+%make_install
+
+%post
+/sbin/ldconfig
+
+%files
+%manifest %{name}.manifest
+%license LICENSE
+%defattr(-,root,root,-)
+%{_libdir}/lib%{name}.so.*
+%{_bindir}/capmgr-test
+
+%files devel
+%{_includedir}/capmgr.h
+%{_libdir}/pkgconfig/%{name}.pc
+%{_libdir}/lib%{name}.so
diff --git a/src/CMakeLists.txt b/src/CMakeLists.txt
new file mode 100644 (file)
index 0000000..5187397
--- /dev/null
@@ -0,0 +1,23 @@
+AUX_SOURCE_DIRECTORY(${CMAKE_CURRENT_SOURCE_DIR} SRCS)
+AUX_SOURCE_DIRECTORY(${CMAKE_CURRENT_SOURCE_DIR}/utils UTILS_SRCS)
+INCLUDE_DIRECTORIES(${CMAKE_CURRENT_SOURCE_DIR}/../)
+
+ADD_LIBRARY(${TARGET_LIB_CAPMGR} SHARED
+  ${SRCS}
+  ${UTILS_SRCS}
+)
+
+APPLY_PKG_CONFIG(${TARGET_LIB_CAPMGR} PUBLIC
+  AUL_DEPS
+  BUNDLE_DEPS
+  DLOG_DEPS
+  GIO_DEPS
+  GLIB_DEPS
+)
+
+SET_TARGET_PROPERTIES(${TARGET_LIB_CAPMGR} PROPERTIES VERSION ${FULLVER})
+SET_TARGET_PROPERTIES(${TARGET_LIB_CAPMGR} PROPERTIES SOVERSION ${MAJORVER})
+
+INSTALL(TARGETS ${TARGET_LIB_CAPMGR} DESTINATION ${LIB_INSTALL_DIR})
+CONFIGURE_FILE(capi-appfw-capmgr.pc.in capi-appfw-capmgr.pc @ONLY)
+INSTALL(FILES capi-appfw-capmgr.pc DESTINATION ${LIB_INSTALL_DIR}/pkgconfig)
diff --git a/src/capi-appfw-capmgr.pc.in b/src/capi-appfw-capmgr.pc.in
new file mode 100644 (file)
index 0000000..e1284f7
--- /dev/null
@@ -0,0 +1,11 @@
+prefix=@PREFIX@
+exec_prefix=@EXEC_PREFIX@
+libdir=@LIBDIR@
+includedir=@INCLUDEDIR@
+
+Name: capi-appfw-capmgr
+Description: capability-manager API
+Version: @FULLVER@
+Requires: capi-base-common
+Libs: -L${libdir} -lcapi-appfw-capmgr
+Cflags: -I${includedir}
diff --git a/src/client.cc b/src/client.cc
new file mode 100644 (file)
index 0000000..9254bc5
--- /dev/null
@@ -0,0 +1,628 @@
+// Copyright (c) 2018 Samsung Electronics Co., Ltd All Rights Reserved
+// Use of this source code is governed by a apache 2.0 license that can be
+// found in the LICENSE file.
+
+#include <aul_svc.h>
+#include <bundle.h>
+#include <bundle_internal.h>
+#include <glib.h>
+
+#include <cstring>
+#include <map>
+#include <memory>
+#include <string>
+#include <vector>
+
+#include "include/capmgr.h"
+#include "src/dbus.h"
+#include "src/sql_connection.h"
+#include "src/sql_statement.h"
+#include "src/sqlite_connection.h"
+#include "src/utils/logging.h"
+
+#define API __attribute__((visibility("default")))
+
+namespace {
+
+const char kDBPath[] = "/run/capmgr/capmgr.db";
+
+}  // namespace
+
+struct capmgr_device_s {
+  std::string device_id;
+  std::string model_name;
+  std::string device_name;
+  std::string platform_ver;
+  std::string profile;
+  std::string sw_ver;
+};
+
+struct capmgr_app_control_s {
+  capmgr_device_h device;
+  bundle* b;
+};
+
+struct capmgr_package_info_s {
+  std::string pkgid;
+  std::string label;
+  std::string version;
+  std::vector<std::string> appid_list;
+};
+
+API int capmgr_device_foreach_devices(capmgr_device_foreach_cb cb,
+    void* user_data) {
+  if (!cb)
+    return CAPMGR_ERROR_INVALID_PARAMETER;
+
+  std::unique_ptr<capmgr::SQLConnection> sql_conn(
+      new capmgr::SQLiteConnection(kDBPath, true));
+
+  const char kQueryForeachDevices[] =
+      "SELECT device_id, model_name, device_name, platform_ver,"
+      "  profile, sw_ver "
+      "FROM devices";
+  std::shared_ptr<capmgr::SQLStatement> stmt = sql_conn->PrepareStatement(
+      kQueryForeachDevices);
+  if (!stmt)
+    return CAPMGR_ERROR_IO_ERROR;
+
+  while (stmt->Step() == capmgr::SQLStatement::StepResult::ROW) {
+    struct capmgr_device_s dev;
+    int idx = 0;
+    dev.device_id = stmt->GetColumnString(idx++);
+    dev.model_name = stmt->GetColumnString(idx++);
+    dev.device_name = stmt->GetColumnString(idx++);
+    dev.platform_ver = stmt->GetColumnString(idx++);
+    dev.profile = stmt->GetColumnString(idx++);
+    dev.sw_ver = stmt->GetColumnString(idx++);
+    if (cb(&dev, user_data))
+      break;
+  }
+
+  return CAPMGR_ERROR_NONE;
+}
+
+API int capmgr_device_clone(const capmgr_device_h device,
+    capmgr_device_h* device_clone) {
+  if (!device || !device_clone)
+    return CAPMGR_ERROR_INVALID_PARAMETER;
+
+  try {
+    struct capmgr_device_s* clone = new struct capmgr_device_s;
+
+    clone->device_id = device->device_id;
+    clone->model_name = device->model_name;
+    clone->device_name = device->device_name;
+    clone->platform_ver = device->platform_ver;
+    clone->profile = device->profile;
+    clone->sw_ver = device->sw_ver;
+
+    *device_clone = clone;
+  } catch (const std::bad_alloc& e) {
+    LOG(ERROR) << e.what();
+    return CAPMGR_ERROR_OUT_OF_MEMORY;
+  }
+
+  return CAPMGR_ERROR_NONE;
+}
+
+API int capmgr_device_destroy(capmgr_device_h device) {
+  if (!device)
+    return CAPMGR_ERROR_INVALID_PARAMETER;
+
+  delete device;
+
+  return CAPMGR_ERROR_NONE;
+}
+
+API int capmgr_device_get_device_id(capmgr_device_h device,
+    char** device_id) {
+  if (!device || !device_id)
+    return CAPMGR_ERROR_INVALID_PARAMETER;
+
+  *device_id = strdup(device->device_id.c_str());
+  if (*device_id == nullptr)
+    return CAPMGR_ERROR_OUT_OF_MEMORY;
+
+  return CAPMGR_ERROR_NONE;
+}
+
+API int capmgr_device_get_model_name(capmgr_device_h device,
+    char** model_name) {
+  if (!device || !model_name)
+    return CAPMGR_ERROR_INVALID_PARAMETER;
+
+  *model_name = strdup(device->model_name.c_str());
+  if (*model_name == nullptr)
+    return CAPMGR_ERROR_OUT_OF_MEMORY;
+
+  return CAPMGR_ERROR_NONE;
+}
+
+API int capmgr_device_get_device_name(capmgr_device_h device,
+    char** device_name) {
+  if (!device || !device_name)
+    return CAPMGR_ERROR_INVALID_PARAMETER;
+
+  *device_name = strdup(device->device_name.c_str());
+  if (*device_name == nullptr)
+    return CAPMGR_ERROR_OUT_OF_MEMORY;
+
+  return CAPMGR_ERROR_NONE;
+}
+
+API int capmgr_device_get_platform_ver(capmgr_device_h device,
+    char** platform_ver) {
+  if (!device || !platform_ver)
+    return CAPMGR_ERROR_INVALID_PARAMETER;
+
+  *platform_ver = strdup(device->platform_ver.c_str());
+  if (*platform_ver == nullptr)
+    return CAPMGR_ERROR_OUT_OF_MEMORY;
+
+  return CAPMGR_ERROR_NONE;
+}
+
+API int capmgr_device_get_profile(capmgr_device_h device, char** profile) {
+  if (!device || !profile)
+    return CAPMGR_ERROR_INVALID_PARAMETER;
+
+  *profile = strdup(device->profile.c_str());
+  if (*profile == nullptr)
+    return CAPMGR_ERROR_OUT_OF_MEMORY;
+
+  return CAPMGR_ERROR_NONE;
+}
+
+API int capmgr_device_get_sw_ver(capmgr_device_h device,
+    char** sw_ver) {
+  if (!device || !sw_ver)
+    return CAPMGR_ERROR_INVALID_PARAMETER;
+
+  *sw_ver = strdup(device->sw_ver.c_str());
+  if (*sw_ver == nullptr)
+    return CAPMGR_ERROR_OUT_OF_MEMORY;
+
+  return CAPMGR_ERROR_NONE;
+}
+
+API int capmgr_app_control_create(capmgr_app_control_h* app_control) {
+  if (!app_control)
+    return CAPMGR_ERROR_INVALID_PARAMETER;
+
+  try {
+    struct capmgr_app_control_s* control = new struct capmgr_app_control_s;
+    control->b = bundle_create();
+    if (!control->b) {
+      delete control;
+      return CAPMGR_ERROR_OUT_OF_MEMORY;
+    }
+    int r = aul_svc_set_operation(control->b, AUL_SVC_OPERATION_DEFAULT);
+    if (r != AUL_SVC_RET_OK) {
+      bundle_free(control->b);
+      delete control;
+      return CAPMGR_ERROR_OUT_OF_MEMORY;
+    }
+    *app_control = control;
+  } catch (const std::bad_alloc& e) {
+    LOG(ERROR) << e.what();
+    return CAPMGR_ERROR_OUT_OF_MEMORY;
+  }
+
+  return CAPMGR_ERROR_NONE;
+}
+
+API int capmgr_app_control_clone(const capmgr_app_control_h app_control,
+    capmgr_app_control_h* app_control_clone) {
+  if (!app_control || !app_control_clone)
+    return CAPMGR_ERROR_INVALID_PARAMETER;
+
+  try {
+    struct capmgr_app_control_s* clone = new struct capmgr_app_control_s;
+
+    int ret = capmgr_device_clone(app_control->device, &clone->device);
+    if (ret != CAPMGR_ERROR_NONE) {
+      delete clone;
+      return CAPMGR_ERROR_OUT_OF_MEMORY;
+    }
+
+    clone->b = bundle_dup(app_control->b);
+    if (!clone->b) {
+      capmgr_app_control_destroy(clone);
+      return CAPMGR_ERROR_OUT_OF_MEMORY;
+    }
+
+    *app_control_clone = clone;
+  } catch (const std::bad_alloc& e) {
+    LOG(ERROR) << e.what();
+    return CAPMGR_ERROR_OUT_OF_MEMORY;
+  }
+
+  return CAPMGR_ERROR_NONE;
+}
+
+API int capmgr_app_control_destroy(capmgr_app_control_h app_control) {
+  if (!app_control)
+    return CAPMGR_ERROR_INVALID_PARAMETER;
+
+  capmgr_device_destroy(app_control->device);
+  bundle_free(app_control->b);
+  delete app_control;
+
+  return CAPMGR_ERROR_NONE;
+}
+
+API int capmgr_app_control_get_operation(capmgr_app_control_h app_control,
+    char** operation) {
+  if (!app_control || !operation)
+    return CAPMGR_ERROR_INVALID_PARAMETER;
+
+  const char* val = aul_svc_get_operation(app_control->b);
+  if (!val)
+    return CAPMGR_ERROR_INVALID_PARAMETER;
+
+  *operation = strdup(val);
+  if (*operation == nullptr)
+    return CAPMGR_ERROR_OUT_OF_MEMORY;
+
+  return CAPMGR_ERROR_NONE;
+}
+
+API int capmgr_app_control_get_uri(capmgr_app_control_h app_control,
+    char** uri) {
+  if (!app_control || !uri)
+    return CAPMGR_ERROR_INVALID_PARAMETER;
+
+  const char* val = aul_svc_get_uri(app_control->b);
+  if (!val)
+    return CAPMGR_ERROR_INVALID_PARAMETER;
+
+  *uri = strdup(val);
+  if (*uri == nullptr)
+    return CAPMGR_ERROR_OUT_OF_MEMORY;
+
+  return CAPMGR_ERROR_NONE;
+}
+
+API int capmgr_app_control_get_mime(capmgr_app_control_h app_control,
+    char** mime) {
+  if (!app_control || !mime)
+    return CAPMGR_ERROR_INVALID_PARAMETER;
+
+  const char* val = aul_svc_get_mime(app_control->b);
+  if (!val)
+    return CAPMGR_ERROR_INVALID_PARAMETER;
+
+  *mime = strdup(val);
+  if (*mime == nullptr)
+    return CAPMGR_ERROR_OUT_OF_MEMORY;
+
+  return CAPMGR_ERROR_NONE;
+}
+
+API int capmgr_app_control_get_appid(capmgr_app_control_h app_control,
+    char** appid) {
+  if (!app_control || !appid)
+    return CAPMGR_ERROR_INVALID_PARAMETER;
+
+  const char* val = aul_svc_get_appid(app_control->b);
+  if (!val)
+    return CAPMGR_ERROR_INVALID_PARAMETER;
+
+  *appid = strdup(val);
+  if (*appid == nullptr)
+    return CAPMGR_ERROR_OUT_OF_MEMORY;
+
+  return CAPMGR_ERROR_NONE;
+}
+
+API int capmgr_app_control_get_extra_data(capmgr_app_control_h app_control,
+    const char* key, char** value) {
+  if (!app_control || !key || !value)
+    return CAPMGR_ERROR_INVALID_PARAMETER;
+
+  // TODO(jeremy.jang): handle reserved key
+
+  const char* val = aul_svc_get_data(app_control->b, key);
+  if (!val) {
+    LOG(ERROR) << "There is no extra data of key(" << key << ")";
+    return CAPMGR_ERROR_INVALID_PARAMETER;
+  }
+
+  *value = strdup(val);
+  if (*value == nullptr)
+    return CAPMGR_ERROR_OUT_OF_MEMORY;
+
+  return CAPMGR_ERROR_NONE;
+}
+
+API int capmgr_app_control_set_device(capmgr_app_control_h app_control,
+    const capmgr_device_h device) {
+  if (!app_control || !device)
+    return CAPMGR_ERROR_INVALID_PARAMETER;
+
+  int ret = capmgr_device_clone(device, &app_control->device);
+  if (ret != CAPMGR_ERROR_NONE)
+    return CAPMGR_ERROR_OUT_OF_MEMORY;
+
+  return CAPMGR_ERROR_NONE;
+}
+
+API int capmgr_app_control_set_operation(capmgr_app_control_h app_control,
+    const char* operation) {
+  if (!app_control || !operation)
+    return CAPMGR_ERROR_INVALID_PARAMETER;
+
+  int r = aul_svc_set_operation(app_control->b, operation);
+  if (r != AUL_SVC_RET_OK)
+    return CAPMGR_ERROR_OUT_OF_MEMORY;
+
+  return CAPMGR_ERROR_NONE;
+}
+
+API int capmgr_app_control_set_uri(capmgr_app_control_h app_control,
+    const char* uri) {
+  if (!app_control || !uri)
+    return CAPMGR_ERROR_INVALID_PARAMETER;
+
+  int r = aul_svc_set_uri(app_control->b, uri);
+  if (r != AUL_SVC_RET_OK)
+    return CAPMGR_ERROR_OUT_OF_MEMORY;
+
+  return CAPMGR_ERROR_NONE;
+}
+
+API int capmgr_app_control_set_mime(capmgr_app_control_h app_control,
+    const char* mime) {
+  if (!app_control || !mime)
+    return CAPMGR_ERROR_INVALID_PARAMETER;
+
+  int r = aul_svc_set_mime(app_control->b, mime);
+  if (r != AUL_SVC_RET_OK)
+    return CAPMGR_ERROR_OUT_OF_MEMORY;
+
+  return CAPMGR_ERROR_NONE;
+}
+
+API int capmgr_app_control_set_appid(capmgr_app_control_h app_control,
+    const char* appid) {
+  if (!app_control || !appid)
+    return CAPMGR_ERROR_INVALID_PARAMETER;
+
+  int r = aul_svc_set_appid(app_control->b, appid);
+  if (r != AUL_SVC_RET_OK)
+    return CAPMGR_ERROR_OUT_OF_MEMORY;
+
+  return CAPMGR_ERROR_NONE;
+}
+
+API int capmgr_app_control_add_extra_data(capmgr_app_control_h app_control,
+    const char* key, const char* value) {
+  if (!app_control || !key || !value)
+    return CAPMGR_ERROR_INVALID_PARAMETER;
+
+  // TODO(jeremy.jang): handle reserved key
+
+  int r = aul_svc_add_data(app_control->b, key, value);
+  if (r != AUL_SVC_RET_OK)
+    return CAPMGR_ERROR_OUT_OF_MEMORY;
+
+  return CAPMGR_ERROR_NONE;
+}
+
+API int capmgr_app_control_remove_extra_data(capmgr_app_control_h app_control,
+    const char* key) {
+  if (!app_control || !key)
+    return CAPMGR_ERROR_INVALID_PARAMETER;
+
+  // TODO(jeremy.jang): handle reserved key
+
+  int r = bundle_del(app_control->b, key);
+  if (r != BUNDLE_ERROR_NONE)
+    return CAPMGR_ERROR_INVALID_PARAMETER;
+
+  return CAPMGR_ERROR_NONE;
+}
+
+struct cbdata {
+  capmgr_app_control_h request;
+  capmgr_app_control_reply_cb cb;
+  void* user_data;
+};
+
+void capmgr_dbus_callback(GVariant* result, void* user_data) {
+  LOG(DEBUG) << "Dbus callback for client called";
+
+  // TODO(jeremy.jang): some data maybe returned
+  GVariantIter* iter;
+  guchar* data;
+  guint len;
+  g_variant_get(result, "(ayu)", &iter, &len);
+  if (!iter)
+    LOG(ERROR) << "Some error occurred";
+
+  data = reinterpret_cast<guchar*>(g_try_malloc(len));
+  if (!data) {
+    LOG(ERROR) << "Out of memory";
+    return;
+  }
+
+  for (unsigned int i = 0; i < len; i++) {
+    if (!g_variant_iter_loop(iter, "y", &data[i])) {
+      LOG(ERROR) << "Failed to get data from GVariant!";
+      break;
+    }
+  }
+  g_variant_iter_free(iter);
+
+  struct cbdata* cbdata = reinterpret_cast<struct cbdata*>(user_data);
+  struct capmgr_app_control_s* reply = new struct capmgr_app_control_s;
+  reply->b = bundle_decode(data, len);
+  if (!reply->b) {
+    LOG(ERROR) << "Invalid bundle data!";
+    capmgr_app_control_destroy(cbdata->request);
+    delete cbdata;
+    return;
+  }
+  reply->device = cbdata->request->device;
+
+  // TODO(jeremy.jang): need to receive aul_svc result code
+  cbdata->cb(cbdata->request, reply, CAPMGR_APP_CONTROL_RESULT_OK,
+      cbdata->user_data);
+
+  capmgr_app_control_destroy(cbdata->request);
+  delete cbdata;
+}
+
+API int capmgr_app_control_send(capmgr_app_control_h app_control,
+    capmgr_app_control_reply_cb cb, void* user_data) {
+  if (!app_control || !app_control->device || !cb)
+    return CAPMGR_ERROR_INVALID_PARAMETER;
+
+  bundle_raw* raw;
+  int len;
+  int r = bundle_encode(app_control->b, &raw, &len);
+  if (r != BUNDLE_ERROR_NONE) {
+    LOG(ERROR) << "Failed to encode bundle: " << r;
+    return CAPMGR_ERROR_INVALID_PARAMETER;
+  }
+
+  // send app_control
+  GVariantBuilder* array_builder = g_variant_builder_new(G_VARIANT_TYPE("ay"));
+  for (int i = 0; i < len; i++)
+    g_variant_builder_add(array_builder, "y", raw[i]);
+  GVariant* gv = g_variant_new("(sayu)",
+      app_control->device->device_id.c_str(), array_builder, len);
+  g_variant_builder_unref(array_builder);
+  bundle_free_encoded_rawdata(&raw);
+  if (!gv) {
+    LOG(ERROR) << "Failed to create GVariant";
+    return CAPMGR_ERROR_INVALID_PARAMETER;
+  }
+  g_variant_ref_sink(gv);
+
+  capmgr_app_control_h clone;
+  r = capmgr_app_control_clone(app_control, &clone);
+  if (r != CAPMGR_ERROR_NONE) {
+    LOG(ERROR) << "Failed to clone app control request: " << r;
+    return r;
+  }
+
+  struct cbdata* cbdata = new struct cbdata;
+  cbdata->request = clone;
+  cbdata->cb = cb;
+  cbdata->user_data = user_data;
+
+  if (!capmgr::ProxyCallAsync("SendRemoteAppControl", gv, capmgr_dbus_callback,
+        cbdata)) {
+    LOG(ERROR) << "Failed to dbus method call";
+    delete cbdata;
+    capmgr_app_control_destroy(clone);
+    g_variant_unref(gv);
+    // errcode?
+    return CAPMGR_ERROR_INVALID_PARAMETER;
+  }
+
+  g_variant_unref(gv);
+
+  return CAPMGR_ERROR_NONE;
+}
+
+API int capmgr_package_info_get_pkgid(capmgr_package_info_h remote_package_info,
+    char** pkgid) {
+  if (!remote_package_info || !pkgid ||
+      remote_package_info->pkgid.empty())
+    return CAPMGR_ERROR_INVALID_PARAMETER;
+
+  *pkgid = strdup(remote_package_info->pkgid.c_str());
+  if (*pkgid == nullptr)
+    return CAPMGR_ERROR_OUT_OF_MEMORY;
+
+  return CAPMGR_ERROR_NONE;
+}
+
+API int capmgr_package_info_get_label(capmgr_package_info_h remote_package_info,
+    char** label) {
+  if (!remote_package_info || !label ||
+      remote_package_info->label.empty())
+    return CAPMGR_ERROR_INVALID_PARAMETER;
+
+  *label = strdup(remote_package_info->label.c_str());
+  if (*label == nullptr)
+    return CAPMGR_ERROR_OUT_OF_MEMORY;
+
+  return CAPMGR_ERROR_NONE;
+}
+
+API int capmgr_package_info_get_version(
+    capmgr_package_info_h remote_package_info, char** version) {
+  if (!remote_package_info || !version ||
+      remote_package_info->version.empty())
+    return CAPMGR_ERROR_INVALID_PARAMETER;
+
+  *version = strdup(remote_package_info->version.c_str());
+  if (*version == nullptr)
+    return CAPMGR_ERROR_OUT_OF_MEMORY;
+
+  return CAPMGR_ERROR_NONE;
+}
+
+API int capmgr_package_info_foreach_packages(const capmgr_device_h device,
+    capmgr_package_info_foreach_package_cb cb,
+    void* user_data) {
+  std::map<std::string, capmgr_package_info_s> pkg_map;
+
+  if (!cb)
+    return CAPMGR_ERROR_INVALID_PARAMETER;
+
+  std::unique_ptr<capmgr::SQLConnection> sql_conn(
+      new capmgr::SQLiteConnection(kDBPath, true));
+
+  const char kQueryForeachPackages[] =
+      "SELECT appid, pkgid, label, version FROM remote_app_info WHERE "
+      "device_id = ?";
+
+  std::shared_ptr<capmgr::SQLStatement> stmt = sql_conn->PrepareStatement(
+      kQueryForeachPackages);
+  if (!stmt)
+    return CAPMGR_ERROR_IO_ERROR;
+
+  if (stmt->BindString(1, device->device_id)) {
+    while (stmt->Step() == capmgr::SQLStatement::StepResult::ROW) {
+      struct capmgr_package_info_s info;
+      std::string appid;
+      int idx = 0;
+      appid = stmt->GetColumnString(idx++);
+      info.pkgid = stmt->GetColumnString(idx++);
+      info.label = stmt->GetColumnString(idx++);
+      info.version = stmt->GetColumnString(idx++);
+
+      auto search_info = pkg_map.find(appid);
+      if (search_info != pkg_map.end()) {
+        info.appid_list.emplace_back(appid);
+        pkg_map.emplace(appid, info);
+      } else {
+        struct capmgr_package_info_s found = search_info->second;
+        found.appid_list.emplace_back(appid);
+      }
+    }
+  }
+
+  for (auto it = pkg_map.begin(); it != pkg_map.end(); it++) {
+    struct capmgr_package_info_s info = it->second;
+    if (cb(&info, user_data))
+      break;
+  }
+
+  return CAPMGR_ERROR_NONE;
+}
+
+API int capmgr_package_info_foreach_applications(
+    const capmgr_package_info_h remote_pkg_info,
+    capmgr_package_info_foreach_app_cb cb,
+    void* user_data) {
+  if (!cb)
+    return CAPMGR_ERROR_INVALID_PARAMETER;
+
+  return CAPMGR_ERROR_NONE;
+}
diff --git a/src/dbus.cc b/src/dbus.cc
new file mode 100644 (file)
index 0000000..edd3138
--- /dev/null
@@ -0,0 +1,77 @@
+// Copyright (c) 2018 Samsung Electronics Co., Ltd All Rights Reserved
+// Use of this source code is governed by a apache 2.0 license that can be
+// found in the LICENSE file.
+
+#include "src/dbus.h"
+
+#include <glib.h>
+#include <gio/gio.h>
+
+#include "src/utils/logging.h"
+
+namespace {
+
+const char kDBusServiceName[] = "org.tizen.capmgr";
+const char kDBusObjectPath[] = "/org/tizen/capmgr";
+const char kDBusInterfaceName[] = "org.tizen.capmgr";
+
+struct cbdata {
+  capmgr::DBusCallback cb;
+  void* user_data;
+};
+
+void MethodCallback(GObject* source_object, GAsyncResult* res,
+    gpointer user_data) {
+  LOG(DEBUG) << "Got a response from capmgr";
+  GDBusProxy* proxy = reinterpret_cast<GDBusProxy*>(source_object);
+  GError* error = nullptr;
+  GVariant* result = g_dbus_proxy_call_finish(proxy, res, &error);
+
+  if (error) {
+    LOG(ERROR) << "g_dbus_proxy_call_finish() failed: " << error->message;
+    return;
+  }
+
+  struct cbdata* cbdata = reinterpret_cast<struct cbdata*>(user_data);
+  cbdata->cb(result, cbdata->user_data);
+  delete cbdata;
+}
+
+}  // namespace
+
+namespace capmgr {
+
+bool ProxyCallAsync(const char* method, GVariant* params, DBusCallback cb,
+    void* user_data) {
+  GError* error = nullptr;
+  GDBusConnection* conn = g_bus_get_sync(G_BUS_TYPE_SYSTEM, nullptr, &error);
+  if (!conn || error) {
+    LOG(ERROR) << "g_bus_get_sync() failed: " << error->message;
+    return false;
+  }
+  GDBusProxy* proxy = g_dbus_proxy_new_sync(conn,
+      G_DBUS_PROXY_FLAGS_DO_NOT_LOAD_PROPERTIES, nullptr,
+      kDBusServiceName, kDBusObjectPath, kDBusInterfaceName, nullptr,
+      &error);
+  if (!proxy || error) {
+    LOG(ERROR) << "g_dbus_proxy_new_sync() failed: " << error->message;
+    g_object_unref(conn);
+    return false;
+  }
+
+  // will be freed at MethodCallback()
+  struct cbdata* cbdata = new struct cbdata;
+  cbdata->cb = cb;
+  cbdata->user_data = user_data;
+
+  g_dbus_proxy_call(proxy, method,
+      params, G_DBUS_CALL_FLAGS_NONE, -1, nullptr, MethodCallback, cbdata);
+
+  g_object_unref(proxy);
+  g_dbus_connection_flush_sync(conn, nullptr, nullptr);
+  g_object_unref(conn);
+
+  return true;
+}
+
+}  // namespace capmgr
diff --git a/src/dbus.h b/src/dbus.h
new file mode 100644 (file)
index 0000000..123a5bb
--- /dev/null
@@ -0,0 +1,21 @@
+// Copyright (c) 2018 Samsung Electronics Co., Ltd All Rights Reserved
+// Use of this source code is governed by a apache 2.0 license that can be
+// found in the LICENSE file.
+
+#ifndef DBUS_H_
+#define DBUS_H_
+
+#include <glib.h>
+
+#include "include/capmgr.h"
+
+namespace capmgr {
+
+typedef void (*DBusCallback)(GVariant* result, void* user_data);
+
+bool ProxyCallAsync(const char* method, GVariant* params, DBusCallback cb,
+    void* user_data);
+
+}  // namespace capmgr
+
+#endif  // DBUS_H_
diff --git a/src/sql_connection.h b/src/sql_connection.h
new file mode 100644 (file)
index 0000000..722a312
--- /dev/null
@@ -0,0 +1,61 @@
+// Copyright (c) 2018 Samsung Electronics Co., Ltd All Rights Reserved
+// Use of this source code is governed by a apache 2.0 license that can be
+// found in the LICENSE file.
+
+#ifndef SQL_CONNECTION_H_
+#define SQL_CONNECTION_H_
+
+#include <memory>
+#include <mutex>
+#include <string>
+#include <utility>
+
+#include "src/sql_transaction.h"
+
+namespace capmgr {
+
+class SQLStatement;
+class SQLTransaction;
+
+class SQLConnection {
+ public:
+  SQLConnection() : error_code_(0), transaction_(this) {}
+  virtual ~SQLConnection() = default;
+
+  virtual bool Execute(const std::string& command) = 0;
+
+  virtual std::shared_ptr<SQLStatement> PrepareStatement(
+      const std::string& query) = 0;
+
+  virtual bool IsValid() = 0;
+
+  virtual void SetErrorCode(int error_code) {
+    error_code_ = error_code;
+  }
+
+  virtual int GetErrorCode() {
+    return error_code_;
+  }
+
+  virtual std::unique_lock<const SQLTransaction> GetTransactionGuard() {
+    return std::move(std::unique_lock<const SQLTransaction>(transaction_));
+  }
+
+ protected:
+  friend class SQLTransaction;
+
+  virtual void UnsetErrorCode() {
+    error_code_ = 0;
+  }
+
+  virtual bool BeginTransaction() = 0;
+  virtual bool CommitTransaction() = 0;
+  virtual bool RollbackTransaction() = 0;
+
+  int error_code_;
+  SQLTransaction transaction_;
+};
+
+}  // namespace capmgr
+
+#endif  // SQL_CONNECTION_H_
diff --git a/src/sql_statement.h b/src/sql_statement.h
new file mode 100644 (file)
index 0000000..d8742aa
--- /dev/null
@@ -0,0 +1,42 @@
+// Copyright (c) 2018 Samsung Electronics Co., Ltd All Rights Reserved
+// Use of this source code is governed by a apache 2.0 license that can be
+// found in the LICENSE file.
+
+#ifndef SQL_STATEMENT_H_
+#define SQL_STATEMENT_H_
+
+#include <string>
+
+namespace capmgr {
+
+class SQLConnection;
+
+class SQLStatement {
+ public:
+  enum class StepResult : int {
+    DONE,
+    ROW,
+    ERROR,
+  };
+
+  explicit SQLStatement(SQLConnection* sql_conn) : sql_conn_(sql_conn) {}
+  virtual ~SQLStatement() = default;
+
+  virtual StepResult Step() = 0;
+
+  virtual bool BindInt(int pos, int val) = 0;
+  virtual bool BindString(int pos, const std::string& val) = 0;
+
+  virtual int GetColumnInt(int pos) const = 0;
+  virtual std::string GetColumnString(int pos) const = 0;
+
+  virtual bool Reset() = 0;
+  virtual void Clear() = 0;
+
+ protected:
+  SQLConnection* sql_conn_;
+};
+
+}  // namespace capmgr
+
+#endif  // SQL_STATEMENT_H_
diff --git a/src/sql_transaction.cc b/src/sql_transaction.cc
new file mode 100644 (file)
index 0000000..9b70084
--- /dev/null
@@ -0,0 +1,22 @@
+// Copyright (c) 2018 Samsung Electronics Co., Ltd All Rights Reserved
+// Use of this source code is governed by a apache 2.0 license that can be
+// found in the LICENSE file.
+
+#include "src/sql_transaction.h"
+
+#include "src/sql_connection.h"
+
+namespace capmgr {
+
+void SQLTransaction::lock() const {
+  sql_conn_->BeginTransaction();
+}
+
+void SQLTransaction::unlock() const {
+  if (!sql_conn_->GetErrorCode())
+    sql_conn_->CommitTransaction();
+  else
+    sql_conn_->RollbackTransaction();
+}
+
+}  // namespace capmgr
diff --git a/src/sql_transaction.h b/src/sql_transaction.h
new file mode 100644 (file)
index 0000000..8ef5fc4
--- /dev/null
@@ -0,0 +1,28 @@
+// Copyright (c) 2018 Samsung Electronics Co., Ltd All Rights Reserved
+// Use of this source code is governed by a apache 2.0 license that can be
+// found in the LICENSE file.
+
+#ifndef SQL_TRANSACTION_H_
+#define SQL_TRANSACTION_H_
+
+namespace capmgr {
+
+class SQLConnection;
+
+// BasicLockableClass.
+// usage:
+//  SQLTransaction t;
+//  std::lock_guard<SQLTransaction> guard(t);
+class SQLTransaction {
+ public:
+  explicit SQLTransaction(SQLConnection* sql_conn) : sql_conn_(sql_conn) {}
+  void lock() const;
+  void unlock() const;
+
+ private:
+  SQLConnection* sql_conn_;
+};
+
+}  // namespace capmgr
+
+#endif  // SQL_TRANSACTION_H_
diff --git a/src/sqlite_connection.cc b/src/sqlite_connection.cc
new file mode 100644 (file)
index 0000000..8a0c36f
--- /dev/null
@@ -0,0 +1,117 @@
+// Copyright (c) 2018 Samsung Electronics Co., Ltd All Rights Reserved
+// Use of this source code is governed by a apache 2.0 license that can be
+// found in the LICENSE file.
+
+#include "src/sqlite_connection.h"
+
+#include <sqlite3.h>
+#include <sys/types.h>
+#include <unistd.h>
+
+#include <boost/optional.hpp>
+
+#include <string>
+#include <utility>
+
+#include "src/sqlite_statement.h"
+#include "src/utils/logging.h"
+
+namespace capmgr {
+
+SQLiteConnection::SQLiteConnection(std::string path, bool readonly)
+    : path_(std::move(path)), db_(nullptr) {
+  if (!Connect(readonly))
+    LOG(ERROR) << "Failed to connect db";
+}
+
+SQLiteConnection::~SQLiteConnection() {
+  Disconnect();
+}
+
+bool SQLiteConnection::Connect(bool readonly) {
+  int flags;
+  if (readonly)
+    flags = SQLITE_OPEN_READONLY;
+  else
+    flags = SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE;
+
+  sqlite3* db;
+  int r = sqlite3_open_v2(path_.c_str(), &db, flags, nullptr);
+  if (r != SQLITE_OK) {
+    LOG(ERROR) << "Failed to open sqlite3 db("
+               << path_ << "). Error code: " << r;
+    SetErrorCode(r);
+    sqlite3_close_v2(db);
+    return false;
+  }
+  r = sqlite3_exec(db, "PRAGMA foreign_keys=ON", nullptr, nullptr, nullptr);
+  if (r != SQLITE_OK)
+    LOG(ERROR) << "Failed to enable foreign key support: " << r;
+  db_ = db;
+  return true;
+}
+
+bool SQLiteConnection::Disconnect() {
+  if (db_) {
+    sqlite3_close_v2(db_);
+    db_ = nullptr;
+  }
+  return true;
+}
+
+bool SQLiteConnection::Execute(const std::string& command) {
+  if (!db_) {
+    LOG(ERROR) << "Invalid SQLite connection";
+    return false;
+  }
+
+  int r = sqlite3_exec(db_, command.c_str(), nullptr, nullptr, nullptr);
+  if (r != SQLITE_OK) {
+    LOG(ERROR) << "Execute command(" << command << ") failed: "
+               << GetErrorMessage();
+    SetErrorCode(r);
+    return false;
+  }
+  return true;
+}
+
+bool SQLiteConnection::BeginTransaction() {
+  return Execute("BEGIN EXCLUSIVE");
+}
+
+bool SQLiteConnection::CommitTransaction() {
+  return Execute("COMMIT");
+}
+
+bool SQLiteConnection::RollbackTransaction() {
+  return Execute("ROLLBACK");
+}
+
+std::string SQLiteConnection::GetErrorMessage() const {
+  return sqlite3_errmsg(db_);
+}
+
+std::shared_ptr<SQLStatement> SQLiteConnection::PrepareStatement(
+    const std::string& query) {
+  if (!db_) {
+    LOG(ERROR) << "Invalid SQLite connection";
+    return {};
+  }
+
+  sqlite3_stmt* stmt;
+  int r = sqlite3_prepare_v2(db_, query.c_str(), query.length(), &stmt,
+      nullptr);
+  if (r != SQLITE_OK) {
+    LOG(ERROR) << "sqlite3_prepare_v2() failed: " << GetErrorMessage();
+    return {};
+  }
+  return std::shared_ptr<SQLStatement>(new SQLiteStatement(this, stmt));
+}
+
+bool SQLiteConnection::IsValid() {
+  if (db_)
+    return true;
+  return false;
+}
+
+}  // namespace capmgr
diff --git a/src/sqlite_connection.h b/src/sqlite_connection.h
new file mode 100644 (file)
index 0000000..a257713
--- /dev/null
@@ -0,0 +1,52 @@
+// Copyright (c) 2018 Samsung Electronics Co., Ltd All Rights Reserved
+// Use of this source code is governed by a apache 2.0 license that can be
+// found in the LICENSE file.
+
+#ifndef SQLITE_CONNECTION_H_
+#define SQLITE_CONNECTION_H_
+
+#include <sqlite3.h>
+
+#include <memory>
+#include <mutex>
+#include <string>
+
+#include "src/sql_connection.h"
+#include "src/sql_statement.h"
+
+namespace capmgr {
+
+class SQLTransaction;
+
+class SQLiteConnection final : public SQLConnection {
+ public:
+  explicit SQLiteConnection(std::string path, bool readonly);
+  virtual ~SQLiteConnection();
+
+  // non-copyable
+  SQLiteConnection(const SQLiteConnection&) = delete;
+  SQLiteConnection& operator=(const SQLiteConnection&) = delete;
+
+  bool Execute(const std::string& command) override;
+
+  std::shared_ptr<SQLStatement> PrepareStatement(
+      const std::string& query) override;
+
+  bool IsValid() override;
+
+ private:
+  bool Connect(bool readonly);
+  bool Disconnect();
+  std::string GetErrorMessage() const;
+
+  bool BeginTransaction() override;
+  bool CommitTransaction() override;
+  bool RollbackTransaction() override;
+
+  std::string path_;
+  sqlite3* db_;
+};
+
+}  // namespace capmgr
+
+#endif  // SQLITE_CONNECTION_H_
diff --git a/src/sqlite_statement.cc b/src/sqlite_statement.cc
new file mode 100644 (file)
index 0000000..1738c13
--- /dev/null
@@ -0,0 +1,97 @@
+// Copyright (c) 2018 Samsung Electronics Co., Ltd All Rights Reserved
+// Use of this source code is governed by a apache 2.0 license that can be
+// found in the LICENSE file.
+
+#include "src/sqlite_statement.h"
+
+#include <sqlite3.h>
+
+#include <string>
+
+#include "src/sql_connection.h"
+#include "src/sql_statement.h"
+#include "src/utils/logging.h"
+
+namespace capmgr {
+
+SQLiteStatement::SQLiteStatement(SQLConnection* sql_conn, sqlite3_stmt* stmt)
+    : SQLStatement(sql_conn), stmt_(stmt) {}
+
+SQLiteStatement::~SQLiteStatement() {
+  int r = sqlite3_finalize(stmt_);
+  if (r != SQLITE_OK)
+    LOG(ERROR) << "sqlite3_finalize() failed: " << GetErrorMessage();
+}
+
+SQLStatement::StepResult SQLiteStatement::Step() {
+  int r = sqlite3_step(stmt_);
+  if (r != SQLITE_ROW && r != SQLITE_DONE) {
+    LOG(ERROR) << "sqlite3_step() failed: " << GetErrorMessage();
+    sql_conn_->SetErrorCode(r);
+    return SQLStatement::StepResult::ERROR;
+  }
+  SQLStatement::StepResult res;
+  if (r == SQLITE_ROW) {
+    res = SQLStatement::StepResult::ROW;
+  } else if (r == SQLITE_DONE) {
+    res = SQLStatement::StepResult::DONE;
+  } else {
+    LOG(ERROR) << "Unexpected sqlite3 result code: " << r;
+    res = SQLStatement::StepResult::ERROR;
+  }
+  return res;
+}
+
+bool SQLiteStatement::BindInt(int pos, int val) {
+  int r = sqlite3_bind_int(stmt_, pos, val);
+  if (r != SQLITE_OK) {
+    LOG(ERROR) << "sqlite3_bind_int() failed: " << GetErrorMessage();
+    sql_conn_->SetErrorCode(r);
+    return false;
+  }
+  return false;
+}
+
+bool SQLiteStatement::BindString(int pos, const std::string& val) {
+  int r = sqlite3_bind_text(stmt_, pos, val.c_str(), -1, SQLITE_STATIC);
+  if (r != SQLITE_OK) {
+    LOG(ERROR) << "sqlite3_bind_text() failed: " << GetErrorMessage();
+    sql_conn_->SetErrorCode(r);
+    return false;
+  }
+  return true;
+}
+
+int SQLiteStatement::GetColumnInt(int pos) const {
+  int val = sqlite3_column_int(stmt_, pos);
+  return val;
+}
+
+std::string SQLiteStatement::GetColumnString(int pos) const {
+  const char* val = reinterpret_cast<const char*>(
+      sqlite3_column_text(stmt_, pos));
+  if (!val) {
+    LOG(ERROR) << "sqlite3_column_text() failed: " << GetErrorMessage();
+    return {};
+  }
+  return std::string(val);
+}
+
+bool SQLiteStatement::Reset() {
+  int r = sqlite3_reset(stmt_);
+  if (r != SQLITE_OK) {
+    LOG(ERROR) << "sqlite3_reset failed: " << GetErrorMessage();
+    return false;
+  }
+  return true;
+}
+
+void SQLiteStatement::Clear() {
+  sqlite3_clear_bindings(stmt_);
+}
+
+std::string SQLiteStatement::GetErrorMessage() const {
+  return sqlite3_errmsg(sqlite3_db_handle(stmt_));
+}
+
+}  // namespace capmgr
diff --git a/src/sqlite_statement.h b/src/sqlite_statement.h
new file mode 100644 (file)
index 0000000..2509dcc
--- /dev/null
@@ -0,0 +1,46 @@
+// Copyright (c) 2018 Samsung Electronics Co., Ltd All Rights Reserved
+// Use of this source code is governed by a apache 2.0 license that can be
+// found in the LICENSE file.
+
+#ifndef SQLITE_STATEMENT_H_
+#define SQLITE_STATEMENT_H_
+
+#include <sqlite3.h>
+
+#include <string>
+
+#include "src/sql_statement.h"
+
+namespace capmgr {
+
+class SQLConnection;
+
+class SQLiteStatement final : public SQLStatement {
+ public:
+  SQLiteStatement(SQLConnection* sql_conn, sqlite3_stmt* stmt);
+  virtual ~SQLiteStatement();
+
+  // non-copyable
+  SQLiteStatement(const SQLiteStatement&) = delete;
+  SQLiteStatement& operator=(const SQLiteStatement&) = delete;
+
+  SQLStatement::StepResult Step() override;
+
+  bool BindInt(int pos, int val) override;
+  bool BindString(int pos, const std::string& val) override;
+
+  int GetColumnInt(int pos) const override;
+  std::string GetColumnString(int pos) const override;
+
+  bool Reset() override;
+  void Clear() override;
+
+ private:
+  std::string GetErrorMessage() const;
+
+  sqlite3_stmt* stmt_;
+};
+
+}  // namespace capmgr
+
+#endif  // SQLITE_STATEMENT_H_
diff --git a/src/utils/glist_range.h b/src/utils/glist_range.h
new file mode 100644 (file)
index 0000000..1d093dc
--- /dev/null
@@ -0,0 +1,84 @@
+// Copyright (c) 2015 Samsung Electronics Co., Ltd All Rights Reserved
+// Use of this source code is governed by an apache-2.0 license that can be
+// found in the LICENSE file.
+
+#ifndef UTILS_GLIST_RANGE_H_
+#define UTILS_GLIST_RANGE_H_
+
+#include <glib.h>
+
+#include <cstddef>
+#include <iterator>
+
+// Range with mutable forward iterator based on GList
+// supporting language foreach construct
+template<typename T>
+class GListRange {
+ public:
+  class Iterator {
+   public:
+    typedef T value_type;
+    typedef T& reference;
+    typedef T* pointer;
+    typedef const T* const_pointer;
+    typedef std::size_t difference_type;
+    typedef std::forward_iterator_tag iterator_category;
+
+    explicit Iterator(std::nullptr_t ptr = nullptr) : ptr_(ptr) { }
+    explicit Iterator(GList* ptr) : ptr_(ptr) { }
+    explicit operator bool() const {
+      return ptr_;
+    }
+    const reference& operator*() const {
+      return reinterpret_cast<const T&>(ptr_->data);
+    }
+    reference& operator*() {
+      return reinterpret_cast<T&>(ptr_->data);
+    }
+    const_pointer operator->() const {
+      return reinterpret_cast<pointer>(&ptr_->data);
+    }
+    pointer operator->() {
+      return reinterpret_cast<pointer>(&ptr_->data);
+    }
+    Iterator& operator++() {
+      ptr_ = g_list_next(ptr_);
+      return *this;
+    }
+    Iterator operator++(int) {
+      Iterator iter(ptr_);
+      ptr_ = g_list_next(ptr_);
+      return iter;
+    }
+    bool operator==(const Iterator& other) const {
+      return ptr_ == other.ptr_;
+    }
+    bool operator!=(const Iterator& other) const {
+      return !this->operator==(other);
+    }
+
+   private:
+    GList* ptr_;
+  };
+
+  explicit GListRange(GList* list) : list_(list) {  }
+  Iterator begin() {
+    return Iterator(list_);
+  }
+  Iterator end() {
+    return Iterator();
+  }
+
+  bool Empty() const noexcept {
+    return !list_;
+  }
+
+  guint Size() const {
+    return g_list_length(list_);
+  }
+
+ private:
+  GList* list_;
+};
+
+#endif  // UTILS_GLIST_RANGE_H_
diff --git a/src/utils/logging.cc b/src/utils/logging.cc
new file mode 100644 (file)
index 0000000..edfdbaf
--- /dev/null
@@ -0,0 +1,24 @@
+// Copyright (c) 2016 Samsung Electronics Co., Ltd All Rights Reserved
+// Use of this source code is governed by a apache 2.0 license that can be
+// found in the LICENSE file.
+
+#include "src/utils/logging.h"
+
+namespace utils {
+
+log_priority LogLevelToPriority(LogLevel level) {
+  switch (level) {
+    case LogLevel::LOG_ERROR:
+      return log_priority::DLOG_ERROR;
+    case LogLevel::LOG_WARNING:
+      return log_priority::DLOG_WARN;
+    case LogLevel::LOG_INFO:
+      return log_priority::DLOG_INFO;
+    case LogLevel::LOG_DEBUG:
+      return log_priority::DLOG_DEBUG;
+    default:
+      return log_priority::DLOG_UNKNOWN;
+  }
+}
+
+}  // namespace utils
diff --git a/src/utils/logging.h b/src/utils/logging.h
new file mode 100644 (file)
index 0000000..491521c
--- /dev/null
@@ -0,0 +1,116 @@
+// Copyright (c) 2014 Samsung Electronics Co., Ltd All Rights Reserved
+// Use of this source code is governed by a apache 2.0 license that can be
+// found in the LICENSE file.
+
+#ifndef UTILS_LOGGING_H_
+#define UTILS_LOGGING_H_
+
+#include <dlog.h>
+
+#ifndef PROJECT_TAG
+#define PROJECT_TAG ""
+#endif
+
+#ifdef LOG
+#undef LOG
+#endif
+
+#include <cassert>
+#include <cstring>
+#include <iomanip>
+#include <iostream>
+#include <sstream>
+#include <string>
+
+#ifndef __FILENAME__
+#define __FILENAME__                                                           \
+    (strrchr(__FILE__, '/') ? strrchr(__FILE__, '/') + 1 : __FILE__)
+#endif
+
+namespace utils {
+
+enum class LogLevel {
+  LOG_ERROR,
+  LOG_WARNING,
+  LOG_INFO,
+  LOG_DEBUG,
+};
+
+log_priority LogLevelToPriority(LogLevel level);
+
+template<LogLevel> struct LogTag;
+template<> struct LogTag<LogLevel::LOG_ERROR> {
+  static constexpr const char* value = "\033[1;31m| ERROR   |\033[0m";
+};
+template<> struct LogTag<LogLevel::LOG_WARNING> {
+  static constexpr const char* value = "\033[1;33m| WARNING |\033[0m";
+};
+template<> struct LogTag<LogLevel::LOG_INFO>  {
+  static constexpr const char* value = "\033[1;32m| INFO    |\033[0m";
+};
+template<> struct LogTag<LogLevel::LOG_DEBUG> {
+  static constexpr const char* value = "\033[0m| DEBUG   |\033[0m";
+};
+
+template <class charT, class traits = std::char_traits<charT>>
+class StringStream : private std::basic_ostringstream<charT, traits> {
+ public:
+  using std::basic_ostringstream<charT, traits>::str;
+
+  template <class T>
+  StringStream&  operator<<(const T& value) {
+    static_cast<std::basic_ostringstream<charT, traits> &>(*this) << value;
+    return *this;
+  }
+};
+
+class LogCatcher {
+ public:
+  LogCatcher(LogLevel level, const char* tag)
+    : level_(level), tag_(tag) { }
+
+  void operator&(const StringStream<char>& str) const {
+    dlog_print(LogLevelToPriority(level_), tag_.c_str(),
+        Escape(str.str()).c_str());
+  }
+
+ private:
+  // Since LogCatcher passes input to dlog_print(), the input which contains
+  // format string(such as %d, %n) can cause unexpected result.
+  // This is simple function to escape '%'.
+  // NOTE: Is there any gorgeous way instead of this?
+  std::string Escape(const std::string& str) const {
+    std::string escaped = std::string(str);
+    size_t start_pos = 0;
+    std::string from = "%";
+    std::string to = "%%";
+    while ((start_pos = escaped.find(from, start_pos)) != std::string::npos) {
+      escaped.replace(start_pos, from.length(), to);
+      start_pos += to.length();
+    }
+    return escaped;
+  }
+  LogLevel level_;
+  std::string tag_;
+};
+
+}  // namespace utils
+
+inline static const constexpr char* __tag_for_project() {
+  return PROJECT_TAG;
+}
+
+// Simple logging macro of following usage:
+//   LOG(LEVEL) << object_1 << object_2 << object_n;
+//     where:
+//       LEVEL = ERROR | WARNING | INFO | DEBUG
+#define LOG(LEVEL)                                                             \
+    ::utils::LogCatcher(                                                       \
+      ::utils::LogLevel::LOG_ ## LEVEL, __tag_for_project())                   \
+      & ::utils::StringStream<char>()                                          \
+      << std::string(::utils::LogTag<::utils::LogLevel::LOG_ ## LEVEL>::value) \
+      << " : " << std::setw(36)                                                \
+      << (std::string(__FILENAME__) + ":" + std::to_string(__LINE__)).c_str()  \
+      << std::setw(0) << " : "                                                 \
+
+#endif  // UTILS_LOGGING_H_
diff --git a/tools/CMakeLists.txt b/tools/CMakeLists.txt
new file mode 100644 (file)
index 0000000..6517088
--- /dev/null
@@ -0,0 +1,16 @@
+SET(CAPMGR_TEST "capmgr-test")
+
+AUX_SOURCE_DIRECTORY(${CMAKE_CURRENT_SOURCE_DIR} TOOLS_SRCS)
+INCLUDE_DIRECTORIES(${CMAKE_CURRENT_SOURCE_DIR}/../)
+
+ADD_EXECUTABLE(${CAPMGR_TEST} ${TOOLS_SRCS})
+
+APPLY_PKG_CONFIG(${CAPMGR_TEST} PUBLIC
+  GIO_DEPS
+  GLIB_DEPS
+  Boost
+)
+
+TARGET_LINK_LIBRARIES(${CAPMGR_TEST} PUBLIC ${TARGET_LIB_CAPMGR})
+
+INSTALL(TARGETS ${CAPMGR_TEST} DESTINATION bin)
diff --git a/tools/capmgr_test.cc b/tools/capmgr_test.cc
new file mode 100644 (file)
index 0000000..14cd131
--- /dev/null
@@ -0,0 +1,312 @@
+// Copyright (c) 2018 Samsung Electronics Co., Ltd All Rights Reserved
+// Use of this source code is governed by a apache 2.0 license that can be
+// found in the LICENSE file.
+
+#include <glib.h>
+#include <gio/gio.h>
+
+#include <boost/program_options.hpp>
+
+#include <iostream>
+
+#include "include/capmgr.h"
+
+namespace bpo = boost::program_options;
+
+namespace {
+
+const char kDBusServiceName[] = "org.tizen.capmgr";
+const char kDBusObjectPath[] = "/org/tizen/capmgr";
+const char kDBusInterfaceName[] = "org.tizen.capmgr";
+
+struct cbdata {
+  capmgr_device_h* device;
+  std::string device_id;
+};
+
+class Client {
+ public:
+  Client();
+  ~Client();
+
+  void CapExchange(GVariant* params);
+  void SendAppControl(const std::string& device_id, const std::string& appid);
+  void SendFile(const std::string& device_id, const std::string& file_path);
+  void ListDevices();
+
+ private:
+  GVariant* ProxyCallSync(const char* method, GVariant* params);
+  void WaitForResult();
+  void Quit();
+
+  static int AppControlCb(const capmgr_app_control_h request,
+      const capmgr_app_control_h reply, capmgr_app_control_result_e result,
+      void* user_data);
+
+  GMainLoop* loop_;
+  GDBusConnection* conn_;
+  GDBusProxy* proxy_;
+};
+
+int DeviceForeachCb(const capmgr_device_h device, void* user_data) {
+  char* device_id = nullptr;
+  char* model_name = nullptr;
+  char* device_name = nullptr;
+  char* platform_ver = nullptr;
+  char* profile = nullptr;
+  char* sw_ver = nullptr;
+
+  int ret = capmgr_device_get_device_id(device, &device_id);
+  if (ret != CAPMGR_ERROR_NONE)
+    std::cout << "Failed to get device id" << std::endl;
+
+  ret = capmgr_device_get_model_name(device, &model_name);
+  if (ret != CAPMGR_ERROR_NONE)
+    std::cout << "Failed to get model name" << std::endl;
+
+  ret = capmgr_device_get_device_name(device, &device_name);
+  if (ret != CAPMGR_ERROR_NONE)
+    std::cout << "Failed to get device name" << std::endl;
+
+  ret = capmgr_device_get_platform_ver(device, &platform_ver);
+  if (ret != CAPMGR_ERROR_NONE)
+    std::cout << "Failed to get platform version" << std::endl;
+
+  ret = capmgr_device_get_profile(device, &profile);
+  if (ret != CAPMGR_ERROR_NONE)
+    std::cout << "Failed to get profile" << std::endl;
+
+  ret = capmgr_device_get_sw_ver(device, &sw_ver);
+  if (ret != CAPMGR_ERROR_NONE)
+    std::cout << "Failed to get sw version" << std::endl;
+
+  if (user_data) {
+    struct cbdata* cbdata = reinterpret_cast<struct cbdata*>(user_data);
+    if (!strcmp(device_id, cbdata->device_id.c_str())) {
+      ret = capmgr_device_clone(device, cbdata->device);
+      if (ret != CAPMGR_ERROR_NONE)
+        std::cout << "capmgr_device_clone() failed: " << ret << std::endl;
+    }
+  } else {
+    std::cout << "==============================================" << std::endl;
+    std::cout << "DeviceID: " << device_id << std::endl
+              << "Model name: " << model_name << std::endl
+              << "Device name: " << device_name << std::endl
+              << "Platform version: " << platform_ver << std::endl
+              << "Profile: " << profile << std::endl
+              << "SW version: " << sw_ver << std::endl;
+  }
+
+  free(device_id);
+  free(model_name);
+  free(device_name);
+  free(platform_ver);
+  free(profile);
+  free(sw_ver);
+
+  return 0;
+}
+
+Client::Client() {
+  loop_ = g_main_loop_new(nullptr, FALSE);
+
+  GError* error = nullptr;
+  conn_ = g_bus_get_sync(G_BUS_TYPE_SYSTEM, nullptr, &error);
+  if (!conn_ || error) {
+    std::cout << "g_bus_get_sync() failed: " << error->message << std::endl;
+    exit(1);
+  }
+
+  proxy_ = g_dbus_proxy_new_sync(conn_, G_DBUS_PROXY_FLAGS_NONE, nullptr,
+      kDBusServiceName, kDBusObjectPath, kDBusInterfaceName, nullptr, &error);
+  if (!proxy_ || error) {
+    std::cout << "g_dbus_proxy_new_sync() failed: " << error->message
+              << std::endl;
+    exit(1);
+  }
+}
+
+Client::~Client() {
+  g_object_unref(proxy_);
+  g_dbus_connection_flush_sync(conn_, nullptr, nullptr);
+  g_object_unref(conn_);
+  g_main_loop_unref(loop_);
+}
+
+void Client::CapExchange(GVariant* params) {
+  GVariant* ret = ProxyCallSync("ExchangeCapabilities", params);
+  if (!ret)
+    return;
+
+  g_variant_unref(ret);
+}
+
+void Client::SendAppControl(const std::string& device_id,
+    const std::string& appid) {
+  if (device_id.empty()) {
+    std::cout << "Target device is missing!" << std::endl;
+    return;
+  }
+
+  capmgr_device_h device = nullptr;
+  struct cbdata cbdata = {&device, device_id};
+  int ret = capmgr_device_foreach_devices(DeviceForeachCb, &cbdata);
+  if (ret != CAPMGR_ERROR_NONE) {
+    std::cout << "capmgr_device_foreach_devices() failed: " << ret
+              << std::endl;
+    return;
+  }
+
+  if (*cbdata.device == nullptr) {
+    std::cout << "There is no such device!" << std::endl;
+    return;
+  }
+
+  capmgr_app_control_h ac;
+  ret = capmgr_app_control_create(&ac);
+  if (ret != CAPMGR_ERROR_NONE) {
+    std::cout << "capmgr_app_control_create() failed: " << ret << std::endl;
+    capmgr_device_destroy(device);
+    return;
+  }
+
+  ret = capmgr_app_control_set_device(ac, device);
+  if (ret != CAPMGR_ERROR_NONE) {
+    std::cout << "capmgr_app_control_set_device() failed: " << ret
+              << std::endl;
+    capmgr_device_destroy(device);
+    capmgr_app_control_destroy(ac);
+    return;
+  }
+
+  ret = capmgr_app_control_set_appid(ac, appid.c_str());
+  if (ret != CAPMGR_ERROR_NONE) {
+    std::cout << "capmgr_app_control_set_appid() failed: " << ret
+              << std::endl;
+    capmgr_device_destroy(device);
+    capmgr_app_control_destroy(ac);
+    return;
+  }
+
+  ret = capmgr_app_control_send(ac, &Client::AppControlCb, this);
+  if (ret != CAPMGR_ERROR_NONE)
+    std::cout << "capmgr_app_control_set_appid() failed: " << ret
+              << std::endl;
+
+  capmgr_device_destroy(device);
+  capmgr_app_control_destroy(ac);
+
+  WaitForResult();
+}
+
+void Client::ListDevices() {
+  int ret = capmgr_device_foreach_devices(DeviceForeachCb, nullptr);
+  if (ret != CAPMGR_ERROR_NONE)
+    std::cout << "capmgr_device_foreach_devices() failed: " << ret
+              << std::endl;
+}
+
+void Client::SendFile(const std::string& device_id,
+    const std::string& file_path) {
+  if (device_id.empty()) {
+    std::cout << "Target device is missing!" << std::endl;
+    return;
+  }
+
+  if (file_path.empty()) {
+    std::cout << "File path is missing!" << std::endl;
+    return;
+  }
+
+  std::cout << "Send file " << file_path << " to " << device_id << std::endl;
+
+  GVariant* params = g_variant_new("(ss)", device_id.c_str(),
+                       file_path.c_str());
+  if (!params) {
+    std::cout << "out of memory" << std::endl;
+    return;
+  }
+
+  GVariant* ret = ProxyCallSync("SendFile", params);
+
+  g_object_unref(params);
+  g_object_unref(ret);
+}
+
+GVariant* Client::ProxyCallSync(const char* method, GVariant* params) {
+  GError* error = nullptr;
+  GVariant* ret = g_dbus_proxy_call_sync(proxy_, method,
+      params, G_DBUS_CALL_FLAGS_NONE, -1, nullptr, &error);
+  if (error) {
+    std::cout << "g_dbus_proxy_call_sync of " << method << " failed: "
+      << error->message << std::endl;
+  }
+  return ret;
+}
+
+void Client::WaitForResult() {
+  g_main_loop_run(loop_);
+}
+
+void Client::Quit() {
+  g_main_loop_quit(loop_);
+}
+
+int Client::AppControlCb(const capmgr_app_control_h request,
+    const capmgr_app_control_h reply, capmgr_app_control_result_e result,
+    void* user_data) {
+  std::cout << "AppControlCb called" << std::endl;
+
+  char* data;
+  int ret = capmgr_app_control_get_extra_data(reply, "REPLY", &data);
+  if (ret != CAPMGR_ERROR_NONE) {
+    std::cout << "Failed to get extra data from appcontrol reply: " << ret
+              << std::endl;
+  } else {
+    std::cout << "Get reply from remote app: " << data << std::endl;
+    free(data);
+  }
+
+  Client* client = static_cast<Client*>(user_data);
+  client->Quit();
+  return 0;
+}
+
+}  // namespace
+
+int main(int argc, char* argv[]) {
+  bpo::options_description options("Allowed options");
+  bpo::variables_map opt_map;
+
+  ::Client client;
+  try {
+    options.add_options()
+        ("help,h", "help")
+        ("capexchange,c", "capability exchange")
+        ("device,d", bpo::value<std::string>(), "device id")
+        ("send-appcontrol,s", bpo::value<std::string>(),
+            "send remote app-control")
+        ("list-devices,l", "list remote devices")
+        ("send-file,f", bpo::value<std::string>(), "send file");
+    bpo::store(bpo::parse_command_line(argc, argv, options), opt_map);
+
+    if (opt_map.count("help"))
+      std::cout << options << std::endl;
+    else if (opt_map.count("capexchange"))
+      client.CapExchange(nullptr);
+    else if (opt_map.count("send-appcontrol"))
+      client.SendAppControl(opt_map["device"].as<std::string>(),
+          opt_map["send-appcontrol"].as<std::string>());
+    else if (opt_map.count("list-devices"))
+      client.ListDevices();
+    else if (opt_map.count("send-file"))
+      client.SendFile(opt_map["device"].as<std::string>(),
+          opt_map["send-file"].as<std::string>());
+    else
+      std::cout << options << std::endl;
+  } catch (...) {
+    std::cout << "Exception occured" << std::endl;
+  }
+
+  return 0;
+}
diff --git a/tools/check-coding-style b/tools/check-coding-style
new file mode 100755 (executable)
index 0000000..fd60481
--- /dev/null
@@ -0,0 +1,28 @@
+#!/bin/bash
+# Copyright (c) 2014 Samsung Electronics Co., Ltd All Rights Reserved
+# Use of this source code is governed by a BSD-style license that can be
+# found in the LICENSE file.
+
+if [ ! `which cpplint.py` ]; then
+   echo -e "\nPlease make sure cpplint.py is in your PATH. It is part of depot_tools inside Chromium repository."
+   exit 1
+fi
+
+OLDPWD=$PWD
+BASE=`dirname $0`
+cd $BASE/..
+
+# filters
+FILTERS="-readability/streams,-build/c++11"
+
+cpplint.py --root=src --filter="$FILTERS" $(find . \( -name '*.h' -o -name '*.cc' \) )
+RET=$?
+
+JS_RET_VAL=$?
+cd $OLDPWD
+
+if [ "x$RET" == "x0" ]; then
+  exit 0
+else
+  exit 1
+fi