92813f91fa0258400508f7099578ed20c2f02fe4
[iec.git] / src / type3_AndroidCloud / anbox-master / src / anbox / dbus / bus.cpp
1 /*
2  * Copyright (C) 2016 Simon Fels <morphis@gravedo.de>
3  *
4  * This program is free software: you can redistribute it and/or modify it
5  * under the terms of the GNU General Public License version 3, as published
6  * by the Free Software Foundation.
7  *
8  * This program is distributed in the hope that it will be useful, but
9  * WITHOUT ANY WARRANTY; without even the implied warranties of
10  * MERCHANTABILITY, SATISFACTORY QUALITY, or FITNESS FOR A PARTICULAR
11  * PURPOSE.  See the GNU General Public License for more details.
12  *
13  * You should have received a copy of the GNU General Public License along
14  * with this program.  If not, see <http://www.gnu.org/licenses/>.
15  *
16  */
17
18 #include "anbox/dbus/bus.h"
19 #include "anbox/logger.h"
20
21 namespace anbox {
22 namespace dbus {
23 Bus::Bus(Type type) {
24   int ret = 0;
25   switch (type) {
26   case Type::Session:
27     ret = sd_bus_open_user(&bus_);
28     break;
29   case Type::System:
30     ret = sd_bus_open_system(&bus_);
31     break;
32   default:
33     throw std::invalid_argument("Invalid bus type");
34   }
35
36   if (ret < 0 || !bus_)
37     throw std::runtime_error("Failed to connect to DBus");
38 }
39
40 Bus::~Bus() {
41   stop();
42
43   if (bus_)
44     sd_bus_unref(bus_);
45 }
46
47 bool Bus::has_service_with_name(const std::string &name) {
48   auto r = sd_bus_get_name_creds(bus_,
49                                  name.c_str(),
50                                  0,
51                                  nullptr);
52   return r >= 0;
53 }
54
55 sd_bus* Bus::raw() {
56   return bus_;
57 }
58
59 void Bus::run_async() {
60   running_ = true;
61   worker_thread_ = std::thread(&Bus::worker_main, this);
62 }
63
64 void Bus::stop() {
65   running_ = false;
66   if (worker_thread_.joinable())
67     worker_thread_.join();
68 }
69
70 void Bus::worker_main() {
71   while (running_) {
72     auto ret = sd_bus_process(bus_, nullptr);
73     if (ret < 0)
74       break;
75     if (ret > 0)
76       continue;
77
78     ret = sd_bus_wait(bus_, 1000 * 500);
79     if (ret < 0)
80       break;
81   }
82 }
83 }  // namespace dbus
84 }  // namespace anbox