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 = std::move(*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 = std::move(*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(CrowApp& 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& req,
147                const std::vector<std::string>& params) 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                 const std::string* s =
172                     std::get_if<std::string>(&timeSyncMethod);
173 
174                 if (*s == "xyz.openbmc_project.Time.Synchronization.Method.NTP")
175                 {
176                     asyncResp->res.jsonValue["NTP"]["ProtocolEnabled"] = true;
177                 }
178                 else if (*s == "xyz.openbmc_project.Time.Synchronization."
179                                "Method.Manual")
180                 {
181                     asyncResp->res.jsonValue["NTP"]["ProtocolEnabled"] = false;
182                 }
183             },
184             "xyz.openbmc_project.Settings",
185             "/xyz/openbmc_project/time/sync_method",
186             "org.freedesktop.DBus.Properties", "Get",
187             "xyz.openbmc_project.Time.Synchronization", "TimeSyncMethod");
188     }
189 
190     void getData(const std::shared_ptr<AsyncResp>& asyncResp)
191     {
192         asyncResp->res.jsonValue["@odata.type"] =
193             "#ManagerNetworkProtocol.v1_5_0.ManagerNetworkProtocol";
194         asyncResp->res.jsonValue["@odata.id"] =
195             "/redfish/v1/Managers/bmc/NetworkProtocol";
196         asyncResp->res.jsonValue["Id"] = "NetworkProtocol";
197         asyncResp->res.jsonValue["Name"] = "Manager Network Protocol";
198         asyncResp->res.jsonValue["Description"] = "Manager Network Service";
199         asyncResp->res.jsonValue["Status"]["Health"] = "OK";
200         asyncResp->res.jsonValue["Status"]["HealthRollup"] = "OK";
201         asyncResp->res.jsonValue["Status"]["State"] = "Enabled";
202         asyncResp->res.jsonValue["SNMP"]["ProtocolEnabled"] = true;
203         asyncResp->res.jsonValue["SNMP"]["Port"] = 161;
204         asyncResp->res.jsonValue["SNMP"]["AuthenticationProtocol"] =
205             "CommunityString";
206         asyncResp->res.jsonValue["SNMP"]["CommunityAccessMode"] = "Full";
207         asyncResp->res.jsonValue["SNMP"]["HideCommunityStrings"] = true;
208         asyncResp->res
209             .jsonValue["SNMP"]["EngineId"]["EnterpriseSpecificMethod"] =
210             nullptr;
211         asyncResp->res.jsonValue["SNMP"]["EngineId"]["PrivateEnterpriseId"] =
212             nullptr;
213         asyncResp->res.jsonValue["SNMP"]["EnableSNMPv1"] = false;
214         asyncResp->res.jsonValue["SNMP"]["EnableSNMPv2c"] = true;
215         asyncResp->res.jsonValue["SNMP"]["EnableSNMPv3"] = false;
216         asyncResp->res.jsonValue["SNMP"]["EncryptionProtocol"] = "None";
217         nlohmann::json& memberArray =
218             asyncResp->res.jsonValue["SNMP"]["CommunityStrings"];
219         memberArray = nlohmann::json::array();
220         memberArray.push_back({{"AccessMode", "Full"}});
221         memberArray.push_back({{"CommunityString", ""}});
222         memberArray.push_back({{"Name", ""}});
223 
224         // HTTP is Mandatory attribute as per OCP Baseline Profile - v1.0.0,
225         // but from security perspective it is not recommended to use.
226         // Hence using protocolEnabled as false to make it OCP and security-wise
227         // compliant
228         asyncResp->res.jsonValue["HTTP"]["Port"] = 0;
229         asyncResp->res.jsonValue["HTTP"]["ProtocolEnabled"] = false;
230 
231         for (auto& protocol : protocolToDBus)
232         {
233             asyncResp->res.jsonValue[protocol.first]["ProtocolEnabled"] = false;
234         }
235 
236         std::string hostName = getHostName();
237 
238         asyncResp->res.jsonValue["HostName"] = hostName;
239 
240         getNTPProtocolEnabled(asyncResp);
241 
242         // TODO Get eth0 interface data, and call the below callback for JSON
243         // preparation
244         getEthernetIfaceData(
245             [hostName, asyncResp](const bool& success,
246                                   const std::vector<std::string>& ntpServers,
247                                   const std::vector<std::string>& domainNames) {
248                 if (!success)
249                 {
250                     messages::resourceNotFound(asyncResp->res,
251                                                "EthernetInterface", "eth0");
252                     return;
253                 }
254                 asyncResp->res.jsonValue["NTP"]["NTPServers"] = ntpServers;
255                 if (hostName.empty() == false)
256                 {
257                     std::string FQDN = std::move(hostName);
258                     if (domainNames.empty() == false)
259                     {
260                         FQDN += "." + domainNames[0];
261                     }
262                     asyncResp->res.jsonValue["FQDN"] = std::move(FQDN);
263                 }
264             });
265 
266         crow::connections::systemBus->async_method_call(
267             [asyncResp](const boost::system::error_code e,
268                         const std::vector<UnitStruct>& r) {
269                 if (e)
270                 {
271                     asyncResp->res.jsonValue = nlohmann::json::object();
272                     messages::internalError(asyncResp->res);
273                     return;
274                 }
275                 asyncResp->res.jsonValue["HTTPS"]["Certificates"] = {
276                     {"@odata.id", "/redfish/v1/Managers/bmc/NetworkProtocol/"
277                                   "HTTPS/Certificates"}};
278 
279                 for (auto& unit : r)
280                 {
281                     /* Only traverse through <xyz>.socket units */
282                     std::string unitName = std::get<NET_PROTO_UNIT_NAME>(unit);
283                     if (!boost::ends_with(unitName, ".socket"))
284                     {
285                         continue;
286                     }
287 
288                     for (auto& kv : protocolToDBus)
289                     {
290                         // We are interested in services, which starts with
291                         // mapped service name
292                         if (!boost::starts_with(unitName, kv.second))
293                         {
294                             continue;
295                         }
296                         const char* rfServiceKey = kv.first;
297                         std::string socketPath =
298                             std::get<NET_PROTO_UNIT_OBJ_PATH>(unit);
299                         std::string unitState =
300                             std::get<NET_PROTO_UNIT_SUB_STATE>(unit);
301 
302                         asyncResp->res
303                             .jsonValue[rfServiceKey]["ProtocolEnabled"] =
304                             (unitState == "running") ||
305                             (unitState == "listening");
306 
307                         crow::connections::systemBus->async_method_call(
308                             [asyncResp,
309                              rfServiceKey{std::string(rfServiceKey)}](
310                                 const boost::system::error_code ec,
311                                 const std::variant<std::vector<std::tuple<
312                                     std::string, std::string>>>& resp) {
313                                 if (ec)
314                                 {
315                                     messages::internalError(asyncResp->res);
316                                     return;
317                                 }
318                                 const std::vector<
319                                     std::tuple<std::string, std::string>>*
320                                     responsePtr = std::get_if<std::vector<
321                                         std::tuple<std::string, std::string>>>(
322                                         &resp);
323                                 if (responsePtr == nullptr ||
324                                     responsePtr->size() < 1)
325                                 {
326                                     return;
327                                 }
328 
329                                 const std::string& listenStream =
330                                     std::get<NET_PROTO_LISTEN_STREAM>(
331                                         (*responsePtr)[0]);
332                                 std::size_t lastColonPos =
333                                     listenStream.rfind(":");
334                                 if (lastColonPos == std::string::npos)
335                                 {
336                                     // Not a port
337                                     return;
338                                 }
339                                 std::string portStr =
340                                     listenStream.substr(lastColonPos + 1);
341                                 if (portStr.empty())
342                                 {
343                                     return;
344                                 }
345                                 char* endPtr = nullptr;
346                                 errno = 0;
347                                 // Use strtol instead of stroi to avoid
348                                 // exceptions
349                                 long port =
350                                     std::strtol(portStr.c_str(), &endPtr, 10);
351                                 if ((errno == 0) && (*endPtr == '\0'))
352                                 {
353                                     asyncResp->res
354                                         .jsonValue[rfServiceKey]["Port"] = port;
355                                 }
356                                 return;
357                             },
358                             "org.freedesktop.systemd1", socketPath,
359                             "org.freedesktop.DBus.Properties", "Get",
360                             "org.freedesktop.systemd1.Socket", "Listen");
361 
362                         // We found service, break the inner loop.
363                         break;
364                     }
365                 }
366             },
367             "org.freedesktop.systemd1", "/org/freedesktop/systemd1",
368             "org.freedesktop.systemd1.Manager", "ListUnits");
369     }
370 
371     void handleHostnamePatch(const std::string& hostName,
372                              const std::shared_ptr<AsyncResp>& asyncResp)
373     {
374         crow::connections::systemBus->async_method_call(
375             [asyncResp](const boost::system::error_code ec) {
376                 if (ec)
377                 {
378                     messages::internalError(asyncResp->res);
379                     return;
380                 }
381             },
382             "xyz.openbmc_project.Network",
383             "/xyz/openbmc_project/network/config",
384             "org.freedesktop.DBus.Properties", "Set",
385             "xyz.openbmc_project.Network.SystemConfiguration", "HostName",
386             std::variant<std::string>(hostName));
387     }
388 
389     void handleNTPProtocolEnabled(const bool& ntpEnabled,
390                                   const std::shared_ptr<AsyncResp>& asyncResp)
391     {
392         std::string timeSyncMethod;
393         if (ntpEnabled)
394         {
395             timeSyncMethod =
396                 "xyz.openbmc_project.Time.Synchronization.Method.NTP";
397         }
398         else
399         {
400             timeSyncMethod =
401                 "xyz.openbmc_project.Time.Synchronization.Method.Manual";
402         }
403 
404         crow::connections::systemBus->async_method_call(
405             [asyncResp](const boost::system::error_code error_code) {},
406             "xyz.openbmc_project.Settings",
407             "/xyz/openbmc_project/time/sync_method",
408             "org.freedesktop.DBus.Properties", "Set",
409             "xyz.openbmc_project.Time.Synchronization", "TimeSyncMethod",
410             std::variant<std::string>{timeSyncMethod});
411     }
412 
413     void handleNTPServersPatch(const std::vector<std::string>& ntpServers,
414                                const std::shared_ptr<AsyncResp>& asyncResp)
415     {
416         crow::connections::systemBus->async_method_call(
417             [asyncResp](const boost::system::error_code ec) {
418                 if (ec)
419                 {
420                     messages::internalError(asyncResp->res);
421                     return;
422                 }
423             },
424             "xyz.openbmc_project.Network", "/xyz/openbmc_project/network/eth0",
425             "org.freedesktop.DBus.Properties", "Set",
426             "xyz.openbmc_project.Network.EthernetInterface", "NTPServers",
427             std::variant<std::vector<std::string>>{ntpServers});
428     }
429 
430     void handleIpmiProtocolEnabled(const bool ipmiProtocolEnabled,
431                                    const std::shared_ptr<AsyncResp>& asyncResp)
432     {
433         crow::connections::systemBus->async_method_call(
434             [ipmiProtocolEnabled,
435              asyncResp](const boost::system::error_code ec,
436                         const crow::openbmc_mapper::GetSubTreeType& subtree) {
437                 if (ec)
438                 {
439                     messages::internalError(asyncResp->res);
440                     return;
441                 }
442 
443                 constexpr char const* netipmidBasePath =
444                     "/xyz/openbmc_project/control/service/"
445                     "phosphor_2dipmi_2dnet_40";
446 
447                 for (const auto& entry : subtree)
448                 {
449                     if (boost::algorithm::starts_with(entry.first,
450                                                       netipmidBasePath))
451                     {
452                         crow::connections::systemBus->async_method_call(
453                             [ipmiProtocolEnabled,
454                              asyncResp](const boost::system::error_code ec) {
455                                 if (ec)
456                                 {
457                                     messages::internalError(asyncResp->res);
458                                     return;
459                                 }
460                             },
461                             entry.second.begin()->first, entry.first,
462                             "org.freedesktop.DBus.Properties", "Set",
463                             "xyz.openbmc_project.Control.Service.Attributes",
464                             "Running", std::variant<bool>{ipmiProtocolEnabled});
465 
466                         crow::connections::systemBus->async_method_call(
467                             [ipmiProtocolEnabled,
468                              asyncResp](const boost::system::error_code ec) {
469                                 if (ec)
470                                 {
471                                     messages::internalError(asyncResp->res);
472                                     return;
473                                 }
474                             },
475                             entry.second.begin()->first, entry.first,
476                             "org.freedesktop.DBus.Properties", "Set",
477                             "xyz.openbmc_project.Control.Service.Attributes",
478                             "Enabled", std::variant<bool>{ipmiProtocolEnabled});
479                     }
480                 }
481             },
482             "xyz.openbmc_project.ObjectMapper",
483             "/xyz/openbmc_project/object_mapper",
484             "xyz.openbmc_project.ObjectMapper", "GetSubTree",
485             "/xyz/openbmc_project/control/service", 0,
486             std::array<const char*, 1>{
487                 "xyz.openbmc_project.Control.Service.Attributes"});
488     }
489 
490     void doPatch(crow::Response& res, const crow::Request& req,
491                  const std::vector<std::string>& params) override
492     {
493         std::shared_ptr<AsyncResp> asyncResp = std::make_shared<AsyncResp>(res);
494         std::optional<std::string> newHostName;
495         std::optional<nlohmann::json> ntp;
496         std::optional<nlohmann::json> ipmi;
497 
498         if (!json_util::readJson(req, res, "HostName", newHostName, "NTP", ntp,
499                                  "IPMI", ipmi))
500         {
501             return;
502         }
503 
504         res.result(boost::beast::http::status::no_content);
505         if (newHostName)
506         {
507             handleHostnamePatch(*newHostName, asyncResp);
508         }
509 
510         if (ntp)
511         {
512             std::optional<std::vector<std::string>> ntpServers;
513             std::optional<bool> ntpEnabled;
514             if (!json_util::readJson(*ntp, res, "NTPServers", ntpServers,
515                                      "ProtocolEnabled", ntpEnabled))
516             {
517                 return;
518             }
519 
520             if (ntpEnabled)
521             {
522                 handleNTPProtocolEnabled(*ntpEnabled, asyncResp);
523             }
524 
525             if (ntpServers)
526             {
527                 std::sort((*ntpServers).begin(), (*ntpServers).end());
528                 (*ntpServers)
529                     .erase(
530                         std::unique((*ntpServers).begin(), (*ntpServers).end()),
531                         (*ntpServers).end());
532                 handleNTPServersPatch(*ntpServers, asyncResp);
533             }
534         }
535 
536         if (ipmi)
537         {
538             std::optional<bool> ipmiProtocolEnabled;
539             if (!json_util::readJson(*ipmi, res, "ProtocolEnabled",
540                                      ipmiProtocolEnabled))
541             {
542                 return;
543             }
544 
545             if (ipmiProtocolEnabled)
546             {
547                 handleIpmiProtocolEnabled(*ipmiProtocolEnabled, asyncResp);
548             }
549         }
550     }
551 };
552 
553 } // namespace redfish
554