blob: 2eabc868adaedfddaa46b2dcb76fbff1a706d13e [file] [log] [blame]
Szymon Dompke1cdd7e42022-06-08 14:43:13 +02001#include "utils/dbus_path_utils.hpp"
2
3namespace utils
4{
5sdbusplus::message::object_path pathAppend(sdbusplus::message::object_path path,
6 const std::string& appended)
7{
8 if (appended.starts_with('/') || !isValidDbusPath(appended))
9 {
10 throw sdbusplus::exception::SdBusError(
11 static_cast<int>(std::errc::invalid_argument),
12 "Invalid appended string");
13 }
14
15 size_t pos_start = 0;
16 size_t pos_end = 0;
17 while ((pos_end = appended.find('/', pos_start)) != std::string::npos)
18 {
19 if (pos_start == pos_end)
20 {
21 throw sdbusplus::exception::SdBusError(
22 static_cast<int>(std::errc::invalid_argument),
23 "Invalid appended string");
24 }
25 path /= std::string_view(appended.begin() + pos_start,
26 appended.begin() + pos_end);
27 pos_start = pos_end + 1;
28 }
29 path /= std::string_view(appended.begin() + pos_start, appended.end());
30 return path;
31}
32
33std::string reportPathToId(const sdbusplus::message::object_path& path)
34{
35 if (path.str.starts_with(constants::reportDirStr))
36 {
37 auto id = path.str.substr(constants::reportDirStr.length());
Szymon Dompke32305f12022-07-05 15:37:21 +020038 verifyIdPrefixes(id);
Szymon Dompke1cdd7e42022-06-08 14:43:13 +020039 return id;
40 }
41 throw sdbusplus::exception::SdBusError(
42 static_cast<int>(std::errc::invalid_argument), "Invalid path prefix");
43}
Szymon Dompke32305f12022-07-05 15:37:21 +020044
45void verifyIdPrefixes(std::string_view id)
46{
47 size_t pos_start = 0;
48 size_t pos_end = 0;
49 size_t prefix_cnt = 0;
50 while ((pos_end = id.find('/', pos_start)) != std::string::npos)
51 {
52 if (pos_start == pos_end)
53 {
Krzysztof Grobelny62c08e92022-09-16 10:28:53 +020054 throw errors::InvalidArgument("Id", "Invalid prefixes in id.");
Szymon Dompke32305f12022-07-05 15:37:21 +020055 }
56
57 if (++prefix_cnt > constants::maxPrefixesInId)
58 {
Krzysztof Grobelny62c08e92022-09-16 10:28:53 +020059 throw errors::InvalidArgument("Id", "Too many prefixes.");
Szymon Dompke32305f12022-07-05 15:37:21 +020060 }
61
62 if (pos_end - pos_start > constants::maxPrefixLength)
63 {
Krzysztof Grobelny62c08e92022-09-16 10:28:53 +020064 throw errors::InvalidArgument("Id", "Prefix too long.");
Szymon Dompke32305f12022-07-05 15:37:21 +020065 }
66
67 pos_start = pos_end + 1;
68 }
69
70 if (id.length() - pos_start > constants::maxIdNameLength)
71 {
Krzysztof Grobelny62c08e92022-09-16 10:28:53 +020072 throw errors::InvalidArgument("Id", "Too long.");
Szymon Dompke32305f12022-07-05 15:37:21 +020073 }
74}
Szymon Dompke1cdd7e42022-06-08 14:43:13 +020075} // namespace utils