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