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