blob: 1f3dfc16dea0afab250da4e45a81c8f6ad55fa36 [file] [log] [blame]
Vernon Mauery240b1862018-10-08 12:05:16 -07001/**
2 * Copyright © 2018 Intel Corporation
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16#include "config.h"
17
18#include "settings.hpp"
19
20#include <dlfcn.h>
21
Vernon Mauery735ee952019-02-15 13:38:52 -080022#include <boost/algorithm/string.hpp>
Ed Tanous778418d2020-08-17 23:20:21 -070023#include <boost/asio/io_context.hpp>
Vernon Mauery240b1862018-10-08 12:05:16 -070024#include <host-cmd-manager.hpp>
25#include <ipmid-host/cmd.hpp>
26#include <ipmid/api.hpp>
27#include <ipmid/handler.hpp>
28#include <ipmid/message.hpp>
29#include <ipmid/oemrouter.hpp>
Vernon Mauery33250242019-03-12 16:49:26 -070030#include <ipmid/types.hpp>
Vernon Mauerye808bae2024-05-31 14:55:36 -070031#include <phosphor-logging/lg2.hpp>
Vernon Mauery240b1862018-10-08 12:05:16 -070032#include <sdbusplus/asio/connection.hpp>
33#include <sdbusplus/asio/object_server.hpp>
34#include <sdbusplus/asio/sd_event.hpp>
35#include <sdbusplus/bus.hpp>
36#include <sdbusplus/bus/match.hpp>
37#include <sdbusplus/timer.hpp>
Patrick Williamsfbc6c9d2023-05-10 07:50:16 -050038
39#include <algorithm>
40#include <any>
41#include <exception>
42#include <filesystem>
43#include <forward_list>
44#include <map>
45#include <memory>
46#include <optional>
Vernon Mauery240b1862018-10-08 12:05:16 -070047#include <tuple>
Vernon Mauery240b1862018-10-08 12:05:16 -070048#include <unordered_map>
49#include <utility>
50#include <vector>
51
Vernon Mauery240b1862018-10-08 12:05:16 -070052namespace fs = std::filesystem;
53
54using namespace phosphor::logging;
55
Vernon Mauery240b1862018-10-08 12:05:16 -070056// IPMI Spec, shared Reservation ID.
57static unsigned short selReservationID = 0xFFFF;
58static bool selReservationValid = false;
59
60unsigned short reserveSel(void)
61{
62 // IPMI spec, Reservation ID, the value simply increases against each
63 // execution of the Reserve SEL command.
64 if (++selReservationID == 0)
65 {
66 selReservationID = 1;
67 }
68 selReservationValid = true;
69 return selReservationID;
70}
71
72bool checkSELReservation(unsigned short id)
73{
74 return (selReservationValid && selReservationID == id);
75}
76
77void cancelSELReservation(void)
78{
79 selReservationValid = false;
80}
81
82EInterfaceIndex getInterfaceIndex(void)
83{
84 return interfaceKCS;
85}
86
87sd_bus* bus;
88sd_event* events = nullptr;
89sd_event* ipmid_get_sd_event_connection(void)
90{
91 return events;
92}
93sd_bus* ipmid_get_sd_bus_connection(void)
94{
95 return bus;
96}
97
98namespace ipmi
99{
100
101static inline unsigned int makeCmdKey(unsigned int cluster, unsigned int cmd)
102{
103 return (cluster << 8) | cmd;
104}
105
106using HandlerTuple = std::tuple<int, /* prio */
107 Privilege, HandlerBase::ptr /* handler */
108 >;
109
110/* map to handle standard registered commands */
111static std::unordered_map<unsigned int, /* key is NetFn/Cmd */
112 HandlerTuple>
113 handlerMap;
114
Vernon Maueryf984a012018-10-08 12:05:18 -0700115/* special map for decoding Group registered commands (NetFn 2Ch) */
116static std::unordered_map<unsigned int, /* key is Group/Cmd (NetFn is 2Ch) */
117 HandlerTuple>
118 groupHandlerMap;
119
120/* special map for decoding OEM registered commands (NetFn 2Eh) */
121static std::unordered_map<unsigned int, /* key is Iana/Cmd (NetFn is 2Eh) */
122 HandlerTuple>
123 oemHandlerMap;
124
Vernon Mauery08a70aa2018-11-07 09:36:22 -0800125using FilterTuple = std::tuple<int, /* prio */
126 FilterBase::ptr /* filter */
127 >;
128
129/* list to hold all registered ipmi command filters */
130static std::forward_list<FilterTuple> filterList;
131
Vernon Mauery240b1862018-10-08 12:05:16 -0700132namespace impl
133{
134/* common function to register all standard IPMI handlers */
135bool registerHandler(int prio, NetFn netFn, Cmd cmd, Privilege priv,
136 HandlerBase::ptr handler)
137{
138 // check for valid NetFn: even; 00-0Ch, 30-3Eh
139 if (netFn & 1 || (netFn > netFnTransport && netFn < netFnGroup) ||
140 netFn > netFnOemEight)
141 {
142 return false;
143 }
144
145 // create key and value for this handler
146 unsigned int netFnCmd = makeCmdKey(netFn, cmd);
147 HandlerTuple item(prio, priv, handler);
148
149 // consult the handler map and look for a match
150 auto& mapCmd = handlerMap[netFnCmd];
151 if (!std::get<HandlerBase::ptr>(mapCmd) || std::get<int>(mapCmd) <= prio)
152 {
153 mapCmd = item;
154 return true;
155 }
156 return false;
157}
158
Vernon Maueryf984a012018-10-08 12:05:18 -0700159/* common function to register all Group IPMI handlers */
160bool registerGroupHandler(int prio, Group group, Cmd cmd, Privilege priv,
161 HandlerBase::ptr handler)
162{
163 // create key and value for this handler
164 unsigned int netFnCmd = makeCmdKey(group, cmd);
165 HandlerTuple item(prio, priv, handler);
166
167 // consult the handler map and look for a match
168 auto& mapCmd = groupHandlerMap[netFnCmd];
169 if (!std::get<HandlerBase::ptr>(mapCmd) || std::get<int>(mapCmd) <= prio)
170 {
171 mapCmd = item;
172 return true;
173 }
174 return false;
175}
176
177/* common function to register all OEM IPMI handlers */
178bool registerOemHandler(int prio, Iana iana, Cmd cmd, Privilege priv,
179 HandlerBase::ptr handler)
180{
181 // create key and value for this handler
182 unsigned int netFnCmd = makeCmdKey(iana, cmd);
183 HandlerTuple item(prio, priv, handler);
184
185 // consult the handler map and look for a match
186 auto& mapCmd = oemHandlerMap[netFnCmd];
187 if (!std::get<HandlerBase::ptr>(mapCmd) || std::get<int>(mapCmd) <= prio)
188 {
189 mapCmd = item;
Vernon Mauerye808bae2024-05-31 14:55:36 -0700190 lg2::debug("registered OEM Handler: NetFn/Cmd={NETFNCMD}", "IANA",
191 lg2::hex, iana, "CMD", lg2::hex, cmd, "NETFNCMD", lg2::hex,
192 netFnCmd);
Vernon Maueryf984a012018-10-08 12:05:18 -0700193 return true;
194 }
Alexander Hansen7197b342023-09-06 11:45:15 +0200195
Vernon Mauerye808bae2024-05-31 14:55:36 -0700196 lg2::warning("could not register OEM Handler: NetFn/Cmd={NETFNCMD}", "IANA",
197 lg2::hex, iana, "CMD", lg2::hex, cmd, "NETFNCMD", lg2::hex,
198 netFnCmd);
Vernon Maueryf984a012018-10-08 12:05:18 -0700199 return false;
200}
201
Vernon Mauery08a70aa2018-11-07 09:36:22 -0800202/* common function to register all IPMI filter handlers */
203void registerFilter(int prio, FilterBase::ptr filter)
204{
205 // check for initial placement
206 if (filterList.empty() || std::get<int>(filterList.front()) < prio)
207 {
208 filterList.emplace_front(std::make_tuple(prio, filter));
Yong Libe063232021-03-04 16:52:52 +0800209 return;
Vernon Mauery08a70aa2018-11-07 09:36:22 -0800210 }
211 // walk the list and put it in the right place
212 auto j = filterList.begin();
213 for (auto i = j; i != filterList.end() && std::get<int>(*i) > prio; i++)
214 {
215 j = i;
216 }
217 filterList.emplace_after(j, std::make_tuple(prio, filter));
218}
219
Vernon Mauery240b1862018-10-08 12:05:16 -0700220} // namespace impl
221
Vernon Mauery08a70aa2018-11-07 09:36:22 -0800222message::Response::ptr filterIpmiCommand(message::Request::ptr request)
223{
224 // pass the command through the filter mechanism
225 // This can be the firmware firewall or any OEM mechanism like
226 // whitelist filtering based on operational mode
227 for (auto& item : filterList)
228 {
229 FilterBase::ptr filter = std::get<FilterBase::ptr>(item);
230 ipmi::Cc cc = filter->call(request);
231 if (ipmi::ccSuccess != cc)
232 {
233 return errorResponse(request, cc);
234 }
235 }
236 return message::Response::ptr();
237}
238
Vernon Mauery240b1862018-10-08 12:05:16 -0700239message::Response::ptr executeIpmiCommandCommon(
240 std::unordered_map<unsigned int, HandlerTuple>& handlers,
241 unsigned int keyCommon, message::Request::ptr request)
242{
Vernon Mauery08a70aa2018-11-07 09:36:22 -0800243 // filter the command first; a non-null message::Response::ptr
244 // means that the message has been rejected for some reason
Vernon Mauery51f78142020-01-13 16:28:59 -0800245 message::Response::ptr filterResponse = filterIpmiCommand(request);
Vernon Mauery08a70aa2018-11-07 09:36:22 -0800246
Vernon Mauery240b1862018-10-08 12:05:16 -0700247 Cmd cmd = request->ctx->cmd;
248 unsigned int key = makeCmdKey(keyCommon, cmd);
249 auto cmdIter = handlers.find(key);
250 if (cmdIter != handlers.end())
251 {
Vernon Mauery51f78142020-01-13 16:28:59 -0800252 // only return the filter response if the command is found
253 if (filterResponse)
254 {
Vernon Mauerye808bae2024-05-31 14:55:36 -0700255 lg2::debug("request for NetFn/Cmd {NETFN}/{CMD} has been filtered",
256 "NETFN", lg2::hex, keyCommon, "CMD", lg2::hex, cmd);
Vernon Mauery51f78142020-01-13 16:28:59 -0800257 return filterResponse;
258 }
Vernon Mauery240b1862018-10-08 12:05:16 -0700259 HandlerTuple& chosen = cmdIter->second;
260 if (request->ctx->priv < std::get<Privilege>(chosen))
261 {
262 return errorResponse(request, ccInsufficientPrivilege);
263 }
264 return std::get<HandlerBase::ptr>(chosen)->call(request);
265 }
266 else
267 {
268 unsigned int wildcard = makeCmdKey(keyCommon, cmdWildcard);
269 cmdIter = handlers.find(wildcard);
270 if (cmdIter != handlers.end())
271 {
Vernon Mauery51f78142020-01-13 16:28:59 -0800272 // only return the filter response if the command is found
273 if (filterResponse)
274 {
Vernon Mauerye808bae2024-05-31 14:55:36 -0700275 lg2::debug(
276 "request for NetFn/Cmd {NETFN}/{CMD} has been filtered",
277 "NETFN", lg2::hex, keyCommon, "CMD", lg2::hex, cmd);
Vernon Mauery51f78142020-01-13 16:28:59 -0800278 return filterResponse;
279 }
Vernon Mauery240b1862018-10-08 12:05:16 -0700280 HandlerTuple& chosen = cmdIter->second;
281 if (request->ctx->priv < std::get<Privilege>(chosen))
282 {
283 return errorResponse(request, ccInsufficientPrivilege);
284 }
285 return std::get<HandlerBase::ptr>(chosen)->call(request);
286 }
287 }
288 return errorResponse(request, ccInvalidCommand);
289}
290
Vernon Maueryf984a012018-10-08 12:05:18 -0700291message::Response::ptr executeIpmiGroupCommand(message::Request::ptr request)
292{
293 // look up the group for this request
William A. Kennington IIId10d9052019-04-24 01:57:36 -0700294 uint8_t bytes;
295 if (0 != request->payload.unpack(bytes))
Vernon Maueryf984a012018-10-08 12:05:18 -0700296 {
297 return errorResponse(request, ccReqDataLenInvalid);
298 }
William A. Kennington IIId10d9052019-04-24 01:57:36 -0700299 auto group = static_cast<Group>(bytes);
Patrick Williams1318a5e2024-08-16 15:19:54 -0400300 message::Response::ptr response =
301 executeIpmiCommandCommon(groupHandlerMap, group, request);
William A. Kennington IIIda31f9a2019-04-25 01:36:32 -0700302 ipmi::message::Payload prefix;
303 prefix.pack(bytes);
304 response->prepend(prefix);
Vernon Maueryf984a012018-10-08 12:05:18 -0700305 return response;
306}
307
308message::Response::ptr executeIpmiOemCommand(message::Request::ptr request)
309{
310 // look up the iana for this request
William A. Kennington IIId10d9052019-04-24 01:57:36 -0700311 uint24_t bytes;
312 if (0 != request->payload.unpack(bytes))
Vernon Maueryf984a012018-10-08 12:05:18 -0700313 {
314 return errorResponse(request, ccReqDataLenInvalid);
315 }
William A. Kennington IIId10d9052019-04-24 01:57:36 -0700316 auto iana = static_cast<Iana>(bytes);
Alexander Hansen7197b342023-09-06 11:45:15 +0200317
Vernon Mauerye808bae2024-05-31 14:55:36 -0700318 lg2::debug("unpack IANA {IANA}", "IANA", lg2::hex, iana);
Alexander Hansen7197b342023-09-06 11:45:15 +0200319
Patrick Williams1318a5e2024-08-16 15:19:54 -0400320 message::Response::ptr response =
321 executeIpmiCommandCommon(oemHandlerMap, iana, request);
William A. Kennington IIIda31f9a2019-04-25 01:36:32 -0700322 ipmi::message::Payload prefix;
323 prefix.pack(bytes);
324 response->prepend(prefix);
Vernon Maueryf984a012018-10-08 12:05:18 -0700325 return response;
326}
327
Vernon Mauery240b1862018-10-08 12:05:16 -0700328message::Response::ptr executeIpmiCommand(message::Request::ptr request)
329{
330 NetFn netFn = request->ctx->netFn;
Vernon Maueryf984a012018-10-08 12:05:18 -0700331 if (netFnGroup == netFn)
332 {
333 return executeIpmiGroupCommand(request);
334 }
335 else if (netFnOem == netFn)
336 {
337 return executeIpmiOemCommand(request);
338 }
Vernon Mauery240b1862018-10-08 12:05:16 -0700339 return executeIpmiCommandCommon(handlerMap, netFn, request);
340}
341
Vernon Mauery735ee952019-02-15 13:38:52 -0800342namespace utils
343{
344template <typename AssocContainer, typename UnaryPredicate>
345void assoc_erase_if(AssocContainer& c, UnaryPredicate p)
346{
347 typename AssocContainer::iterator next = c.begin();
348 typename AssocContainer::iterator last = c.end();
349 while ((next = std::find_if(next, last, p)) != last)
350 {
351 c.erase(next++);
352 }
353}
354} // namespace utils
355
356namespace
357{
358std::unordered_map<std::string, uint8_t> uniqueNameToChannelNumber;
359
360// sdbusplus::bus::match::rules::arg0namespace() wants the prefix
361// to match without any trailing '.'
362constexpr const char ipmiDbusChannelMatch[] =
363 "xyz.openbmc_project.Ipmi.Channel";
364void updateOwners(sdbusplus::asio::connection& conn, const std::string& name)
365{
366 conn.async_method_call(
367 [name](const boost::system::error_code ec,
368 const std::string& nameOwner) {
Patrick Williams1318a5e2024-08-16 15:19:54 -0400369 if (ec)
370 {
371 lg2::error("Error getting dbus owner for {INTERFACE}",
372 "INTERFACE", name);
373 return;
374 }
375 // start after ipmiDbusChannelPrefix (after the '.')
376 std::string chName =
377 name.substr(std::strlen(ipmiDbusChannelMatch) + 1);
378 try
379 {
380 uint8_t channel = getChannelByName(chName);
381 uniqueNameToChannelNumber[nameOwner] = channel;
382 lg2::info(
383 "New interface mapping: {INTERFACE} -> channel {CHANNEL}",
384 "INTERFACE", name, "CHANNEL", channel);
385 }
386 catch (const std::exception& e)
387 {
388 lg2::info("Failed interface mapping, no such name: {INTERFACE}",
389 "INTERFACE", name);
390 }
391 },
Vernon Mauery735ee952019-02-15 13:38:52 -0800392 "org.freedesktop.DBus", "/", "org.freedesktop.DBus", "GetNameOwner",
393 name);
394}
395
Ed Tanous778418d2020-08-17 23:20:21 -0700396void doListNames(boost::asio::io_context& io, sdbusplus::asio::connection& conn)
Vernon Mauery735ee952019-02-15 13:38:52 -0800397{
398 conn.async_method_call(
399 [&io, &conn](const boost::system::error_code ec,
400 std::vector<std::string> busNames) {
Patrick Williams1318a5e2024-08-16 15:19:54 -0400401 if (ec)
Vernon Mauery735ee952019-02-15 13:38:52 -0800402 {
Patrick Williams1318a5e2024-08-16 15:19:54 -0400403 lg2::error("Error getting dbus names: {ERROR}", "ERROR",
404 ec.message());
405 std::exit(EXIT_FAILURE);
406 return;
Vernon Mauery735ee952019-02-15 13:38:52 -0800407 }
Patrick Williams1318a5e2024-08-16 15:19:54 -0400408 // Try to make startup consistent
409 std::sort(busNames.begin(), busNames.end());
410
411 const std::string channelPrefix =
412 std::string(ipmiDbusChannelMatch) + ".";
413 for (const std::string& busName : busNames)
414 {
415 if (busName.find(channelPrefix) == 0)
416 {
417 updateOwners(conn, busName);
418 }
419 }
420 },
Vernon Mauery735ee952019-02-15 13:38:52 -0800421 "org.freedesktop.DBus", "/org/freedesktop/DBus", "org.freedesktop.DBus",
422 "ListNames");
423}
424
Patrick Williams5d82f472022-07-22 19:26:53 -0500425void nameChangeHandler(sdbusplus::message_t& message)
Vernon Mauery735ee952019-02-15 13:38:52 -0800426{
427 std::string name;
428 std::string oldOwner;
429 std::string newOwner;
430
431 message.read(name, oldOwner, newOwner);
432
433 if (!oldOwner.empty())
434 {
435 if (boost::starts_with(oldOwner, ":"))
436 {
437 // Connection removed
438 auto it = uniqueNameToChannelNumber.find(oldOwner);
439 if (it != uniqueNameToChannelNumber.end())
440 {
441 uniqueNameToChannelNumber.erase(it);
442 }
443 }
444 }
445 if (!newOwner.empty())
446 {
447 // start after ipmiDbusChannelMatch (and after the '.')
448 std::string chName = name.substr(std::strlen(ipmiDbusChannelMatch) + 1);
449 try
450 {
451 uint8_t channel = getChannelByName(chName);
452 uniqueNameToChannelNumber[newOwner] = channel;
Vernon Mauerye808bae2024-05-31 14:55:36 -0700453 lg2::info("New interface mapping: {INTERFACE} -> channel {CHANNEL}",
454 "INTERFACE", name, "CHANNEL", channel);
Vernon Mauery735ee952019-02-15 13:38:52 -0800455 }
456 catch (const std::exception& e)
457 {
Vernon Mauerye808bae2024-05-31 14:55:36 -0700458 lg2::info("Failed interface mapping, no such name: {INTERFACE}",
459 "INTERFACE", name);
Vernon Mauery735ee952019-02-15 13:38:52 -0800460 }
461 }
462};
463
464} // anonymous namespace
465
466static constexpr const char intraBmcName[] = "INTRABMC";
Patrick Williams5d82f472022-07-22 19:26:53 -0500467uint8_t channelFromMessage(sdbusplus::message_t& msg)
Vernon Mauery735ee952019-02-15 13:38:52 -0800468{
469 // channel name for ipmitool to resolve to
470 std::string sender = msg.get_sender();
471 auto chIter = uniqueNameToChannelNumber.find(sender);
472 if (chIter != uniqueNameToChannelNumber.end())
473 {
474 return chIter->second;
475 }
476 // FIXME: currently internal connections are ephemeral and hard to pin down
477 try
478 {
479 return getChannelByName(intraBmcName);
480 }
481 catch (const std::exception& e)
482 {
483 return invalidChannel;
484 }
485} // namespace ipmi
486
Vernon Mauery240b1862018-10-08 12:05:16 -0700487/* called from sdbus async server context */
Patrick Williams5d82f472022-07-22 19:26:53 -0500488auto executionEntry(boost::asio::yield_context yield, sdbusplus::message_t& m,
489 NetFn netFn, uint8_t lun, Cmd cmd, ipmi::SecureBuffer& data,
Vernon Mauery240b1862018-10-08 12:05:16 -0700490 std::map<std::string, ipmi::Value>& options)
491{
Vernon Mauery735ee952019-02-15 13:38:52 -0800492 const auto dbusResponse =
Vernon Mauery997952a2021-07-30 14:06:14 -0700493 [netFn, lun, cmd](Cc cc, const ipmi::SecureBuffer& data = {}) {
Patrick Williams1318a5e2024-08-16 15:19:54 -0400494 constexpr uint8_t netFnResponse = 0x01;
495 uint8_t retNetFn = netFn | netFnResponse;
496 return std::make_tuple(retNetFn, lun, cmd, cc, data);
497 };
Vernon Mauery735ee952019-02-15 13:38:52 -0800498 std::string sender = m.get_sender();
499 Privilege privilege = Privilege::None;
Vernon Maueryd6a2da02019-04-09 16:00:46 -0700500 int rqSA = 0;
Kumar Thangavelf7d081f2020-08-19 20:41:18 +0530501 int hostIdx = 0;
Vernon Mauery735ee952019-02-15 13:38:52 -0800502 uint8_t userId = 0; // undefined user
Rajashekar Gade Reddy4d226402019-11-13 17:13:05 +0530503 uint32_t sessionId = 0;
Vernon Mauery735ee952019-02-15 13:38:52 -0800504
505 // figure out what channel the request came in on
506 uint8_t channel = channelFromMessage(m);
507 if (channel == invalidChannel)
508 {
509 // unknown sender channel; refuse to service the request
Vernon Mauerye808bae2024-05-31 14:55:36 -0700510 lg2::error("ERROR determining source IPMI channel from "
511 "{SENDER} NetFn/Cmd {NETFN}/{CMD}",
512 "SENDER", sender, "NETFN", lg2::hex, netFn, "CMD", lg2::hex,
513 cmd);
Vernon Mauery735ee952019-02-15 13:38:52 -0800514 return dbusResponse(ipmi::ccDestinationUnavailable);
515 }
516
Rajashekar Gade Reddy4d226402019-11-13 17:13:05 +0530517 // session-based channels are required to provide userId, privilege and
518 // sessionId
Vernon Mauery735ee952019-02-15 13:38:52 -0800519 if (getChannelSessionSupport(channel) != EChannelSessSupported::none)
520 {
521 try
522 {
523 Value requestPriv = options.at("privilege");
524 Value requestUserId = options.at("userId");
Rajashekar Gade Reddy4d226402019-11-13 17:13:05 +0530525 Value requestSessionId = options.at("currentSessionId");
Vernon Mauery735ee952019-02-15 13:38:52 -0800526 privilege = static_cast<Privilege>(std::get<int>(requestPriv));
527 userId = static_cast<uint8_t>(std::get<int>(requestUserId));
Rajashekar Gade Reddy4d226402019-11-13 17:13:05 +0530528 sessionId =
529 static_cast<uint32_t>(std::get<uint32_t>(requestSessionId));
Vernon Mauery735ee952019-02-15 13:38:52 -0800530 }
531 catch (const std::exception& e)
532 {
Vernon Mauerye808bae2024-05-31 14:55:36 -0700533 lg2::error("ERROR determining IPMI session credentials on "
534 "channel {CHANNEL} for userid {USERID}",
535 "CHANNEL", channel, "USERID", userId, "NETFN", lg2::hex,
536 netFn, "CMD", lg2::hex, cmd);
Vernon Mauery735ee952019-02-15 13:38:52 -0800537 return dbusResponse(ipmi::ccUnspecifiedError);
538 }
539 }
540 else
541 {
542 // get max privilege for session-less channels
543 // For now, there is not a way to configure this, default to Admin
544 privilege = Privilege::Admin;
Vernon Maueryd6a2da02019-04-09 16:00:46 -0700545
546 // ipmb should supply rqSA
547 ChannelInfo chInfo;
548 getChannelInfo(channel, chInfo);
549 if (static_cast<EChannelMediumType>(chInfo.mediumType) ==
550 EChannelMediumType::ipmb)
551 {
552 const auto iter = options.find("rqSA");
553 if (iter != options.end())
554 {
555 if (std::holds_alternative<int>(iter->second))
556 {
557 rqSA = std::get<int>(iter->second);
558 }
559 }
Kumar Thangavelf7d081f2020-08-19 20:41:18 +0530560 const auto iteration = options.find("hostId");
561 if (iteration != options.end())
562 {
563 if (std::holds_alternative<int>(iteration->second))
564 {
565 hostIdx = std::get<int>(iteration->second);
566 }
567 }
Vernon Maueryd6a2da02019-04-09 16:00:46 -0700568 }
Vernon Mauery735ee952019-02-15 13:38:52 -0800569 }
570 // check to see if the requested priv/username is valid
Vernon Mauerye808bae2024-05-31 14:55:36 -0700571 lg2::debug("Set up ipmi context: Ch:NetFn/Cmd={CHANNEL}:{NETFN}/{CMD}",
572 "SENDER", sender, "NETFN", lg2::hex, netFn, "LUN", lg2::hex, lun,
573 "CMD", lg2::hex, cmd, "CHANNEL", channel, "USERID", userId,
574 "SESSIONID", lg2::hex, sessionId, "PRIVILEGE",
575 static_cast<uint8_t>(privilege), "RQSA", lg2::hex, rqSA);
Vernon Mauery735ee952019-02-15 13:38:52 -0800576
Patrick Williams1318a5e2024-08-16 15:19:54 -0400577 auto ctx = std::make_shared<ipmi::Context>(
578 getSdBus(), netFn, lun, cmd, channel, userId, sessionId, privilege,
579 rqSA, hostIdx, yield);
Vernon Mauery240b1862018-10-08 12:05:16 -0700580 auto request = std::make_shared<ipmi::message::Request>(
Vernon Mauery997952a2021-07-30 14:06:14 -0700581 ctx, std::forward<ipmi::SecureBuffer>(data));
Vernon Mauery240b1862018-10-08 12:05:16 -0700582 message::Response::ptr response = executeIpmiCommand(request);
583
Vernon Mauery735ee952019-02-15 13:38:52 -0800584 return dbusResponse(response->cc, response->payload.raw);
Vernon Mauery240b1862018-10-08 12:05:16 -0700585}
586
587/** @struct IpmiProvider
588 *
589 * RAII wrapper for dlopen so that dlclose gets called on exit
590 */
591struct IpmiProvider
592{
593 public:
594 /** @brief address of the opened library */
595 void* addr;
596 std::string name;
597
598 IpmiProvider() = delete;
599 IpmiProvider(const IpmiProvider&) = delete;
600 IpmiProvider& operator=(const IpmiProvider&) = delete;
601 IpmiProvider(IpmiProvider&&) = delete;
602 IpmiProvider& operator=(IpmiProvider&&) = delete;
603
604 /** @brief dlopen a shared object file by path
605 * @param[in] filename - path of shared object to open
606 */
607 explicit IpmiProvider(const char* fname) : addr(nullptr), name(fname)
608 {
Vernon Mauerye808bae2024-05-31 14:55:36 -0700609 lg2::debug("Open IPMI provider library: {PROVIDER}", "PROVIDER", name);
Vernon Mauery240b1862018-10-08 12:05:16 -0700610 try
611 {
612 addr = dlopen(name.c_str(), RTLD_NOW);
613 }
Patrick Williamsa2ad2da2021-10-06 12:21:46 -0500614 catch (const std::exception& e)
Vernon Mauery240b1862018-10-08 12:05:16 -0700615 {
Vernon Mauerye808bae2024-05-31 14:55:36 -0700616 lg2::error("ERROR opening IPMI provider {PROVIDER}: {ERROR}",
617 "PROVIDER", name, "ERROR", e);
Vernon Mauery240b1862018-10-08 12:05:16 -0700618 }
619 catch (...)
620 {
Vernon Mauery03d7a4b2021-01-19 11:22:17 -0800621 const char* what = currentExceptionType();
Vernon Mauerye808bae2024-05-31 14:55:36 -0700622 lg2::error("ERROR opening IPMI provider {PROVIDER}: {ERROR}",
623 "PROVIDER", name, "ERROR", what);
Vernon Mauery240b1862018-10-08 12:05:16 -0700624 }
625 if (!isOpen())
626 {
Vernon Mauerye808bae2024-05-31 14:55:36 -0700627 lg2::error("ERROR opening IPMI provider {PROVIDER}: {ERROR}",
628 "PROVIDER", name, "ERROR", dlerror());
Vernon Mauery240b1862018-10-08 12:05:16 -0700629 }
630 }
631
632 ~IpmiProvider()
633 {
634 if (isOpen())
635 {
636 dlclose(addr);
637 }
638 }
639 bool isOpen() const
640 {
641 return (nullptr != addr);
642 }
643};
644
645// Plugin libraries need to contain .so either at the end or in the middle
646constexpr const char ipmiPluginExtn[] = ".so";
647
648/* return a list of self-closing library handles */
649std::forward_list<IpmiProvider> loadProviders(const fs::path& ipmiLibsPath)
650{
651 std::vector<fs::path> libs;
652 for (const auto& libPath : fs::directory_iterator(ipmiLibsPath))
653 {
Vernon Maueryb0ab5fe2019-03-06 14:03:00 -0800654 std::error_code ec;
Vernon Mauery240b1862018-10-08 12:05:16 -0700655 fs::path fname = libPath.path();
Vernon Maueryb0ab5fe2019-03-06 14:03:00 -0800656 if (fs::is_symlink(fname, ec) || ec)
657 {
658 // it's a symlink or some other error; skip it
659 continue;
660 }
Vernon Mauery240b1862018-10-08 12:05:16 -0700661 while (fname.has_extension())
662 {
663 fs::path extn = fname.extension();
664 if (extn == ipmiPluginExtn)
665 {
666 libs.push_back(libPath.path());
667 break;
668 }
669 fname.replace_extension();
670 }
671 }
672 std::sort(libs.begin(), libs.end());
673
674 std::forward_list<IpmiProvider> handles;
675 for (auto& lib : libs)
676 {
677#ifdef __IPMI_DEBUG__
Vernon Mauerye808bae2024-05-31 14:55:36 -0700678 lg2::debug("Registering handler {HANDLER}", "HANDLER", lib);
Vernon Mauery240b1862018-10-08 12:05:16 -0700679#endif
680 handles.emplace_front(lib.c_str());
681 }
682 return handles;
683}
684
685} // namespace ipmi
686
Vernon Mauery240b1862018-10-08 12:05:16 -0700687#ifdef ALLOW_DEPRECATED_API
688/* legacy registration */
689void ipmi_register_callback(ipmi_netfn_t netFn, ipmi_cmd_t cmd,
690 ipmi_context_t context, ipmid_callback_t handler,
691 ipmi_cmd_privilege_t priv)
692{
Vernon Mauerybe376302019-03-21 13:02:05 -0700693 auto h = ipmi::makeLegacyHandler(handler, context);
Vernon Mauery240b1862018-10-08 12:05:16 -0700694 // translate priv from deprecated enum to current
695 ipmi::Privilege realPriv;
696 switch (priv)
697 {
698 case PRIVILEGE_CALLBACK:
699 realPriv = ipmi::Privilege::Callback;
700 break;
701 case PRIVILEGE_USER:
702 realPriv = ipmi::Privilege::User;
703 break;
704 case PRIVILEGE_OPERATOR:
705 realPriv = ipmi::Privilege::Operator;
706 break;
707 case PRIVILEGE_ADMIN:
708 realPriv = ipmi::Privilege::Admin;
709 break;
710 case PRIVILEGE_OEM:
711 realPriv = ipmi::Privilege::Oem;
712 break;
713 case SYSTEM_INTERFACE:
714 realPriv = ipmi::Privilege::Admin;
715 break;
716 default:
717 realPriv = ipmi::Privilege::Admin;
718 break;
719 }
Vernon Mauerye8d43232019-03-26 16:23:43 -0700720 // The original ipmi_register_callback allowed for group OEM handlers
721 // to be registered via this same interface. It just so happened that
722 // all the handlers were part of the DCMI group, so default to that.
723 if (netFn == NETFUN_GRPEXT)
724 {
Vernon Mauery82cffcc2023-07-27 10:59:20 -0700725 ipmi::impl::registerGroupHandler(ipmi::prioOpenBmcBase, ipmi::groupDCMI,
726 cmd, realPriv, h);
Vernon Mauerye8d43232019-03-26 16:23:43 -0700727 }
728 else
729 {
730 ipmi::impl::registerHandler(ipmi::prioOpenBmcBase, netFn, cmd, realPriv,
731 h);
732 }
Vernon Mauery240b1862018-10-08 12:05:16 -0700733}
734
Vernon Maueryf984a012018-10-08 12:05:18 -0700735namespace oem
736{
737
738class LegacyRouter : public oem::Router
739{
740 public:
Patrick Williamsfbc6c9d2023-05-10 07:50:16 -0500741 virtual ~LegacyRouter() {}
Vernon Maueryf984a012018-10-08 12:05:18 -0700742
743 /// Enable message routing to begin.
Patrick Williamsfbc6c9d2023-05-10 07:50:16 -0500744 void activate() override {}
Vernon Maueryf984a012018-10-08 12:05:18 -0700745
746 void registerHandler(Number oen, ipmi_cmd_t cmd, Handler handler) override
747 {
748 auto h = ipmi::makeLegacyHandler(std::forward<Handler>(handler));
749 ipmi::impl::registerOemHandler(ipmi::prioOpenBmcBase, oen, cmd,
750 ipmi::Privilege::Admin, h);
751 }
752};
753static LegacyRouter legacyRouter;
754
755Router* mutableRouter()
756{
757 return &legacyRouter;
758}
759
760} // namespace oem
761
Vernon Mauery240b1862018-10-08 12:05:16 -0700762/* legacy alternative to executionEntry */
Patrick Williams5d82f472022-07-22 19:26:53 -0500763void handleLegacyIpmiCommand(sdbusplus::message_t& m)
Vernon Mauery240b1862018-10-08 12:05:16 -0700764{
Vernon Mauery23b70212019-05-08 15:19:05 -0700765 // make a copy so the next two moves don't wreak havoc on the stack
Patrick Williams5d82f472022-07-22 19:26:53 -0500766 sdbusplus::message_t b{m};
Patrick Williams1318a5e2024-08-16 15:19:54 -0400767 boost::asio::spawn(*getIoContext(), [b = std::move(b)](
768 boost::asio::yield_context yield) {
Patrick Williams5d82f472022-07-22 19:26:53 -0500769 sdbusplus::message_t m{std::move(b)};
Snehalatha Venkatesh55f5d532021-07-13 11:06:36 +0000770 unsigned char seq = 0, netFn = 0, lun = 0, cmd = 0;
Vernon Mauery997952a2021-07-30 14:06:14 -0700771 ipmi::SecureBuffer data;
Vernon Mauery240b1862018-10-08 12:05:16 -0700772
Vernon Mauery23b70212019-05-08 15:19:05 -0700773 m.read(seq, netFn, lun, cmd, data);
Vernon Mauery33298af2019-05-13 15:32:37 -0700774 std::shared_ptr<sdbusplus::asio::connection> bus = getSdBus();
Vernon Mauery23b70212019-05-08 15:19:05 -0700775 auto ctx = std::make_shared<ipmi::Context>(
Kumar Thangavelf7d081f2020-08-19 20:41:18 +0530776 bus, netFn, lun, cmd, 0, 0, 0, ipmi::Privilege::Admin, 0, 0, yield);
Vernon Mauery23b70212019-05-08 15:19:05 -0700777 auto request = std::make_shared<ipmi::message::Request>(
Vernon Mauery997952a2021-07-30 14:06:14 -0700778 ctx, std::forward<ipmi::SecureBuffer>(data));
Vernon Mauery23b70212019-05-08 15:19:05 -0700779 ipmi::message::Response::ptr response =
780 ipmi::executeIpmiCommand(request);
Vernon Mauery240b1862018-10-08 12:05:16 -0700781
Vernon Mauery23b70212019-05-08 15:19:05 -0700782 // Responses in IPMI require a bit set. So there ya go...
783 netFn |= 0x01;
Vernon Mauery240b1862018-10-08 12:05:16 -0700784
Vernon Mauery23b70212019-05-08 15:19:05 -0700785 const char *dest, *path;
786 constexpr const char* DBUS_INTF = "org.openbmc.HostIpmi";
Vernon Mauery240b1862018-10-08 12:05:16 -0700787
Vernon Mauery23b70212019-05-08 15:19:05 -0700788 dest = m.get_sender();
789 path = m.get_path();
790 boost::system::error_code ec;
Vernon Mauery33298af2019-05-13 15:32:37 -0700791 bus->yield_method_call(yield, ec, dest, path, DBUS_INTF, "sendMessage",
792 seq, netFn, lun, cmd, response->cc,
793 response->payload.raw);
Vernon Mauery23b70212019-05-08 15:19:05 -0700794 if (ec)
795 {
Vernon Mauerye808bae2024-05-31 14:55:36 -0700796 lg2::error(
797 "Failed to send response to requestor ({NETFN}/{CMD}): {ERROR}",
798 "ERROR", ec.message(), "SENDER", dest, "NETFN", lg2::hex, netFn,
799 "CMD", lg2::hex, cmd);
Vernon Mauery23b70212019-05-08 15:19:05 -0700800 }
801 });
Vernon Mauery240b1862018-10-08 12:05:16 -0700802}
803
804#endif /* ALLOW_DEPRECATED_API */
805
806// Calls host command manager to do the right thing for the command
807using CommandHandler = phosphor::host::command::CommandHandler;
808std::unique_ptr<phosphor::host::command::Manager> cmdManager;
809void ipmid_send_cmd_to_host(CommandHandler&& cmd)
810{
Vernon Mauery5e096a22022-06-01 15:11:16 -0700811 cmdManager->execute(std::forward<CommandHandler>(cmd));
Vernon Mauery240b1862018-10-08 12:05:16 -0700812}
813
814std::unique_ptr<phosphor::host::command::Manager>& ipmid_get_host_cmd_manager()
815{
816 return cmdManager;
817}
818
Vernon Mauery20ff3332019-03-01 16:52:25 -0800819// These are symbols that are present in libipmid, but not expected
820// to be used except here (or maybe a unit test), so declare them here
821extern void setIoContext(std::shared_ptr<boost::asio::io_context>& newIo);
822extern void setSdBus(std::shared_ptr<sdbusplus::asio::connection>& newBus);
823
Vernon Mauery240b1862018-10-08 12:05:16 -0700824int main(int argc, char* argv[])
825{
826 // Connect to system bus
Vernon Mauery20ff3332019-03-01 16:52:25 -0800827 auto io = std::make_shared<boost::asio::io_context>();
828 setIoContext(io);
Vernon Mauery240b1862018-10-08 12:05:16 -0700829 if (argc > 1 && std::string(argv[1]) == "-session")
830 {
831 sd_bus_default_user(&bus);
832 }
833 else
834 {
835 sd_bus_default_system(&bus);
836 }
Vernon Mauery20ff3332019-03-01 16:52:25 -0800837 auto sdbusp = std::make_shared<sdbusplus::asio::connection>(*io, bus);
838 setSdBus(sdbusp);
Vernon Mauery240b1862018-10-08 12:05:16 -0700839
840 // TODO: Hack to keep the sdEvents running.... Not sure why the sd_event
841 // queue stops running if we don't have a timer that keeps re-arming
Patrick Williams95655222023-12-05 12:45:02 -0600842 sdbusplus::Timer t2([]() { ; });
Vernon Mauery240b1862018-10-08 12:05:16 -0700843 t2.start(std::chrono::microseconds(500000), true);
844
845 // TODO: Remove all vestiges of sd_event from phosphor-host-ipmid
846 // until that is done, add the sd_event wrapper to the io object
847 sdbusplus::asio::sd_event_wrapper sdEvents(*io);
848
849 cmdManager = std::make_unique<phosphor::host::command::Manager>(*sdbusp);
850
851 // Register all command providers and filters
Vernon Mauery4ec4e402019-03-20 13:09:27 -0700852 std::forward_list<ipmi::IpmiProvider> providers =
853 ipmi::loadProviders(HOST_IPMI_LIB_PATH);
Vernon Mauery240b1862018-10-08 12:05:16 -0700854
Vernon Mauery240b1862018-10-08 12:05:16 -0700855#ifdef ALLOW_DEPRECATED_API
856 // listen on deprecated signal interface for kcs/bt commands
857 constexpr const char* FILTER = "type='signal',interface='org.openbmc."
858 "HostIpmi',member='ReceivedMessage'";
Patrick Williams5d82f472022-07-22 19:26:53 -0500859 sdbusplus::bus::match_t oldIpmiInterface(*sdbusp, FILTER,
860 handleLegacyIpmiCommand);
Vernon Mauery240b1862018-10-08 12:05:16 -0700861#endif /* ALLOW_DEPRECATED_API */
862
Vernon Mauery735ee952019-02-15 13:38:52 -0800863 // set up bus name watching to match channels with bus names
Patrick Williams5d82f472022-07-22 19:26:53 -0500864 sdbusplus::bus::match_t nameOwnerChanged(
Vernon Mauery735ee952019-02-15 13:38:52 -0800865 *sdbusp,
866 sdbusplus::bus::match::rules::nameOwnerChanged() +
867 sdbusplus::bus::match::rules::arg0namespace(
868 ipmi::ipmiDbusChannelMatch),
869 ipmi::nameChangeHandler);
870 ipmi::doListNames(*io, *sdbusp);
871
James Feistb0094a72019-11-26 09:07:15 -0800872 int exitCode = 0;
Vernon Mauery1b7f6f22019-03-13 13:11:25 -0700873 // set up boost::asio signal handling
Patrick Williams1318a5e2024-08-16 15:19:54 -0400874 std::function<SignalResponse(int)> stopAsioRunLoop = [&io, &exitCode](
875 int signalNumber) {
Vernon Mauerye808bae2024-05-31 14:55:36 -0700876 lg2::info("Received signal {SIGNAL}; quitting", "SIGNAL", signalNumber);
Patrick Williamsfbc6c9d2023-05-10 07:50:16 -0500877 io->stop();
878 exitCode = signalNumber;
879 return SignalResponse::breakExecution;
880 };
Vernon Mauery1b7f6f22019-03-13 13:11:25 -0700881 registerSignalHandler(ipmi::prioOpenBmcBase, SIGINT, stopAsioRunLoop);
882 registerSignalHandler(ipmi::prioOpenBmcBase, SIGTERM, stopAsioRunLoop);
883
Richard Marian Thomaiyar369406e2020-01-09 14:56:54 +0530884 sdbusp->request_name("xyz.openbmc_project.Ipmi.Host");
885 // Add bindings for inbound IPMI requests
886 auto server = sdbusplus::asio::object_server(sdbusp);
887 auto iface = server.add_interface("/xyz/openbmc_project/Ipmi",
888 "xyz.openbmc_project.Ipmi.Server");
889 iface->register_method("execute", ipmi::executionEntry);
890 iface->initialize();
891
Vernon Mauery240b1862018-10-08 12:05:16 -0700892 io->run();
893
Vernon Mauery1b7f6f22019-03-13 13:11:25 -0700894 // destroy all the IPMI handlers so the providers can unload safely
895 ipmi::handlerMap.clear();
896 ipmi::groupHandlerMap.clear();
897 ipmi::oemHandlerMap.clear();
898 ipmi::filterList.clear();
899 // unload the provider libraries
Vernon Mauery4ec4e402019-03-20 13:09:27 -0700900 providers.clear();
Vernon Mauery1b7f6f22019-03-13 13:11:25 -0700901
James Feistb0094a72019-11-26 09:07:15 -0800902 std::exit(exitCode);
Vernon Mauery240b1862018-10-08 12:05:16 -0700903}