xref: /openbmc/phosphor-objmgr/src/main.cpp (revision 7f1c44dc)
1 #include "associations.hpp"
2 #include "processing.hpp"
3 #include "src/argument.hpp"
4 
5 #include <tinyxml2.h>
6 
7 #include <atomic>
8 #include <boost/algorithm/string/predicate.hpp>
9 #include <boost/container/flat_map.hpp>
10 #include <chrono>
11 #include <iomanip>
12 #include <iostream>
13 #include <sdbusplus/asio/connection.hpp>
14 #include <sdbusplus/asio/object_server.hpp>
15 
16 constexpr const char* OBJECT_MAPPER_DBUS_NAME =
17     "xyz.openbmc_project.ObjectMapper";
18 constexpr const char* XYZ_ASSOCIATION_INTERFACE =
19     "xyz.openbmc_project.Association";
20 
21 using Association = std::tuple<std::string, std::string, std::string>;
22 
23 AssociationInterfaces associationInterfaces;
24 AssociationOwnersType associationOwners;
25 
26 static WhiteBlackList service_whitelist;
27 static WhiteBlackList service_blacklist;
28 
29 /** Exception thrown when a path is not found in the object list. */
30 struct NotFoundException final : public sdbusplus::exception_t
31 {
32     const char* name() const noexcept override
33     {
34         return "org.freedesktop.DBus.Error.FileNotFound";
35     };
36     const char* description() const noexcept override
37     {
38         return "path or object not found";
39     };
40     const char* what() const noexcept override
41     {
42         return "org.freedesktop.DBus.Error.FileNotFound: "
43                "The requested object was not found";
44     };
45 };
46 
47 void update_owners(sdbusplus::asio::connection* conn,
48                    boost::container::flat_map<std::string, std::string>& owners,
49                    const std::string& new_object)
50 {
51     if (boost::starts_with(new_object, ":"))
52     {
53         return;
54     }
55     conn->async_method_call(
56         [&, new_object](const boost::system::error_code ec,
57                         const std::string& nameOwner) {
58             if (ec)
59             {
60                 std::cerr << "Error getting owner of " << new_object << " : "
61                           << ec << "\n";
62                 return;
63             }
64             owners[nameOwner] = new_object;
65         },
66         "org.freedesktop.DBus", "/", "org.freedesktop.DBus", "GetNameOwner",
67         new_object);
68 }
69 
70 void send_introspection_complete_signal(sdbusplus::asio::connection* system_bus,
71                                         const std::string& process_name)
72 {
73     // TODO(ed) This signal doesn't get exposed properly in the
74     // introspect right now.  Find out how to register signals in
75     // sdbusplus
76     sdbusplus::message::message m = system_bus->new_signal(
77         "/xyz/openbmc_project/object_mapper",
78         "xyz.openbmc_project.ObjectMapper.Private", "IntrospectionComplete");
79     m.append(process_name);
80     m.signal_send();
81 }
82 
83 struct InProgressIntrospect
84 {
85     InProgressIntrospect(
86         sdbusplus::asio::connection* system_bus, boost::asio::io_service& io,
87         const std::string& process_name
88 #ifdef DEBUG
89         ,
90         std::shared_ptr<std::chrono::time_point<std::chrono::steady_clock>>
91             global_start_time
92 #endif
93         ) :
94         system_bus(system_bus),
95         io(io), process_name(process_name)
96 #ifdef DEBUG
97         ,
98         global_start_time(global_start_time),
99         process_start_time(std::chrono::steady_clock::now())
100 #endif
101     {
102     }
103     ~InProgressIntrospect()
104     {
105         send_introspection_complete_signal(system_bus, process_name);
106 
107 #ifdef DEBUG
108         std::chrono::duration<float> diff =
109             std::chrono::steady_clock::now() - process_start_time;
110         std::cout << std::setw(50) << process_name << " scan took "
111                   << diff.count() << " seconds\n";
112 
113         // If we're the last outstanding caller globally, calculate the
114         // time it took
115         if (global_start_time != nullptr && global_start_time.use_count() == 1)
116         {
117             diff = std::chrono::steady_clock::now() - *global_start_time;
118             std::cout << "Total scan took " << diff.count()
119                       << " seconds to complete\n";
120         }
121 #endif
122     }
123     sdbusplus::asio::connection* system_bus;
124     boost::asio::io_service& io;
125     std::string process_name;
126 #ifdef DEBUG
127     std::shared_ptr<std::chrono::time_point<std::chrono::steady_clock>>
128         global_start_time;
129     std::chrono::time_point<std::chrono::steady_clock> process_start_time;
130 #endif
131 };
132 
133 // Called when either a new org.openbmc.Associations interface was
134 // created, or the associations property on that interface changed.
135 void associationChanged(sdbusplus::asio::object_server& objectServer,
136                         const std::vector<Association>& associations,
137                         const std::string& path, const std::string& owner)
138 {
139     AssociationPaths objects;
140 
141     for (const Association& association : associations)
142     {
143         std::string forward;
144         std::string reverse;
145         std::string endpoint;
146         std::tie(forward, reverse, endpoint) = association;
147 
148         if (forward.size())
149         {
150             objects[path + "/" + forward].emplace(endpoint);
151         }
152         if (reverse.size())
153         {
154             if (endpoint.empty())
155             {
156                 std::cerr << "Found invalid association on path " << path
157                           << "\n";
158                 continue;
159             }
160             objects[endpoint + "/" + reverse].emplace(path);
161         }
162     }
163     for (const auto& object : objects)
164     {
165         // the mapper exposes the new association interface but intakes
166         // the old
167 
168         auto& iface = associationInterfaces[object.first];
169         auto& i = std::get<ifacePos>(iface);
170         auto& endpoints = std::get<endpointsPos>(iface);
171 
172         // Only add new endpoints
173         for (auto& e : object.second)
174         {
175             if (std::find(endpoints.begin(), endpoints.end(), e) ==
176                 endpoints.end())
177             {
178                 endpoints.push_back(e);
179             }
180         }
181 
182         // If the interface already exists, only need to update
183         // the property value, otherwise create it
184         if (i)
185         {
186             i->set_property("endpoints", endpoints);
187         }
188         else
189         {
190             i = objectServer.add_interface(object.first,
191                                            XYZ_ASSOCIATION_INTERFACE);
192             i->register_property("endpoints", endpoints);
193             i->initialize();
194         }
195     }
196 
197     // Check for endpoints being removed instead of added
198     checkAssociationEndpointRemoves(path, owner, objects, objectServer,
199                                     associationOwners, associationInterfaces);
200 
201     // Update associationOwners with the latest info
202     auto a = associationOwners.find(path);
203     if (a != associationOwners.end())
204     {
205         auto o = a->second.find(owner);
206         if (o != a->second.end())
207         {
208             o->second = std::move(objects);
209         }
210         else
211         {
212             a->second.emplace(owner, std::move(objects));
213         }
214     }
215     else
216     {
217         boost::container::flat_map<std::string, AssociationPaths> owners;
218         owners.emplace(owner, std::move(objects));
219         associationOwners.emplace(path, owners);
220     }
221 }
222 
223 void do_associations(sdbusplus::asio::connection* system_bus,
224                      sdbusplus::asio::object_server& objectServer,
225                      const std::string& processName, const std::string& path)
226 {
227     system_bus->async_method_call(
228         [&objectServer, path, processName](
229             const boost::system::error_code ec,
230             const sdbusplus::message::variant<std::vector<Association>>&
231                 variantAssociations) {
232             if (ec)
233             {
234                 std::cerr << "Error getting associations from " << path << "\n";
235             }
236             std::vector<Association> associations =
237                 sdbusplus::message::variant_ns::get<std::vector<Association>>(
238                     variantAssociations);
239             associationChanged(objectServer, associations, path, processName);
240         },
241         processName, path, "org.freedesktop.DBus.Properties", "Get",
242         ASSOCIATIONS_INTERFACE, "associations");
243 }
244 
245 void do_introspect(sdbusplus::asio::connection* system_bus,
246                    std::shared_ptr<InProgressIntrospect> transaction,
247                    interface_map_type& interface_map,
248                    sdbusplus::asio::object_server& objectServer,
249                    std::string path)
250 {
251     system_bus->async_method_call(
252         [&interface_map, &objectServer, transaction, path,
253          system_bus](const boost::system::error_code ec,
254                      const std::string& introspect_xml) {
255             if (ec)
256             {
257                 std::cerr << "Introspect call failed with error: " << ec << ", "
258                           << ec.message()
259                           << " on process: " << transaction->process_name
260                           << " path: " << path << "\n";
261                 return;
262             }
263 
264             tinyxml2::XMLDocument doc;
265 
266             tinyxml2::XMLError e = doc.Parse(introspect_xml.c_str());
267             if (e != tinyxml2::XMLError::XML_SUCCESS)
268             {
269                 std::cerr << "XML parsing failed\n";
270                 return;
271             }
272 
273             tinyxml2::XMLNode* pRoot = doc.FirstChildElement("node");
274             if (pRoot == nullptr)
275             {
276                 std::cerr << "XML document did not contain any data\n";
277                 return;
278             }
279             auto& thisPathMap = interface_map[path];
280             tinyxml2::XMLElement* pElement =
281                 pRoot->FirstChildElement("interface");
282             while (pElement != nullptr)
283             {
284                 const char* iface_name = pElement->Attribute("name");
285                 if (iface_name == nullptr)
286                 {
287                     continue;
288                 }
289 
290                 std::string iface{iface_name};
291 
292                 thisPathMap[transaction->process_name].emplace(iface_name);
293 
294                 if (std::strcmp(iface_name, ASSOCIATIONS_INTERFACE) == 0)
295                 {
296                     do_associations(system_bus, objectServer,
297                                     transaction->process_name, path);
298                 }
299 
300                 pElement = pElement->NextSiblingElement("interface");
301             }
302 
303             pElement = pRoot->FirstChildElement("node");
304             while (pElement != nullptr)
305             {
306                 const char* child_path = pElement->Attribute("name");
307                 if (child_path != nullptr)
308                 {
309                     std::string parent_path(path);
310                     if (parent_path == "/")
311                     {
312                         parent_path.clear();
313                     }
314 
315                     do_introspect(system_bus, transaction, interface_map,
316                                   objectServer, parent_path + "/" + child_path);
317                 }
318                 pElement = pElement->NextSiblingElement("node");
319             }
320         },
321         transaction->process_name, path, "org.freedesktop.DBus.Introspectable",
322         "Introspect");
323 }
324 
325 void start_new_introspect(
326     sdbusplus::asio::connection* system_bus, boost::asio::io_service& io,
327     interface_map_type& interface_map, const std::string& process_name,
328 #ifdef DEBUG
329     std::shared_ptr<std::chrono::time_point<std::chrono::steady_clock>>
330         global_start_time,
331 #endif
332     sdbusplus::asio::object_server& objectServer)
333 {
334     if (needToIntrospect(process_name, service_whitelist, service_blacklist))
335     {
336         std::shared_ptr<InProgressIntrospect> transaction =
337             std::make_shared<InProgressIntrospect>(system_bus, io, process_name
338 #ifdef DEBUG
339                                                    ,
340                                                    global_start_time
341 #endif
342             );
343 
344         do_introspect(system_bus, transaction, interface_map, objectServer,
345                       "/");
346     }
347 }
348 
349 // TODO(ed) replace with std::set_intersection once c++17 is available
350 template <class InputIt1, class InputIt2>
351 bool intersect(InputIt1 first1, InputIt1 last1, InputIt2 first2, InputIt2 last2)
352 {
353     while (first1 != last1 && first2 != last2)
354     {
355         if (*first1 < *first2)
356         {
357             ++first1;
358             continue;
359         }
360         if (*first2 < *first1)
361         {
362             ++first2;
363             continue;
364         }
365         return true;
366     }
367     return false;
368 }
369 
370 void doListNames(
371     boost::asio::io_service& io, interface_map_type& interface_map,
372     sdbusplus::asio::connection* system_bus,
373     boost::container::flat_map<std::string, std::string>& name_owners,
374     sdbusplus::asio::object_server& objectServer)
375 {
376     system_bus->async_method_call(
377         [&io, &interface_map, &name_owners, &objectServer,
378          system_bus](const boost::system::error_code ec,
379                      std::vector<std::string> process_names) {
380             if (ec)
381             {
382                 std::cerr << "Error getting names: " << ec << "\n";
383                 std::exit(EXIT_FAILURE);
384                 return;
385             }
386             // Try to make startup consistent
387             std::sort(process_names.begin(), process_names.end());
388 #ifdef DEBUG
389             std::shared_ptr<std::chrono::time_point<std::chrono::steady_clock>>
390                 global_start_time = std::make_shared<
391                     std::chrono::time_point<std::chrono::steady_clock>>(
392                     std::chrono::steady_clock::now());
393 #endif
394             for (const std::string& process_name : process_names)
395             {
396                 if (needToIntrospect(process_name, service_whitelist,
397                                      service_blacklist))
398                 {
399                     start_new_introspect(system_bus, io, interface_map,
400                                          process_name,
401 #ifdef DEBUG
402                                          global_start_time,
403 #endif
404                                          objectServer);
405                     update_owners(system_bus, name_owners, process_name);
406                 }
407             }
408         },
409         "org.freedesktop.DBus", "/org/freedesktop/DBus", "org.freedesktop.DBus",
410         "ListNames");
411 }
412 
413 void splitArgs(const std::string& stringArgs,
414                boost::container::flat_set<std::string>& listArgs)
415 {
416     std::istringstream args;
417     std::string arg;
418 
419     args.str(stringArgs);
420 
421     while (!args.eof())
422     {
423         args >> arg;
424         if (!arg.empty())
425         {
426             listArgs.insert(arg);
427         }
428     }
429 }
430 
431 void addObjectMapResult(
432     std::vector<interface_map_type::value_type>& objectMap,
433     const std::string& objectPath,
434     const std::pair<std::string, boost::container::flat_set<std::string>>&
435         interfaceMap)
436 {
437     // Adds an object path/service name/interface list entry to
438     // the results of GetSubTree and GetAncestors.
439     // If an entry for the object path already exists, just add the
440     // service name and interfaces to that entry, otherwise create
441     // a new entry.
442     auto entry = std::find_if(
443         objectMap.begin(), objectMap.end(),
444         [&objectPath](const auto& i) { return objectPath == i.first; });
445 
446     if (entry != objectMap.end())
447     {
448         entry->second.emplace(interfaceMap);
449     }
450     else
451     {
452         interface_map_type::value_type object;
453         object.first = objectPath;
454         object.second.emplace(interfaceMap);
455         objectMap.push_back(object);
456     }
457 }
458 
459 // Remove parents of the passed in path that:
460 // 1) Only have the 3 default interfaces on them
461 //    - Means D-Bus created these, not application code,
462 //      with the Properties, Introspectable, and Peer ifaces
463 // 2) Have no other child for this owner
464 void removeUnneededParents(const std::string& objectPath,
465                            const std::string& owner,
466                            interface_map_type& interface_map)
467 {
468     auto parent = objectPath;
469 
470     while (true)
471     {
472         auto pos = parent.find_last_of('/');
473         if ((pos == std::string::npos) || (pos == 0))
474         {
475             break;
476         }
477         parent = parent.substr(0, pos);
478 
479         auto parent_it = interface_map.find(parent);
480         if (parent_it == interface_map.end())
481         {
482             break;
483         }
484 
485         auto ifaces_it = parent_it->second.find(owner);
486         if (ifaces_it == parent_it->second.end())
487         {
488             break;
489         }
490 
491         if (ifaces_it->second.size() != 3)
492         {
493             break;
494         }
495 
496         auto child_path = parent + '/';
497 
498         // Remove this parent if there isn't a remaining child on this owner
499         auto child = std::find_if(
500             interface_map.begin(), interface_map.end(),
501             [&owner, &child_path](const auto& entry) {
502                 return boost::starts_with(entry.first, child_path) &&
503                        (entry.second.find(owner) != entry.second.end());
504             });
505 
506         if (child == interface_map.end())
507         {
508             parent_it->second.erase(ifaces_it);
509             if (parent_it->second.empty())
510             {
511                 interface_map.erase(parent_it);
512             }
513         }
514         else
515         {
516             break;
517         }
518     }
519 }
520 
521 int main(int argc, char** argv)
522 {
523     auto options = ArgumentParser(argc, argv);
524     boost::asio::io_service io;
525     std::shared_ptr<sdbusplus::asio::connection> system_bus =
526         std::make_shared<sdbusplus::asio::connection>(io);
527 
528     splitArgs(options["service-namespaces"], service_whitelist);
529     splitArgs(options["service-blacklists"], service_blacklist);
530 
531     // TODO(Ed) Remove this once all service files are updated to not use this.
532     // For now, simply squash the input, and ignore it.
533     boost::container::flat_set<std::string> iface_whitelist;
534     splitArgs(options["interface-namespaces"], iface_whitelist);
535 
536     system_bus->request_name(OBJECT_MAPPER_DBUS_NAME);
537     sdbusplus::asio::object_server server(system_bus);
538 
539     // Construct a signal set registered for process termination.
540     boost::asio::signal_set signals(io, SIGINT, SIGTERM);
541     signals.async_wait([&io](const boost::system::error_code& error,
542                              int signal_number) { io.stop(); });
543 
544     interface_map_type interface_map;
545     boost::container::flat_map<std::string, std::string> name_owners;
546 
547     std::function<void(sdbusplus::message::message & message)>
548         nameChangeHandler = [&interface_map, &io, &name_owners, &server,
549                              system_bus](sdbusplus::message::message& message) {
550             std::string name;      // well-known
551             std::string old_owner; // unique-name
552             std::string new_owner; // unique-name
553 
554             message.read(name, old_owner, new_owner);
555 
556             if (!old_owner.empty())
557             {
558                 processNameChangeDelete(name_owners, name, old_owner,
559                                         interface_map, associationOwners,
560                                         associationInterfaces, server);
561             }
562 
563             if (!new_owner.empty())
564             {
565 #ifdef DEBUG
566                 auto transaction = std::make_shared<
567                     std::chrono::time_point<std::chrono::steady_clock>>(
568                     std::chrono::steady_clock::now());
569 #endif
570                 // New daemon added
571                 if (needToIntrospect(name, service_whitelist,
572                                      service_blacklist))
573                 {
574                     name_owners[new_owner] = name;
575                     start_new_introspect(system_bus.get(), io, interface_map,
576                                          name,
577 #ifdef DEBUG
578                                          transaction,
579 #endif
580                                          server);
581                 }
582             }
583         };
584 
585     sdbusplus::bus::match::match nameOwnerChanged(
586         static_cast<sdbusplus::bus::bus&>(*system_bus),
587         sdbusplus::bus::match::rules::nameOwnerChanged(), nameChangeHandler);
588 
589     std::function<void(sdbusplus::message::message & message)>
590         interfacesAddedHandler = [&interface_map, &name_owners, &server](
591                                      sdbusplus::message::message& message) {
592             sdbusplus::message::object_path obj_path;
593             std::vector<std::pair<
594                 std::string, std::vector<std::pair<
595                                  std::string, sdbusplus::message::variant<
596                                                   std::vector<Association>>>>>>
597                 interfaces_added;
598             message.read(obj_path, interfaces_added);
599             std::string well_known;
600             if (!getWellKnown(name_owners, message.get_sender(), well_known))
601             {
602                 return; // only introspect well-known
603             }
604             if (needToIntrospect(well_known, service_whitelist,
605                                  service_blacklist))
606             {
607                 auto& iface_list = interface_map[obj_path.str];
608 
609                 for (const auto& interface_pair : interfaces_added)
610                 {
611                     iface_list[well_known].emplace(interface_pair.first);
612 
613                     if (interface_pair.first == ASSOCIATIONS_INTERFACE)
614                     {
615                         const sdbusplus::message::variant<
616                             std::vector<Association>>* variantAssociations =
617                             nullptr;
618                         for (const auto& interface : interface_pair.second)
619                         {
620                             if (interface.first == "associations")
621                             {
622                                 variantAssociations = &(interface.second);
623                             }
624                         }
625                         if (variantAssociations == nullptr)
626                         {
627                             std::cerr << "Illegal association found on "
628                                       << well_known << "\n";
629                             continue;
630                         }
631                         std::vector<Association> associations =
632                             sdbusplus::message::variant_ns::get<
633                                 std::vector<Association>>(*variantAssociations);
634                         associationChanged(server, associations, obj_path.str,
635                                            well_known);
636                     }
637                 }
638 
639                 // To handle the case where an object path is being created
640                 // with 2 or more new path segments, check if the parent paths
641                 // of this path are already in the interface map, and add them
642                 // if they aren't with just the default freedesktop interfaces.
643                 // This would be done via introspection if they would have
644                 // already existed at startup.  While we could also introspect
645                 // them now to do the work, we know there aren't any other
646                 // interfaces or we would have gotten signals for them as well,
647                 // so take a shortcut to speed things up.
648                 //
649                 // This is all needed so that mapper operations can be done
650                 // on the new parent paths.
651                 using iface_map_iterator = interface_map_type::iterator;
652                 using iface_map_value_type = boost::container::flat_map<
653                     std::string, boost::container::flat_set<std::string>>;
654                 using name_map_iterator = iface_map_value_type::iterator;
655 
656                 static const boost::container::flat_set<std::string>
657                     default_ifaces{"org.freedesktop.DBus.Introspectable",
658                                    "org.freedesktop.DBus.Peer",
659                                    "org.freedesktop.DBus.Properties"};
660 
661                 std::string parent = obj_path.str;
662                 auto pos = parent.find_last_of('/');
663 
664                 while (pos != std::string::npos)
665                 {
666                     parent = parent.substr(0, pos);
667 
668                     std::pair<iface_map_iterator, bool> parentEntry =
669                         interface_map.insert(
670                             std::make_pair(parent, iface_map_value_type{}));
671 
672                     std::pair<name_map_iterator, bool> ifaceEntry =
673                         parentEntry.first->second.insert(
674                             std::make_pair(well_known, default_ifaces));
675 
676                     if (!ifaceEntry.second)
677                     {
678                         // Entry was already there for this name so done.
679                         break;
680                     }
681 
682                     pos = parent.find_last_of('/');
683                 }
684             }
685         };
686 
687     sdbusplus::bus::match::match interfacesAdded(
688         static_cast<sdbusplus::bus::bus&>(*system_bus),
689         sdbusplus::bus::match::rules::interfacesAdded(),
690         interfacesAddedHandler);
691 
692     std::function<void(sdbusplus::message::message & message)>
693         interfacesRemovedHandler = [&interface_map, &name_owners, &server](
694                                        sdbusplus::message::message& message) {
695             sdbusplus::message::object_path obj_path;
696             std::vector<std::string> interfaces_removed;
697             message.read(obj_path, interfaces_removed);
698             auto connection_map = interface_map.find(obj_path.str);
699             if (connection_map == interface_map.end())
700             {
701                 return;
702             }
703 
704             std::string sender;
705             if (!getWellKnown(name_owners, message.get_sender(), sender))
706             {
707                 return;
708             }
709             for (const std::string& interface : interfaces_removed)
710             {
711                 auto interface_set = connection_map->second.find(sender);
712                 if (interface_set == connection_map->second.end())
713                 {
714                     continue;
715                 }
716 
717                 if (interface == ASSOCIATIONS_INTERFACE)
718                 {
719                     removeAssociation(obj_path.str, sender, server,
720                                       associationOwners, associationInterfaces);
721                 }
722 
723                 interface_set->second.erase(interface);
724                 // If this was the last interface on this connection,
725                 // erase the connection
726                 if (interface_set->second.empty())
727                 {
728                     connection_map->second.erase(interface_set);
729                 }
730             }
731             // If this was the last connection on this object path,
732             // erase the object path
733             if (connection_map->second.empty())
734             {
735                 interface_map.erase(connection_map);
736             }
737 
738             removeUnneededParents(obj_path.str, sender, interface_map);
739         };
740 
741     sdbusplus::bus::match::match interfacesRemoved(
742         static_cast<sdbusplus::bus::bus&>(*system_bus),
743         sdbusplus::bus::match::rules::interfacesRemoved(),
744         interfacesRemovedHandler);
745 
746     std::function<void(sdbusplus::message::message & message)>
747         associationChangedHandler =
748             [&server, &name_owners](sdbusplus::message::message& message) {
749                 std::string objectName;
750                 boost::container::flat_map<
751                     std::string,
752                     sdbusplus::message::variant<std::vector<Association>>>
753                     values;
754                 message.read(objectName, values);
755                 auto findAssociations = values.find("associations");
756                 if (findAssociations != values.end())
757                 {
758                     std::vector<Association> associations =
759                         sdbusplus::message::variant_ns::get<
760                             std::vector<Association>>(findAssociations->second);
761 
762                     std::string well_known;
763                     if (!getWellKnown(name_owners, message.get_sender(),
764                                       well_known))
765                     {
766                         return;
767                     }
768                     associationChanged(server, associations, message.get_path(),
769                                        well_known);
770                 }
771             };
772     sdbusplus::bus::match::match associationChanged(
773         static_cast<sdbusplus::bus::bus&>(*system_bus),
774         sdbusplus::bus::match::rules::interface(
775             "org.freedesktop.DBus.Properties") +
776             sdbusplus::bus::match::rules::member("PropertiesChanged") +
777             sdbusplus::bus::match::rules::argN(0, ASSOCIATIONS_INTERFACE),
778         associationChangedHandler);
779 
780     std::shared_ptr<sdbusplus::asio::dbus_interface> iface =
781         server.add_interface("/xyz/openbmc_project/object_mapper",
782                              "xyz.openbmc_project.ObjectMapper");
783 
784     iface->register_method(
785         "GetAncestors", [&interface_map](std::string& req_path,
786                                          std::vector<std::string>& interfaces) {
787             // Interfaces need to be sorted for intersect to function
788             std::sort(interfaces.begin(), interfaces.end());
789 
790             if (boost::ends_with(req_path, "/"))
791             {
792                 req_path.pop_back();
793             }
794             if (req_path.size() &&
795                 interface_map.find(req_path) == interface_map.end())
796             {
797                 throw NotFoundException();
798             }
799 
800             std::vector<interface_map_type::value_type> ret;
801             for (auto& object_path : interface_map)
802             {
803                 auto& this_path = object_path.first;
804                 if (boost::starts_with(req_path, this_path) &&
805                     (req_path != this_path))
806                 {
807                     if (interfaces.empty())
808                     {
809                         ret.emplace_back(object_path);
810                     }
811                     else
812                     {
813                         for (auto& interface_map : object_path.second)
814                         {
815 
816                             if (intersect(interfaces.begin(), interfaces.end(),
817                                           interface_map.second.begin(),
818                                           interface_map.second.end()))
819                             {
820                                 addObjectMapResult(ret, this_path,
821                                                    interface_map);
822                             }
823                         }
824                     }
825                 }
826             }
827 
828             return ret;
829         });
830 
831     iface->register_method(
832         "GetObject", [&interface_map](const std::string& path,
833                                       std::vector<std::string>& interfaces) {
834             boost::container::flat_map<std::string,
835                                        boost::container::flat_set<std::string>>
836                 results;
837 
838             // Interfaces need to be sorted for intersect to function
839             std::sort(interfaces.begin(), interfaces.end());
840             auto path_ref = interface_map.find(path);
841             if (path_ref == interface_map.end())
842             {
843                 throw NotFoundException();
844             }
845             if (interfaces.empty())
846             {
847                 return path_ref->second;
848             }
849             for (auto& interface_map : path_ref->second)
850             {
851                 if (intersect(interfaces.begin(), interfaces.end(),
852                               interface_map.second.begin(),
853                               interface_map.second.end()))
854                 {
855                     results.emplace(interface_map.first, interface_map.second);
856                 }
857             }
858 
859             if (results.empty())
860             {
861                 throw NotFoundException();
862             }
863 
864             return results;
865         });
866 
867     iface->register_method(
868         "GetSubTree", [&interface_map](std::string& req_path, int32_t depth,
869                                        std::vector<std::string>& interfaces) {
870             if (depth <= 0)
871             {
872                 depth = std::numeric_limits<int32_t>::max();
873             }
874             // Interfaces need to be sorted for intersect to function
875             std::sort(interfaces.begin(), interfaces.end());
876             std::vector<interface_map_type::value_type> ret;
877 
878             if (boost::ends_with(req_path, "/"))
879             {
880                 req_path.pop_back();
881             }
882             if (req_path.size() &&
883                 interface_map.find(req_path) == interface_map.end())
884             {
885                 throw NotFoundException();
886             }
887 
888             for (auto& object_path : interface_map)
889             {
890                 auto& this_path = object_path.first;
891 
892                 if (this_path == req_path)
893                 {
894                     continue;
895                 }
896 
897                 if (boost::starts_with(this_path, req_path))
898                 {
899                     // count the number of slashes past the search term
900                     int32_t this_depth =
901                         std::count(this_path.begin() + req_path.size(),
902                                    this_path.end(), '/');
903                     if (this_depth <= depth)
904                     {
905                         for (auto& interface_map : object_path.second)
906                         {
907                             if (intersect(interfaces.begin(), interfaces.end(),
908                                           interface_map.second.begin(),
909                                           interface_map.second.end()) ||
910                                 interfaces.empty())
911                             {
912                                 addObjectMapResult(ret, this_path,
913                                                    interface_map);
914                             }
915                         }
916                     }
917                 }
918             }
919 
920             return ret;
921         });
922 
923     iface->register_method(
924         "GetSubTreePaths",
925         [&interface_map](std::string& req_path, int32_t depth,
926                          std::vector<std::string>& interfaces) {
927             if (depth <= 0)
928             {
929                 depth = std::numeric_limits<int32_t>::max();
930             }
931             // Interfaces need to be sorted for intersect to function
932             std::sort(interfaces.begin(), interfaces.end());
933             std::vector<std::string> ret;
934 
935             if (boost::ends_with(req_path, "/"))
936             {
937                 req_path.pop_back();
938             }
939             if (req_path.size() &&
940                 interface_map.find(req_path) == interface_map.end())
941             {
942                 throw NotFoundException();
943             }
944 
945             for (auto& object_path : interface_map)
946             {
947                 auto& this_path = object_path.first;
948 
949                 if (this_path == req_path)
950                 {
951                     continue;
952                 }
953 
954                 if (boost::starts_with(this_path, req_path))
955                 {
956                     // count the number of slashes past the search term
957                     int this_depth =
958                         std::count(this_path.begin() + req_path.size(),
959                                    this_path.end(), '/');
960                     if (this_depth <= depth)
961                     {
962                         bool add = interfaces.empty();
963                         for (auto& interface_map : object_path.second)
964                         {
965                             if (intersect(interfaces.begin(), interfaces.end(),
966                                           interface_map.second.begin(),
967                                           interface_map.second.end()))
968                             {
969                                 add = true;
970                                 break;
971                             }
972                         }
973                         if (add)
974                         {
975                             // TODO(ed) this is a copy
976                             ret.emplace_back(this_path);
977                         }
978                     }
979                 }
980             }
981 
982             return ret;
983         });
984 
985     iface->initialize();
986 
987     io.post([&]() {
988         doListNames(io, interface_map, system_bus.get(), name_owners, server);
989     });
990 
991     io.run();
992 }
993