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 << " " << instance.interface << "\n";
67 
68             auto timer = std::make_shared<boost::asio::steady_timer>(io);
69             timer->expires_after(std::chrono::seconds(2));
70 
71             timer->async_wait([timer, instance, scan, probeVector,
72                                retries](const boost::system::error_code&) {
73                 getInterfaces(instance, probeVector, scan, retries - 1);
74             });
75             return;
76         }
77 
78         scan->dbusProbeObjects[instance.path][instance.interface] = resp;
79     },
80         instance.busName, instance.path, "org.freedesktop.DBus.Properties",
81         "GetAll", instance.interface);
82 
83     if constexpr (debug)
84     {
85         std::cerr << __LINE__ << "\n";
86     }
87 }
88 
89 static void registerCallback(nlohmann::json& systemConfiguration,
90                              sdbusplus::asio::object_server& objServer,
91                              const std::string& path)
92 {
93     static boost::container::flat_map<std::string, sdbusplus::bus::match_t>
94         dbusMatches;
95 
96     auto find = dbusMatches.find(path);
97     if (find != dbusMatches.end())
98     {
99         return;
100     }
101 
102     std::function<void(sdbusplus::message_t & message)> eventHandler =
103         [&](sdbusplus::message_t&) {
104         propertiesChangedCallback(systemConfiguration, objServer);
105     };
106 
107     sdbusplus::bus::match_t match(
108         static_cast<sdbusplus::bus_t&>(*systemBus),
109         "type='signal',member='PropertiesChanged',path='" + path + "'",
110         eventHandler);
111     dbusMatches.emplace(path, std::move(match));
112 }
113 
114 static void
115     processDbusObjects(std::vector<std::shared_ptr<PerformProbe>>& probeVector,
116                        const std::shared_ptr<PerformScan>& scan,
117                        const GetSubTreeType& interfaceSubtree)
118 {
119     for (const auto& [path, object] : interfaceSubtree)
120     {
121         // Get a PropertiesChanged callback for all interfaces on this path.
122         registerCallback(scan->_systemConfiguration, scan->objServer, path);
123 
124         for (const auto& [busname, ifaces] : object)
125         {
126             for (const std::string& iface : ifaces)
127             {
128                 // The 3 default org.freedeskstop interfaces (Peer,
129                 // Introspectable, and Properties) are returned by
130                 // the mapper but don't have properties, so don't bother
131                 // with the GetAll call to save some cycles.
132                 if (!boost::algorithm::starts_with(iface, "org.freedesktop"))
133                 {
134                     getInterfaces({busname, path, iface}, probeVector, scan);
135                 }
136             }
137         }
138     }
139 }
140 
141 // Populates scan->dbusProbeObjects with all interfaces and properties
142 // for the paths that own the interfaces passed in.
143 void findDbusObjects(std::vector<std::shared_ptr<PerformProbe>>&& probeVector,
144                      boost::container::flat_set<std::string>&& interfaces,
145                      const std::shared_ptr<PerformScan>& scan,
146                      size_t retries = 5)
147 {
148     // Filter out interfaces already obtained.
149     for (const auto& [path, probeInterfaces] : scan->dbusProbeObjects)
150     {
151         for (const auto& [interface, _] : probeInterfaces)
152         {
153             interfaces.erase(interface);
154         }
155     }
156     if (interfaces.empty())
157     {
158         return;
159     }
160 
161     // find all connections in the mapper that expose a specific type
162     systemBus->async_method_call(
163         [interfaces, probeVector{std::move(probeVector)}, scan,
164          retries](boost::system::error_code& ec,
165                   const GetSubTreeType& interfaceSubtree) mutable {
166         if (ec)
167         {
168             if (ec.value() == ENOENT)
169             {
170                 return; // wasn't found by mapper
171             }
172             std::cerr << "Error communicating to mapper.\n";
173 
174             if (retries == 0U)
175             {
176                 // if we can't communicate to the mapper something is very
177                 // wrong
178                 std::exit(EXIT_FAILURE);
179             }
180 
181             auto timer = std::make_shared<boost::asio::steady_timer>(io);
182             timer->expires_after(std::chrono::seconds(10));
183 
184             timer->async_wait([timer, interfaces{std::move(interfaces)}, scan,
185                                probeVector{std::move(probeVector)}, retries](
186                                   const boost::system::error_code&) mutable {
187                 findDbusObjects(std::move(probeVector), std::move(interfaces),
188                                 scan, retries - 1);
189             });
190             return;
191         }
192 
193         processDbusObjects(probeVector, scan, interfaceSubtree);
194     },
195         "xyz.openbmc_project.ObjectMapper",
196         "/xyz/openbmc_project/object_mapper",
197         "xyz.openbmc_project.ObjectMapper", "GetSubTree", "/", maxMapperDepth,
198         interfaces);
199 
200     if constexpr (debug)
201     {
202         std::cerr << __LINE__ << "\n";
203     }
204 }
205 
206 static std::string getRecordName(const DBusInterface& probe,
207                                  const std::string& probeName)
208 {
209     if (probe.empty())
210     {
211         return probeName;
212     }
213 
214     // use an array so alphabetical order from the flat_map is maintained
215     auto device = nlohmann::json::array();
216     for (const auto& devPair : probe)
217     {
218         device.push_back(devPair.first);
219         std::visit([&device](auto&& v) { device.push_back(v); },
220                    devPair.second);
221     }
222 
223     // hashes are hard to distinguish, use the non-hashed version if we want
224     // debug
225     if constexpr (debug)
226     {
227         return probeName + device.dump();
228     }
229 
230     return std::to_string(std::hash<std::string>{}(probeName + device.dump()));
231 }
232 
233 PerformScan::PerformScan(nlohmann::json& systemConfiguration,
234                          nlohmann::json& missingConfigurations,
235                          std::list<nlohmann::json>& configurations,
236                          sdbusplus::asio::object_server& objServerIn,
237                          std::function<void()>&& callback) :
238     _systemConfiguration(systemConfiguration),
239     _missingConfigurations(missingConfigurations),
240     _configurations(configurations), objServer(objServerIn),
241     _callback(std::move(callback))
242 {}
243 
244 static void pruneRecordExposes(nlohmann::json& record)
245 {
246     auto findExposes = record.find("Exposes");
247     if (findExposes == record.end())
248     {
249         return;
250     }
251 
252     auto copy = nlohmann::json::array();
253     for (auto& expose : *findExposes)
254     {
255         if (!expose.is_null())
256         {
257             copy.emplace_back(expose);
258         }
259     }
260     *findExposes = copy;
261 }
262 
263 static void recordDiscoveredIdentifiers(std::set<nlohmann::json>& usedNames,
264                                         std::list<size_t>& indexes,
265                                         const std::string& probeName,
266                                         const nlohmann::json& record)
267 {
268     size_t indexIdx = probeName.find('$');
269     if (indexIdx == std::string::npos)
270     {
271         return;
272     }
273 
274     auto nameIt = record.find("Name");
275     if (nameIt == record.end())
276     {
277         std::cerr << "Last JSON Illegal\n";
278         return;
279     }
280 
281     int index = 0;
282     auto str = nameIt->get<std::string>().substr(indexIdx);
283     // NOLINTNEXTLINE(cppcoreguidelines-pro-bounds-pointer-arithmetic)
284     const char* endPtr = str.data() + str.size();
285     auto [p, ec] = std::from_chars(str.data(), endPtr, index);
286     if (ec != std::errc())
287     {
288         return; // non-numeric replacement
289     }
290 
291     usedNames.insert(nameIt.value());
292 
293     auto usedIt = std::find(indexes.begin(), indexes.end(), index);
294     if (usedIt != indexes.end())
295     {
296         indexes.erase(usedIt);
297     }
298 }
299 
300 static bool extractExposeActionRecordNames(std::vector<std::string>& matches,
301                                            nlohmann::json::iterator& keyPair)
302 {
303     if (keyPair.value().is_string())
304     {
305         matches.emplace_back(keyPair.value());
306         return true;
307     }
308 
309     if (keyPair.value().is_array())
310     {
311         for (const auto& value : keyPair.value())
312         {
313             if (!value.is_string())
314             {
315                 std::cerr << "Value is invalid type " << value << "\n";
316                 break;
317             }
318             matches.emplace_back(value);
319         }
320 
321         return true;
322     }
323 
324     std::cerr << "Value is invalid type " << keyPair.key() << "\n";
325 
326     return false;
327 }
328 
329 static std::optional<std::vector<std::string>::iterator>
330     findExposeActionRecord(std::vector<std::string>& matches,
331                            const nlohmann::json& record)
332 {
333     const auto& name = (record)["Name"].get_ref<const std::string&>();
334     auto compare = [&name](const std::string& s) { return s == name; };
335     auto matchIt = std::find_if(matches.begin(), matches.end(), compare);
336 
337     if (matchIt == matches.end())
338     {
339         return std::nullopt;
340     }
341 
342     return matchIt;
343 }
344 
345 static void applyBindExposeAction(nlohmann::json& exposedObject,
346                                   nlohmann::json& expose,
347                                   const std::string& propertyName)
348 {
349     if (boost::starts_with(propertyName, "Bind"))
350     {
351         std::string bind = propertyName.substr(sizeof("Bind") - 1);
352         exposedObject["Status"] = "okay";
353         expose[bind] = exposedObject;
354     }
355 }
356 
357 static void applyDisableExposeAction(nlohmann::json& exposedObject,
358                                      const std::string& propertyName)
359 {
360     if (propertyName == "DisableNode")
361     {
362         exposedObject["Status"] = "disabled";
363     }
364 }
365 
366 static void applyConfigExposeActions(std::vector<std::string>& matches,
367                                      nlohmann::json& expose,
368                                      const std::string& propertyName,
369                                      nlohmann::json& configExposes)
370 {
371     for (auto& exposedObject : configExposes)
372     {
373         auto match = findExposeActionRecord(matches, exposedObject);
374         if (match)
375         {
376             matches.erase(*match);
377             applyBindExposeAction(exposedObject, expose, propertyName);
378             applyDisableExposeAction(exposedObject, propertyName);
379         }
380     }
381 }
382 
383 static void applyExposeActions(nlohmann::json& systemConfiguration,
384                                const std::string& recordName,
385                                nlohmann::json& expose,
386                                nlohmann::json::iterator& keyPair)
387 {
388     bool isBind = boost::starts_with(keyPair.key(), "Bind");
389     bool isDisable = keyPair.key() == "DisableNode";
390     bool isExposeAction = isBind || isDisable;
391 
392     if (!isExposeAction)
393     {
394         return;
395     }
396 
397     std::vector<std::string> matches;
398 
399     if (!extractExposeActionRecordNames(matches, keyPair))
400     {
401         return;
402     }
403 
404     for (const auto& [configId, config] : systemConfiguration.items())
405     {
406         // don't disable ourselves
407         if (isDisable && configId == recordName)
408         {
409             continue;
410         }
411 
412         auto configListFind = config.find("Exposes");
413         if (configListFind == config.end())
414         {
415             continue;
416         }
417 
418         if (!configListFind->is_array())
419         {
420             continue;
421         }
422 
423         applyConfigExposeActions(matches, expose, keyPair.key(),
424                                  *configListFind);
425     }
426 
427     if (!matches.empty())
428     {
429         std::cerr << "configuration file dependency error, could not find "
430                   << keyPair.key() << " " << keyPair.value() << "\n";
431     }
432 }
433 
434 static std::string generateDeviceName(const std::set<nlohmann::json>& usedNames,
435                                       const DBusObject& dbusObject,
436                                       size_t foundDeviceIdx,
437                                       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