blob: 7d3dd2d6d079e0c88ec140f181ed4c349903896b [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 Tanous98605052025-02-13 16:57:13 -080023#include <boost/asio/detached.hpp>
Ed Tanous778418d2020-08-17 23:20:21 -070024#include <boost/asio/io_context.hpp>
Ed Tanous26a386f2025-02-13 16:57:13 -080025#include <boost/asio/spawn.hpp>
Vernon Mauery240b1862018-10-08 12:05:16 -070026#include <host-cmd-manager.hpp>
27#include <ipmid-host/cmd.hpp>
28#include <ipmid/api.hpp>
29#include <ipmid/handler.hpp>
30#include <ipmid/message.hpp>
31#include <ipmid/oemrouter.hpp>
Vernon Mauery33250242019-03-12 16:49:26 -070032#include <ipmid/types.hpp>
George Liude1420d2025-03-03 15:14:25 +080033#include <ipmid/utils.hpp>
Vernon Mauerye808bae2024-05-31 14:55:36 -070034#include <phosphor-logging/lg2.hpp>
Vernon Mauery240b1862018-10-08 12:05:16 -070035#include <sdbusplus/asio/connection.hpp>
36#include <sdbusplus/asio/object_server.hpp>
Patrick Williams3b301a32025-02-03 13:05:36 -050037#include <sdbusplus/asio/sd_event.hpp>
Vernon Mauery240b1862018-10-08 12:05:16 -070038#include <sdbusplus/bus.hpp>
39#include <sdbusplus/bus/match.hpp>
40#include <sdbusplus/timer.hpp>
Patrick Williamsfbc6c9d2023-05-10 07:50:16 -050041
42#include <algorithm>
43#include <any>
44#include <exception>
45#include <filesystem>
46#include <forward_list>
47#include <map>
48#include <memory>
49#include <optional>
Vernon Mauery240b1862018-10-08 12:05:16 -070050#include <tuple>
Vernon Mauery240b1862018-10-08 12:05:16 -070051#include <unordered_map>
52#include <utility>
53#include <vector>
54
Vernon Mauery240b1862018-10-08 12:05:16 -070055namespace fs = std::filesystem;
56
57using namespace phosphor::logging;
58
Vernon Mauery240b1862018-10-08 12:05:16 -070059// IPMI Spec, shared Reservation ID.
60static unsigned short selReservationID = 0xFFFF;
61static bool selReservationValid = false;
62
63unsigned short reserveSel(void)
64{
65 // IPMI spec, Reservation ID, the value simply increases against each
66 // execution of the Reserve SEL command.
67 if (++selReservationID == 0)
68 {
69 selReservationID = 1;
70 }
71 selReservationValid = true;
72 return selReservationID;
73}
74
75bool checkSELReservation(unsigned short id)
76{
77 return (selReservationValid && selReservationID == id);
78}
79
80void cancelSELReservation(void)
81{
82 selReservationValid = false;
83}
84
85EInterfaceIndex getInterfaceIndex(void)
86{
87 return interfaceKCS;
88}
89
90sd_bus* bus;
Patrick Williams3b301a32025-02-03 13:05:36 -050091sd_event* events = nullptr;
92sd_event* ipmid_get_sd_event_connection(void)
93{
94 return events;
95}
Vernon Mauery240b1862018-10-08 12:05:16 -070096sd_bus* ipmid_get_sd_bus_connection(void)
97{
98 return bus;
99}
100
101namespace ipmi
102{
103
104static inline unsigned int makeCmdKey(unsigned int cluster, unsigned int cmd)
105{
106 return (cluster << 8) | cmd;
107}
108
109using HandlerTuple = std::tuple<int, /* prio */
110 Privilege, HandlerBase::ptr /* handler */
111 >;
112
113/* map to handle standard registered commands */
114static std::unordered_map<unsigned int, /* key is NetFn/Cmd */
115 HandlerTuple>
116 handlerMap;
117
Vernon Maueryf984a012018-10-08 12:05:18 -0700118/* special map for decoding Group registered commands (NetFn 2Ch) */
119static std::unordered_map<unsigned int, /* key is Group/Cmd (NetFn is 2Ch) */
120 HandlerTuple>
121 groupHandlerMap;
122
123/* special map for decoding OEM registered commands (NetFn 2Eh) */
124static std::unordered_map<unsigned int, /* key is Iana/Cmd (NetFn is 2Eh) */
125 HandlerTuple>
126 oemHandlerMap;
127
Vernon Mauery08a70aa2018-11-07 09:36:22 -0800128using FilterTuple = std::tuple<int, /* prio */
129 FilterBase::ptr /* filter */
130 >;
131
132/* list to hold all registered ipmi command filters */
133static std::forward_list<FilterTuple> filterList;
134
Vernon Mauery240b1862018-10-08 12:05:16 -0700135namespace impl
136{
137/* common function to register all standard IPMI handlers */
138bool registerHandler(int prio, NetFn netFn, Cmd cmd, Privilege priv,
139 HandlerBase::ptr handler)
140{
141 // check for valid NetFn: even; 00-0Ch, 30-3Eh
142 if (netFn & 1 || (netFn > netFnTransport && netFn < netFnGroup) ||
143 netFn > netFnOemEight)
144 {
145 return false;
146 }
147
148 // create key and value for this handler
149 unsigned int netFnCmd = makeCmdKey(netFn, cmd);
150 HandlerTuple item(prio, priv, handler);
151
152 // consult the handler map and look for a match
153 auto& mapCmd = handlerMap[netFnCmd];
154 if (!std::get<HandlerBase::ptr>(mapCmd) || std::get<int>(mapCmd) <= prio)
155 {
156 mapCmd = item;
157 return true;
158 }
159 return false;
160}
161
Vernon Maueryf984a012018-10-08 12:05:18 -0700162/* common function to register all Group IPMI handlers */
163bool registerGroupHandler(int prio, Group group, Cmd cmd, Privilege priv,
164 HandlerBase::ptr handler)
165{
166 // create key and value for this handler
167 unsigned int netFnCmd = makeCmdKey(group, cmd);
168 HandlerTuple item(prio, priv, handler);
169
170 // consult the handler map and look for a match
171 auto& mapCmd = groupHandlerMap[netFnCmd];
172 if (!std::get<HandlerBase::ptr>(mapCmd) || std::get<int>(mapCmd) <= prio)
173 {
174 mapCmd = item;
175 return true;
176 }
177 return false;
178}
179
180/* common function to register all OEM IPMI handlers */
181bool registerOemHandler(int prio, Iana iana, Cmd cmd, Privilege priv,
182 HandlerBase::ptr handler)
183{
184 // create key and value for this handler
185 unsigned int netFnCmd = makeCmdKey(iana, cmd);
186 HandlerTuple item(prio, priv, handler);
187
188 // consult the handler map and look for a match
189 auto& mapCmd = oemHandlerMap[netFnCmd];
190 if (!std::get<HandlerBase::ptr>(mapCmd) || std::get<int>(mapCmd) <= prio)
191 {
192 mapCmd = item;
Vernon Mauerye808bae2024-05-31 14:55:36 -0700193 lg2::debug("registered OEM Handler: NetFn/Cmd={NETFNCMD}", "IANA",
194 lg2::hex, iana, "CMD", lg2::hex, cmd, "NETFNCMD", lg2::hex,
195 netFnCmd);
Vernon Maueryf984a012018-10-08 12:05:18 -0700196 return true;
197 }
Alexander Hansen7197b342023-09-06 11:45:15 +0200198
Vernon Mauerye808bae2024-05-31 14:55:36 -0700199 lg2::warning("could not register OEM Handler: NetFn/Cmd={NETFNCMD}", "IANA",
200 lg2::hex, iana, "CMD", lg2::hex, cmd, "NETFNCMD", lg2::hex,
201 netFnCmd);
Vernon Maueryf984a012018-10-08 12:05:18 -0700202 return false;
203}
204
Vernon Mauery08a70aa2018-11-07 09:36:22 -0800205/* common function to register all IPMI filter handlers */
206void registerFilter(int prio, FilterBase::ptr filter)
207{
208 // check for initial placement
209 if (filterList.empty() || std::get<int>(filterList.front()) < prio)
210 {
211 filterList.emplace_front(std::make_tuple(prio, filter));
Yong Libe063232021-03-04 16:52:52 +0800212 return;
Vernon Mauery08a70aa2018-11-07 09:36:22 -0800213 }
214 // walk the list and put it in the right place
215 auto j = filterList.begin();
216 for (auto i = j; i != filterList.end() && std::get<int>(*i) > prio; i++)
217 {
218 j = i;
219 }
220 filterList.emplace_after(j, std::make_tuple(prio, filter));
221}
222
Vernon Mauery240b1862018-10-08 12:05:16 -0700223} // namespace impl
224
Vernon Mauery08a70aa2018-11-07 09:36:22 -0800225message::Response::ptr filterIpmiCommand(message::Request::ptr request)
226{
227 // pass the command through the filter mechanism
228 // This can be the firmware firewall or any OEM mechanism like
229 // whitelist filtering based on operational mode
230 for (auto& item : filterList)
231 {
232 FilterBase::ptr filter = std::get<FilterBase::ptr>(item);
233 ipmi::Cc cc = filter->call(request);
234 if (ipmi::ccSuccess != cc)
235 {
236 return errorResponse(request, cc);
237 }
238 }
239 return message::Response::ptr();
240}
241
Vernon Mauery240b1862018-10-08 12:05:16 -0700242message::Response::ptr executeIpmiCommandCommon(
243 std::unordered_map<unsigned int, HandlerTuple>& handlers,
244 unsigned int keyCommon, message::Request::ptr request)
245{
Vernon Mauery08a70aa2018-11-07 09:36:22 -0800246 // filter the command first; a non-null message::Response::ptr
247 // means that the message has been rejected for some reason
Vernon Mauery51f78142020-01-13 16:28:59 -0800248 message::Response::ptr filterResponse = filterIpmiCommand(request);
Vernon Mauery08a70aa2018-11-07 09:36:22 -0800249
Vernon Mauery240b1862018-10-08 12:05:16 -0700250 Cmd cmd = request->ctx->cmd;
251 unsigned int key = makeCmdKey(keyCommon, cmd);
252 auto cmdIter = handlers.find(key);
253 if (cmdIter != handlers.end())
254 {
Vernon Mauery51f78142020-01-13 16:28:59 -0800255 // only return the filter response if the command is found
256 if (filterResponse)
257 {
Vernon Mauerye808bae2024-05-31 14:55:36 -0700258 lg2::debug("request for NetFn/Cmd {NETFN}/{CMD} has been filtered",
259 "NETFN", lg2::hex, keyCommon, "CMD", lg2::hex, cmd);
Vernon Mauery51f78142020-01-13 16:28:59 -0800260 return filterResponse;
261 }
Vernon Mauery240b1862018-10-08 12:05:16 -0700262 HandlerTuple& chosen = cmdIter->second;
263 if (request->ctx->priv < std::get<Privilege>(chosen))
264 {
265 return errorResponse(request, ccInsufficientPrivilege);
266 }
267 return std::get<HandlerBase::ptr>(chosen)->call(request);
268 }
269 else
270 {
271 unsigned int wildcard = makeCmdKey(keyCommon, cmdWildcard);
272 cmdIter = handlers.find(wildcard);
273 if (cmdIter != handlers.end())
274 {
Vernon Mauery51f78142020-01-13 16:28:59 -0800275 // only return the filter response if the command is found
276 if (filterResponse)
277 {
Vernon Mauerye808bae2024-05-31 14:55:36 -0700278 lg2::debug(
279 "request for NetFn/Cmd {NETFN}/{CMD} has been filtered",
280 "NETFN", lg2::hex, keyCommon, "CMD", lg2::hex, cmd);
Vernon Mauery51f78142020-01-13 16:28:59 -0800281 return filterResponse;
282 }
Vernon Mauery240b1862018-10-08 12:05:16 -0700283 HandlerTuple& chosen = cmdIter->second;
284 if (request->ctx->priv < std::get<Privilege>(chosen))
285 {
286 return errorResponse(request, ccInsufficientPrivilege);
287 }
288 return std::get<HandlerBase::ptr>(chosen)->call(request);
289 }
290 }
291 return errorResponse(request, ccInvalidCommand);
292}
293
Vernon Maueryf984a012018-10-08 12:05:18 -0700294message::Response::ptr executeIpmiGroupCommand(message::Request::ptr request)
295{
296 // look up the group for this request
William A. Kennington IIId10d9052019-04-24 01:57:36 -0700297 uint8_t bytes;
298 if (0 != request->payload.unpack(bytes))
Vernon Maueryf984a012018-10-08 12:05:18 -0700299 {
300 return errorResponse(request, ccReqDataLenInvalid);
301 }
William A. Kennington IIId10d9052019-04-24 01:57:36 -0700302 auto group = static_cast<Group>(bytes);
John Chung0a3f40b2025-01-22 18:07:52 -0600303 // Set defining body code
304 request->ctx->group = group;
Patrick Williams1318a5e2024-08-16 15:19:54 -0400305 message::Response::ptr response =
306 executeIpmiCommandCommon(groupHandlerMap, group, request);
William A. Kennington IIIda31f9a2019-04-25 01:36:32 -0700307 ipmi::message::Payload prefix;
308 prefix.pack(bytes);
309 response->prepend(prefix);
Vernon Maueryf984a012018-10-08 12:05:18 -0700310 return response;
311}
312
313message::Response::ptr executeIpmiOemCommand(message::Request::ptr request)
314{
315 // look up the iana for this request
William A. Kennington IIId10d9052019-04-24 01:57:36 -0700316 uint24_t bytes;
317 if (0 != request->payload.unpack(bytes))
Vernon Maueryf984a012018-10-08 12:05:18 -0700318 {
319 return errorResponse(request, ccReqDataLenInvalid);
320 }
William A. Kennington IIId10d9052019-04-24 01:57:36 -0700321 auto iana = static_cast<Iana>(bytes);
Alexander Hansen7197b342023-09-06 11:45:15 +0200322
Vernon Mauerye808bae2024-05-31 14:55:36 -0700323 lg2::debug("unpack IANA {IANA}", "IANA", lg2::hex, iana);
Alexander Hansen7197b342023-09-06 11:45:15 +0200324
Patrick Williams1318a5e2024-08-16 15:19:54 -0400325 message::Response::ptr response =
326 executeIpmiCommandCommon(oemHandlerMap, iana, request);
William A. Kennington IIIda31f9a2019-04-25 01:36:32 -0700327 ipmi::message::Payload prefix;
328 prefix.pack(bytes);
329 response->prepend(prefix);
Vernon Maueryf984a012018-10-08 12:05:18 -0700330 return response;
331}
332
Vernon Mauery240b1862018-10-08 12:05:16 -0700333message::Response::ptr executeIpmiCommand(message::Request::ptr request)
334{
335 NetFn netFn = request->ctx->netFn;
Vernon Maueryf984a012018-10-08 12:05:18 -0700336 if (netFnGroup == netFn)
337 {
338 return executeIpmiGroupCommand(request);
339 }
340 else if (netFnOem == netFn)
341 {
342 return executeIpmiOemCommand(request);
343 }
Vernon Mauery240b1862018-10-08 12:05:16 -0700344 return executeIpmiCommandCommon(handlerMap, netFn, request);
345}
346
Vernon Mauery735ee952019-02-15 13:38:52 -0800347namespace utils
348{
349template <typename AssocContainer, typename UnaryPredicate>
350void assoc_erase_if(AssocContainer& c, UnaryPredicate p)
351{
352 typename AssocContainer::iterator next = c.begin();
353 typename AssocContainer::iterator last = c.end();
354 while ((next = std::find_if(next, last, p)) != last)
355 {
356 c.erase(next++);
357 }
358}
359} // namespace utils
360
361namespace
362{
363std::unordered_map<std::string, uint8_t> uniqueNameToChannelNumber;
364
365// sdbusplus::bus::match::rules::arg0namespace() wants the prefix
366// to match without any trailing '.'
367constexpr const char ipmiDbusChannelMatch[] =
368 "xyz.openbmc_project.Ipmi.Channel";
369void updateOwners(sdbusplus::asio::connection& conn, const std::string& name)
370{
371 conn.async_method_call(
372 [name](const boost::system::error_code ec,
373 const std::string& nameOwner) {
Patrick Williams1318a5e2024-08-16 15:19:54 -0400374 if (ec)
375 {
376 lg2::error("Error getting dbus owner for {INTERFACE}",
377 "INTERFACE", name);
378 return;
379 }
380 // start after ipmiDbusChannelPrefix (after the '.')
381 std::string chName =
382 name.substr(std::strlen(ipmiDbusChannelMatch) + 1);
383 try
384 {
385 uint8_t channel = getChannelByName(chName);
386 uniqueNameToChannelNumber[nameOwner] = channel;
387 lg2::info(
388 "New interface mapping: {INTERFACE} -> channel {CHANNEL}",
389 "INTERFACE", name, "CHANNEL", channel);
390 }
391 catch (const std::exception& e)
392 {
393 lg2::info("Failed interface mapping, no such name: {INTERFACE}",
394 "INTERFACE", name);
395 }
396 },
Vernon Mauery735ee952019-02-15 13:38:52 -0800397 "org.freedesktop.DBus", "/", "org.freedesktop.DBus", "GetNameOwner",
398 name);
399}
400
Jayanth Othayoth9f3073a2024-12-08 09:29:43 -0600401void doListNames(sdbusplus::asio::connection& conn)
Vernon Mauery735ee952019-02-15 13:38:52 -0800402{
403 conn.async_method_call(
Jayanth Othayoth9f3073a2024-12-08 09:29:43 -0600404 [&conn](const boost::system::error_code ec,
405 std::vector<std::string> busNames) {
Patrick Williams1318a5e2024-08-16 15:19:54 -0400406 if (ec)
Vernon Mauery735ee952019-02-15 13:38:52 -0800407 {
Patrick Williams1318a5e2024-08-16 15:19:54 -0400408 lg2::error("Error getting dbus names: {ERROR}", "ERROR",
409 ec.message());
410 std::exit(EXIT_FAILURE);
411 return;
Vernon Mauery735ee952019-02-15 13:38:52 -0800412 }
Patrick Williams1318a5e2024-08-16 15:19:54 -0400413 // Try to make startup consistent
414 std::sort(busNames.begin(), busNames.end());
415
416 const std::string channelPrefix =
417 std::string(ipmiDbusChannelMatch) + ".";
418 for (const std::string& busName : busNames)
419 {
420 if (busName.find(channelPrefix) == 0)
421 {
422 updateOwners(conn, busName);
423 }
424 }
425 },
Vernon Mauery735ee952019-02-15 13:38:52 -0800426 "org.freedesktop.DBus", "/org/freedesktop/DBus", "org.freedesktop.DBus",
427 "ListNames");
428}
429
Patrick Williams5d82f472022-07-22 19:26:53 -0500430void nameChangeHandler(sdbusplus::message_t& message)
Vernon Mauery735ee952019-02-15 13:38:52 -0800431{
432 std::string name;
433 std::string oldOwner;
434 std::string newOwner;
435
436 message.read(name, oldOwner, newOwner);
437
438 if (!oldOwner.empty())
439 {
440 if (boost::starts_with(oldOwner, ":"))
441 {
442 // Connection removed
443 auto it = uniqueNameToChannelNumber.find(oldOwner);
444 if (it != uniqueNameToChannelNumber.end())
445 {
446 uniqueNameToChannelNumber.erase(it);
447 }
448 }
449 }
450 if (!newOwner.empty())
451 {
452 // start after ipmiDbusChannelMatch (and after the '.')
453 std::string chName = name.substr(std::strlen(ipmiDbusChannelMatch) + 1);
454 try
455 {
456 uint8_t channel = getChannelByName(chName);
457 uniqueNameToChannelNumber[newOwner] = channel;
Vernon Mauerye808bae2024-05-31 14:55:36 -0700458 lg2::info("New interface mapping: {INTERFACE} -> channel {CHANNEL}",
459 "INTERFACE", name, "CHANNEL", channel);
Vernon Mauery735ee952019-02-15 13:38:52 -0800460 }
461 catch (const std::exception& e)
462 {
Vernon Mauerye808bae2024-05-31 14:55:36 -0700463 lg2::info("Failed interface mapping, no such name: {INTERFACE}",
464 "INTERFACE", name);
Vernon Mauery735ee952019-02-15 13:38:52 -0800465 }
466 }
467};
468
469} // anonymous namespace
470
471static constexpr const char intraBmcName[] = "INTRABMC";
Patrick Williams5d82f472022-07-22 19:26:53 -0500472uint8_t channelFromMessage(sdbusplus::message_t& msg)
Vernon Mauery735ee952019-02-15 13:38:52 -0800473{
474 // channel name for ipmitool to resolve to
475 std::string sender = msg.get_sender();
476 auto chIter = uniqueNameToChannelNumber.find(sender);
477 if (chIter != uniqueNameToChannelNumber.end())
478 {
479 return chIter->second;
480 }
481 // FIXME: currently internal connections are ephemeral and hard to pin down
482 try
483 {
484 return getChannelByName(intraBmcName);
485 }
486 catch (const std::exception& e)
487 {
488 return invalidChannel;
489 }
490} // namespace ipmi
491
Vernon Mauery240b1862018-10-08 12:05:16 -0700492/* called from sdbus async server context */
Patrick Williams5d82f472022-07-22 19:26:53 -0500493auto executionEntry(boost::asio::yield_context yield, sdbusplus::message_t& m,
494 NetFn netFn, uint8_t lun, Cmd cmd, ipmi::SecureBuffer& data,
Vernon Mauery240b1862018-10-08 12:05:16 -0700495 std::map<std::string, ipmi::Value>& options)
496{
Vernon Mauery735ee952019-02-15 13:38:52 -0800497 const auto dbusResponse =
Vernon Mauery997952a2021-07-30 14:06:14 -0700498 [netFn, lun, cmd](Cc cc, const ipmi::SecureBuffer& data = {}) {
Patrick Williams1318a5e2024-08-16 15:19:54 -0400499 constexpr uint8_t netFnResponse = 0x01;
500 uint8_t retNetFn = netFn | netFnResponse;
501 return std::make_tuple(retNetFn, lun, cmd, cc, data);
502 };
Vernon Mauery735ee952019-02-15 13:38:52 -0800503 std::string sender = m.get_sender();
504 Privilege privilege = Privilege::None;
Vernon Maueryd6a2da02019-04-09 16:00:46 -0700505 int rqSA = 0;
Kumar Thangavelf7d081f2020-08-19 20:41:18 +0530506 int hostIdx = 0;
Vernon Mauery735ee952019-02-15 13:38:52 -0800507 uint8_t userId = 0; // undefined user
Rajashekar Gade Reddy4d226402019-11-13 17:13:05 +0530508 uint32_t sessionId = 0;
Vernon Mauery735ee952019-02-15 13:38:52 -0800509
510 // figure out what channel the request came in on
511 uint8_t channel = channelFromMessage(m);
512 if (channel == invalidChannel)
513 {
514 // unknown sender channel; refuse to service the request
Vernon Mauerye808bae2024-05-31 14:55:36 -0700515 lg2::error("ERROR determining source IPMI channel from "
516 "{SENDER} NetFn/Cmd {NETFN}/{CMD}",
517 "SENDER", sender, "NETFN", lg2::hex, netFn, "CMD", lg2::hex,
518 cmd);
Vernon Mauery735ee952019-02-15 13:38:52 -0800519 return dbusResponse(ipmi::ccDestinationUnavailable);
520 }
521
Rajashekar Gade Reddy4d226402019-11-13 17:13:05 +0530522 // session-based channels are required to provide userId, privilege and
523 // sessionId
Vernon Mauery735ee952019-02-15 13:38:52 -0800524 if (getChannelSessionSupport(channel) != EChannelSessSupported::none)
525 {
526 try
527 {
528 Value requestPriv = options.at("privilege");
529 Value requestUserId = options.at("userId");
Rajashekar Gade Reddy4d226402019-11-13 17:13:05 +0530530 Value requestSessionId = options.at("currentSessionId");
Vernon Mauery735ee952019-02-15 13:38:52 -0800531 privilege = static_cast<Privilege>(std::get<int>(requestPriv));
532 userId = static_cast<uint8_t>(std::get<int>(requestUserId));
Rajashekar Gade Reddy4d226402019-11-13 17:13:05 +0530533 sessionId =
534 static_cast<uint32_t>(std::get<uint32_t>(requestSessionId));
Vernon Mauery735ee952019-02-15 13:38:52 -0800535 }
536 catch (const std::exception& e)
537 {
Vernon Mauerye808bae2024-05-31 14:55:36 -0700538 lg2::error("ERROR determining IPMI session credentials on "
539 "channel {CHANNEL} for userid {USERID}",
540 "CHANNEL", channel, "USERID", userId, "NETFN", lg2::hex,
541 netFn, "CMD", lg2::hex, cmd);
Vernon Mauery735ee952019-02-15 13:38:52 -0800542 return dbusResponse(ipmi::ccUnspecifiedError);
543 }
544 }
545 else
546 {
547 // get max privilege for session-less channels
548 // For now, there is not a way to configure this, default to Admin
549 privilege = Privilege::Admin;
Vernon Maueryd6a2da02019-04-09 16:00:46 -0700550
551 // ipmb should supply rqSA
552 ChannelInfo chInfo;
553 getChannelInfo(channel, chInfo);
554 if (static_cast<EChannelMediumType>(chInfo.mediumType) ==
555 EChannelMediumType::ipmb)
556 {
557 const auto iter = options.find("rqSA");
558 if (iter != options.end())
559 {
560 if (std::holds_alternative<int>(iter->second))
561 {
562 rqSA = std::get<int>(iter->second);
563 }
564 }
Kumar Thangavelf7d081f2020-08-19 20:41:18 +0530565 const auto iteration = options.find("hostId");
566 if (iteration != options.end())
567 {
568 if (std::holds_alternative<int>(iteration->second))
569 {
570 hostIdx = std::get<int>(iteration->second);
571 }
572 }
Vernon Maueryd6a2da02019-04-09 16:00:46 -0700573 }
Vernon Mauery735ee952019-02-15 13:38:52 -0800574 }
575 // check to see if the requested priv/username is valid
Vernon Mauerye808bae2024-05-31 14:55:36 -0700576 lg2::debug("Set up ipmi context: Ch:NetFn/Cmd={CHANNEL}:{NETFN}/{CMD}",
577 "SENDER", sender, "NETFN", lg2::hex, netFn, "LUN", lg2::hex, lun,
578 "CMD", lg2::hex, cmd, "CHANNEL", channel, "USERID", userId,
579 "SESSIONID", lg2::hex, sessionId, "PRIVILEGE",
580 static_cast<uint8_t>(privilege), "RQSA", lg2::hex, rqSA);
Vernon Mauery735ee952019-02-15 13:38:52 -0800581
Patrick Williams1318a5e2024-08-16 15:19:54 -0400582 auto ctx = std::make_shared<ipmi::Context>(
583 getSdBus(), netFn, lun, cmd, channel, userId, sessionId, privilege,
584 rqSA, hostIdx, yield);
Vernon Mauery240b1862018-10-08 12:05:16 -0700585 auto request = std::make_shared<ipmi::message::Request>(
Vernon Mauery997952a2021-07-30 14:06:14 -0700586 ctx, std::forward<ipmi::SecureBuffer>(data));
Vernon Mauery240b1862018-10-08 12:05:16 -0700587 message::Response::ptr response = executeIpmiCommand(request);
588
Vernon Mauery735ee952019-02-15 13:38:52 -0800589 return dbusResponse(response->cc, response->payload.raw);
Vernon Mauery240b1862018-10-08 12:05:16 -0700590}
591
592/** @struct IpmiProvider
593 *
594 * RAII wrapper for dlopen so that dlclose gets called on exit
595 */
596struct IpmiProvider
597{
598 public:
599 /** @brief address of the opened library */
600 void* addr;
601 std::string name;
602
603 IpmiProvider() = delete;
604 IpmiProvider(const IpmiProvider&) = delete;
605 IpmiProvider& operator=(const IpmiProvider&) = delete;
606 IpmiProvider(IpmiProvider&&) = delete;
607 IpmiProvider& operator=(IpmiProvider&&) = delete;
608
609 /** @brief dlopen a shared object file by path
610 * @param[in] filename - path of shared object to open
611 */
612 explicit IpmiProvider(const char* fname) : addr(nullptr), name(fname)
613 {
Vernon Mauerye808bae2024-05-31 14:55:36 -0700614 lg2::debug("Open IPMI provider library: {PROVIDER}", "PROVIDER", name);
Vernon Mauery240b1862018-10-08 12:05:16 -0700615 try
616 {
617 addr = dlopen(name.c_str(), RTLD_NOW);
618 }
Patrick Williamsa2ad2da2021-10-06 12:21:46 -0500619 catch (const std::exception& e)
Vernon Mauery240b1862018-10-08 12:05:16 -0700620 {
Vernon Mauerye808bae2024-05-31 14:55:36 -0700621 lg2::error("ERROR opening IPMI provider {PROVIDER}: {ERROR}",
622 "PROVIDER", name, "ERROR", e);
Vernon Mauery240b1862018-10-08 12:05:16 -0700623 }
624 catch (...)
625 {
Vernon Mauery03d7a4b2021-01-19 11:22:17 -0800626 const char* what = currentExceptionType();
Vernon Mauerye808bae2024-05-31 14:55:36 -0700627 lg2::error("ERROR opening IPMI provider {PROVIDER}: {ERROR}",
628 "PROVIDER", name, "ERROR", what);
Vernon Mauery240b1862018-10-08 12:05:16 -0700629 }
630 if (!isOpen())
631 {
Vernon Mauerye808bae2024-05-31 14:55:36 -0700632 lg2::error("ERROR opening IPMI provider {PROVIDER}: {ERROR}",
633 "PROVIDER", name, "ERROR", dlerror());
Vernon Mauery240b1862018-10-08 12:05:16 -0700634 }
635 }
636
637 ~IpmiProvider()
638 {
639 if (isOpen())
640 {
641 dlclose(addr);
642 }
643 }
644 bool isOpen() const
645 {
646 return (nullptr != addr);
647 }
648};
649
650// Plugin libraries need to contain .so either at the end or in the middle
651constexpr const char ipmiPluginExtn[] = ".so";
652
653/* return a list of self-closing library handles */
654std::forward_list<IpmiProvider> loadProviders(const fs::path& ipmiLibsPath)
655{
656 std::vector<fs::path> libs;
657 for (const auto& libPath : fs::directory_iterator(ipmiLibsPath))
658 {
Vernon Maueryb0ab5fe2019-03-06 14:03:00 -0800659 std::error_code ec;
Vernon Mauery240b1862018-10-08 12:05:16 -0700660 fs::path fname = libPath.path();
Vernon Maueryb0ab5fe2019-03-06 14:03:00 -0800661 if (fs::is_symlink(fname, ec) || ec)
662 {
663 // it's a symlink or some other error; skip it
664 continue;
665 }
Vernon Mauery240b1862018-10-08 12:05:16 -0700666 while (fname.has_extension())
667 {
668 fs::path extn = fname.extension();
669 if (extn == ipmiPluginExtn)
670 {
671 libs.push_back(libPath.path());
672 break;
673 }
674 fname.replace_extension();
675 }
676 }
677 std::sort(libs.begin(), libs.end());
678
679 std::forward_list<IpmiProvider> handles;
680 for (auto& lib : libs)
681 {
682#ifdef __IPMI_DEBUG__
Vernon Mauerye808bae2024-05-31 14:55:36 -0700683 lg2::debug("Registering handler {HANDLER}", "HANDLER", lib);
Vernon Mauery240b1862018-10-08 12:05:16 -0700684#endif
685 handles.emplace_front(lib.c_str());
686 }
687 return handles;
688}
689
690} // namespace ipmi
691
Vernon Mauery240b1862018-10-08 12:05:16 -0700692#ifdef ALLOW_DEPRECATED_API
693/* legacy registration */
694void ipmi_register_callback(ipmi_netfn_t netFn, ipmi_cmd_t cmd,
695 ipmi_context_t context, ipmid_callback_t handler,
696 ipmi_cmd_privilege_t priv)
697{
Vernon Mauerybe376302019-03-21 13:02:05 -0700698 auto h = ipmi::makeLegacyHandler(handler, context);
Vernon Mauery240b1862018-10-08 12:05:16 -0700699 // translate priv from deprecated enum to current
700 ipmi::Privilege realPriv;
701 switch (priv)
702 {
703 case PRIVILEGE_CALLBACK:
704 realPriv = ipmi::Privilege::Callback;
705 break;
706 case PRIVILEGE_USER:
707 realPriv = ipmi::Privilege::User;
708 break;
709 case PRIVILEGE_OPERATOR:
710 realPriv = ipmi::Privilege::Operator;
711 break;
712 case PRIVILEGE_ADMIN:
713 realPriv = ipmi::Privilege::Admin;
714 break;
715 case PRIVILEGE_OEM:
716 realPriv = ipmi::Privilege::Oem;
717 break;
718 case SYSTEM_INTERFACE:
719 realPriv = ipmi::Privilege::Admin;
720 break;
721 default:
722 realPriv = ipmi::Privilege::Admin;
723 break;
724 }
Vernon Mauerye8d43232019-03-26 16:23:43 -0700725 // The original ipmi_register_callback allowed for group OEM handlers
726 // to be registered via this same interface. It just so happened that
727 // all the handlers were part of the DCMI group, so default to that.
728 if (netFn == NETFUN_GRPEXT)
729 {
Vernon Mauery82cffcc2023-07-27 10:59:20 -0700730 ipmi::impl::registerGroupHandler(ipmi::prioOpenBmcBase, ipmi::groupDCMI,
731 cmd, realPriv, h);
Vernon Mauerye8d43232019-03-26 16:23:43 -0700732 }
733 else
734 {
735 ipmi::impl::registerHandler(ipmi::prioOpenBmcBase, netFn, cmd, realPriv,
736 h);
737 }
Vernon Mauery240b1862018-10-08 12:05:16 -0700738}
739
Vernon Maueryf984a012018-10-08 12:05:18 -0700740namespace oem
741{
742
743class LegacyRouter : public oem::Router
744{
745 public:
Patrick Williamsfbc6c9d2023-05-10 07:50:16 -0500746 virtual ~LegacyRouter() {}
Vernon Maueryf984a012018-10-08 12:05:18 -0700747
748 /// Enable message routing to begin.
Patrick Williamsfbc6c9d2023-05-10 07:50:16 -0500749 void activate() override {}
Vernon Maueryf984a012018-10-08 12:05:18 -0700750
751 void registerHandler(Number oen, ipmi_cmd_t cmd, Handler handler) override
752 {
753 auto h = ipmi::makeLegacyHandler(std::forward<Handler>(handler));
754 ipmi::impl::registerOemHandler(ipmi::prioOpenBmcBase, oen, cmd,
755 ipmi::Privilege::Admin, h);
756 }
757};
758static LegacyRouter legacyRouter;
759
760Router* mutableRouter()
761{
762 return &legacyRouter;
763}
764
765} // namespace oem
766
Vernon Mauery240b1862018-10-08 12:05:16 -0700767/* legacy alternative to executionEntry */
Patrick Williams5d82f472022-07-22 19:26:53 -0500768void handleLegacyIpmiCommand(sdbusplus::message_t& m)
Vernon Mauery240b1862018-10-08 12:05:16 -0700769{
Vernon Mauery23b70212019-05-08 15:19:05 -0700770 // make a copy so the next two moves don't wreak havoc on the stack
Patrick Williams5d82f472022-07-22 19:26:53 -0500771 sdbusplus::message_t b{m};
Ed Tanous98605052025-02-13 16:57:13 -0800772 boost::asio::spawn(
Jayanth Othayoth531223f2024-11-11 07:30:15 -0600773 *getIoContext(),
774 [b = std::move(b)](boost::asio::yield_context yield) {
775 sdbusplus::message_t m{std::move(b)};
776 unsigned char seq = 0, netFn = 0, lun = 0, cmd = 0;
777 ipmi::SecureBuffer data;
Vernon Mauery240b1862018-10-08 12:05:16 -0700778
Jayanth Othayoth531223f2024-11-11 07:30:15 -0600779 m.read(seq, netFn, lun, cmd, data);
780 std::shared_ptr<sdbusplus::asio::connection> bus = getSdBus();
781 auto ctx = std::make_shared<ipmi::Context>(
782 bus, netFn, lun, cmd, 0, 0, 0, ipmi::Privilege::Admin, 0, 0,
783 yield);
784 auto request = std::make_shared<ipmi::message::Request>(
785 ctx, std::forward<ipmi::SecureBuffer>(data));
786 ipmi::message::Response::ptr response =
787 ipmi::executeIpmiCommand(request);
Vernon Mauery240b1862018-10-08 12:05:16 -0700788
Jayanth Othayoth531223f2024-11-11 07:30:15 -0600789 // Responses in IPMI require a bit set. So there ya go...
790 netFn |= 0x01;
Vernon Mauery240b1862018-10-08 12:05:16 -0700791
Jayanth Othayoth531223f2024-11-11 07:30:15 -0600792 constexpr const char* DBUS_INTF = "org.openbmc.HostIpmi";
Vernon Mauery240b1862018-10-08 12:05:16 -0700793
George Liude1420d2025-03-03 15:14:25 +0800794 std::string dest = m.get_sender();
795 std::string path = m.get_path();
796 boost::system::error_code ec = ipmi::callDbusMethod(
797 ctx, dest, path, DBUS_INTF, "sendMessage", seq, netFn, lun, cmd,
798 response->cc, response->payload.raw);
799
Jayanth Othayoth531223f2024-11-11 07:30:15 -0600800 if (ec)
801 {
802 lg2::error(
803 "Failed to send response to requestor ({NETFN}/{CMD}): {ERROR}",
804 "ERROR", ec.message(), "SENDER", dest, "NETFN", lg2::hex,
805 netFn, "CMD", lg2::hex, cmd);
806 }
807 },
Ed Tanous98605052025-02-13 16:57:13 -0800808 boost::asio::detached);
Vernon Mauery240b1862018-10-08 12:05:16 -0700809}
810
811#endif /* ALLOW_DEPRECATED_API */
812
813// Calls host command manager to do the right thing for the command
814using CommandHandler = phosphor::host::command::CommandHandler;
815std::unique_ptr<phosphor::host::command::Manager> cmdManager;
816void ipmid_send_cmd_to_host(CommandHandler&& cmd)
817{
Vernon Mauery5e096a22022-06-01 15:11:16 -0700818 cmdManager->execute(std::forward<CommandHandler>(cmd));
Vernon Mauery240b1862018-10-08 12:05:16 -0700819}
820
821std::unique_ptr<phosphor::host::command::Manager>& ipmid_get_host_cmd_manager()
822{
823 return cmdManager;
824}
825
Vernon Mauery20ff3332019-03-01 16:52:25 -0800826// These are symbols that are present in libipmid, but not expected
827// to be used except here (or maybe a unit test), so declare them here
828extern void setIoContext(std::shared_ptr<boost::asio::io_context>& newIo);
829extern void setSdBus(std::shared_ptr<sdbusplus::asio::connection>& newBus);
830
Vernon Mauery240b1862018-10-08 12:05:16 -0700831int main(int argc, char* argv[])
832{
833 // Connect to system bus
Vernon Mauery20ff3332019-03-01 16:52:25 -0800834 auto io = std::make_shared<boost::asio::io_context>();
835 setIoContext(io);
Vernon Mauery240b1862018-10-08 12:05:16 -0700836 if (argc > 1 && std::string(argv[1]) == "-session")
837 {
838 sd_bus_default_user(&bus);
839 }
840 else
841 {
842 sd_bus_default_system(&bus);
843 }
Vernon Mauery20ff3332019-03-01 16:52:25 -0800844 auto sdbusp = std::make_shared<sdbusplus::asio::connection>(*io, bus);
845 setSdBus(sdbusp);
Vernon Mauery240b1862018-10-08 12:05:16 -0700846
Patrick Williams3b301a32025-02-03 13:05:36 -0500847 // TODO: Hack to keep the sdEvents running.... Not sure why the sd_event
848 // queue stops running if we don't have a timer that keeps re-arming
849 sdbusplus::Timer t2([]() { ; });
850 t2.start(std::chrono::microseconds(500000), true);
851
852 // TODO: Remove all vestiges of sd_event from phosphor-host-ipmid
853 // until that is done, add the sd_event wrapper to the io object
854 sdbusplus::asio::sd_event_wrapper sdEvents(*io);
855
Vernon Mauery240b1862018-10-08 12:05:16 -0700856 cmdManager = std::make_unique<phosphor::host::command::Manager>(*sdbusp);
857
858 // Register all command providers and filters
Vernon Mauery4ec4e402019-03-20 13:09:27 -0700859 std::forward_list<ipmi::IpmiProvider> providers =
860 ipmi::loadProviders(HOST_IPMI_LIB_PATH);
Vernon Mauery240b1862018-10-08 12:05:16 -0700861
Vernon Mauery240b1862018-10-08 12:05:16 -0700862#ifdef ALLOW_DEPRECATED_API
863 // listen on deprecated signal interface for kcs/bt commands
864 constexpr const char* FILTER = "type='signal',interface='org.openbmc."
865 "HostIpmi',member='ReceivedMessage'";
Patrick Williams5d82f472022-07-22 19:26:53 -0500866 sdbusplus::bus::match_t oldIpmiInterface(*sdbusp, FILTER,
867 handleLegacyIpmiCommand);
Vernon Mauery240b1862018-10-08 12:05:16 -0700868#endif /* ALLOW_DEPRECATED_API */
869
Vernon Mauery735ee952019-02-15 13:38:52 -0800870 // set up bus name watching to match channels with bus names
Patrick Williams5d82f472022-07-22 19:26:53 -0500871 sdbusplus::bus::match_t nameOwnerChanged(
Vernon Mauery735ee952019-02-15 13:38:52 -0800872 *sdbusp,
873 sdbusplus::bus::match::rules::nameOwnerChanged() +
874 sdbusplus::bus::match::rules::arg0namespace(
875 ipmi::ipmiDbusChannelMatch),
876 ipmi::nameChangeHandler);
Jayanth Othayoth9f3073a2024-12-08 09:29:43 -0600877 ipmi::doListNames(*sdbusp);
Vernon Mauery735ee952019-02-15 13:38:52 -0800878
James Feistb0094a72019-11-26 09:07:15 -0800879 int exitCode = 0;
Vernon Mauery1b7f6f22019-03-13 13:11:25 -0700880 // set up boost::asio signal handling
Patrick Williams1318a5e2024-08-16 15:19:54 -0400881 std::function<SignalResponse(int)> stopAsioRunLoop = [&io, &exitCode](
882 int signalNumber) {
Vernon Mauerye808bae2024-05-31 14:55:36 -0700883 lg2::info("Received signal {SIGNAL}; quitting", "SIGNAL", signalNumber);
Patrick Williamsfbc6c9d2023-05-10 07:50:16 -0500884 io->stop();
885 exitCode = signalNumber;
886 return SignalResponse::breakExecution;
887 };
Vernon Mauery1b7f6f22019-03-13 13:11:25 -0700888 registerSignalHandler(ipmi::prioOpenBmcBase, SIGINT, stopAsioRunLoop);
889 registerSignalHandler(ipmi::prioOpenBmcBase, SIGTERM, stopAsioRunLoop);
890
Richard Marian Thomaiyar369406e2020-01-09 14:56:54 +0530891 sdbusp->request_name("xyz.openbmc_project.Ipmi.Host");
892 // Add bindings for inbound IPMI requests
893 auto server = sdbusplus::asio::object_server(sdbusp);
894 auto iface = server.add_interface("/xyz/openbmc_project/Ipmi",
895 "xyz.openbmc_project.Ipmi.Server");
896 iface->register_method("execute", ipmi::executionEntry);
897 iface->initialize();
898
Vernon Mauery240b1862018-10-08 12:05:16 -0700899 io->run();
900
Vernon Mauery1b7f6f22019-03-13 13:11:25 -0700901 // destroy all the IPMI handlers so the providers can unload safely
902 ipmi::handlerMap.clear();
903 ipmi::groupHandlerMap.clear();
904 ipmi::oemHandlerMap.clear();
905 ipmi::filterList.clear();
906 // unload the provider libraries
Vernon Mauery4ec4e402019-03-20 13:09:27 -0700907 providers.clear();
Vernon Mauery1b7f6f22019-03-13 13:11:25 -0700908
James Feistb0094a72019-11-26 09:07:15 -0800909 std::exit(exitCode);
Vernon Mauery240b1862018-10-08 12:05:16 -0700910}