xref: /openbmc/bmcweb/redfish-core/lib/network_protocol.hpp (revision a1ffbb84cf0f7f75ccb84fa6e0752b645b81ebdf)
1 /*
2 // Copyright (c) 2018 Intel Corporation
3 //
4 // Licensed under the Apache License, Version 2.0 (the "License");
5 // you may not use this file except in compliance with the License.
6 // You may obtain a copy of the License at
7 //
8 //      http://www.apache.org/licenses/LICENSE-2.0
9 //
10 // Unless required by applicable law or agreed to in writing, software
11 // distributed under the License is distributed on an "AS IS" BASIS,
12 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 // See the License for the specific language governing permissions and
14 // limitations under the License.
15 */
16 #pragma once
17 
18 #include "error_messages.hpp"
19 #include "node.hpp"
20 #include "openbmc_dbus_rest.hpp"
21 
22 #include <utils/json_utils.hpp>
23 
24 #include <optional>
25 #include <variant>
26 namespace redfish
27 {
28 
29 enum NetworkProtocolUnitStructFields
30 {
31     NET_PROTO_UNIT_NAME,
32     NET_PROTO_UNIT_DESC,
33     NET_PROTO_UNIT_LOAD_STATE,
34     NET_PROTO_UNIT_ACTIVE_STATE,
35     NET_PROTO_UNIT_SUB_STATE,
36     NET_PROTO_UNIT_DEVICE,
37     NET_PROTO_UNIT_OBJ_PATH,
38     NET_PROTO_UNIT_ALWAYS_0,
39     NET_PROTO_UNIT_ALWAYS_EMPTY,
40     NET_PROTO_UNIT_ALWAYS_ROOT_PATH
41 };
42 
43 enum NetworkProtocolListenResponseElements
44 {
45     NET_PROTO_LISTEN_TYPE,
46     NET_PROTO_LISTEN_STREAM
47 };
48 
49 /**
50  * @brief D-Bus Unit structure returned in array from ListUnits Method
51  */
52 using UnitStruct =
53     std::tuple<std::string, std::string, std::string, std::string, std::string,
54                std::string, sdbusplus::message::object_path, uint32_t,
55                std::string, sdbusplus::message::object_path>;
56 
57 const static boost::container::flat_map<const char*, std::string>
58     protocolToDBus{{"SSH", "dropbear"},
59                    {"HTTPS", "bmcweb"},
60                    {"IPMI", "phosphor-ipmi-net"}};
61 
62 inline void
63     extractNTPServersAndDomainNamesData(const GetManagedObjects& dbus_data,
64                                         std::vector<std::string>& ntpData,
65                                         std::vector<std::string>& dnData)
66 {
67     for (const auto& obj : dbus_data)
68     {
69         for (const auto& ifacePair : obj.second)
70         {
71             if (obj.first == "/xyz/openbmc_project/network/eth0")
72             {
73                 if (ifacePair.first ==
74                     "xyz.openbmc_project.Network.EthernetInterface")
75                 {
76                     for (const auto& propertyPair : ifacePair.second)
77                     {
78                         if (propertyPair.first == "NTPServers")
79                         {
80                             const std::vector<std::string>* ntpServers =
81                                 std::get_if<std::vector<std::string>>(
82                                     &propertyPair.second);
83                             if (ntpServers != nullptr)
84                             {
85                                 ntpData = *ntpServers;
86                             }
87                         }
88                         else if (propertyPair.first == "DomainName")
89                         {
90                             const std::vector<std::string>* domainNames =
91                                 std::get_if<std::vector<std::string>>(
92                                     &propertyPair.second);
93                             if (domainNames != nullptr)
94                             {
95                                 dnData = *domainNames;
96                             }
97                         }
98                     }
99                 }
100             }
101         }
102     }
103 }
104 
105 template <typename CallbackFunc>
106 void getEthernetIfaceData(CallbackFunc&& callback)
107 {
108     crow::connections::systemBus->async_method_call(
109         [callback{std::move(callback)}](
110             const boost::system::error_code error_code,
111             const GetManagedObjects& dbus_data) {
112             std::vector<std::string> ntpServers;
113             std::vector<std::string> domainNames;
114 
115             if (error_code)
116             {
117                 callback(false, ntpServers, domainNames);
118                 return;
119             }
120 
121             extractNTPServersAndDomainNamesData(dbus_data, ntpServers,
122                                                 domainNames);
123 
124             callback(true, ntpServers, domainNames);
125         },
126         "xyz.openbmc_project.Network", "/xyz/openbmc_project/network",
127         "org.freedesktop.DBus.ObjectManager", "GetManagedObjects");
128 }
129 
130 class NetworkProtocol : public Node
131 {
132   public:
133     NetworkProtocol(App& app) :
134         Node(app, "/redfish/v1/Managers/bmc/NetworkProtocol/")
135     {
136         entityPrivileges = {
137             {boost::beast::http::verb::get, {{"Login"}}},
138             {boost::beast::http::verb::head, {{"Login"}}},
139             {boost::beast::http::verb::patch, {{"ConfigureManager"}}},
140             {boost::beast::http::verb::put, {{"ConfigureManager"}}},
141             {boost::beast::http::verb::delete_, {{"ConfigureManager"}}},
142             {boost::beast::http::verb::post, {{"ConfigureManager"}}}};
143     }
144 
145   private:
146     void doGet(crow::Response& res, const crow::Request&,
147                const std::vector<std::string>&) override
148     {
149         std::shared_ptr<AsyncResp> asyncResp = std::make_shared<AsyncResp>(res);
150 
151         getData(asyncResp);
152     }
153 
154     std::string getHostName() const
155     {
156         std::string hostName;
157 
158         std::array<char, HOST_NAME_MAX> hostNameCStr;
159         if (gethostname(hostNameCStr.data(), hostNameCStr.size()) == 0)
160         {
161             hostName = hostNameCStr.data();
162         }
163         return hostName;
164     }
165 
166     void getNTPProtocolEnabled(const std::shared_ptr<AsyncResp>& asyncResp)
167     {
168         crow::connections::systemBus->async_method_call(
169             [asyncResp](const boost::system::error_code error_code,
170                         const std::variant<std::string>& timeSyncMethod) {
171                 if (error_code)
172                 {
173                     return;
174                 }
175 
176                 const std::string* s =
177                     std::get_if<std::string>(&timeSyncMethod);
178 
179                 if (*s == "xyz.openbmc_project.Time.Synchronization.Method.NTP")
180                 {
181                     asyncResp->res.jsonValue["NTP"]["ProtocolEnabled"] = true;
182                 }
183                 else if (*s == "xyz.openbmc_project.Time.Synchronization."
184                                "Method.Manual")
185                 {
186                     asyncResp->res.jsonValue["NTP"]["ProtocolEnabled"] = false;
187                 }
188             },
189             "xyz.openbmc_project.Settings",
190             "/xyz/openbmc_project/time/sync_method",
191             "org.freedesktop.DBus.Properties", "Get",
192             "xyz.openbmc_project.Time.Synchronization", "TimeSyncMethod");
193     }
194 
195     void getData(const std::shared_ptr<AsyncResp>& asyncResp)
196     {
197         asyncResp->res.jsonValue["@odata.type"] =
198             "#ManagerNetworkProtocol.v1_5_0.ManagerNetworkProtocol";
199         asyncResp->res.jsonValue["@odata.id"] =
200             "/redfish/v1/Managers/bmc/NetworkProtocol";
201         asyncResp->res.jsonValue["Id"] = "NetworkProtocol";
202         asyncResp->res.jsonValue["Name"] = "Manager Network Protocol";
203         asyncResp->res.jsonValue["Description"] = "Manager Network Service";
204         asyncResp->res.jsonValue["Status"]["Health"] = "OK";
205         asyncResp->res.jsonValue["Status"]["HealthRollup"] = "OK";
206         asyncResp->res.jsonValue["Status"]["State"] = "Enabled";
207 
208         // HTTP is Mandatory attribute as per OCP Baseline Profile - v1.0.0,
209         // but from security perspective it is not recommended to use.
210         // Hence using protocolEnabled as false to make it OCP and security-wise
211         // compliant
212         asyncResp->res.jsonValue["HTTP"]["Port"] = 0;
213         asyncResp->res.jsonValue["HTTP"]["ProtocolEnabled"] = false;
214 
215         for (auto& protocol : protocolToDBus)
216         {
217             asyncResp->res.jsonValue[protocol.first]["Port"] =
218                 nlohmann::detail::value_t::null;
219             asyncResp->res.jsonValue[protocol.first]["ProtocolEnabled"] = false;
220         }
221 
222         std::string hostName = getHostName();
223 
224         asyncResp->res.jsonValue["HostName"] = hostName;
225 
226         getNTPProtocolEnabled(asyncResp);
227 
228         // TODO Get eth0 interface data, and call the below callback for JSON
229         // preparation
230         getEthernetIfaceData(
231             [hostName, asyncResp](const bool& success,
232                                   const std::vector<std::string>& ntpServers,
233                                   const std::vector<std::string>& domainNames) {
234                 if (!success)
235                 {
236                     messages::resourceNotFound(asyncResp->res,
237                                                "EthernetInterface", "eth0");
238                     return;
239                 }
240                 asyncResp->res.jsonValue["NTP"]["NTPServers"] = ntpServers;
241                 if (hostName.empty() == false)
242                 {
243                     std::string fqdn = hostName;
244                     if (domainNames.empty() == false)
245                     {
246                         fqdn += ".";
247                         fqdn += domainNames[0];
248                     }
249                     asyncResp->res.jsonValue["FQDN"] = std::move(fqdn);
250                 }
251             });
252 
253         crow::connections::systemBus->async_method_call(
254             [asyncResp](const boost::system::error_code e,
255                         const std::vector<UnitStruct>& r) {
256                 if (e)
257                 {
258                     asyncResp->res.jsonValue = nlohmann::json::object();
259                     messages::internalError(asyncResp->res);
260                     return;
261                 }
262                 asyncResp->res.jsonValue["HTTPS"]["Certificates"] = {
263                     {"@odata.id", "/redfish/v1/Managers/bmc/NetworkProtocol/"
264                                   "HTTPS/Certificates"}};
265 
266                 for (auto& unit : r)
267                 {
268                     /* Only traverse through <xyz>.socket units */
269                     const std::string& unitName =
270                         std::get<NET_PROTO_UNIT_NAME>(unit);
271                     if (!boost::ends_with(unitName, ".socket"))
272                     {
273                         continue;
274                     }
275 
276                     for (auto& kv : protocolToDBus)
277                     {
278                         // We are interested in services, which starts with
279                         // mapped service name
280                         if (!boost::starts_with(unitName, kv.second))
281                         {
282                             continue;
283                         }
284                         const char* rfServiceKey = kv.first;
285                         const std::string& socketPath =
286                             std::get<NET_PROTO_UNIT_OBJ_PATH>(unit);
287                         const std::string& unitState =
288                             std::get<NET_PROTO_UNIT_SUB_STATE>(unit);
289 
290                         asyncResp->res
291                             .jsonValue[rfServiceKey]["ProtocolEnabled"] =
292                             (unitState == "running") ||
293                             (unitState == "listening");
294 
295                         crow::connections::systemBus->async_method_call(
296                             [asyncResp,
297                              rfServiceKey{std::string(rfServiceKey)}](
298                                 const boost::system::error_code ec,
299                                 const std::variant<std::vector<std::tuple<
300                                     std::string, std::string>>>& resp) {
301                                 if (ec)
302                                 {
303                                     messages::internalError(asyncResp->res);
304                                     return;
305                                 }
306                                 const std::vector<
307                                     std::tuple<std::string, std::string>>*
308                                     responsePtr = std::get_if<std::vector<
309                                         std::tuple<std::string, std::string>>>(
310                                         &resp);
311                                 if (responsePtr == nullptr ||
312                                     responsePtr->size() < 1)
313                                 {
314                                     return;
315                                 }
316 
317                                 const std::string& listenStream =
318                                     std::get<NET_PROTO_LISTEN_STREAM>(
319                                         (*responsePtr)[0]);
320                                 std::size_t lastColonPos =
321                                     listenStream.rfind(':');
322                                 if (lastColonPos == std::string::npos)
323                                 {
324                                     // Not a port
325                                     return;
326                                 }
327                                 std::string portStr =
328                                     listenStream.substr(lastColonPos + 1);
329                                 if (portStr.empty())
330                                 {
331                                     return;
332                                 }
333                                 char* endPtr = nullptr;
334                                 errno = 0;
335                                 // Use strtol instead of stroi to avoid
336                                 // exceptions
337                                 long port =
338                                     std::strtol(portStr.c_str(), &endPtr, 10);
339                                 if ((errno == 0) && (*endPtr == '\0'))
340                                 {
341                                     asyncResp->res
342                                         .jsonValue[rfServiceKey]["Port"] = port;
343                                 }
344                                 return;
345                             },
346                             "org.freedesktop.systemd1", socketPath,
347                             "org.freedesktop.DBus.Properties", "Get",
348                             "org.freedesktop.systemd1.Socket", "Listen");
349 
350                         // We found service, break the inner loop.
351                         break;
352                     }
353                 }
354             },
355             "org.freedesktop.systemd1", "/org/freedesktop/systemd1",
356             "org.freedesktop.systemd1.Manager", "ListUnits");
357     }
358 
359     void handleHostnamePatch(const std::string& hostName,
360                              const std::shared_ptr<AsyncResp>& asyncResp)
361     {
362         crow::connections::systemBus->async_method_call(
363             [asyncResp](const boost::system::error_code ec) {
364                 if (ec)
365                 {
366                     messages::internalError(asyncResp->res);
367                     return;
368                 }
369             },
370             "xyz.openbmc_project.Network",
371             "/xyz/openbmc_project/network/config",
372             "org.freedesktop.DBus.Properties", "Set",
373             "xyz.openbmc_project.Network.SystemConfiguration", "HostName",
374             std::variant<std::string>(hostName));
375     }
376 
377     void handleNTPProtocolEnabled(const bool& ntpEnabled,
378                                   const std::shared_ptr<AsyncResp>& asyncResp)
379     {
380         std::string timeSyncMethod;
381         if (ntpEnabled)
382         {
383             timeSyncMethod =
384                 "xyz.openbmc_project.Time.Synchronization.Method.NTP";
385         }
386         else
387         {
388             timeSyncMethod =
389                 "xyz.openbmc_project.Time.Synchronization.Method.Manual";
390         }
391 
392         crow::connections::systemBus->async_method_call(
393             [asyncResp](const boost::system::error_code error_code) {
394                 if (error_code)
395                 {
396                     messages::internalError(asyncResp->res);
397                 }
398             },
399             "xyz.openbmc_project.Settings",
400             "/xyz/openbmc_project/time/sync_method",
401             "org.freedesktop.DBus.Properties", "Set",
402             "xyz.openbmc_project.Time.Synchronization", "TimeSyncMethod",
403             std::variant<std::string>{timeSyncMethod});
404     }
405 
406     void handleNTPServersPatch(const std::vector<std::string>& ntpServers,
407                                const std::shared_ptr<AsyncResp>& asyncResp)
408     {
409         crow::connections::systemBus->async_method_call(
410             [asyncResp](const boost::system::error_code ec) {
411                 if (ec)
412                 {
413                     messages::internalError(asyncResp->res);
414                     return;
415                 }
416             },
417             "xyz.openbmc_project.Network", "/xyz/openbmc_project/network/eth0",
418             "org.freedesktop.DBus.Properties", "Set",
419             "xyz.openbmc_project.Network.EthernetInterface", "NTPServers",
420             std::variant<std::vector<std::string>>{ntpServers});
421     }
422 
423     void handleIpmiProtocolEnabled(const bool ipmiProtocolEnabled,
424                                    const std::shared_ptr<AsyncResp>& asyncResp)
425     {
426         crow::connections::systemBus->async_method_call(
427             [ipmiProtocolEnabled,
428              asyncResp](const boost::system::error_code ec,
429                         const crow::openbmc_mapper::GetSubTreeType& subtree) {
430                 if (ec)
431                 {
432                     messages::internalError(asyncResp->res);
433                     return;
434                 }
435 
436                 constexpr char const* netipmidBasePath =
437                     "/xyz/openbmc_project/control/service/"
438                     "phosphor_2dipmi_2dnet_40";
439 
440                 for (const auto& entry : subtree)
441                 {
442                     if (boost::algorithm::starts_with(entry.first,
443                                                       netipmidBasePath))
444                     {
445                         crow::connections::systemBus->async_method_call(
446                             [asyncResp](const boost::system::error_code ec2) {
447                                 if (ec2)
448                                 {
449                                     messages::internalError(asyncResp->res);
450                                     return;
451                                 }
452                             },
453                             entry.second.begin()->first, entry.first,
454                             "org.freedesktop.DBus.Properties", "Set",
455                             "xyz.openbmc_project.Control.Service.Attributes",
456                             "Running", std::variant<bool>{ipmiProtocolEnabled});
457 
458                         crow::connections::systemBus->async_method_call(
459                             [asyncResp](const boost::system::error_code ec2) {
460                                 if (ec2)
461                                 {
462                                     messages::internalError(asyncResp->res);
463                                     return;
464                                 }
465                             },
466                             entry.second.begin()->first, entry.first,
467                             "org.freedesktop.DBus.Properties", "Set",
468                             "xyz.openbmc_project.Control.Service.Attributes",
469                             "Enabled", std::variant<bool>{ipmiProtocolEnabled});
470                     }
471                 }
472             },
473             "xyz.openbmc_project.ObjectMapper",
474             "/xyz/openbmc_project/object_mapper",
475             "xyz.openbmc_project.ObjectMapper", "GetSubTree",
476             "/xyz/openbmc_project/control/service", 0,
477             std::array<const char*, 1>{
478                 "xyz.openbmc_project.Control.Service.Attributes"});
479     }
480 
481     void doPatch(crow::Response& res, const crow::Request& req,
482                  const std::vector<std::string>&) override
483     {
484         std::shared_ptr<AsyncResp> asyncResp = std::make_shared<AsyncResp>(res);
485         std::optional<std::string> newHostName;
486         std::optional<nlohmann::json> ntp;
487         std::optional<nlohmann::json> ipmi;
488 
489         if (!json_util::readJson(req, res, "HostName", newHostName, "NTP", ntp,
490                                  "IPMI", ipmi))
491         {
492             return;
493         }
494 
495         res.result(boost::beast::http::status::no_content);
496         if (newHostName)
497         {
498             handleHostnamePatch(*newHostName, asyncResp);
499         }
500 
501         if (ntp)
502         {
503             std::optional<std::vector<std::string>> ntpServers;
504             std::optional<bool> ntpEnabled;
505             if (!json_util::readJson(*ntp, res, "NTPServers", ntpServers,
506                                      "ProtocolEnabled", ntpEnabled))
507             {
508                 return;
509             }
510 
511             if (ntpEnabled)
512             {
513                 handleNTPProtocolEnabled(*ntpEnabled, asyncResp);
514             }
515 
516             if (ntpServers)
517             {
518                 std::sort((*ntpServers).begin(), (*ntpServers).end());
519                 (*ntpServers)
520                     .erase(
521                         std::unique((*ntpServers).begin(), (*ntpServers).end()),
522                         (*ntpServers).end());
523                 handleNTPServersPatch(*ntpServers, asyncResp);
524             }
525         }
526 
527         if (ipmi)
528         {
529             std::optional<bool> ipmiProtocolEnabled;
530             if (!json_util::readJson(*ipmi, res, "ProtocolEnabled",
531                                      ipmiProtocolEnabled))
532             {
533                 return;
534             }
535 
536             if (ipmiProtocolEnabled)
537             {
538                 handleIpmiProtocolEnabled(*ipmiProtocolEnabled, asyncResp);
539             }
540         }
541     }
542 };
543 
544 } // namespace redfish
545