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 /// \file perform_scan.cpp
17 #include "entity_manager.hpp"
18 
19 #include <boost/algorithm/string/predicate.hpp>
20 #include <boost/asio/steady_timer.hpp>
21 #include <boost/container/flat_map.hpp>
22 #include <boost/container/flat_set.hpp>
23 
24 #include <charconv>
25 
26 /* Hacks from splitting entity_manager.cpp */
27 // NOLINTBEGIN(cppcoreguidelines-avoid-non-const-global-variables)
28 extern std::shared_ptr<sdbusplus::asio::connection> systemBus;
29 extern nlohmann::json lastJson;
30 extern void
31     propertiesChangedCallback(nlohmann::json& systemConfiguration,
32                               sdbusplus::asio::object_server& objServer);
33 // NOLINTEND(cppcoreguidelines-avoid-non-const-global-variables)
34 
35 using GetSubTreeType = std::vector<
36     std::pair<std::string,
37               std::vector<std::pair<std::string, std::vector<std::string>>>>>;
38 
39 constexpr const int32_t maxMapperDepth = 0;
40 
41 constexpr const bool debug = false;
42 
43 struct DBusInterfaceInstance
44 {
45     std::string busName;
46     std::string path;
47     std::string interface;
48 };
49 
50 void getInterfaces(
51     const DBusInterfaceInstance& instance,
52     const std::vector<std::shared_ptr<PerformProbe>>& probeVector,
53     const std::shared_ptr<PerformScan>& scan, size_t retries = 5)
54 {
55     if (retries == 0U)
56     {
57         std::cerr << "retries exhausted on " << instance.busName << " "
58                   << instance.path << " " << instance.interface << "\n";
59         return;
60     }
61 
62     systemBus->async_method_call(
63         [instance, scan, probeVector,
64          retries](boost::system::error_code& errc, const DBusInterface& resp) {
65             if (errc)
66             {
67                 std::cerr << "error calling getall on  " << instance.busName
68                           << " " << instance.path << " "
69                           << instance.interface << "\n";
70 
71                 auto timer = std::make_shared<boost::asio::steady_timer>(io);
72                 timer->expires_after(std::chrono::seconds(2));
73 
74                 timer->async_wait([timer, instance, scan, probeVector,
75                                    retries](const boost::system::error_code&) {
76                     getInterfaces(instance, probeVector, scan, retries - 1);
77                 });
78                 return;
79             }
80 
81             scan->dbusProbeObjects[instance.path][instance.interface] = resp;
82         },
83         instance.busName, instance.path, "org.freedesktop.DBus.Properties",
84         "GetAll", instance.interface);
85 
86     if constexpr (debug)
87     {
88         std::cerr << __LINE__ << "\n";
89     }
90 }
91 
92 static void registerCallback(nlohmann::json& systemConfiguration,
93                              sdbusplus::asio::object_server& objServer,
94                              const std::string& path)
95 {
96     static boost::container::flat_map<std::string, sdbusplus::bus::match_t>
97         dbusMatches;
98 
99     auto find = dbusMatches.find(path);
100     if (find != dbusMatches.end())
101     {
102         return;
103     }
104 
105     std::function<void(sdbusplus::message_t & message)> eventHandler =
106         [&](sdbusplus::message_t&) {
107             propertiesChangedCallback(systemConfiguration, objServer);
108         };
109 
110     sdbusplus::bus::match_t match(
111         static_cast<sdbusplus::bus_t&>(*systemBus),
112         "type='signal',member='PropertiesChanged',path='" + path + "'",
113         eventHandler);
114     dbusMatches.emplace(path, std::move(match));
115 }
116 
117 static void
118     processDbusObjects(std::vector<std::shared_ptr<PerformProbe>>& probeVector,
119                        const std::shared_ptr<PerformScan>& scan,
120                        const GetSubTreeType& interfaceSubtree)
121 {
122     for (const auto& [path, object] : interfaceSubtree)
123     {
124         // Get a PropertiesChanged callback for all interfaces on this path.
125         registerCallback(scan->_systemConfiguration, scan->objServer, path);
126 
127         for (const auto& [busname, ifaces] : object)
128         {
129             for (const std::string& iface : ifaces)
130             {
131                 // The 3 default org.freedeskstop interfaces (Peer,
132                 // Introspectable, and Properties) are returned by
133                 // the mapper but don't have properties, so don't bother
134                 // with the GetAll call to save some cycles.
135                 if (!boost::algorithm::starts_with(iface, "org.freedesktop"))
136                 {
137                     getInterfaces({busname, path, iface}, probeVector, scan);
138                 }
139             }
140         }
141     }
142 }
143 
144 // Populates scan->dbusProbeObjects with all interfaces and properties
145 // for the paths that own the interfaces passed in.
146 void findDbusObjects(std::vector<std::shared_ptr<PerformProbe>>&& probeVector,
147                      boost::container::flat_set<std::string>&& interfaces,
148                      const std::shared_ptr<PerformScan>& scan,
149                      size_t retries = 5)
150 {
151     // Filter out interfaces already obtained.
152     for (const auto& [path, probeInterfaces] : scan->dbusProbeObjects)
153     {
154         for (const auto& [interface, _] : probeInterfaces)
155         {
156             interfaces.erase(interface);
157         }
158     }
159     if (interfaces.empty())
160     {
161         return;
162     }
163 
164     // find all connections in the mapper that expose a specific type
165     systemBus->async_method_call(
166         [interfaces, probeVector{std::move(probeVector)}, scan,
167          retries](boost::system::error_code& ec,
168                   const GetSubTreeType& interfaceSubtree) mutable {
169             if (ec)
170             {
171                 if (ec.value() == ENOENT)
172                 {
173                     return; // wasn't found by mapper
174                 }
175                 std::cerr << "Error communicating to mapper.\n";
176 
177                 if (retries == 0U)
178                 {
179                     // if we can't communicate to the mapper something is very
180                     // wrong
181                     std::exit(EXIT_FAILURE);
182                 }
183 
184                 auto timer = std::make_shared<boost::asio::steady_timer>(io);
185                 timer->expires_after(std::chrono::seconds(10));
186 
187                 timer->async_wait(
188                     [timer, interfaces{std::move(interfaces)}, scan,
189                      probeVector{std::move(probeVector)},
190                      retries](const boost::system::error_code&) mutable {
191                         findDbusObjects(std::move(probeVector),
192                                         std::move(interfaces), scan,
193                                         retries - 1);
194                     });
195                 return;
196             }
197 
198             processDbusObjects(probeVector, scan, interfaceSubtree);
199         },
200         "xyz.openbmc_project.ObjectMapper",
201         "/xyz/openbmc_project/object_mapper",
202         "xyz.openbmc_project.ObjectMapper", "GetSubTree", "/", maxMapperDepth,
203         interfaces);
204 
205     if constexpr (debug)
206     {
207         std::cerr << __LINE__ << "\n";
208     }
209 }
210 
211 static std::string getRecordName(const DBusInterface& probe,
212                                  const std::string& probeName)
213 {
214     if (probe.empty())
215     {
216         return probeName;
217     }
218 
219     // use an array so alphabetical order from the flat_map is maintained
220     auto device = nlohmann::json::array();
221     for (const auto& devPair : probe)
222     {
223         device.push_back(devPair.first);
224         std::visit([&device](auto&& v) { device.push_back(v); },
225                    devPair.second);
226     }
227 
228     // hashes are hard to distinguish, use the non-hashed version if we want
229     // debug
230     if constexpr (debug)
231     {
232         return probeName + device.dump();
233     }
234 
235     return std::to_string(std::hash<std::string>{}(probeName + device.dump()));
236 }
237 
238 PerformScan::PerformScan(nlohmann::json& systemConfiguration,
239                          nlohmann::json& missingConfigurations,
240                          std::list<nlohmann::json>& configurations,
241                          sdbusplus::asio::object_server& objServerIn,
242                          std::function<void()>&& callback) :
243     _systemConfiguration(systemConfiguration),
244     _missingConfigurations(missingConfigurations),
245     _configurations(configurations), objServer(objServerIn),
246     _callback(std::move(callback))
247 {}
248 
249 static void pruneRecordExposes(nlohmann::json& record)
250 {
251     auto findExposes = record.find("Exposes");
252     if (findExposes == record.end())
253     {
254         return;
255     }
256 
257     auto copy = nlohmann::json::array();
258     for (auto& expose : *findExposes)
259     {
260         if (!expose.is_null())
261         {
262             copy.emplace_back(expose);
263         }
264     }
265     *findExposes = copy;
266 }
267 
268 static void recordDiscoveredIdentifiers(
269     std::set<nlohmann::json>& usedNames, std::list<size_t>& indexes,
270     const std::string& probeName, const nlohmann::json& record)
271 {
272     size_t indexIdx = probeName.find('$');
273     if (indexIdx == std::string::npos)
274     {
275         return;
276     }
277 
278     auto nameIt = record.find("Name");
279     if (nameIt == record.end())
280     {
281         std::cerr << "Last JSON Illegal\n";
282         return;
283     }
284 
285     int index = 0;
286     auto str = nameIt->get<std::string>().substr(indexIdx);
287     // NOLINTNEXTLINE(cppcoreguidelines-pro-bounds-pointer-arithmetic)
288     const char* endPtr = str.data() + str.size();
289     auto [p, ec] = std::from_chars(str.data(), endPtr, index);
290     if (ec != std::errc())
291     {
292         return; // non-numeric replacement
293     }
294 
295     usedNames.insert(nameIt.value());
296 
297     auto usedIt = std::find(indexes.begin(), indexes.end(), index);
298     if (usedIt != indexes.end())
299     {
300         indexes.erase(usedIt);
301     }
302 }
303 
304 static bool extractExposeActionRecordNames(std::vector<std::string>& matches,
305                                            nlohmann::json::iterator& keyPair)
306 {
307     if (keyPair.value().is_string())
308     {
309         matches.emplace_back(keyPair.value());
310         return true;
311     }
312 
313     if (keyPair.value().is_array())
314     {
315         for (const auto& value : keyPair.value())
316         {
317             if (!value.is_string())
318             {
319                 std::cerr << "Value is invalid type " << value << "\n";
320                 break;
321             }
322             matches.emplace_back(value);
323         }
324 
325         return true;
326     }
327 
328     std::cerr << "Value is invalid type " << keyPair.key() << "\n";
329 
330     return false;
331 }
332 
333 static std::optional<std::vector<std::string>::iterator> findExposeActionRecord(
334     std::vector<std::string>& matches, const nlohmann::json& record)
335 {
336     const auto& name = (record)["Name"].get_ref<const std::string&>();
337     auto compare = [&name](const std::string& s) { return s == name; };
338     auto matchIt = std::find_if(matches.begin(), matches.end(), compare);
339 
340     if (matchIt == matches.end())
341     {
342         return std::nullopt;
343     }
344 
345     return matchIt;
346 }
347 
348 static void applyBindExposeAction(nlohmann::json& exposedObject,
349                                   nlohmann::json& expose,
350                                   const std::string& propertyName)
351 {
352     if (boost::starts_with(propertyName, "Bind"))
353     {
354         std::string bind = propertyName.substr(sizeof("Bind") - 1);
355         exposedObject["Status"] = "okay";
356         expose[bind] = exposedObject;
357     }
358 }
359 
360 static void applyDisableExposeAction(nlohmann::json& exposedObject,
361                                      const std::string& propertyName)
362 {
363     if (propertyName == "DisableNode")
364     {
365         exposedObject["Status"] = "disabled";
366     }
367 }
368 
369 static void applyConfigExposeActions(
370     std::vector<std::string>& matches, nlohmann::json& expose,
371     const std::string& propertyName, nlohmann::json& configExposes)
372 {
373     for (auto& exposedObject : configExposes)
374     {
375         auto match = findExposeActionRecord(matches, exposedObject);
376         if (match)
377         {
378             matches.erase(*match);
379             applyBindExposeAction(exposedObject, expose, propertyName);
380             applyDisableExposeAction(exposedObject, propertyName);
381         }
382     }
383 }
384 
385 static void applyExposeActions(
386     nlohmann::json& systemConfiguration, const std::string& recordName,
387     nlohmann::json& expose, nlohmann::json::iterator& keyPair)
388 {
389     bool isBind = boost::starts_with(keyPair.key(), "Bind");
390     bool isDisable = keyPair.key() == "DisableNode";
391     bool isExposeAction = isBind || isDisable;
392 
393     if (!isExposeAction)
394     {
395         return;
396     }
397 
398     std::vector<std::string> matches;
399 
400     if (!extractExposeActionRecordNames(matches, keyPair))
401     {
402         return;
403     }
404 
405     for (const auto& [configId, config] : systemConfiguration.items())
406     {
407         // don't disable ourselves
408         if (isDisable && configId == recordName)
409         {
410             continue;
411         }
412 
413         auto configListFind = config.find("Exposes");
414         if (configListFind == config.end())
415         {
416             continue;
417         }
418 
419         if (!configListFind->is_array())
420         {
421             continue;
422         }
423 
424         applyConfigExposeActions(matches, expose, keyPair.key(),
425                                  *configListFind);
426     }
427 
428     if (!matches.empty())
429     {
430         std::cerr << "configuration file dependency error, could not find "
431                   << keyPair.key() << " " << keyPair.value() << "\n";
432     }
433 }
434 
435 static std::string generateDeviceName(
436     const std::set<nlohmann::json>& usedNames, const DBusObject& dbusObject,
437     size_t foundDeviceIdx, const std::string& nameTemplate,
438     std::optional<std::string>& replaceStr)
439 {
440     nlohmann::json copyForName = {{"Name", nameTemplate}};
441     nlohmann::json::iterator copyIt = copyForName.begin();
442     std::optional<std::string> replaceVal =
443         templateCharReplace(copyIt, dbusObject, foundDeviceIdx, replaceStr);
444 
445     if (!replaceStr && replaceVal)
446     {
447         if (usedNames.find(copyIt.value()) != usedNames.end())
448         {
449             replaceStr = replaceVal;
450             copyForName = {{"Name", nameTemplate}};
451             copyIt = copyForName.begin();
452             templateCharReplace(copyIt, dbusObject, foundDeviceIdx, replaceStr);
453         }
454     }
455 
456     if (replaceStr)
457     {
458         std::cerr << "Duplicates found, replacing " << *replaceStr
459                   << " with found device index.\n Consider "
460                      "fixing template to not have duplicates\n";
461     }
462 
463     return copyIt.value();
464 }
465 
466 void PerformScan::updateSystemConfiguration(const nlohmann::json& recordRef,
467                                             const std::string& probeName,
468                                             FoundDevices& foundDevices)
469 {
470     _passed = true;
471     passedProbes.push_back(probeName);
472 
473     std::set<nlohmann::json> usedNames;
474     std::list<size_t> indexes(foundDevices.size());
475     std::iota(indexes.begin(), indexes.end(), 1);
476 
477     // copy over persisted configurations and make sure we remove
478     // indexes that are already used
479     for (auto itr = foundDevices.begin(); itr != foundDevices.end();)
480     {
481         std::string recordName = getRecordName(itr->interface, probeName);
482 
483         auto record = _systemConfiguration.find(recordName);
484         if (record == _systemConfiguration.end())
485         {
486             record = lastJson.find(recordName);
487             if (record == lastJson.end())
488             {
489                 itr++;
490                 continue;
491             }
492 
493             pruneRecordExposes(*record);
494 
495             _systemConfiguration[recordName] = *record;
496         }
497         _missingConfigurations.erase(recordName);
498 
499         // We've processed the device, remove it and advance the
500         // iterator
501         itr = foundDevices.erase(itr);
502         recordDiscoveredIdentifiers(usedNames, indexes, probeName, *record);
503     }
504 
505     std::optional<std::string> replaceStr;
506 
507     DBusObject emptyObject;
508     DBusInterface emptyInterface;
509     emptyObject.emplace(std::string{}, emptyInterface);
510 
511     for (const auto& [foundDevice, path] : foundDevices)
512     {
513         // Need all interfaces on this path so that template
514         // substitutions can be done with any of the contained
515         // properties.  If the probe that passed didn't use an
516         // interface, such as if it was just TRUE, then
517         // templateCharReplace will just get passed in an empty
518         // map.
519         auto objectIt = dbusProbeObjects.find(path);
520         const DBusObject& dbusObject = (objectIt == dbusProbeObjects.end())
521                                            ? emptyObject
522                                            : objectIt->second;
523 
524         nlohmann::json record = recordRef;
525         std::string recordName = getRecordName(foundDevice, probeName);
526         size_t foundDeviceIdx = indexes.front();
527         indexes.pop_front();
528 
529         // check name first so we have no duplicate names
530         auto getName = record.find("Name");
531         if (getName == record.end())
532         {
533             std::cerr << "Record Missing Name! " << record.dump();
534             continue; // this should be impossible at this level
535         }
536 
537         std::string deviceName = generateDeviceName(
538             usedNames, dbusObject, foundDeviceIdx, getName.value(), replaceStr);
539         getName.value() = deviceName;
540         usedNames.insert(deviceName);
541 
542         for (auto keyPair = record.begin(); keyPair != record.end(); keyPair++)
543         {
544             if (keyPair.key() != "Name")
545             {
546                 templateCharReplace(keyPair, dbusObject, foundDeviceIdx,
547                                     replaceStr);
548             }
549         }
550 
551         // insert into configuration temporarily to be able to
552         // reference ourselves
553 
554         _systemConfiguration[recordName] = record;
555 
556         auto findExpose = record.find("Exposes");
557         if (findExpose == record.end())
558         {
559             continue;
560         }
561 
562         for (auto& expose : *findExpose)
563         {
564             for (auto keyPair = expose.begin(); keyPair != expose.end();
565                  keyPair++)
566             {
567                 templateCharReplace(keyPair, dbusObject, foundDeviceIdx,
568                                     replaceStr);
569 
570                 applyExposeActions(_systemConfiguration, recordName, expose,
571                                    keyPair);
572             }
573         }
574 
575         // overwrite ourselves with cleaned up version
576         _systemConfiguration[recordName] = record;
577         _missingConfigurations.erase(recordName);
578     }
579 }
580 
581 void PerformScan::run()
582 {
583     boost::container::flat_set<std::string> dbusProbeInterfaces;
584     std::vector<std::shared_ptr<PerformProbe>> dbusProbePointers;
585 
586     for (auto it = _configurations.begin(); it != _configurations.end();)
587     {
588         // check for poorly formatted fields, probe must be an array
589         auto findProbe = it->find("Probe");
590         if (findProbe == it->end())
591         {
592             std::cerr << "configuration file missing probe:\n " << *it << "\n";
593             it = _configurations.erase(it);
594             continue;
595         }
596 
597         auto findName = it->find("Name");
598         if (findName == it->end())
599         {
600             std::cerr << "configuration file missing name:\n " << *it << "\n";
601             it = _configurations.erase(it);
602             continue;
603         }
604         std::string probeName = *findName;
605 
606         if (std::find(passedProbes.begin(), passedProbes.end(), probeName) !=
607             passedProbes.end())
608         {
609             it = _configurations.erase(it);
610             continue;
611         }
612 
613         nlohmann::json& recordRef = *it;
614         nlohmann::json probeCommand;
615         if ((*findProbe).type() != nlohmann::json::value_t::array)
616         {
617             probeCommand = nlohmann::json::array();
618             probeCommand.push_back(*findProbe);
619         }
620         else
621         {
622             probeCommand = *findProbe;
623         }
624 
625         // store reference to this to children to makes sure we don't get
626         // destroyed too early
627         auto thisRef = shared_from_this();
628         auto probePointer = std::make_shared<PerformProbe>(
629             recordRef, probeCommand, probeName, thisRef);
630 
631         // parse out dbus probes by discarding other probe types, store in a
632         // map
633         for (const nlohmann::json& probeJson : probeCommand)
634         {
635             const std::string* probe = probeJson.get_ptr<const std::string*>();
636             if (probe == nullptr)
637             {
638                 std::cerr << "Probe statement wasn't a string, can't parse";
639                 continue;
640             }
641             if (findProbeType(*probe))
642             {
643                 continue;
644             }
645             // syntax requires probe before first open brace
646             auto findStart = probe->find('(');
647             std::string interface = probe->substr(0, findStart);
648             dbusProbeInterfaces.emplace(interface);
649             dbusProbePointers.emplace_back(probePointer);
650         }
651         it++;
652     }
653 
654     // probe vector stores a shared_ptr to each PerformProbe that cares
655     // about a dbus interface
656     findDbusObjects(std::move(dbusProbePointers),
657                     std::move(dbusProbeInterfaces), shared_from_this());
658     if constexpr (debug)
659     {
660         std::cerr << __LINE__ << "\n";
661     }
662 }
663 
664 PerformScan::~PerformScan()
665 {
666     if (_passed)
667     {
668         auto nextScan = std::make_shared<PerformScan>(
669             _systemConfiguration, _missingConfigurations, _configurations,
670             objServer, std::move(_callback));
671         nextScan->passedProbes = std::move(passedProbes);
672         nextScan->dbusProbeObjects = std::move(dbusProbeObjects);
673         nextScan->run();
674 
675         if constexpr (debug)
676         {
677             std::cerr << __LINE__ << "\n";
678         }
679     }
680     else
681     {
682         _callback();
683 
684         if constexpr (debug)
685         {
686             std::cerr << __LINE__ << "\n";
687         }
688     }
689 }
690