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)
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 << __func__ << " " << __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::match>
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::message & message)> eventHandler =
104         [&](sdbusplus::message::message&) {
105             propertiesChangedCallback(systemConfiguration, objServer);
106         };
107 
108     sdbusplus::bus::match::match match(
109         static_cast<sdbusplus::bus::bus&>(*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)
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 << __func__ << " " << __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 (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     auto [p, ec] = std::from_chars(str.data(), str.data() + str.size(), index);
287     if (ec != std::errc())
288     {
289         return; // non-numeric replacement
290     }
291 
292     usedNames.insert(nameIt.value());
293 
294     auto usedIt = std::find(indexes.begin(), indexes.end(), index);
295     if (usedIt != indexes.end())
296     {
297         indexes.erase(usedIt);
298     }
299 }
300 
301 static bool extractExposeActionRecordNames(std::vector<std::string>& matches,
302                                            nlohmann::json::iterator& keyPair)
303 {
304     if (keyPair.value().is_string())
305     {
306         matches.emplace_back(keyPair.value());
307         return true;
308     }
309 
310     if (keyPair.value().is_array())
311     {
312         for (const auto& value : keyPair.value())
313         {
314             if (!value.is_string())
315             {
316                 std::cerr << "Value is invalid type " << value << "\n";
317                 break;
318             }
319             matches.emplace_back(value);
320         }
321 
322         return true;
323     }
324 
325     std::cerr << "Value is invalid type " << keyPair.key() << "\n";
326 
327     return false;
328 }
329 
330 static std::optional<std::vector<std::string>::iterator>
331     findExposeActionRecord(std::vector<std::string>& matches,
332                            const nlohmann::json& record)
333 {
334     const auto& name = (record)["Name"].get_ref<const std::string&>();
335     auto compare = [&name](const std::string& s) { return s == name; };
336     auto matchIt = std::find_if(matches.begin(), matches.end(), compare);
337 
338     if (matchIt == matches.end())
339     {
340         return std::nullopt;
341     }
342 
343     return matchIt;
344 }
345 
346 static void applyBindExposeAction(nlohmann::json& exposedObject,
347                                   nlohmann::json& expose,
348                                   const std::string& propertyName)
349 {
350     if (boost::starts_with(propertyName, "Bind"))
351     {
352         std::string bind = propertyName.substr(sizeof("Bind") - 1);
353         exposedObject["Status"] = "okay";
354         expose[bind] = exposedObject;
355     }
356 }
357 
358 static void applyDisableExposeAction(nlohmann::json& exposedObject,
359                                      const std::string& propertyName)
360 {
361     if (propertyName == "DisableNode")
362     {
363         exposedObject["Status"] = "disabled";
364     }
365 }
366 
367 static void applyConfigExposeActions(std::vector<std::string>& matches,
368                                      nlohmann::json& expose,
369                                      const std::string& propertyName,
370                                      nlohmann::json& configExposes)
371 {
372     for (auto& exposedObject : configExposes)
373     {
374         auto match = findExposeActionRecord(matches, exposedObject);
375         if (match)
376         {
377             matches.erase(*match);
378             applyBindExposeAction(exposedObject, expose, propertyName);
379             applyDisableExposeAction(exposedObject, propertyName);
380         }
381     }
382 }
383 
384 static void applyExposeActions(nlohmann::json& systemConfiguration,
385                                const std::string& recordName,
386                                nlohmann::json& expose,
387                                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 (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(const std::set<nlohmann::json>& usedNames,
436                                       const DBusObject& dbusObject,
437                                       size_t foundDeviceIdx,
438                                       const std::string& nameTemplate,
439                                       std::optional<std::string>& replaceStr)
440 {
441     nlohmann::json copyForName = {{"Name", nameTemplate}};
442     nlohmann::json::iterator copyIt = copyForName.begin();
443     std::optional<std::string> replaceVal =
444         templateCharReplace(copyIt, dbusObject, foundDeviceIdx, replaceStr);
445 
446     if (!replaceStr && replaceVal)
447     {
448         if (usedNames.find(copyIt.value()) != usedNames.end())
449         {
450             replaceStr = replaceVal;
451             copyForName = {{"Name", nameTemplate}};
452             copyIt = copyForName.begin();
453             templateCharReplace(copyIt, dbusObject, foundDeviceIdx, replaceStr);
454         }
455     }
456 
457     if (replaceStr)
458     {
459         std::cerr << "Duplicates found, replacing " << *replaceStr
460                   << " with found device index.\n Consider "
461                      "fixing template to not have duplicates\n";
462     }
463 
464     return copyIt.value();
465 }
466 
467 void PerformScan::updateSystemConfiguration(const nlohmann::json& recordRef,
468                                             const std::string& probeName,
469                                             FoundDevices& foundDevices)
470 {
471     _passed = true;
472     passedProbes.push_back(probeName);
473 
474     std::set<nlohmann::json> usedNames;
475     std::list<size_t> indexes(foundDevices.size());
476     std::iota(indexes.begin(), indexes.end(), 1);
477 
478     // copy over persisted configurations and make sure we remove
479     // indexes that are already used
480     for (auto itr = foundDevices.begin(); itr != foundDevices.end();)
481     {
482         std::string recordName = getRecordName(itr->interface, probeName);
483 
484         auto record = lastJson.find(recordName);
485         if (record == lastJson.end())
486         {
487             itr++;
488             continue;
489         }
490 
491         pruneRecordExposes(*record);
492 
493         recordDiscoveredIdentifiers(usedNames, indexes, probeName, *record);
494 
495         // keep user changes
496         _systemConfiguration[recordName] = *record;
497         _missingConfigurations.erase(recordName);
498 
499         // We've processed the device, remove it and advance the
500         // iterator
501         itr = foundDevices.erase(itr);
502     }
503 
504     std::optional<std::string> replaceStr;
505 
506     DBusObject emptyObject;
507     DBusInterface emptyInterface;
508     emptyObject.emplace(std::string{}, emptyInterface);
509 
510     for (const auto& [foundDevice, path] : foundDevices)
511     {
512         // Need all interfaces on this path so that template
513         // substitutions can be done with any of the contained
514         // properties.  If the probe that passed didn't use an
515         // interface, such as if it was just TRUE, then
516         // templateCharReplace will just get passed in an empty
517         // map.
518         auto objectIt = dbusProbeObjects.find(path);
519         const DBusObject& dbusObject = (objectIt == dbusProbeObjects.end())
520                                            ? emptyObject
521                                            : objectIt->second;
522 
523         nlohmann::json record = recordRef;
524         std::string recordName = getRecordName(foundDevice, probeName);
525         size_t foundDeviceIdx = indexes.front();
526         indexes.pop_front();
527 
528         // check name first so we have no duplicate names
529         auto getName = record.find("Name");
530         if (getName == record.end())
531         {
532             std::cerr << "Record Missing Name! " << record.dump();
533             continue; // this should be impossible at this level
534         }
535 
536         std::string deviceName = generateDeviceName(
537             usedNames, dbusObject, foundDeviceIdx, getName.value(), replaceStr);
538         getName.value() = deviceName;
539         usedNames.insert(deviceName);
540 
541         for (auto keyPair = record.begin(); keyPair != record.end(); keyPair++)
542         {
543             if (keyPair.key() != "Name")
544             {
545                 templateCharReplace(keyPair, dbusObject, foundDeviceIdx,
546                                     replaceStr);
547             }
548         }
549 
550         // insert into configuration temporarily to be able to
551         // reference ourselves
552 
553         _systemConfiguration[recordName] = record;
554 
555         auto findExpose = record.find("Exposes");
556         if (findExpose == record.end())
557         {
558             continue;
559         }
560 
561         for (auto& expose : *findExpose)
562         {
563             for (auto keyPair = expose.begin(); keyPair != expose.end();
564                  keyPair++)
565             {
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->c_str()))
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 << __func__ << " " << __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 << __func__ << " " << __LINE__ << "\n";
678         }
679     }
680     else
681     {
682         _callback();
683 
684         if constexpr (debug)
685         {
686             std::cerr << __func__ << " " << __LINE__ << "\n";
687         }
688     }
689 }
690