xref: /openbmc/bmcweb/include/dbus_monitor.hpp (revision f8fe53e7114ab10c9059377541277739ace5c1ff)
1 #pragma once
2 #include <app.hpp>
3 #include <async_resp.hpp>
4 #include <boost/container/flat_map.hpp>
5 #include <boost/container/flat_set.hpp>
6 #include <dbus_singleton.hpp>
7 #include <openbmc_dbus_rest.hpp>
8 #include <sdbusplus/bus/match.hpp>
9 #include <sdbusplus/message/types.hpp>
10 #include <websocket.hpp>
11 
12 #include <variant>
13 
14 namespace crow
15 {
16 namespace dbus_monitor
17 {
18 
19 struct DbusWebsocketSession
20 {
21     std::vector<std::unique_ptr<sdbusplus::bus::match_t>> matches;
22     boost::container::flat_set<std::string, std::less<>,
23                                std::vector<std::string>>
24         interfaces;
25 };
26 
27 static boost::container::flat_map<crow::websocket::Connection*,
28                                   DbusWebsocketSession>
29     sessions;
30 
31 inline int onPropertyUpdate(sd_bus_message* m, void* userdata,
32                             sd_bus_error* retError)
33 {
34     if (retError == nullptr || (sd_bus_error_is_set(retError) != 0))
35     {
36         BMCWEB_LOG_ERROR << "Got sdbus error on match";
37         return 0;
38     }
39     crow::websocket::Connection* connection =
40         static_cast<crow::websocket::Connection*>(userdata);
41     auto thisSession = sessions.find(connection);
42     if (thisSession == sessions.end())
43     {
44         BMCWEB_LOG_ERROR << "Couldn't find dbus connection " << connection;
45         return 0;
46     }
47     sdbusplus::message_t message(m);
48     nlohmann::json json;
49     json["event"] = message.get_member();
50     json["path"] = message.get_path();
51     if (strcmp(message.get_member(), "PropertiesChanged") == 0)
52     {
53         nlohmann::json data;
54         int r = openbmc_mapper::convertDBusToJSON("sa{sv}as", message, data);
55         if (r < 0)
56         {
57             BMCWEB_LOG_ERROR << "convertDBusToJSON failed with " << r;
58             return 0;
59         }
60         if (!data.is_array())
61         {
62             BMCWEB_LOG_ERROR << "No data in PropertiesChanged signal";
63             return 0;
64         }
65 
66         // data is type sa{sv}as and is an array[3] of string, object, array
67         json["interface"] = data[0];
68         json["properties"] = data[1];
69     }
70     else if (strcmp(message.get_member(), "InterfacesAdded") == 0)
71     {
72         nlohmann::json data;
73         int r = openbmc_mapper::convertDBusToJSON("oa{sa{sv}}", message, data);
74         if (r < 0)
75         {
76             BMCWEB_LOG_ERROR << "convertDBusToJSON failed with " << r;
77             return 0;
78         }
79 
80         if (!data.is_array())
81         {
82             BMCWEB_LOG_ERROR << "No data in InterfacesAdded signal";
83             return 0;
84         }
85 
86         // data is type oa{sa{sv}} which is an array[2] of string, object
87         for (const auto& entry : data[1].items())
88         {
89             auto it = thisSession->second.interfaces.find(entry.key());
90             if (it != thisSession->second.interfaces.end())
91             {
92                 json["interfaces"][entry.key()] = entry.value();
93             }
94         }
95     }
96     else
97     {
98         BMCWEB_LOG_CRITICAL << "message " << message.get_member()
99                             << " was unexpected";
100         return 0;
101     }
102 
103     connection->sendText(
104         json.dump(2, ' ', true, nlohmann::json::error_handler_t::replace));
105     return 0;
106 }
107 
108 inline void requestRoutes(App& app)
109 {
110     BMCWEB_ROUTE(app, "/subscribe")
111         .privileges({{"Login"}})
112         .websocket()
113         .onopen([&](crow::websocket::Connection& conn) {
114             BMCWEB_LOG_DEBUG << "Connection " << &conn << " opened";
115             sessions.try_emplace(&conn);
116         })
117         .onclose([&](crow::websocket::Connection& conn, const std::string&) {
118             sessions.erase(&conn);
119         })
120         .onmessage(
121             [&](crow::websocket::Connection& conn, const std::string& data,
122                 bool) {
123         const auto sessionPair = sessions.find(&conn);
124         if (sessionPair == sessions.end())
125         {
126             conn.close("Internal error");
127         }
128         DbusWebsocketSession& thisSession = sessionPair->second;
129         BMCWEB_LOG_DEBUG << "Connection " << &conn << " received " << data;
130         nlohmann::json j = nlohmann::json::parse(data, nullptr, false);
131         if (j.is_discarded())
132         {
133             BMCWEB_LOG_ERROR << "Unable to parse json data for monitor";
134             conn.close("Unable to parse json request");
135             return;
136         }
137         nlohmann::json::iterator interfaces = j.find("interfaces");
138         if (interfaces != j.end())
139         {
140             thisSession.interfaces.reserve(interfaces->size());
141             for (auto& interface : *interfaces)
142             {
143                 const std::string* str =
144                     interface.get_ptr<const std::string*>();
145                 if (str != nullptr)
146                 {
147                     thisSession.interfaces.insert(*str);
148                 }
149             }
150         }
151 
152         nlohmann::json::iterator paths = j.find("paths");
153         if (paths == j.end())
154         {
155             BMCWEB_LOG_ERROR << "Unable to find paths in json data";
156             conn.close("Unable to find paths in json data");
157             return;
158         }
159 
160         size_t interfaceCount = thisSession.interfaces.size();
161         if (interfaceCount == 0)
162         {
163             interfaceCount = 1;
164         }
165         // Reserve our matches upfront.  For each path there is 1 for
166         // interfacesAdded, and InterfaceCount number for
167         // PropertiesChanged
168         thisSession.matches.reserve(thisSession.matches.size() +
169                                     paths->size() * (1U + interfaceCount));
170 
171         // These regexes derived on the rules here:
172         // https://dbus.freedesktop.org/doc/dbus-specification.html#message-protocol-names
173         std::regex validPath("^/([A-Za-z0-9_]+/?)*$");
174         std::regex validInterface(
175             "^[A-Za-z_][A-Za-z0-9_]*(\\.[A-Za-z_][A-Za-z0-9_]*)+$");
176 
177         for (const auto& thisPath : *paths)
178         {
179             const std::string* thisPathString =
180                 thisPath.get_ptr<const std::string*>();
181             if (thisPathString == nullptr)
182             {
183                 BMCWEB_LOG_ERROR << "subscribe path isn't a string?";
184                 conn.close();
185                 return;
186             }
187             if (!std::regex_match(*thisPathString, validPath))
188             {
189                 BMCWEB_LOG_ERROR << "Invalid path name " << *thisPathString;
190                 conn.close();
191                 return;
192             }
193             std::string propertiesMatchString =
194                 ("type='signal',"
195                  "interface='org.freedesktop.DBus.Properties',"
196                  "path_namespace='" +
197                  *thisPathString +
198                  "',"
199                  "member='PropertiesChanged'");
200             // If interfaces weren't specified, add a single match for all
201             // interfaces
202             if (thisSession.interfaces.empty())
203             {
204                 BMCWEB_LOG_DEBUG << "Creating match " << propertiesMatchString;
205 
206                 thisSession.matches.emplace_back(
207                     std::make_unique<sdbusplus::bus::match_t>(
208                         *crow::connections::systemBus, propertiesMatchString,
209                         onPropertyUpdate, &conn));
210             }
211             else
212             {
213                 // If interfaces were specified, add a match for each
214                 // interface
215                 for (const std::string& interface : thisSession.interfaces)
216                 {
217                     if (!std::regex_match(interface, validInterface))
218                     {
219                         BMCWEB_LOG_ERROR << "Invalid interface name "
220                                          << interface;
221                         conn.close();
222                         return;
223                     }
224                     std::string ifaceMatchString = propertiesMatchString;
225                     ifaceMatchString += ",arg0='";
226                     ifaceMatchString += interface;
227                     ifaceMatchString += "'";
228                     BMCWEB_LOG_DEBUG << "Creating match " << ifaceMatchString;
229                     thisSession.matches.emplace_back(
230                         std::make_unique<sdbusplus::bus::match_t>(
231                             *crow::connections::systemBus, ifaceMatchString,
232                             onPropertyUpdate, &conn));
233                 }
234             }
235             std::string objectManagerMatchString =
236                 ("type='signal',"
237                  "interface='org.freedesktop.DBus.ObjectManager',"
238                  "path_namespace='" +
239                  *thisPathString +
240                  "',"
241                  "member='InterfacesAdded'");
242             BMCWEB_LOG_DEBUG << "Creating match " << objectManagerMatchString;
243             thisSession.matches.emplace_back(
244                 std::make_unique<sdbusplus::bus::match_t>(
245                     *crow::connections::systemBus, objectManagerMatchString,
246                     onPropertyUpdate, &conn));
247         }
248         });
249 }
250 } // namespace dbus_monitor
251 } // namespace crow
252