aboutsummaryrefslogtreecommitdiff
path: root/libs/kdbinder/kdbus/connection.cpp
blob: 65ee566f48c8a855e17343bbdca65d67a0a05423 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
/*
 * Copyright (C) 2015 The Android Open Source Project
 *
 * 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.
 */

#define LOG_TAG "KDBUS::Connection"
#include <cutils/log.h>

#include <kdbinder/kdbus/KDBinder.h>
#include "cmds.h"
#include "items.h"
#include "iterable.h"
#include "msg.h"

#include <kdbus.h>
#include <poll.h>
#include <sys/mman.h>
#include <errno.h>

#include <vector>
#include <string>

namespace android {
namespace kdbus {

std::unique_ptr<Connection> Connection::hello(
    const Bus& bus,
    const std::string& connection_name) {
  return hello(bus.name, connection_name);
}

std::unique_ptr<Connection> Connection::hello(
    const std::string& bus_name,
    const std::string& connection_name) {
  std::string path(Bus::domain + bus_name + "/bus");

  FILE *bus_file = fopen(path.c_str(), "re");
  if (bus_file == nullptr) {
    ALOGE("Could not open bus file %s: %s\n", path.c_str(), strerror(errno));
    return nullptr;
  }

  // struct kdbus_cmd_hello takes the following items:
  //   - KDBUS_ITEM_CONN_DESCRIPTION: name of the connection
  auto reply = send_command_hello(bus_file,
                                  Connection::kPoolSize(),
                                  ItemConnDescription(connection_name));
  if (reply.error_code < 0) {
    ALOGE("Could not connect to Bus \"%s\" with Connection \"%s\": %s\n",
          bus_name.c_str(),
          connection_name.c_str(),
          reply.error_string.c_str());
    fclose(bus_file);
    return nullptr;
  }

  // map a memory region for future communications. Note that we
  // do not need to unmap it since it will be done automatically by the
  // kernel when we close the file descriptor.
  void *buf = mmap(NULL, Connection::kPoolSize(), PROT_READ, MAP_SHARED, fileno(bus_file), 0);
  if (buf == MAP_FAILED) {
    ALOGE("Could not mmap a memory pool for Connection %s: %s\n",
          connection_name.c_str(),
          strerror(errno));
    fclose(bus_file);
    return nullptr;
  }

  ALOGI("New Connection on Bus \"%s\": ID %d, description \"%s\"",
        bus_name.c_str(),
        (int) reply.id,
        connection_name.c_str());

  return std::unique_ptr<Connection>(new Connection(bus_file, reply.id, buf));
}

const Reply Connection::acquire_name(const std::string& name,
                                     uint64_t flags) const {
  // struct kdbus_cmd_name requires a KDBUS_ITEM_NAME.
  auto reply = send_command_name_acquire(bus_file_.get(),
                                         flags,
                                         ItemName(name));

  if (reply.error_code < 0) {
    ALOGE("ID %d could not acquire name \"%s\": %s\n",
          (int) id,
          name.c_str(),
          reply.error_string.c_str());
  }

  return reply;
}

const Reply Connection::release_name(const std::string& name) const {
  // struct kdbus_cmd_name requires a KDBUS_ITEM_NAME.
  auto reply = send_command_name_release(bus_file_.get(), ItemName(name));

  if (reply.error_code < 0) {
    ALOGE("ID %d could not release name \"%s\": %s\n",
          (int) id,
          name.c_str(),
          reply.error_string.c_str());
  }

  return reply;
}

std::vector<NameInfo> Connection::name_list(uint64_t flags) const {
  struct kdbus_name_list *list;
  std::vector<NameInfo> list_vector = {};

  auto reply = send_command_name_list(bus_file_.get(), flags);

  if (reply.error_code < 0) {
    ALOGE("ID %d could not get the list of acquired names: %s\n",
          (int) id,
          reply.error_string.c_str());
    return {};
  }

  // The list of names will be stored in our mapped memory region and
  // the kernel will have written the offset at which to read the data.
  list = reinterpret_cast<struct kdbus_name_list *>(
      reinterpret_cast<uint8_t *>(buf_.get()) + reply.offset);

  if (list->size != reply.list_size) {
    ALOGE("The size of the received list does not match the reply.");
    return {};
  }

  for_each_name_info(list, [&list_vector, &flags](struct kdbus_name_info *name) {
    // Include IDs.
    if ((flags & Unique) == Unique) {
      list_vector.emplace_back("", 0, name->conn_flags, name->owner_id);
    }

    // Include well-known names.
    if ((flags & Names) == Names) {
      for_each_item(name, [&list_vector, &name](struct kdbus_item *item) {
        if (item->type == KDBUS_ITEM_OWNED_NAME) {
          list_vector.emplace_back(item->name.name,
                                   item->name.flags,
                                   name->conn_flags,
                                   name->owner_id);
        }
      });
    }
  });

  return list_vector;
}

const Reply Connection::queue_message(const Connection& dst,
                                      const uint8_t *data,
                                      uint64_t size,
                                      uint64_t cookie) const {
  return queue_message(dst.id, data, size, cookie);
}

const Reply Connection::queue_message(uint64_t dst_id,
                                      const uint8_t *data,
                                      uint64_t size,
                                      uint64_t cookie) const {
  // When sending a asynchronous message, we do not need to use cookies so we
  // set it to 0. We are using cookies only for messages which expect a reply.
  Message message(dst_id, id, cookie, 0, ItemPayloadVec(data, size));

  auto reply = send_command_send_message(bus_file_.get(), message);

  if (reply.error_code < 0) {
    ALOGE("ID %d could not queue message: %s\n",
          (int) id,
          reply.error_string.c_str());
  }

  return reply;
}

const DataReply Connection::dequeue_message() const {
  auto reply = send_command_receive_message(bus_file_.get());
  if (reply.error_code < 0) {
    ALOGE("ID %d could not dequeue message: %s\n",
          (int) id,
          reply.error_string.c_str());
    return DataReply(reply);
  }

  struct kdbus_msg *msg = reinterpret_cast<struct kdbus_msg *>(
      reinterpret_cast<uint8_t *>(buf_.get()) + reply.offset);
  struct kdbus_item *item = nullptr;
  uint64_t size;
  uint8_t *data;

  // TODO: parse the rest of the items for extra information.
  for_each_item(msg, [&data, this, &size](struct kdbus_item *item) {
    switch (item->type) {
      case KDBUS_ITEM_PAYLOAD_OFF: {
        // This is potentially unsafe, as we are returning a pointer to the buffer
        // owned by the connection.
        size = item->vec.size;
        data = reinterpret_cast<uint8_t *>(buf_.get()) + item->vec.offset;
        break;
      }
    }
  });

  return DataReply(reply, data, size, reply.offset, msg->src_id, msg->cookie);
}

const DataReply Connection::dequeue_message_blocking(int timeout_ms) const {
  struct pollfd pollfd = {
    .fd = fileno(bus_file_.get()),
    .events = POLLIN | POLLPRI | POLLHUP,
    .revents = 0
  };

  int ret = poll(&pollfd, 1, timeout_ms);

  if (ret == 0) {
    ALOGW("ID %d timed out dequeuing a message: timeout of %d ms\n",
          (int) id,
          timeout_ms);
    return DataReply(Reply(-ETIMEDOUT, std::string(strerror(-errno))));
  } else if (ret > 0) {
    if (pollfd.revents & POLLIN) {
      return dequeue_message();
    }

    if (pollfd.revents & (POLLHUP | POLLERR)) {
      ret = -ECONNRESET;
    }
  }

  return DataReply(Reply(ret, std::string(strerror(-errno))));
}

const DataReply Connection::transact(const Connection& dst,
                                     uint64_t cookie,
                                     const uint8_t *data,
                                     uint64_t size,
                                     uint64_t timeout_ms) const {
  return transact(dst.id, cookie, data, size, timeout_ms);
}

const DataReply Connection::transact(uint64_t dst_id,
                                     uint64_t cookie,
                                     const uint8_t *data,
                                     uint64_t size,
                                     uint64_t timeout_ms) const {
  MessageSync message(dst_id,
                      id,
                      cookie,
                      timeout_ms,
                      ItemPayloadVec(data, size));

  auto reply = send_command_transact_message(bus_file_.get(), message);

  if (reply.error_code < 0) {
    ALOGE("ID %d could not issue transaction: %s\n",
          (int) id,
          reply.error_string.c_str());
    return DataReply(reply);
  }

  struct kdbus_msg *msg = reinterpret_cast<struct kdbus_msg *>(
      reinterpret_cast<uint8_t *>(buf_.get()) + reply.offset);
  struct kdbus_item *item = nullptr;
  uint8_t *data_out;
  uint64_t size_out;

  // TODO: parse the rest of the items for extra information.
  for_each_item(msg, [&data_out, this, &size_out](struct kdbus_item *item) {
    if (item->type == KDBUS_ITEM_PAYLOAD_OFF) {
      size_out = item->vec.size;
      data_out = reinterpret_cast<uint8_t *>(buf_.get()) + item->vec.offset;
    }
  });

  return DataReply(reply,
                   data_out,
                   size_out,
                   reply.offset,
                   msg->src_id,
                   msg->cookie);
}

const Reply Connection::reply(const Connection& dst,
                              uint64_t cookie,
                              const uint8_t *data,
                              uint64_t size) const {
  return reply(dst.id, cookie, data, size);
}

const Reply Connection::reply(uint64_t dst_id,
                              uint64_t cookie,
                              const uint8_t *data,
                              uint64_t size) const {
  MessageReply message(dst_id, id, cookie, ItemPayloadVec(data, size));

  auto reply = send_command_send_message(bus_file_.get(), message);

  if (reply.error_code < 0) {
    ALOGE("ID %d could not send a reply: %s\n",
          (int) id,
          reply.error_string.c_str());
  }

  return reply;
}

}  // namespace kdbus
}  // namespace android