blob: c10148e783618af4f0e5108b15aad67d9ee6fbfa [file] [log] [blame]
Ed Tanous911ac312017-08-15 09:37:42 -07001#include <crow/app.h>
2
3#include <tinyxml2.h>
Ed Tanous911ac312017-08-15 09:37:42 -07004#include <dbus_singleton.hpp>
Ed Tanousd4bb9bb2018-05-16 13:36:42 -07005#include <experimental/filesystem>
6#include <fstream>
Ed Tanouse0d918b2018-03-27 17:41:04 -07007#include <boost/algorithm/string.hpp>
Ed Tanous64530012018-02-06 17:08:16 -08008#include <boost/container/flat_set.hpp>
Ed Tanous911ac312017-08-15 09:37:42 -07009
10namespace crow {
11namespace openbmc_mapper {
Ed Tanousba9f9a62017-10-11 16:40:35 -070012
Ed Tanous911ac312017-08-15 09:37:42 -070013void introspect_objects(crow::response &res, std::string process_name,
Ed Tanous64530012018-02-06 17:08:16 -080014 std::string path,
15 std::shared_ptr<nlohmann::json> transaction) {
Ed Tanous911ac312017-08-15 09:37:42 -070016 crow::connections::system_bus->async_method_call(
Ed Tanousaa2e59c2018-04-12 12:17:20 -070017 [
18 &res, transaction, process_name{std::move(process_name)},
19 object_path{std::move(path)}
20 ](const boost::system::error_code ec, const std::string &introspect_xml) {
Ed Tanous911ac312017-08-15 09:37:42 -070021 if (ec) {
Ed Tanous64530012018-02-06 17:08:16 -080022 CROW_LOG_ERROR << "Introspect call failed with error: "
23 << ec.message() << " on process: " << process_name
24 << " path: " << object_path << "\n";
Ed Tanous911ac312017-08-15 09:37:42 -070025
26 } else {
Ed Tanous64530012018-02-06 17:08:16 -080027 transaction->push_back({{"path", object_path}});
Ed Tanous911ac312017-08-15 09:37:42 -070028
29 tinyxml2::XMLDocument doc;
30
31 doc.Parse(introspect_xml.c_str());
32 tinyxml2::XMLNode *pRoot = doc.FirstChildElement("node");
33 if (pRoot == nullptr) {
Ed Tanous64530012018-02-06 17:08:16 -080034 CROW_LOG_ERROR << "XML document failed to parse " << process_name
Ed Tanousaa2e59c2018-04-12 12:17:20 -070035 << " " << object_path << "\n";
Ed Tanous911ac312017-08-15 09:37:42 -070036
37 } else {
38 tinyxml2::XMLElement *node = pRoot->FirstChildElement("node");
39 while (node != nullptr) {
40 std::string child_path = node->Attribute("name");
41 std::string newpath;
42 if (object_path != "/") {
43 newpath += object_path;
44 }
45 newpath += "/" + child_path;
Ed Tanous64530012018-02-06 17:08:16 -080046 // introspect the subobjects as well
47 introspect_objects(res, process_name, newpath, transaction);
Ed Tanous911ac312017-08-15 09:37:42 -070048
49 node = node->NextSiblingElement("node");
50 }
51 }
52 }
53 // if we're the last outstanding caller, finish the request
Ed Tanous64530012018-02-06 17:08:16 -080054 if (transaction.use_count() == 1) {
55 res.json_value = {{"status", "ok"},
56 {"bus_name", process_name},
Ed Tanousd4bb9bb2018-05-16 13:36:42 -070057 {"objects", std::move(*transaction)}};
Ed Tanous911ac312017-08-15 09:37:42 -070058 res.end();
59 }
60 },
Ed Tanousaa2e59c2018-04-12 12:17:20 -070061 process_name, path, "org.freedesktop.DBus.Introspectable", "Introspect");
Ed Tanous911ac312017-08-15 09:37:42 -070062}
Ed Tanous64530012018-02-06 17:08:16 -080063
Ed Tanousaa2e59c2018-04-12 12:17:20 -070064// A smattering of common types to unpack. TODO(ed) this should really iterate
65// the sdbusplus object directly and build the json response
66using DbusRestVariantType = sdbusplus::message::variant<
67 std::vector<std::tuple<std::string, std::string, std::string>>, std::string,
68 int64_t, uint64_t, double, int32_t, uint32_t, int16_t, uint16_t, uint8_t,
69 bool>;
70
71using ManagedObjectType = std::vector<std::pair<
72 sdbusplus::message::object_path,
73 boost::container::flat_map<
74 std::string,
75 boost::container::flat_map<std::string, DbusRestVariantType>>>>;
76
77void get_managed_objects_for_enumerate(
Ed Tanous64530012018-02-06 17:08:16 -080078 const std::string &object_name, const std::string &connection_name,
79 crow::response &res, std::shared_ptr<nlohmann::json> transaction) {
80 crow::connections::system_bus->async_method_call(
81 [&res, transaction](const boost::system::error_code ec,
82 const ManagedObjectType &objects) {
83 if (ec) {
84 CROW_LOG_ERROR << ec;
85 } else {
86 nlohmann::json &data_json = *transaction;
Ed Tanousaa2e59c2018-04-12 12:17:20 -070087
Ed Tanous64530012018-02-06 17:08:16 -080088 for (auto &object_path : objects) {
Ed Tanousaa2e59c2018-04-12 12:17:20 -070089 CROW_LOG_DEBUG << "Reading object "
Ed Tanousa4e18f22018-04-27 10:25:29 -070090 << static_cast<const std::string &>(
91 object_path.first);
Ed Tanousaa2e59c2018-04-12 12:17:20 -070092 nlohmann::json &object_json =
Ed Tanousa4e18f22018-04-27 10:25:29 -070093 data_json[static_cast<const std::string &>(object_path.first)];
Ed Tanousaa2e59c2018-04-12 12:17:20 -070094 if (object_json.is_null()) {
95 object_json = nlohmann::json::object();
96 }
Ed Tanous64530012018-02-06 17:08:16 -080097 for (const auto &interface : object_path.second) {
98 for (const auto &property : interface.second) {
Ed Tanousaa2e59c2018-04-12 12:17:20 -070099 nlohmann::json &property_json = object_json[property.first];
100 mapbox::util::apply_visitor(
101 [&property_json](auto &&val) { property_json = val; },
Ed Tanous64530012018-02-06 17:08:16 -0800102 property.second);
Ed Tanousaa2e59c2018-04-12 12:17:20 -0700103
104 // dbus-rest represents booleans as 1 or 0, implement to match
105 // TODO(ed) see if dbus-rest should be changed
106 const bool *property_bool =
107 property_json.get_ptr<const bool *>();
108 if (property_bool != nullptr) {
109 property_json = *property_bool ? 1 : 0;
110 }
Ed Tanous64530012018-02-06 17:08:16 -0800111 }
112 }
113 }
114 }
115
116 if (transaction.use_count() == 1) {
117 res.json_value = {{"message", "200 OK"},
118 {"status", "ok"},
119 {"data", std::move(*transaction)}};
120 res.end();
121 }
122 },
Ed Tanousaa2e59c2018-04-12 12:17:20 -0700123 connection_name, object_name, "org.freedesktop.DBus.ObjectManager",
124 "GetManagedObjects");
125}
Ed Tanous64530012018-02-06 17:08:16 -0800126
127using GetSubTreeType = std::vector<
128 std::pair<std::string,
129 std::vector<std::pair<std::string, std::vector<std::string>>>>>;
130
Ed Tanousd4bb9bb2018-05-16 13:36:42 -0700131// Structure for storing data on an in progress action
132struct InProgressActionData {
133 InProgressActionData(crow::response &res) : res(res){};
134 ~InProgressActionData() {
135 if (res.result() == boost::beast::http::status::internal_server_error) {
136 // Reset the json object to clear out any data that made it in before the
137 // error happened
138 // todo(ed) handle error condition with proper code
139 res.json_value = nlohmann::json::object();
140 }
141 res.end();
142 }
143
144 void setErrorStatus() {
145 res.result(boost::beast::http::status::internal_server_error);
146 }
147 crow::response &res;
148 std::string path;
149 std::string method_name;
150 nlohmann::json arguments;
151};
152
153std::vector<std::string> dbus_arg_split(const std::string &string) {
154 std::vector<std::string> ret;
155 if (string.empty()) {
156 return ret;
157 }
158 ret.push_back("");
159 int container_depth = 0;
160 std::string::const_iterator character = string.begin();
161 while (character != string.end()) {
162 switch (*character) {
163 case ('a'):
164 ret.back() += *character;
165 break;
166 case ('('):
167 case ('{'):
168 ret.back() += *character;
169 container_depth++;
170 break;
171 case ('}'):
172 case (')'):
173 ret.back() += *character;
174 container_depth--;
175 if (container_depth == 0) {
176 character++;
177 if (character != string.end()) {
178 ret.push_back("");
179 }
180 continue;
181 }
182 break;
183 default:
184 ret.back() += *character;
185 if (container_depth == 0) {
186 character++;
187 if (character != string.end()) {
188 ret.push_back("");
189 }
190 continue;
191 }
192 break;
193 }
194 character++;
195 }
196}
197
198int convert_json_to_dbus(sd_bus_message *m, const std::string &arg_type,
199 const nlohmann::json &input_json) {
200 int r = 0;
201 CROW_LOG_DEBUG << "Converting " << input_json.dump()
202 << " to type: " << arg_type;
203 const std::vector<std::string> arg_types = dbus_arg_split(arg_type);
204
205 // Assume a single object for now.
206 const nlohmann::json *j = &input_json;
207 nlohmann::json::const_iterator j_it = input_json.begin();
208
209 for (const std::string &arg_code : arg_types) {
210 // If we are decoding multiple objects, grab the pointer to the iterator,
211 // and increment it for the next loop
212 if (arg_types.size() > 1) {
213 if (j_it == input_json.end()) {
214 return -2;
215 }
216 j = &*j_it;
217 j_it++;
218 }
219 const int64_t *int_value = j->get_ptr<const int64_t *>();
220 const uint64_t *uint_value = j->get_ptr<const uint64_t *>();
221 const std::string *string_value = j->get_ptr<const std::string *>();
222 const double *double_value = j->get_ptr<const double *>();
223 const bool *b = j->get_ptr<const bool *>();
224 int64_t v = 0;
225 double d = 0.0;
226
227 // Do some basic type conversions that make sense. uint can be converted to
228 // int. int and uint can be converted to double
229 if (uint_value != nullptr && int_value == nullptr) {
230 v = static_cast<int64_t>(*uint_value);
231 int_value = &v;
232 }
233 if (uint_value != nullptr && double_value == nullptr) {
234 d = static_cast<double>(*uint_value);
235 double_value = &d;
236 }
237 if (int_value != nullptr && double_value == nullptr) {
238 d = static_cast<double>(*int_value);
239 double_value = &d;
240 }
241
242 if (arg_code == "s") {
243 if (string_value == nullptr) {
244 return -1;
245 }
246 r = sd_bus_message_append_basic(m, arg_code[0],
247 (void *)string_value->c_str());
248 if (r < 0) {
249 return r;
250 }
251 } else if (arg_code == "i") {
252 if (int_value == nullptr) {
253 return -1;
254 }
255 int32_t i = static_cast<int32_t>(*int_value);
256 r = sd_bus_message_append_basic(m, arg_code[0], &i);
257 if (r < 0) {
258 return r;
259 }
260 } else if (arg_code == "b") {
261 // lots of ways bool could be represented here. Try them all
262 int bool_int = false;
263 if (int_value != nullptr) {
264 bool_int = *int_value > 0 ? 1 : 0;
265 } else if (b != nullptr) {
266 bool_int = b ? 1 : 0;
267 } else if (string_value != nullptr) {
268 bool_int = boost::istarts_with(*string_value, "t") ? 1 : 0;
269 } else {
270 return -1;
271 }
272 r = sd_bus_message_append_basic(m, arg_code[0], &bool_int);
273 if (r < 0) {
274 return r;
275 }
276 } else if (arg_code == "n") {
277 if (int_value == nullptr) {
278 return -1;
279 }
280 int16_t n = static_cast<int16_t>(*int_value);
281 r = sd_bus_message_append_basic(m, arg_code[0], &n);
282 if (r < 0) {
283 return r;
284 }
285 } else if (arg_code == "x") {
286 if (int_value == nullptr) {
287 return -1;
288 }
289 r = sd_bus_message_append_basic(m, arg_code[0], int_value);
290 if (r < 0) {
291 return r;
292 }
293 } else if (arg_code == "y") {
294 if (uint_value == nullptr) {
295 return -1;
296 }
297 uint8_t y = static_cast<uint8_t>(*uint_value);
298 r = sd_bus_message_append_basic(m, arg_code[0], &y);
299 } else if (arg_code == "q") {
300 if (uint_value == nullptr) {
301 return -1;
302 }
303 uint16_t q = static_cast<uint16_t>(*uint_value);
304 r = sd_bus_message_append_basic(m, arg_code[0], &q);
305 } else if (arg_code == "u") {
306 if (uint_value == nullptr) {
307 return -1;
308 }
309 uint32_t u = static_cast<uint32_t>(*uint_value);
310 r = sd_bus_message_append_basic(m, arg_code[0], &u);
311 } else if (arg_code == "t") {
312 if (uint_value == nullptr) {
313 return -1;
314 }
315 r = sd_bus_message_append_basic(m, arg_code[0], uint_value);
316 } else if (arg_code == "d") {
317 sd_bus_message_append_basic(m, arg_code[0], double_value);
318 } else if (boost::starts_with(arg_code, "a")) {
319 std::string contained_type = arg_code.substr(1);
320 r = sd_bus_message_open_container(m, SD_BUS_TYPE_ARRAY,
321 contained_type.c_str());
322 if (r < 0) {
323 return r;
324 }
325
326 for (nlohmann::json::const_iterator it = j->begin(); it != j->end();
327 ++it) {
328 r = convert_json_to_dbus(m, contained_type, *it);
329 if (r < 0) {
330 return r;
331 }
332
333 it++;
334 }
335 sd_bus_message_close_container(m);
336 } else if (boost::starts_with(arg_code, "v")) {
337 std::string contained_type = arg_code.substr(1);
338 CROW_LOG_DEBUG << "variant type: " << arg_code
339 << " appending variant of type: " << contained_type;
340 r = sd_bus_message_open_container(m, SD_BUS_TYPE_VARIANT,
341 contained_type.c_str());
342 if (r < 0) {
343 return r;
344 }
345
346 r = convert_json_to_dbus(m, contained_type, input_json);
347 if (r < 0) {
348 return r;
349 }
350
351 r = sd_bus_message_close_container(m);
352 if (r < 0) {
353 return r;
354 }
355
356 } else if (boost::starts_with(arg_code, "(") &&
357 boost::ends_with(arg_code, ")")) {
358 std::string contained_type = arg_code.substr(1, arg_code.size() - 1);
359 r = sd_bus_message_open_container(m, SD_BUS_TYPE_STRUCT,
360 contained_type.c_str());
361 nlohmann::json::const_iterator it = j->begin();
362 for (const std::string &arg_code : dbus_arg_split(arg_type)) {
363 if (it == j->end()) {
364 return -1;
365 }
366 r = convert_json_to_dbus(m, arg_code, *it);
367 if (r < 0) {
368 return r;
369 }
370 it++;
371 }
372 r = sd_bus_message_close_container(m);
373 } else if (boost::starts_with(arg_code, "{") &&
374 boost::ends_with(arg_code, "}")) {
375 std::string contained_type = arg_code.substr(1, arg_code.size() - 1);
376 r = sd_bus_message_open_container(m, SD_BUS_TYPE_DICT_ENTRY,
377 contained_type.c_str());
378 std::vector<std::string> codes = dbus_arg_split(contained_type);
379 if (codes.size() != 2) {
380 return -1;
381 }
382 const std::string &key_type = codes[0];
383 const std::string &value_type = codes[1];
384 for (auto it : j->items()) {
385 r = convert_json_to_dbus(m, key_type, it.key());
386 if (r < 0) {
387 return r;
388 };
389
390 r = convert_json_to_dbus(m, value_type, it.value());
391 if (r < 0) {
392 return r;
393 }
394 }
395 r = sd_bus_message_close_container(m);
396 } else {
397 return -2;
398 }
399 if (r < 0) {
400 return r;
401 }
402
403 if (arg_types.size() > 1) {
404 j_it++;
405 }
406 }
407}
408
409void find_action_on_interface(std::shared_ptr<InProgressActionData> transaction,
410 const std::string &connectionName) {
411 CROW_LOG_DEBUG << "find_action_on_interface for connection "
412 << connectionName;
413 crow::connections::system_bus->async_method_call(
414 [
415 transaction, connectionName{std::string(connectionName)}
416 ](const boost::system::error_code ec, const std::string &introspect_xml) {
417 CROW_LOG_DEBUG << "got xml:\n " << introspect_xml;
418 if (ec) {
419 CROW_LOG_ERROR << "Introspect call failed with error: "
420 << ec.message() << " on process: " << connectionName
421 << "\n";
422 } else {
423 tinyxml2::XMLDocument doc;
424
425 doc.Parse(introspect_xml.c_str());
426 tinyxml2::XMLNode *pRoot = doc.FirstChildElement("node");
427 if (pRoot == nullptr) {
428 CROW_LOG_ERROR << "XML document failed to parse " << connectionName
429 << "\n";
430
431 } else {
432 tinyxml2::XMLElement *interface_node =
433 pRoot->FirstChildElement("interface");
434 while (interface_node != nullptr) {
435 std::string this_interface_name =
436 interface_node->Attribute("name");
437 tinyxml2::XMLElement *method_node =
438 interface_node->FirstChildElement("method");
439 while (method_node != nullptr) {
440 std::string this_method_name = method_node->Attribute("name");
441 CROW_LOG_DEBUG << "Found method: " << this_method_name;
442 if (this_method_name == transaction->method_name) {
443 sdbusplus::message::message m =
444 crow::connections::system_bus->new_method_call(
445 connectionName.c_str(), transaction->path.c_str(),
446 this_interface_name.c_str(),
447 transaction->method_name.c_str());
448
449 tinyxml2::XMLElement *argument_node =
450 method_node->FirstChildElement("arg");
451
452 nlohmann::json::const_iterator arg_it =
453 transaction->arguments.begin();
454
455 while (argument_node != nullptr) {
456 std::string arg_direction =
457 argument_node->Attribute("direction");
458 if (arg_direction == "in") {
459 std::string arg_type = argument_node->Attribute("type");
460 if (arg_it == transaction->arguments.end()) {
461 transaction->setErrorStatus();
462 return;
463 }
464 if (convert_json_to_dbus(m.get(), arg_type, *arg_it) <
465 0) {
466 transaction->setErrorStatus();
467 return;
468 }
469
470 arg_it++;
471 }
472 argument_node = method_node->NextSiblingElement("arg");
473 }
474 crow::connections::system_bus->async_send(
475 m, [transaction](boost::system::error_code ec,
476 sdbusplus::message::message &m) {
477 if (ec) {
478 transaction->setErrorStatus();
479 return;
480 }
481 transaction->res.json_value = {{"status", "ok"},
482 {"message", "200 OK"},
483 {"data", nullptr}};
484 });
485 break;
486 }
487 method_node = method_node->NextSiblingElement("method");
488 }
489 interface_node = interface_node->NextSiblingElement("interface");
490 }
491 }
492 }
493 },
494 connectionName, transaction->path, "org.freedesktop.DBus.Introspectable",
495 "Introspect");
496}
497
498void handle_action(const crow::request &req, crow::response &res,
499 const std::string &object_path,
500 const std::string &method_name) {
501 nlohmann::json request_dbus_data =
502 nlohmann::json::parse(req.body, nullptr, false);
503
504 if (request_dbus_data.is_discarded()) {
505 res.result(boost::beast::http::status::bad_request);
506 res.end();
507 return;
508 }
509 if (!request_dbus_data.is_array()) {
510 res.result(boost::beast::http::status::bad_request);
511 res.end();
512 return;
513 }
514 auto transaction = std::make_shared<InProgressActionData>(res);
515
516 transaction->path = object_path;
517 transaction->method_name = method_name;
518 transaction->arguments = std::move(request_dbus_data);
519 crow::connections::system_bus->async_method_call(
520 [transaction](
521 const boost::system::error_code ec,
522 const std::vector<std::pair<std::string, std::vector<std::string>>>
523 &interface_names) {
524 if (ec || interface_names.size() <= 0) {
525 transaction->setErrorStatus();
526 return;
527 }
528
529 CROW_LOG_DEBUG << "GetObject returned objects "
530 << interface_names.size();
531
532 for (const std::pair<std::string, std::vector<std::string>> &object :
533 interface_names) {
534 find_action_on_interface(transaction, object.first);
535 }
536 },
537 "xyz.openbmc_project.ObjectMapper", "/xyz/openbmc_project/object_mapper",
538 "xyz.openbmc_project.ObjectMapper", "GetObject", object_path,
539 std::array<std::string, 0>());
540}
541
542void handle_list(crow::response &res, const std::string &object_path) {
543 crow::connections::system_bus->async_method_call(
544 [&res](const boost::system::error_code ec,
545 std::vector<std::string> &object_paths) {
546 if (ec) {
547 res.result(boost::beast::http::status::internal_server_error);
548 } else {
549 res.json_value = {{"status", "ok"},
550 {"message", "200 OK"},
551 {"data", std::move(object_paths)}};
552 }
553 res.end();
554 },
555 "xyz.openbmc_project.ObjectMapper", "/xyz/openbmc_project/object_mapper",
556 "xyz.openbmc_project.ObjectMapper", "GetSubTreePaths", object_path,
557 static_cast<int32_t>(99), std::array<std::string, 0>());
558}
559
Ed Tanous64530012018-02-06 17:08:16 -0800560void handle_enumerate(crow::response &res, const std::string &object_path) {
561 crow::connections::system_bus->async_method_call(
562 [&res, object_path{std::string(object_path)} ](
563 const boost::system::error_code ec,
564 const GetSubTreeType &object_names) {
565 if (ec) {
Ed Tanousd4bb9bb2018-05-16 13:36:42 -0700566 res.json_value = {{"message", "200 OK"},
567 {"status", "ok"},
568 {"data", nlohmann::json::object()}};
569
Ed Tanous64530012018-02-06 17:08:16 -0800570 res.end();
571 return;
572 }
573
574 boost::container::flat_set<std::string> connections;
575
576 for (const auto &object : object_names) {
577 for (const auto &connection : object.second) {
578 connections.insert(connection.first);
579 }
580 }
581
582 if (connections.size() <= 0) {
Ed Tanouse0d918b2018-03-27 17:41:04 -0700583 res.result(boost::beast::http::status::not_found);
Ed Tanous64530012018-02-06 17:08:16 -0800584 res.end();
585 return;
586 }
587 auto transaction =
588 std::make_shared<nlohmann::json>(nlohmann::json::object());
589 for (const std::string &connection : connections) {
Ed Tanousaa2e59c2018-04-12 12:17:20 -0700590 get_managed_objects_for_enumerate(object_path, connection, res,
591 transaction);
Ed Tanous64530012018-02-06 17:08:16 -0800592 }
Ed Tanous64530012018-02-06 17:08:16 -0800593 },
Ed Tanousaa2e59c2018-04-12 12:17:20 -0700594 "xyz.openbmc_project.ObjectMapper", "/xyz/openbmc_project/object_mapper",
595 "xyz.openbmc_project.ObjectMapper", "GetSubTree", object_path, (int32_t)0,
596 std::array<std::string, 0>());
Ed Tanous64530012018-02-06 17:08:16 -0800597}
Ed Tanous911ac312017-08-15 09:37:42 -0700598
Ed Tanousd4bb9bb2018-05-16 13:36:42 -0700599void handle_get(crow::response &res, const std::string &object_path,
600 const std::string &dest_property) {
601 std::shared_ptr<std::string> property_name =
602 std::make_shared<std::string>(dest_property);
603 using GetObjectType =
604 std::vector<std::pair<std::string, std::vector<std::string>>>;
605 crow::connections::system_bus->async_method_call(
606 [&res, object_path, property_name](const boost::system::error_code ec,
607 const GetObjectType &object_names) {
608 if (ec || object_names.size() <= 0) {
609 res.result(boost::beast::http::status::not_found);
610 res.end();
611 return;
612 }
613 std::shared_ptr<nlohmann::json> response =
614 std::make_shared<nlohmann::json>(nlohmann::json::object());
615 // The mapper should never give us an empty interface names list, but
616 // check anyway
617 for (const std::pair<std::string, std::vector<std::string>> connection :
618 object_names) {
619 const std::vector<std::string> &interfaceNames = connection.second;
620
621 if (interfaceNames.size() <= 0) {
622 res.result(boost::beast::http::status::not_found);
623 res.end();
624 return;
625 }
626
627 for (const std::string &interface : interfaceNames) {
628 crow::connections::system_bus->async_method_call(
629 [&res, response, property_name](
630 const boost::system::error_code ec,
631 const std::vector<std::pair<
632 std::string, DbusRestVariantType>> &properties) {
633 if (ec) {
634 CROW_LOG_ERROR << "Bad dbus request error: " << ec;
635 } else {
636 for (const std::pair<std::string, DbusRestVariantType>
637 &property : properties) {
638 // if property name is empty, or matches our search query,
639 // add it to the response json
640
641 if (property_name->empty()) {
642 mapbox::util::apply_visitor(
643 [&response, &property](auto &&val) {
644 (*response)[property.first] = val;
645 },
646 property.second);
647 } else if (property.first == *property_name) {
648 mapbox::util::apply_visitor(
649 [&response](auto &&val) { (*response) = val; },
650 property.second);
651 }
652 }
653 }
654 if (response.use_count() == 1) {
655 res.json_value = {{"status", "ok"},
656 {"message", "200 OK"},
657 {"data", *response}};
658
659 res.end();
660 }
661 },
662 connection.first, object_path,
663 "org.freedesktop.DBus.Properties", "GetAll", interface);
664 }
665 }
666 },
667 "xyz.openbmc_project.ObjectMapper", "/xyz/openbmc_project/object_mapper",
668 "xyz.openbmc_project.ObjectMapper", "GetObject", object_path,
669 std::array<std::string, 0>());
670}
671
672struct AsyncPutRequest {
673 AsyncPutRequest(crow::response &res) : res(res) {
674 res.json_value = {
675 {"status", "ok"}, {"message", "200 OK"}, {"data", nullptr}};
676 }
677 ~AsyncPutRequest() {
678 if (res.result() == boost::beast::http::status::internal_server_error) {
679 // Reset the json object to clear out any data that made it in before the
680 // error happened
681 // todo(ed) handle error condition with proper code
682 res.json_value = nlohmann::json::object();
683 }
684
685 if (res.json_value.empty()) {
686 res.result(boost::beast::http::status::forbidden);
687 res.json_value = {
688 {"status", "error"},
689 {"message", "403 Forbidden"},
690 {"data",
691 {{"message",
692 "The specified property cannot be created: " + propertyName}}}};
693 }
694
695 res.end();
696 }
697
698 void setErrorStatus() {
699 res.result(boost::beast::http::status::internal_server_error);
700 }
701
702 crow::response &res;
703 std::string objectPath;
704 std::string propertyName;
705 nlohmann::json propertyValue;
706};
707
708void handle_put(const crow::request &req, crow::response &res,
709 const std::string &objectPath,
710 const std::string &destProperty) {
711 nlohmann::json request_dbus_data =
712 nlohmann::json::parse(req.body, nullptr, false);
713
714 if (request_dbus_data.is_discarded()) {
715 res.result(boost::beast::http::status::bad_request);
716 res.end();
717 return;
718 }
719
720 nlohmann::json::const_iterator property_it = request_dbus_data.find("data");
721 if (property_it == request_dbus_data.end()) {
722 res.result(boost::beast::http::status::bad_request);
723 res.end();
724 return;
725 }
726 const nlohmann::json &propertySetValue = *property_it;
727 auto transaction = std::make_shared<AsyncPutRequest>(res);
728 transaction->objectPath = objectPath;
729 transaction->propertyName = destProperty;
730 transaction->propertyValue = propertySetValue;
731
732 using GetObjectType =
733 std::vector<std::pair<std::string, std::vector<std::string>>>;
734
735 crow::connections::system_bus->async_method_call(
736 [transaction](const boost::system::error_code ec,
737 const GetObjectType &object_names) {
738 if (!ec && object_names.size() <= 0) {
739 transaction->res.result(boost::beast::http::status::not_found);
740 return;
741 }
742
743 for (const std::pair<std::string, std::vector<std::string>> connection :
744 object_names) {
745 const std::string &connectionName = connection.first;
746
747 crow::connections::system_bus->async_method_call(
748 [ connectionName{std::string(connectionName)}, transaction ](
749 const boost::system::error_code ec,
750 const std::string &introspectXml) {
751 if (ec) {
752 CROW_LOG_ERROR
753 << "Introspect call failed with error: " << ec.message()
754 << " on process: " << connectionName;
755 transaction->setErrorStatus();
756 return;
757 }
758 tinyxml2::XMLDocument doc;
759
760 doc.Parse(introspectXml.c_str());
761 tinyxml2::XMLNode *pRoot = doc.FirstChildElement("node");
762 if (pRoot == nullptr) {
763 CROW_LOG_ERROR << "XML document failed to parse: "
764 << introspectXml;
765 transaction->setErrorStatus();
766 return;
767 }
768 tinyxml2::XMLElement *ifaceNode =
769 pRoot->FirstChildElement("interface");
770 while (ifaceNode != nullptr) {
771 const char *interfaceName = ifaceNode->Attribute("name");
772 CROW_LOG_DEBUG << "found interface " << interfaceName;
773 tinyxml2::XMLElement *propNode =
774 ifaceNode->FirstChildElement("property");
775 while (propNode != nullptr) {
776 const char *propertyName = propNode->Attribute("name");
777 CROW_LOG_DEBUG << "Found property " << propertyName;
778 if (propertyName == transaction->propertyName) {
779 const char *argType = propNode->Attribute("type");
780 if (argType != nullptr) {
781 sdbusplus::message::message m =
782 crow::connections::system_bus->new_method_call(
783 connectionName.c_str(),
784 transaction->objectPath.c_str(),
785 "org.freedesktop.DBus.Properties", "Set");
786 m.append(interfaceName, transaction->propertyName);
787 int r = sd_bus_message_open_container(
788 m.get(), SD_BUS_TYPE_VARIANT, argType);
789 if (r < 0) {
790 transaction->setErrorStatus();
791 return;
792 }
793 r = convert_json_to_dbus(m.get(), argType,
794 transaction->propertyValue);
795 if (r < 0) {
796 transaction->setErrorStatus();
797 return;
798 }
799 r = sd_bus_message_close_container(m.get());
800 if (r < 0) {
801 transaction->setErrorStatus();
802 return;
803 }
804
805 crow::connections::system_bus->async_send(
806 m, [transaction](boost::system::error_code ec,
807 sdbusplus::message::message &m) {
808 CROW_LOG_DEBUG << "sent";
809 if (ec) {
810 transaction->res.json_value["status"] = "error";
811 transaction->res.json_value["message"] =
812 ec.message();
813 }
814 });
815 }
816 }
817 propNode = propNode->NextSiblingElement("property");
818 }
819 ifaceNode = ifaceNode->NextSiblingElement("interface");
820 }
821 },
822 connectionName, transaction->objectPath,
823 "org.freedesktop.DBus.Introspectable", "Introspect");
824 }
825 },
826 "xyz.openbmc_project.ObjectMapper", "/xyz/openbmc_project/object_mapper",
827 "xyz.openbmc_project.ObjectMapper", "GetObject", transaction->objectPath,
828 std::array<std::string, 0>());
829}
830
Ed Tanous911ac312017-08-15 09:37:42 -0700831template <typename... Middlewares>
832void request_routes(Crow<Middlewares...> &app) {
Ed Tanouse0d918b2018-03-27 17:41:04 -0700833 CROW_ROUTE(app, "/bus/")
834 .methods("GET"_method)([](const crow::request &req, crow::response &res) {
835 res.json_value = {{"busses", {{{"name", "system"}}}}, {"status", "ok"}};
836 });
Ed Tanous911ac312017-08-15 09:37:42 -0700837
838 CROW_ROUTE(app, "/bus/system/")
839 .methods("GET"_method)([](const crow::request &req, crow::response &res) {
Ed Tanousaa2e59c2018-04-12 12:17:20 -0700840 auto myCallback = [&res](const boost::system::error_code ec,
841 std::vector<std::string> &names) {
842 if (ec) {
Ed Tanousd4bb9bb2018-05-16 13:36:42 -0700843 CROW_LOG_ERROR << "Dbus call failed with code " << ec;
Ed Tanouse0d918b2018-03-27 17:41:04 -0700844 res.result(boost::beast::http::status::internal_server_error);
Ed Tanousaa2e59c2018-04-12 12:17:20 -0700845 } else {
846 std::sort(names.begin(), names.end());
847 nlohmann::json j{{"status", "ok"}};
848 auto &objects_sub = j["objects"];
849 for (auto &name : names) {
850 objects_sub.push_back({{"name", name}});
851 }
852 res.json_value = std::move(j);
853 }
854 res.end();
855 };
Ed Tanous911ac312017-08-15 09:37:42 -0700856 crow::connections::system_bus->async_method_call(
Ed Tanousaa2e59c2018-04-12 12:17:20 -0700857 std::move(myCallback), "org.freedesktop.DBus", "/",
858 "org.freedesktop.DBus", "ListNames");
Ed Tanous911ac312017-08-15 09:37:42 -0700859 });
860
Ed Tanousba9f9a62017-10-11 16:40:35 -0700861 CROW_ROUTE(app, "/list/")
862 .methods("GET"_method)([](const crow::request &req, crow::response &res) {
Ed Tanousd4bb9bb2018-05-16 13:36:42 -0700863 handle_list(res, "/");
Ed Tanousba9f9a62017-10-11 16:40:35 -0700864 });
865
Ed Tanous64530012018-02-06 17:08:16 -0800866 CROW_ROUTE(app, "/xyz/<path>")
Ed Tanousd4bb9bb2018-05-16 13:36:42 -0700867 .methods("GET"_method, "PUT"_method,
868 "POST"_method)([](const crow::request &req, crow::response &res,
869 const std::string &path) {
Ed Tanousa4e18f22018-04-27 10:25:29 -0700870 std::string object_path = "/xyz/" + path;
871
Ed Tanousd4bb9bb2018-05-16 13:36:42 -0700872 // Trim any trailing "/" at the end
873 if (boost::ends_with(object_path, "/")) {
874 object_path.pop_back();
875 }
876
877 // If accessing a single attribute, fill in and update object_path,
878 // otherwise leave dest_property blank
879 std::string dest_property = "";
880 const char *attr_seperator = "/attr/";
Ed Tanousa4e18f22018-04-27 10:25:29 -0700881 size_t attr_position = path.find(attr_seperator);
882 if (attr_position != path.npos) {
shiyilei00b92f72017-11-12 16:21:16 +0800883 object_path = "/xyz/" + path.substr(0, attr_position);
Ed Tanousd4bb9bb2018-05-16 13:36:42 -0700884 dest_property = path.substr(attr_position + strlen(attr_seperator),
Ed Tanousa4e18f22018-04-27 10:25:29 -0700885 path.length());
shiyilei00b92f72017-11-12 16:21:16 +0800886 }
887
Ed Tanousd4bb9bb2018-05-16 13:36:42 -0700888 if (req.method() == "POST"_method) {
889 constexpr const char *action_seperator = "/action/";
890 size_t action_position = path.find(action_seperator);
891 if (action_position != path.npos) {
892 object_path = "/xyz/" + path.substr(0, action_position);
893 std::string post_property = path.substr(
894 (action_position + strlen(action_seperator)), path.length());
895 handle_action(req, res, object_path, post_property);
896 return;
897 }
898 } else if (req.method() == "GET"_method) {
899 if (boost::ends_with(object_path, "/enumerate")) {
900 object_path.erase(object_path.end() - 10, object_path.end());
901 handle_enumerate(res, object_path);
902 } else if (boost::ends_with(object_path, "/list")) {
903 object_path.erase(object_path.end() - 5, object_path.end());
904 handle_list(res, object_path);
905 } else {
906 handle_get(res, object_path, dest_property);
907 }
908 return;
909 } else if (req.method() == "PUT"_method) {
910 handle_put(req, res, object_path, dest_property);
Ed Tanous64530012018-02-06 17:08:16 -0800911 return;
912 }
913
Ed Tanousd4bb9bb2018-05-16 13:36:42 -0700914 res.result(boost::beast::http::status::method_not_allowed);
915 res.end();
Ed Tanousba9f9a62017-10-11 16:40:35 -0700916 });
shiyilei00b92f72017-11-12 16:21:16 +0800917
Ed Tanous911ac312017-08-15 09:37:42 -0700918 CROW_ROUTE(app, "/bus/system/<str>/")
919 .methods("GET"_method)([](const crow::request &req, crow::response &res,
920 const std::string &connection) {
Ed Tanous64530012018-02-06 17:08:16 -0800921 std::shared_ptr<nlohmann::json> transaction;
922 introspect_objects(res, connection, "/", transaction);
Ed Tanous911ac312017-08-15 09:37:42 -0700923 });
924
Ed Tanousd4bb9bb2018-05-16 13:36:42 -0700925 CROW_ROUTE(app, "/download/dump/<str>/")
926 .methods("GET"_method)([](const crow::request &req, crow::response &res,
927 const std::string &dumpId) {
928 std::regex validFilename("^[\\w\\- ]+(\\.?[\\w\\- ]+)$");
929 if (!std::regex_match(dumpId, validFilename)) {
930 res.result(boost::beast::http::status::not_found);
931 res.end();
932 return;
933 }
934 std::experimental::filesystem::path loc(
935 "/var/lib/phosphor-debug-collector/dumps");
936
937 loc += dumpId;
938
939 if (!std::experimental::filesystem::exists(loc) ||
940 !std::experimental::filesystem::is_directory(loc)) {
941 res.result(boost::beast::http::status::not_found);
942 res.end();
943 return;
944 }
945 std::experimental::filesystem::directory_iterator files(loc);
946 for (auto &file : files) {
947 std::ifstream readFile(file.path());
948 if (readFile.good()) {
949 continue;
950 }
951 res.add_header("Content-Type", "application/octet-stream");
952 res.body() = {std::istreambuf_iterator<char>(readFile),
953 std::istreambuf_iterator<char>()};
954 res.end();
955 }
956 res.result(boost::beast::http::status::not_found);
957 res.end();
958 return;
959 });
960
Ed Tanous911ac312017-08-15 09:37:42 -0700961 CROW_ROUTE(app, "/bus/system/<str>/<path>")
962 .methods("GET"_method)([](const crow::request &req, crow::response &res,
963 const std::string &process_name,
964 const std::string &requested_path) {
Ed Tanous911ac312017-08-15 09:37:42 -0700965 std::vector<std::string> strs;
966 boost::split(strs, requested_path, boost::is_any_of("/"));
967 std::string object_path;
968 std::string interface_name;
969 std::string method_name;
970 auto it = strs.begin();
971 if (it == strs.end()) {
972 object_path = "/";
973 }
974 while (it != strs.end()) {
975 // Check if segment contains ".". If it does, it must be an
976 // interface
Ed Tanousd4bb9bb2018-05-16 13:36:42 -0700977 if (it->find(".") != std::string::npos) {
Ed Tanous911ac312017-08-15 09:37:42 -0700978 break;
Ed Tanousba9f9a62017-10-11 16:40:35 -0700979 // THis check is neccesary as the trailing slash gets parsed as
Ed Tanous64530012018-02-06 17:08:16 -0800980 // part of our <path> specifier above, which causes the normal
981 // trailing backslash redirector to fail.
Ed Tanous911ac312017-08-15 09:37:42 -0700982 } else if (!it->empty()) {
983 object_path += "/" + *it;
984 }
985 it++;
986 }
987 if (it != strs.end()) {
988 interface_name = *it;
989 it++;
990
991 // after interface, we might have a method name
992 if (it != strs.end()) {
993 method_name = *it;
994 it++;
995 }
996 }
997 if (it != strs.end()) {
998 // if there is more levels past the method name, something went
Ed Tanousd4bb9bb2018-05-16 13:36:42 -0700999 // wrong, return not found
Ed Tanouse0d918b2018-03-27 17:41:04 -07001000 res.result(boost::beast::http::status::not_found);
Ed Tanous911ac312017-08-15 09:37:42 -07001001 res.end();
1002 return;
1003 }
Ed Tanous911ac312017-08-15 09:37:42 -07001004 if (interface_name.empty()) {
1005 crow::connections::system_bus->async_method_call(
Ed Tanousd4bb9bb2018-05-16 13:36:42 -07001006 [&, process_name, object_path](
1007 const boost::system::error_code ec,
1008 const std::string &introspect_xml) {
Ed Tanous911ac312017-08-15 09:37:42 -07001009 if (ec) {
Ed Tanous64530012018-02-06 17:08:16 -08001010 CROW_LOG_ERROR
Ed Tanous911ac312017-08-15 09:37:42 -07001011 << "Introspect call failed with error: " << ec.message()
1012 << " on process: " << process_name
1013 << " path: " << object_path << "\n";
1014
1015 } else {
1016 tinyxml2::XMLDocument doc;
1017
1018 doc.Parse(introspect_xml.c_str());
1019 tinyxml2::XMLNode *pRoot = doc.FirstChildElement("node");
1020 if (pRoot == nullptr) {
Ed Tanous64530012018-02-06 17:08:16 -08001021 CROW_LOG_ERROR << "XML document failed to parse "
1022 << process_name << " " << object_path
1023 << "\n";
Ed Tanouse0d918b2018-03-27 17:41:04 -07001024 res.json_value = {{"status", "XML parse error"}};
1025 res.result(
1026 boost::beast::http::status::internal_server_error);
Ed Tanous911ac312017-08-15 09:37:42 -07001027 } else {
1028 nlohmann::json interfaces_array = nlohmann::json::array();
1029 tinyxml2::XMLElement *interface =
1030 pRoot->FirstChildElement("interface");
1031
1032 while (interface != nullptr) {
1033 std::string iface_name = interface->Attribute("name");
1034 interfaces_array.push_back({{"name", iface_name}});
1035
1036 interface = interface->NextSiblingElement("interface");
1037 }
Ed Tanous64530012018-02-06 17:08:16 -08001038 res.json_value = {{"status", "ok"},
1039 {"bus_name", process_name},
1040 {"interfaces", interfaces_array},
1041 {"object_path", object_path}};
Ed Tanous911ac312017-08-15 09:37:42 -07001042 }
1043 }
1044 res.end();
1045 },
Ed Tanousaa2e59c2018-04-12 12:17:20 -07001046 process_name, object_path, "org.freedesktop.DBus.Introspectable",
1047 "Introspect");
Ed Tanous911ac312017-08-15 09:37:42 -07001048 } else {
1049 crow::connections::system_bus->async_method_call(
1050 [
Ed Tanousd4bb9bb2018-05-16 13:36:42 -07001051 &, process_name, object_path,
1052 interface_name{std::move(interface_name)}
Ed Tanous911ac312017-08-15 09:37:42 -07001053 ](const boost::system::error_code ec,
1054 const std::string &introspect_xml) {
1055 if (ec) {
Ed Tanous64530012018-02-06 17:08:16 -08001056 CROW_LOG_ERROR
Ed Tanous911ac312017-08-15 09:37:42 -07001057 << "Introspect call failed with error: " << ec.message()
1058 << " on process: " << process_name
1059 << " path: " << object_path << "\n";
1060
1061 } else {
1062 tinyxml2::XMLDocument doc;
1063
1064 doc.Parse(introspect_xml.c_str());
1065 tinyxml2::XMLNode *pRoot = doc.FirstChildElement("node");
1066 if (pRoot == nullptr) {
Ed Tanous64530012018-02-06 17:08:16 -08001067 CROW_LOG_ERROR << "XML document failed to parse "
1068 << process_name << " " << object_path
1069 << "\n";
Ed Tanouse0d918b2018-03-27 17:41:04 -07001070 res.result(
1071 boost::beast::http::status::internal_server_error);
Ed Tanous911ac312017-08-15 09:37:42 -07001072
1073 } else {
1074 tinyxml2::XMLElement *node =
1075 pRoot->FirstChildElement("node");
1076
1077 // if we know we're the only call, build the json directly
1078 nlohmann::json methods_array = nlohmann::json::array();
1079 nlohmann::json signals_array = nlohmann::json::array();
1080 tinyxml2::XMLElement *interface =
1081 pRoot->FirstChildElement("interface");
1082
1083 while (interface != nullptr) {
1084 std::string iface_name = interface->Attribute("name");
1085
1086 if (iface_name == interface_name) {
1087 tinyxml2::XMLElement *methods =
1088 interface->FirstChildElement("method");
1089 while (methods != nullptr) {
1090 nlohmann::json args_array = nlohmann::json::array();
1091 tinyxml2::XMLElement *arg =
1092 methods->FirstChildElement("arg");
1093 while (arg != nullptr) {
1094 args_array.push_back(
1095 {{"name", arg->Attribute("name")},
1096 {"type", arg->Attribute("type")},
1097 {"direction", arg->Attribute("direction")}});
1098 arg = arg->NextSiblingElement("arg");
1099 }
1100 methods_array.push_back(
1101 {{"name", methods->Attribute("name")},
Ed Tanous64530012018-02-06 17:08:16 -08001102 {"uri", "/bus/system/" + process_name +
1103 object_path + "/" + interface_name +
1104 "/" + methods->Attribute("name")},
Ed Tanous911ac312017-08-15 09:37:42 -07001105 {"args", args_array}});
1106 methods = methods->NextSiblingElement("method");
1107 }
1108 tinyxml2::XMLElement *signals =
1109 interface->FirstChildElement("signal");
1110 while (signals != nullptr) {
1111 nlohmann::json args_array = nlohmann::json::array();
1112
1113 tinyxml2::XMLElement *arg =
1114 signals->FirstChildElement("arg");
1115 while (arg != nullptr) {
1116 std::string name = arg->Attribute("name");
1117 std::string type = arg->Attribute("type");
1118 args_array.push_back({
Ed Tanous64530012018-02-06 17:08:16 -08001119 {"name", name},
1120 {"type", type},
Ed Tanous911ac312017-08-15 09:37:42 -07001121 });
1122 arg = arg->NextSiblingElement("arg");
1123 }
1124 signals_array.push_back(
1125 {{"name", signals->Attribute("name")},
1126 {"args", args_array}});
1127 signals = signals->NextSiblingElement("signal");
1128 }
1129
Ed Tanousd4bb9bb2018-05-16 13:36:42 -07001130 res.json_value = {
Ed Tanous911ac312017-08-15 09:37:42 -07001131 {"status", "ok"},
1132 {"bus_name", process_name},
1133 {"interface", interface_name},
1134 {"methods", methods_array},
1135 {"object_path", object_path},
1136 {"properties", nlohmann::json::object()},
1137 {"signals", signals_array}};
1138
Ed Tanous911ac312017-08-15 09:37:42 -07001139 break;
1140 }
1141
1142 interface = interface->NextSiblingElement("interface");
1143 }
1144 if (interface == nullptr) {
1145 // if we got to the end of the list and never found a
1146 // match, throw 404
Ed Tanouse0d918b2018-03-27 17:41:04 -07001147 res.result(boost::beast::http::status::not_found);
Ed Tanous911ac312017-08-15 09:37:42 -07001148 }
1149 }
1150 }
1151 res.end();
1152 },
Ed Tanousaa2e59c2018-04-12 12:17:20 -07001153 process_name, object_path, "org.freedesktop.DBus.Introspectable",
1154 "Introspect");
Ed Tanous911ac312017-08-15 09:37:42 -07001155 }
Ed Tanous911ac312017-08-15 09:37:42 -07001156 });
Ed Tanousd4bb9bb2018-05-16 13:36:42 -07001157}
Ed Tanous911ac312017-08-15 09:37:42 -07001158} // namespace openbmc_mapper
1159} // namespace crow