1 #include "config.h"
2 
3 #include "system_configuration.hpp"
4 
5 #include <phosphor-logging/elog-errors.hpp>
6 #include <phosphor-logging/log.hpp>
7 #include <xyz/openbmc_project/Common/error.hpp>
8 
9 namespace phosphor
10 {
11 namespace network
12 {
13 
14 // systemd service to kick start a target.
15 constexpr auto HOSTNAMED_SERVICE = "org.freedesktop.hostname1";
16 constexpr auto HOSTNAMED_SERVICE_PATH = "/org/freedesktop/hostname1";
17 constexpr auto HOSTNAMED_INTERFACE = "org.freedesktop.hostname1";
18 constexpr auto PROPERTY_INTERFACE = "org.freedesktop.DBus.Properties";
19 constexpr auto METHOD_GET = "Get";
20 constexpr auto METHOD_SET = "SetStaticHostname";
21 
22 using namespace phosphor::logging;
23 using namespace sdbusplus::xyz::openbmc_project::Common::Error;
24 
25 using SystemConfigIntf =
26     sdbusplus::xyz::openbmc_project::Network::server::SystemConfiguration;
27 
28 SystemConfiguration::SystemConfiguration(sdbusplus::bus_t& bus,
29                                          const std::string& objPath) :
30     Iface(bus, objPath.c_str(), Iface::action::defer_emit),
31     bus(bus)
32 {
33     SystemConfigIntf::hostName(getHostNameFromSystem());
34 
35     this->emit_object_added();
36 }
37 
38 std::string SystemConfiguration::hostName(std::string name)
39 {
40     if (SystemConfigIntf::hostName() == name)
41     {
42         return name;
43     }
44     auto method = bus.new_method_call(HOSTNAMED_SERVICE, HOSTNAMED_SERVICE_PATH,
45                                       HOSTNAMED_INTERFACE, METHOD_SET);
46 
47     method.append(name, true);
48 
49     if (!bus.call(method))
50     {
51         log<level::ERR>("Failed to set the hostname");
52         report<InternalFailure>();
53         return SystemConfigIntf::hostName();
54     }
55 
56     return SystemConfigIntf::hostName(name);
57 }
58 
59 std::string SystemConfiguration::getHostNameFromSystem() const
60 {
61     try
62     {
63         std::variant<std::string> name;
64         auto method =
65             bus.new_method_call(HOSTNAMED_SERVICE, HOSTNAMED_SERVICE_PATH,
66                                 PROPERTY_INTERFACE, METHOD_GET);
67 
68         method.append(HOSTNAMED_INTERFACE, "Hostname");
69 
70         auto reply = bus.call(method);
71 
72         reply.read(name);
73         return std::get<std::string>(name);
74     }
75     catch (const sdbusplus::exception_t& ex)
76     {
77         log<level::ERR>(
78             "Failed to get the hostname from systemd-hostnamed service",
79             entry("ERR=%s", ex.what()));
80     }
81     return "";
82 }
83 
84 } // namespace network
85 } // namespace phosphor
86