forked from openbmc/phosphor-host-ipmid
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtransporthandler.cpp
More file actions
2014 lines (1879 loc) · 63.2 KB
/
Copy pathtransporthandler.cpp
File metadata and controls
2014 lines (1879 loc) · 63.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#include "app/channel.hpp"
#include "user_channel/cipher_mgmt.hpp"
#include <arpa/inet.h>
#include <netinet/ether.h>
#include <array>
#include <bitset>
#include <cinttypes>
#include <cstdint>
#include <cstring>
#include <fstream>
#include <functional>
#include <ipmid/api.hpp>
#include <ipmid/message.hpp>
#include <ipmid/message/types.hpp>
#include <ipmid/types.hpp>
#include <ipmid/utils.hpp>
#include <optional>
#include <phosphor-logging/elog-errors.hpp>
#include <phosphor-logging/elog.hpp>
#include <phosphor-logging/log.hpp>
#include <sdbusplus/bus.hpp>
#include <sdbusplus/exception.hpp>
#include <string>
#include <string_view>
#include <type_traits>
#include <unordered_map>
#include <unordered_set>
#include <user_channel/channel_layer.hpp>
#include <utility>
#include <vector>
#include <xyz/openbmc_project/Common/error.hpp>
#include <xyz/openbmc_project/Network/IP/server.hpp>
#include <xyz/openbmc_project/Network/Neighbor/server.hpp>
using phosphor::logging::commit;
using phosphor::logging::elog;
using phosphor::logging::entry;
using phosphor::logging::level;
using phosphor::logging::log;
using sdbusplus::xyz::openbmc_project::Common::Error::InternalFailure;
using sdbusplus::xyz::openbmc_project::Network::server::IP;
using sdbusplus::xyz::openbmc_project::Network::server::Neighbor;
namespace cipher
{
std::vector<uint8_t> getCipherList()
{
std::vector<uint8_t> cipherList;
std::ifstream jsonFile(cipher::configFile);
if (!jsonFile.is_open())
{
log<level::ERR>("Channel Cipher suites file not found");
elog<InternalFailure>();
}
auto data = Json::parse(jsonFile, nullptr, false);
if (data.is_discarded())
{
log<level::ERR>("Parsing channel cipher suites JSON failed");
elog<InternalFailure>();
}
// Byte 1 is reserved
cipherList.push_back(0x00);
for (const auto& record : data)
{
cipherList.push_back(record.value(cipher, 0));
}
return cipherList;
}
} // namespace cipher
namespace ipmi
{
namespace transport
{
// LAN Handler specific response codes
constexpr Cc ccParamNotSupported = 0x80;
constexpr Cc ccParamSetLocked = 0x81;
constexpr Cc ccParamReadOnly = 0x82;
// VLANs are a 12-bit value
constexpr uint16_t VLAN_VALUE_MASK = 0x0fff;
constexpr uint16_t VLAN_ENABLE_FLAG = 0x8000;
// Arbitrary v6 Address Limits to prevent too much output in ipmitool
constexpr uint8_t MAX_IPV6_STATIC_ADDRESSES = 15;
constexpr uint8_t MAX_IPV6_DYNAMIC_ADDRESSES = 15;
// D-Bus Network Daemon definitions
constexpr auto PATH_ROOT = "/xyz/openbmc_project/network";
constexpr auto PATH_SYSTEMCONFIG = "/xyz/openbmc_project/network/config";
constexpr auto INTF_SYSTEMCONFIG =
"xyz.openbmc_project.Network.SystemConfiguration";
constexpr auto INTF_ETHERNET = "xyz.openbmc_project.Network.EthernetInterface";
constexpr auto INTF_IP = "xyz.openbmc_project.Network.IP";
constexpr auto INTF_IP_CREATE = "xyz.openbmc_project.Network.IP.Create";
constexpr auto INTF_MAC = "xyz.openbmc_project.Network.MACAddress";
constexpr auto INTF_NEIGHBOR = "xyz.openbmc_project.Network.Neighbor";
constexpr auto INTF_NEIGHBOR_CREATE_STATIC =
"xyz.openbmc_project.Network.Neighbor.CreateStatic";
constexpr auto INTF_VLAN = "xyz.openbmc_project.Network.VLAN";
constexpr auto INTF_VLAN_CREATE = "xyz.openbmc_project.Network.VLAN.Create";
/** @brief Generic paramters for different address families */
template <int family>
struct AddrFamily
{
};
/** @brief Parameter specialization for IPv4 */
template <>
struct AddrFamily<AF_INET>
{
using addr = in_addr;
static constexpr auto protocol = IP::Protocol::IPv4;
static constexpr size_t maxStrLen = INET6_ADDRSTRLEN;
static constexpr uint8_t defaultPrefix = 32;
static constexpr char propertyGateway[] = "DefaultGateway";
};
/** @brief Parameter specialization for IPv6 */
template <>
struct AddrFamily<AF_INET6>
{
using addr = in6_addr;
static constexpr auto protocol = IP::Protocol::IPv6;
static constexpr size_t maxStrLen = INET6_ADDRSTRLEN;
static constexpr uint8_t defaultPrefix = 128;
static constexpr char propertyGateway[] = "DefaultGateway6";
};
/** @brief Valid address origins for IPv4 */
const std::unordered_set<IP::AddressOrigin> originsV4 = {
IP::AddressOrigin::Static,
IP::AddressOrigin::DHCP,
};
/** @brief Valid address origins for IPv6 */
const std::unordered_set<IP::AddressOrigin> originsV6Static = {
IP::AddressOrigin::Static};
const std::unordered_set<IP::AddressOrigin> originsV6Dynamic = {
IP::AddressOrigin::DHCP,
IP::AddressOrigin::SLAAC,
};
/** @brief Interface IP Address configuration parameters */
template <int family>
struct IfAddr
{
std::string path;
typename AddrFamily<family>::addr address;
IP::AddressOrigin origin;
uint8_t prefix;
};
/** @brief Interface Neighbor configuration parameters */
template <int family>
struct IfNeigh
{
std::string path;
typename AddrFamily<family>::addr ip;
ether_addr mac;
};
/** @brief IPMI LAN Parameters */
enum class LanParam : uint8_t
{
SetStatus = 0,
AuthSupport = 1,
AuthEnables = 2,
IP = 3,
IPSrc = 4,
MAC = 5,
SubnetMask = 6,
Gateway1 = 12,
Gateway1MAC = 13,
VLANId = 20,
CiphersuiteSupport = 22,
CiphersuiteEntries = 23,
cipherSuitePrivilegeLevels = 24,
IPFamilySupport = 50,
IPFamilyEnables = 51,
IPv6Status = 55,
IPv6StaticAddresses = 56,
IPv6DynamicAddresses = 59,
IPv6RouterControl = 64,
IPv6StaticRouter1IP = 65,
IPv6StaticRouter1MAC = 66,
IPv6StaticRouter1PrefixLength = 67,
IPv6StaticRouter1PrefixValue = 68,
};
static constexpr uint8_t oemCmdStart = 192;
static constexpr uint8_t oemCmdEnd = 255;
/** @brief IPMI IP Origin Types */
enum class IPSrc : uint8_t
{
Unspecified = 0,
Static = 1,
DHCP = 2,
BIOS = 3,
BMC = 4,
};
/** @brief IPMI Set Status */
enum class SetStatus : uint8_t
{
Complete = 0,
InProgress = 1,
Commit = 2,
};
/** @brief IPMI Family Suport Bits */
namespace IPFamilySupportFlag
{
constexpr uint8_t IPv6Only = 0;
constexpr uint8_t DualStack = 1;
constexpr uint8_t IPv6Alerts = 2;
} // namespace IPFamilySupportFlag
/** @brief IPMI IPFamily Enables Flag */
enum class IPFamilyEnables : uint8_t
{
IPv4Only = 0,
IPv6Only = 1,
DualStack = 2,
};
/** @brief IPMI IPv6 Dyanmic Status Bits */
namespace IPv6StatusFlag
{
constexpr uint8_t DHCP = 0;
constexpr uint8_t SLAAC = 1;
}; // namespace IPv6StatusFlag
/** @brief IPMI IPv6 Source */
enum class IPv6Source : uint8_t
{
Static = 0,
SLAAC = 1,
DHCP = 2,
};
/** @brief IPMI IPv6 Address Status */
enum class IPv6AddressStatus : uint8_t
{
Active = 0,
Disabled = 1,
};
namespace IPv6RouterControlFlag
{
constexpr uint8_t Static = 0;
constexpr uint8_t Dynamic = 1;
}; // namespace IPv6RouterControlFlag
/** @brief A trivial helper used to determine if two PODs are equal
*
* @params[in] a - The first object to compare
* @params[in] b - The second object to compare
* @return True if the objects are the same bytewise
*/
template <typename T>
bool equal(const T& a, const T& b)
{
static_assert(std::is_trivially_copyable_v<T>);
return std::memcmp(&a, &b, sizeof(T)) == 0;
}
/** @brief Copies bytes from an array into a trivially copyable container
*
* @params[out] t - The container receiving the data
* @params[in] bytes - The data to copy
*/
template <size_t N, typename T>
void copyInto(T& t, const std::array<uint8_t, N>& bytes)
{
static_assert(std::is_trivially_copyable_v<T>);
static_assert(N == sizeof(T));
std::memcpy(&t, bytes.data(), bytes.size());
}
/** @brief Gets a generic view of the bytes in the input container
*
* @params[in] t - The data to reference
* @return A string_view referencing the bytes in the container
*/
template <typename T>
std::string_view dataRef(const T& t)
{
static_assert(std::is_trivially_copyable_v<T>);
return {reinterpret_cast<const char*>(&t), sizeof(T)};
}
/** @brief The dbus parameters for the interface corresponding to a channel
* This helps reduce the number of mapper lookups we need for each
* query and simplifies finding the VLAN interface if needed.
*/
struct ChannelParams
{
/** @brief The channel ID */
int id;
/** @brief channel name for the interface */
std::string ifname;
/** @brief Name of the service on the bus */
std::string service;
/** @brief Lower level adapter path that is guaranteed to not be a VLAN */
std::string ifPath;
/** @brief Logical adapter path used for address assignment */
std::string logicalPath;
};
/** @brief Determines the ethernet interface name corresponding to a channel
* Tries to map a VLAN object first so that the address information
* is accurate. Otherwise it gets the standard ethernet interface.
*
* @param[in] bus - The bus object used for lookups
* @param[in] channel - The channel id corresponding to an ethernet interface
* @return Ethernet interface service and object path if it exists
*/
std::optional<ChannelParams> maybeGetChannelParams(sdbusplus::bus::bus& bus,
uint8_t channel)
{
auto ifname = getChannelName(channel);
if (ifname.empty())
{
return std::nullopt;
}
// Enumerate all VLAN + ETHERNET interfaces
auto req = bus.new_method_call(MAPPER_BUS_NAME, MAPPER_OBJ, MAPPER_INTF,
"GetSubTree");
req.append(PATH_ROOT, 0,
std::vector<std::string>{INTF_VLAN, INTF_ETHERNET});
auto reply = bus.call(req);
ObjectTree objs;
reply.read(objs);
ChannelParams params;
for (const auto& [path, impls] : objs)
{
if (path.find(ifname) == path.npos)
{
continue;
}
for (const auto& [service, intfs] : impls)
{
bool vlan = false;
bool ethernet = false;
for (const auto& intf : intfs)
{
if (intf == INTF_VLAN)
{
vlan = true;
}
else if (intf == INTF_ETHERNET)
{
ethernet = true;
}
}
if (params.service.empty() && (vlan || ethernet))
{
params.service = service;
}
if (params.ifPath.empty() && !vlan && ethernet)
{
params.ifPath = path;
}
if (params.logicalPath.empty() && vlan)
{
params.logicalPath = path;
}
}
}
// We must have a path for the underlying interface
if (params.ifPath.empty())
{
return std::nullopt;
}
// We don't have a VLAN so the logical path is the same
if (params.logicalPath.empty())
{
params.logicalPath = params.ifPath;
}
params.id = channel;
params.ifname = std::move(ifname);
return std::move(params);
}
/** @brief A trivial helper around maybeGetChannelParams() that throws an
* exception when it is unable to acquire parameters for the channel.
*
* @param[in] bus - The bus object used for lookups
* @param[in] channel - The channel id corresponding to an ethernet interface
* @return Ethernet interface service and object path
*/
ChannelParams getChannelParams(sdbusplus::bus::bus& bus, uint8_t channel)
{
auto params = maybeGetChannelParams(bus, channel);
if (!params)
{
log<level::ERR>("Failed to get channel params",
entry("CHANNEL=%" PRIu8, channel));
elog<InternalFailure>();
}
return std::move(*params);
}
/** @brief Wraps the phosphor logging method to insert some additional metadata
*
* @param[in] params - The parameters for the channel
* ...
*/
template <auto level, typename... Args>
auto logWithChannel(const ChannelParams& params, Args&&... args)
{
return log<level>(std::forward<Args>(args)...,
entry("CHANNEL=%d", params.id),
entry("IFNAME=%s", params.ifname.c_str()));
}
template <auto level, typename... Args>
auto logWithChannel(const std::optional<ChannelParams>& params, Args&&... args)
{
if (params)
{
return logWithChannel<level>(*params, std::forward<Args>(args)...);
}
return log<level>(std::forward<Args>(args)...);
}
/** @brief Trivializes using parameter getter functions by providing a bus
* and channel parameters automatically.
*
* @param[in] channel - The channel id corresponding to an ethernet interface
* ...
*/
template <auto func, typename... Args>
auto channelCall(uint8_t channel, Args&&... args)
{
sdbusplus::bus::bus bus(ipmid_get_sd_bus_connection());
auto params = getChannelParams(bus, channel);
return std::invoke(func, bus, params, std::forward<Args>(args)...);
}
/** @brief Determines if the ethernet interface is using DHCP
*
* @param[in] bus - The bus object used for lookups
* @param[in] params - The parameters for the channel
* @return True if DHCP is enabled, false otherwise
*/
bool getDHCPProperty(sdbusplus::bus::bus& bus, const ChannelParams& params)
{
return std::get<bool>(getDbusProperty(
bus, params.service, params.logicalPath, INTF_ETHERNET, "DHCPEnabled"));
}
/** @brief Sets the system value for DHCP on the given interface
*
* @param[in] bus - The bus object used for lookups
* @param[in] params - The parameters for the channel
* @param[in] on - Whether or not to enable DHCP
*/
void setDHCPProperty(sdbusplus::bus::bus& bus, const ChannelParams& params,
bool on)
{
setDbusProperty(bus, params.service, params.logicalPath, INTF_ETHERNET,
"DHCPEnabled", on);
}
/** @brief Converts a human readable MAC string into MAC bytes
*
* @param[in] mac - The MAC string
* @return MAC in bytes
*/
ether_addr stringToMAC(const char* mac)
{
const ether_addr* ret = ether_aton(mac);
if (ret == nullptr)
{
log<level::ERR>("Invalid MAC Address", entry("MAC=%s", mac));
elog<InternalFailure>();
}
return *ret;
}
/** @brief Determines the MAC of the ethernet interface
*
* @param[in] bus - The bus object used for lookups
* @param[in] params - The parameters for the channel
* @return The configured mac address
*/
ether_addr getMACProperty(sdbusplus::bus::bus& bus, const ChannelParams& params)
{
auto macStr = std::get<std::string>(getDbusProperty(
bus, params.service, params.ifPath, INTF_MAC, "MACAddress"));
return stringToMAC(macStr.c_str());
}
/** @brief Sets the system value for MAC address on the given interface
*
* @param[in] bus - The bus object used for lookups
* @param[in] params - The parameters for the channel
* @param[in] mac - MAC address to apply
*/
void setMACProperty(sdbusplus::bus::bus& bus, const ChannelParams& params,
const ether_addr& mac)
{
std::string macStr = ether_ntoa(&mac);
setDbusProperty(bus, params.service, params.ifPath, INTF_MAC, "MACAddress",
macStr);
}
/** @brief Turns an IP address string into the network byte order form
* NOTE: This version strictly validates family matches
*
* @param[in] address - The string form of the address
* @return A network byte order address or none if conversion failed
*/
template <int family>
std::optional<typename AddrFamily<family>::addr>
maybeStringToAddr(const char* address)
{
typename AddrFamily<family>::addr ret;
if (inet_pton(family, address, &ret) == 1)
{
return ret;
}
return std::nullopt;
}
/** @brief Turns an IP address string into the network byte order form
* NOTE: This version strictly validates family matches
*
* @param[in] address - The string form of the address
* @return A network byte order address
*/
template <int family>
typename AddrFamily<family>::addr stringToAddr(const char* address)
{
auto ret = maybeStringToAddr<family>(address);
if (!ret)
{
log<level::ERR>("Failed to convert IP Address",
entry("FAMILY=%d", family),
entry("ADDRESS=%s", address));
elog<InternalFailure>();
}
return *ret;
}
/** @brief Turns an IP address in network byte order into a string
*
* @param[in] address - The string form of the address
* @return A network byte order address
*/
template <int family>
std::string addrToString(const typename AddrFamily<family>::addr& address)
{
std::string ret(AddrFamily<family>::maxStrLen, '\0');
inet_ntop(family, &address, ret.data(), ret.size());
ret.resize(strlen(ret.c_str()));
return ret;
}
/** @brief Retrieves the current gateway for the address family on the system
* NOTE: The gateway is currently system wide and not per channel
*
* @param[in] bus - The bus object used for lookups
* @param[in] params - The parameters for the channel
* @return An address representing the gateway address if it exists
*/
template <int family>
std::optional<typename AddrFamily<family>::addr>
getGatewayProperty(sdbusplus::bus::bus& bus, const ChannelParams& params)
{
auto gatewayStr = std::get<std::string>(getDbusProperty(
bus, params.service, PATH_SYSTEMCONFIG, INTF_SYSTEMCONFIG,
AddrFamily<family>::propertyGateway));
if (gatewayStr.empty())
{
return std::nullopt;
}
return stringToAddr<family>(gatewayStr.c_str());
}
/** @brief A lazy lookup mechanism for iterating over object properties stored
* in DBus. This will only perform the object lookup when needed, and
* retains a cache of previous lookups to speed up future iterations.
*/
class ObjectLookupCache
{
public:
using PropertiesCache = std::unordered_map<std::string, PropertyMap>;
/** @brief Creates a new ObjectLookupCache for the interface on the bus
* NOTE: The inputs to this object must outlive the object since
* they are only referenced by it.
*
* @param[in] bus - The bus object used for lookups
* @param[in] params - The parameters for the channel
* @param[in] intf - The interface we are looking up
*/
ObjectLookupCache(sdbusplus::bus::bus& bus, const ChannelParams& params,
const char* intf) :
bus(bus),
params(params), intf(intf),
objs(getAllDbusObjects(bus, params.logicalPath, intf, ""))
{
}
class iterator : public ObjectTree::const_iterator
{
public:
using value_type = PropertiesCache::value_type;
iterator(ObjectTree::const_iterator it, ObjectLookupCache& container) :
ObjectTree::const_iterator(it), container(container),
ret(container.cache.end())
{
}
value_type& operator*()
{
ret = container.get(ObjectTree::const_iterator::operator*().first);
return *ret;
}
value_type* operator->()
{
return &operator*();
}
private:
ObjectLookupCache& container;
PropertiesCache::iterator ret;
};
iterator begin() noexcept
{
return iterator(objs.begin(), *this);
}
iterator end() noexcept
{
return iterator(objs.end(), *this);
}
private:
sdbusplus::bus::bus& bus;
const ChannelParams& params;
const char* const intf;
const ObjectTree objs;
PropertiesCache cache;
/** @brief Gets a cached copy of the object properties if possible
* Otherwise performs a query on DBus to look them up
*
* @param[in] path - The object path to lookup
* @return An iterator for the specified object path + properties
*/
PropertiesCache::iterator get(const std::string& path)
{
auto it = cache.find(path);
if (it != cache.end())
{
return it;
}
auto properties = getAllDbusProperties(bus, params.service, path, intf);
return cache.insert({path, std::move(properties)}).first;
}
};
/** @brief Searches the ip object lookup cache for an address matching
* the input parameters. NOTE: The index lacks stability across address
* changes since the network daemon has no notion of stable indicies.
*
* @param[in] bus - The bus object used for lookups
* @param[in] params - The parameters for the channel
* @param[in] idx - The index of the desired address on the interface
* @param[in] origins - The allowed origins for the address objects
* @param[in] ips - The object lookup cache holding all of the address info
* @return The address and prefix if it was found
*/
template <int family>
std::optional<IfAddr<family>>
findIfAddr(sdbusplus::bus::bus& bus, const ChannelParams& params,
uint8_t idx,
const std::unordered_set<IP::AddressOrigin>& origins,
ObjectLookupCache& ips)
{
for (const auto& [path, properties] : ips)
{
const auto& addrStr = std::get<std::string>(properties.at("Address"));
auto addr = maybeStringToAddr<family>(addrStr.c_str());
if (!addr)
{
continue;
}
IP::AddressOrigin origin = IP::convertAddressOriginFromString(
std::get<std::string>(properties.at("Origin")));
if (origins.find(origin) == origins.end())
{
continue;
}
if (idx > 0)
{
idx--;
continue;
}
IfAddr<family> ifaddr;
ifaddr.path = path;
ifaddr.address = *addr;
ifaddr.prefix = std::get<uint8_t>(properties.at("PrefixLength"));
ifaddr.origin = origin;
return std::move(ifaddr);
}
return std::nullopt;
}
/** @brief Trivial helper around findIfAddr that simplifies calls
* for one off lookups. Don't use this if you intend to do multiple
* lookups at a time.
*
* @param[in] bus - The bus object used for lookups
* @param[in] params - The parameters for the channel
* @param[in] idx - The index of the desired address on the interface
* @param[in] origins - The allowed origins for the address objects
* @return The address and prefix if it was found
*/
template <int family>
auto getIfAddr(sdbusplus::bus::bus& bus, const ChannelParams& params,
uint8_t idx,
const std::unordered_set<IP::AddressOrigin>& origins)
{
ObjectLookupCache ips(bus, params, INTF_IP);
return findIfAddr<family>(bus, params, idx, origins, ips);
}
/** @brief Deletes the dbus object. Ignores empty objects or objects that are
* missing from the bus.
*
* @param[in] bus - The bus object used for lookups
* @param[in] service - The name of the service
* @param[in] path - The path of the object to delete
*/
void deleteObjectIfExists(sdbusplus::bus::bus& bus, const std::string& service,
const std::string& path)
{
if (path.empty())
{
return;
}
try
{
auto req = bus.new_method_call(service.c_str(), path.c_str(),
ipmi::DELETE_INTERFACE, "Delete");
bus.call_noreply(req);
}
catch (const sdbusplus::exception::SdBusError& e)
{
if (strcmp(e.name(), "org.freedesktop.DBus.Error.UnknownObject") != 0)
{
// We want to rethrow real errors
throw;
}
}
}
/** @brief Sets the address info configured for the interface
* If a previous address path exists then it will be removed
* before the new address is added.
*
* @param[in] bus - The bus object used for lookups
* @param[in] params - The parameters for the channel
* @param[in] address - The address of the new IP
* @param[in] prefix - The prefix of the new IP
*/
template <int family>
void createIfAddr(sdbusplus::bus::bus& bus, const ChannelParams& params,
const typename AddrFamily<family>::addr& address,
uint8_t prefix)
{
auto newreq =
bus.new_method_call(params.service.c_str(), params.logicalPath.c_str(),
INTF_IP_CREATE, "IP");
std::string protocol =
sdbusplus::xyz::openbmc_project::Network::server::convertForMessage(
AddrFamily<family>::protocol);
newreq.append(protocol, addrToString<family>(address), prefix, "");
bus.call_noreply(newreq);
}
/** @brief Trivial helper for getting the IPv4 address from getIfAddrs()
*
* @param[in] bus - The bus object used for lookups
* @param[in] params - The parameters for the channel
* @return The address and prefix if found
*/
auto getIfAddr4(sdbusplus::bus::bus& bus, const ChannelParams& params)
{
return getIfAddr<AF_INET>(bus, params, 0, originsV4);
}
/** @brief Reconfigures the IPv4 address info configured for the interface
*
* @param[in] bus - The bus object used for lookups
* @param[in] params - The parameters for the channel
* @param[in] address - The new address if specified
* @param[in] prefix - The new address prefix if specified
*/
void reconfigureIfAddr4(sdbusplus::bus::bus& bus, const ChannelParams& params,
const std::optional<in_addr>& address,
std::optional<uint8_t> prefix)
{
auto ifaddr = getIfAddr4(bus, params);
if (!ifaddr && !address)
{
log<level::ERR>("Missing address for IPv4 assignment");
elog<InternalFailure>();
}
uint8_t fallbackPrefix = AddrFamily<AF_INET>::defaultPrefix;
if (ifaddr)
{
fallbackPrefix = ifaddr->prefix;
deleteObjectIfExists(bus, params.service, ifaddr->path);
}
createIfAddr<AF_INET>(bus, params, address.value_or(ifaddr->address),
prefix.value_or(fallbackPrefix));
}
template <int family>
std::optional<IfNeigh<family>>
findStaticNeighbor(sdbusplus::bus::bus& bus, const ChannelParams& params,
const typename AddrFamily<family>::addr& ip,
ObjectLookupCache& neighbors)
{
const auto state =
sdbusplus::xyz::openbmc_project::Network::server::convertForMessage(
Neighbor::State::Permanent);
for (const auto& [path, neighbor] : neighbors)
{
const auto& ipStr = std::get<std::string>(neighbor.at("IPAddress"));
auto neighIP = maybeStringToAddr<family>(ipStr.c_str());
if (!neighIP)
{
continue;
}
if (!equal(*neighIP, ip))
{
continue;
}
if (state != std::get<std::string>(neighbor.at("State")))
{
continue;
}
IfNeigh<family> ret;
ret.path = path;
ret.ip = ip;
const auto& macStr = std::get<std::string>(neighbor.at("MACAddress"));
ret.mac = stringToMAC(macStr.c_str());
return std::move(ret);
}
return std::nullopt;
}
template <int family>
void createNeighbor(sdbusplus::bus::bus& bus, const ChannelParams& params,
const typename AddrFamily<family>::addr& address,
const ether_addr& mac)
{
auto newreq =
bus.new_method_call(params.service.c_str(), params.logicalPath.c_str(),
INTF_NEIGHBOR_CREATE_STATIC, "Neighbor");
std::string macStr = ether_ntoa(&mac);
newreq.append(addrToString<family>(address), macStr);
bus.call_noreply(newreq);
}
/** @brief Sets the system wide value for the default gateway
*
* @param[in] bus - The bus object used for lookups
* @param[in] params - The parameters for the channel
* @param[in] gateway - Gateway address to apply
*/
template <int family>
void setGatewayProperty(sdbusplus::bus::bus& bus, const ChannelParams& params,
const typename AddrFamily<family>::addr& address)
{
// Save the old gateway MAC address if it exists so we can recreate it
auto gateway = getGatewayProperty<family>(bus, params);
std::optional<IfNeigh<family>> neighbor;
if (gateway)
{
ObjectLookupCache neighbors(bus, params, INTF_NEIGHBOR);
neighbor = findStaticNeighbor<family>(bus, params, *gateway, neighbors);
}
setDbusProperty(bus, params.service, PATH_SYSTEMCONFIG, INTF_SYSTEMCONFIG,
AddrFamily<family>::propertyGateway,
addrToString<family>(address));
// Restore the gateway MAC if we had one
if (neighbor)
{
deleteObjectIfExists(bus, params.service, neighbor->path);
createNeighbor<family>(bus, params, address, neighbor->mac);
}
}
template <int family>
std::optional<IfNeigh<family>> findGatewayNeighbor(sdbusplus::bus::bus& bus,
const ChannelParams& params,
ObjectLookupCache& neighbors)
{
auto gateway = getGatewayProperty<family>(bus, params);
if (!gateway)
{
return std::nullopt;
}
return findStaticNeighbor<family>(bus, params, *gateway, neighbors);
}
template <int family>
std::optional<IfNeigh<family>> getGatewayNeighbor(sdbusplus::bus::bus& bus,
const ChannelParams& params)
{
ObjectLookupCache neighbors(bus, params, INTF_NEIGHBOR);
return findGatewayNeighbor<family>(bus, params, neighbors);
}
template <int family>
void reconfigureGatewayMAC(sdbusplus::bus::bus& bus,
const ChannelParams& params, const ether_addr& mac)
{
auto gateway = getGatewayProperty<family>(bus, params);
if (!gateway)
{
log<level::ERR>("Tried to set Gateway MAC without Gateway");
elog<InternalFailure>();
}
ObjectLookupCache neighbors(bus, params, INTF_NEIGHBOR);
auto neighbor =
findStaticNeighbor<family>(bus, params, *gateway, neighbors);
if (neighbor)
{
deleteObjectIfExists(bus, params.service, neighbor->path);
}
createNeighbor<family>(bus, params, *gateway, mac);
}
/** @brief Deconfigures the IPv6 address info configured for the interface
*
* @param[in] bus - The bus object used for lookups
* @param[in] params - The parameters for the channel
* @param[in] idx - The address index to operate on
*/
void deconfigureIfAddr6(sdbusplus::bus::bus& bus, const ChannelParams& params,
uint8_t idx)
{
auto ifaddr = getIfAddr<AF_INET6>(bus, params, idx, originsV6Static);
if (ifaddr)
{
deleteObjectIfExists(bus, params.service, ifaddr->path);
}
}
/** @brief Reconfigures the IPv6 address info configured for the interface
*
* @param[in] bus - The bus object used for lookups
* @param[in] params - The parameters for the channel
* @param[in] idx - The address index to operate on
* @param[in] address - The new address
* @param[in] prefix - The new address prefix
*/
void reconfigureIfAddr6(sdbusplus::bus::bus& bus, const ChannelParams& params,
uint8_t idx, const in6_addr& address, uint8_t prefix)
{
deconfigureIfAddr6(bus, params, idx);
createIfAddr<AF_INET6>(bus, params, address, prefix);
}