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