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             recordDiscoveredIdentifiers(usedNames, indexes, probeName, *record);
499 
500             _systemConfiguration[recordName] = *record;
501         }
502         _missingConfigurations.erase(recordName);
503 
504         // We've processed the device, remove it and advance the
505         // iterator
506         itr = foundDevices.erase(itr);
507     }
508 
509     std::optional<std::string> replaceStr;
510 
511     DBusObject emptyObject;
512     DBusInterface emptyInterface;
513     emptyObject.emplace(std::string{}, emptyInterface);
514 
515     for (const auto& [foundDevice, path] : foundDevices)
516     {
517         // Need all interfaces on this path so that template
518         // substitutions can be done with any of the contained
519         // properties.  If the probe that passed didn't use an
520         // interface, such as if it was just TRUE, then
521         // templateCharReplace will just get passed in an empty
522         // map.
523         auto objectIt = dbusProbeObjects.find(path);
524         const DBusObject& dbusObject = (objectIt == dbusProbeObjects.end())
525                                            ? emptyObject
526                                            : objectIt->second;
527 
528         nlohmann::json record = recordRef;
529         std::string recordName = getRecordName(foundDevice, probeName);
530         size_t foundDeviceIdx = indexes.front();
531         indexes.pop_front();
532 
533         // check name first so we have no duplicate names
534         auto getName = record.find("Name");
535         if (getName == record.end())
536         {
537             std::cerr << "Record Missing Name! " << record.dump();
538             continue; // this should be impossible at this level
539         }
540 
541         std::string deviceName = generateDeviceName(
542             usedNames, dbusObject, foundDeviceIdx, getName.value(), replaceStr);
543         getName.value() = deviceName;
544         usedNames.insert(deviceName);
545 
546         for (auto keyPair = record.begin(); keyPair != record.end(); keyPair++)
547         {
548             if (keyPair.key() != "Name")
549             {
550                 templateCharReplace(keyPair, dbusObject, foundDeviceIdx,
551                                     replaceStr);
552             }
553         }
554 
555         // insert into configuration temporarily to be able to
556         // reference ourselves
557 
558         _systemConfiguration[recordName] = record;
559 
560         auto findExpose = record.find("Exposes");
561         if (findExpose == record.end())
562         {
563             continue;
564         }
565 
566         for (auto& expose : *findExpose)
567         {
568             for (auto keyPair = expose.begin(); keyPair != expose.end();
569                  keyPair++)
570             {
571 
572                 templateCharReplace(keyPair, dbusObject, foundDeviceIdx,
573                                     replaceStr);
574 
575                 applyExposeActions(_systemConfiguration, recordName, expose,
576                                    keyPair);
577             }
578         }
579 
580         // overwrite ourselves with cleaned up version
581         _systemConfiguration[recordName] = record;
582         _missingConfigurations.erase(recordName);
583     }
584 }
585 
586 void PerformScan::run()
587 {
588     boost::container::flat_set<std::string> dbusProbeInterfaces;
589     std::vector<std::shared_ptr<PerformProbe>> dbusProbePointers;
590 
591     for (auto it = _configurations.begin(); it != _configurations.end();)
592     {
593         // check for poorly formatted fields, probe must be an array
594         auto findProbe = it->find("Probe");
595         if (findProbe == it->end())
596         {
597             std::cerr << "configuration file missing probe:\n " << *it << "\n";
598             it = _configurations.erase(it);
599             continue;
600         }
601 
602         auto findName = it->find("Name");
603         if (findName == it->end())
604         {
605             std::cerr << "configuration file missing name:\n " << *it << "\n";
606             it = _configurations.erase(it);
607             continue;
608         }
609         std::string probeName = *findName;
610 
611         if (std::find(passedProbes.begin(), passedProbes.end(), probeName) !=
612             passedProbes.end())
613         {
614             it = _configurations.erase(it);
615             continue;
616         }
617 
618         nlohmann::json& recordRef = *it;
619         nlohmann::json probeCommand;
620         if ((*findProbe).type() != nlohmann::json::value_t::array)
621         {
622             probeCommand = nlohmann::json::array();
623             probeCommand.push_back(*findProbe);
624         }
625         else
626         {
627             probeCommand = *findProbe;
628         }
629 
630         // store reference to this to children to makes sure we don't get
631         // destroyed too early
632         auto thisRef = shared_from_this();
633         auto probePointer = std::make_shared<PerformProbe>(
634             recordRef, probeCommand, probeName, thisRef);
635 
636         // parse out dbus probes by discarding other probe types, store in a
637         // map
638         for (const nlohmann::json& probeJson : probeCommand)
639         {
640             const std::string* probe = probeJson.get_ptr<const std::string*>();
641             if (probe == nullptr)
642             {
643                 std::cerr << "Probe statement wasn't a string, can't parse";
644                 continue;
645             }
646             if (findProbeType(*probe))
647             {
648                 continue;
649             }
650             // syntax requires probe before first open brace
651             auto findStart = probe->find('(');
652             std::string interface = probe->substr(0, findStart);
653             dbusProbeInterfaces.emplace(interface);
654             dbusProbePointers.emplace_back(probePointer);
655         }
656         it++;
657     }
658 
659     // probe vector stores a shared_ptr to each PerformProbe that cares
660     // about a dbus interface
661     findDbusObjects(std::move(dbusProbePointers),
662                     std::move(dbusProbeInterfaces), shared_from_this());
663     if constexpr (debug)
664     {
665         std::cerr << __LINE__ << "\n";
666     }
667 }
668 
669 PerformScan::~PerformScan()
670 {
671     if (_passed)
672     {
673         auto nextScan = std::make_shared<PerformScan>(
674             _systemConfiguration, _missingConfigurations, _configurations,
675             objServer, std::move(_callback));
676         nextScan->passedProbes = std::move(passedProbes);
677         nextScan->dbusProbeObjects = std::move(dbusProbeObjects);
678         nextScan->run();
679 
680         if constexpr (debug)
681         {
682             std::cerr << __LINE__ << "\n";
683         }
684     }
685     else
686     {
687         _callback();
688 
689         if constexpr (debug)
690         {
691             std::cerr << __LINE__ << "\n";
692         }
693     }
694 }
695