blob: 23a8399eb6f2f47ecf8b2b7430469d2957ec99bd [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
Ed Tanous98605052025-02-13 16:57:13 -080022#include <boost/asio/detached.hpp>
Ed Tanous778418d2020-08-17 23:20:21 -070023#include <boost/asio/io_context.hpp>
Ed Tanous26a386f2025-02-13 16:57:13 -080024#include <boost/asio/spawn.hpp>
Vernon Mauery240b1862018-10-08 12:05:16 -070025#include <host-cmd-manager.hpp>
26#include <ipmid-host/cmd.hpp>
27#include <ipmid/api.hpp>
28#include <ipmid/handler.hpp>
29#include <ipmid/message.hpp>
30#include <ipmid/oemrouter.hpp>
Vernon Mauery33250242019-03-12 16:49:26 -070031#include <ipmid/types.hpp>
George Liude1420d2025-03-03 15:14:25 +080032#include <ipmid/utils.hpp>
Vernon Mauerye808bae2024-05-31 14:55:36 -070033#include <phosphor-logging/lg2.hpp>
Vernon Mauery240b1862018-10-08 12:05:16 -070034#include <sdbusplus/asio/connection.hpp>
35#include <sdbusplus/asio/object_server.hpp>
Patrick Williams3b301a32025-02-03 13:05:36 -050036#include <sdbusplus/asio/sd_event.hpp>
Vernon Mauery240b1862018-10-08 12:05:16 -070037#include <sdbusplus/bus.hpp>
38#include <sdbusplus/bus/match.hpp>
39#include <sdbusplus/timer.hpp>
Patrick Williamsfbc6c9d2023-05-10 07:50:16 -050040
41#include <algorithm>
42#include <any>
43#include <exception>
44#include <filesystem>
45#include <forward_list>
46#include <map>
47#include <memory>
48#include <optional>
Vernon Mauery240b1862018-10-08 12:05:16 -070049#include <tuple>
Vernon Mauery240b1862018-10-08 12:05:16 -070050#include <unordered_map>
51#include <utility>
52#include <vector>
53
Vernon Mauery240b1862018-10-08 12:05:16 -070054namespace fs = std::filesystem;
55
56using namespace phosphor::logging;
57
Vernon Mauery240b1862018-10-08 12:05:16 -070058// IPMI Spec, shared Reservation ID.
59static unsigned short selReservationID = 0xFFFF;
60static bool selReservationValid = false;
61
62unsigned short reserveSel(void)
63{
64 // IPMI spec, Reservation ID, the value simply increases against each
65 // execution of the Reserve SEL command.
66 if (++selReservationID == 0)
67 {
68 selReservationID = 1;
69 }
70 selReservationValid = true;
71 return selReservationID;
72}
73
74bool checkSELReservation(unsigned short id)
75{
76 return (selReservationValid && selReservationID == id);
77}
78
79void cancelSELReservation(void)
80{
81 selReservationValid = false;
82}
83
84EInterfaceIndex getInterfaceIndex(void)
85{
86 return interfaceKCS;
87}
88
89sd_bus* bus;
Patrick Williams3b301a32025-02-03 13:05:36 -050090sd_event* events = nullptr;
91sd_event* ipmid_get_sd_event_connection(void)
92{
93 return events;
94}
Vernon Mauery240b1862018-10-08 12:05:16 -070095sd_bus* ipmid_get_sd_bus_connection(void)
96{
97 return bus;
98}
99
100namespace ipmi
101{
102
103static inline unsigned int makeCmdKey(unsigned int cluster, unsigned int cmd)
104{
105 return (cluster << 8) | cmd;
106}
107
108using HandlerTuple = std::tuple<int, /* prio */
109 Privilege, HandlerBase::ptr /* handler */
110 >;
111
112/* map to handle standard registered commands */
113static std::unordered_map<unsigned int, /* key is NetFn/Cmd */
114 HandlerTuple>
115 handlerMap;
116
Vernon Maueryf984a012018-10-08 12:05:18 -0700117/* special map for decoding Group registered commands (NetFn 2Ch) */
118static std::unordered_map<unsigned int, /* key is Group/Cmd (NetFn is 2Ch) */
119 HandlerTuple>
120 groupHandlerMap;
121
122/* special map for decoding OEM registered commands (NetFn 2Eh) */
123static std::unordered_map<unsigned int, /* key is Iana/Cmd (NetFn is 2Eh) */
124 HandlerTuple>
125 oemHandlerMap;
126
Vernon Mauery08a70aa2018-11-07 09:36:22 -0800127using FilterTuple = std::tuple<int, /* prio */
128 FilterBase::ptr /* filter */
129 >;
130
131/* list to hold all registered ipmi command filters */
132static std::forward_list<FilterTuple> filterList;
133
Vernon Mauery240b1862018-10-08 12:05:16 -0700134namespace impl
135{
136/* common function to register all standard IPMI handlers */
137bool registerHandler(int prio, NetFn netFn, Cmd cmd, Privilege priv,
138 HandlerBase::ptr handler)
139{
140 // check for valid NetFn: even; 00-0Ch, 30-3Eh
141 if (netFn & 1 || (netFn > netFnTransport && netFn < netFnGroup) ||
142 netFn > netFnOemEight)
143 {
144 return false;
145 }
146
147 // create key and value for this handler
148 unsigned int netFnCmd = makeCmdKey(netFn, cmd);
149 HandlerTuple item(prio, priv, handler);
150
151 // consult the handler map and look for a match
152 auto& mapCmd = handlerMap[netFnCmd];
153 if (!std::get<HandlerBase::ptr>(mapCmd) || std::get<int>(mapCmd) <= prio)
154 {
155 mapCmd = item;
156 return true;
157 }
158 return false;
159}
160
Vernon Maueryf984a012018-10-08 12:05:18 -0700161/* common function to register all Group IPMI handlers */
162bool registerGroupHandler(int prio, Group group, Cmd cmd, Privilege priv,
163 HandlerBase::ptr handler)
164{
165 // create key and value for this handler
166 unsigned int netFnCmd = makeCmdKey(group, cmd);
167 HandlerTuple item(prio, priv, handler);
168
169 // consult the handler map and look for a match
170 auto& mapCmd = groupHandlerMap[netFnCmd];
171 if (!std::get<HandlerBase::ptr>(mapCmd) || std::get<int>(mapCmd) <= prio)
172 {
173 mapCmd = item;
174 return true;
175 }
176 return false;
177}
178
179/* common function to register all OEM IPMI handlers */
180bool registerOemHandler(int prio, Iana iana, Cmd cmd, Privilege priv,
181 HandlerBase::ptr handler)
182{
183 // create key and value for this handler
184 unsigned int netFnCmd = makeCmdKey(iana, cmd);
185 HandlerTuple item(prio, priv, handler);
186
187 // consult the handler map and look for a match
188 auto& mapCmd = oemHandlerMap[netFnCmd];
189 if (!std::get<HandlerBase::ptr>(mapCmd) || std::get<int>(mapCmd) <= prio)
190 {
191 mapCmd = item;
Vernon Mauerye808bae2024-05-31 14:55:36 -0700192 lg2::debug("registered OEM Handler: NetFn/Cmd={NETFNCMD}", "IANA",
193 lg2::hex, iana, "CMD", lg2::hex, cmd, "NETFNCMD", lg2::hex,
194 netFnCmd);
Vernon Maueryf984a012018-10-08 12:05:18 -0700195 return true;
196 }
Alexander Hansen7197b342023-09-06 11:45:15 +0200197
Vernon Mauerye808bae2024-05-31 14:55:36 -0700198 lg2::warning("could not register OEM Handler: NetFn/Cmd={NETFNCMD}", "IANA",
199 lg2::hex, iana, "CMD", lg2::hex, cmd, "NETFNCMD", lg2::hex,
200 netFnCmd);
Vernon Maueryf984a012018-10-08 12:05:18 -0700201 return false;
202}
203
Vernon Mauery08a70aa2018-11-07 09:36:22 -0800204/* common function to register all IPMI filter handlers */
205void registerFilter(int prio, FilterBase::ptr filter)
206{
207 // check for initial placement
208 if (filterList.empty() || std::get<int>(filterList.front()) < prio)
209 {
210 filterList.emplace_front(std::make_tuple(prio, filter));
Yong Libe063232021-03-04 16:52:52 +0800211 return;
Vernon Mauery08a70aa2018-11-07 09:36:22 -0800212 }
213 // walk the list and put it in the right place
214 auto j = filterList.begin();
215 for (auto i = j; i != filterList.end() && std::get<int>(*i) > prio; i++)
216 {
217 j = i;
218 }
219 filterList.emplace_after(j, std::make_tuple(prio, filter));
220}
221
Vernon Mauery240b1862018-10-08 12:05:16 -0700222} // namespace impl
223
Vernon Mauery08a70aa2018-11-07 09:36:22 -0800224message::Response::ptr filterIpmiCommand(message::Request::ptr request)
225{
226 // pass the command through the filter mechanism
227 // This can be the firmware firewall or any OEM mechanism like
228 // whitelist filtering based on operational mode
229 for (auto& item : filterList)
230 {
231 FilterBase::ptr filter = std::get<FilterBase::ptr>(item);
232 ipmi::Cc cc = filter->call(request);
233 if (ipmi::ccSuccess != cc)
234 {
235 return errorResponse(request, cc);
236 }
237 }
238 return message::Response::ptr();
239}
240
Vernon Mauery240b1862018-10-08 12:05:16 -0700241message::Response::ptr executeIpmiCommandCommon(
242 std::unordered_map<unsigned int, HandlerTuple>& handlers,
243 unsigned int keyCommon, message::Request::ptr request)
244{
Vernon Mauery08a70aa2018-11-07 09:36:22 -0800245 // filter the command first; a non-null message::Response::ptr
246 // means that the message has been rejected for some reason
Vernon Mauery51f78142020-01-13 16:28:59 -0800247 message::Response::ptr filterResponse = filterIpmiCommand(request);
Vernon Mauery08a70aa2018-11-07 09:36:22 -0800248
Vernon Mauery240b1862018-10-08 12:05:16 -0700249 Cmd cmd = request->ctx->cmd;
250 unsigned int key = makeCmdKey(keyCommon, cmd);
251 auto cmdIter = handlers.find(key);
252 if (cmdIter != handlers.end())
253 {
Vernon Mauery51f78142020-01-13 16:28:59 -0800254 // only return the filter response if the command is found
255 if (filterResponse)
256 {
Vernon Mauerye808bae2024-05-31 14:55:36 -0700257 lg2::debug("request for NetFn/Cmd {NETFN}/{CMD} has been filtered",
258 "NETFN", lg2::hex, keyCommon, "CMD", lg2::hex, cmd);
Vernon Mauery51f78142020-01-13 16:28:59 -0800259 return filterResponse;
260 }
Vernon Mauery240b1862018-10-08 12:05:16 -0700261 HandlerTuple& chosen = cmdIter->second;
262 if (request->ctx->priv < std::get<Privilege>(chosen))
263 {
264 return errorResponse(request, ccInsufficientPrivilege);
265 }
266 return std::get<HandlerBase::ptr>(chosen)->call(request);
267 }
268 else
269 {
270 unsigned int wildcard = makeCmdKey(keyCommon, cmdWildcard);
271 cmdIter = handlers.find(wildcard);
272 if (cmdIter != handlers.end())
273 {
Vernon Mauery51f78142020-01-13 16:28:59 -0800274 // only return the filter response if the command is found
275 if (filterResponse)
276 {
Vernon Mauerye808bae2024-05-31 14:55:36 -0700277 lg2::debug(
278 "request for NetFn/Cmd {NETFN}/{CMD} has been filtered",
279 "NETFN", lg2::hex, keyCommon, "CMD", lg2::hex, cmd);
Vernon Mauery51f78142020-01-13 16:28:59 -0800280 return filterResponse;
281 }
Vernon Mauery240b1862018-10-08 12:05:16 -0700282 HandlerTuple& chosen = cmdIter->second;
283 if (request->ctx->priv < std::get<Privilege>(chosen))
284 {
285 return errorResponse(request, ccInsufficientPrivilege);
286 }
287 return std::get<HandlerBase::ptr>(chosen)->call(request);
288 }
289 }
290 return errorResponse(request, ccInvalidCommand);
291}
292
Vernon Maueryf984a012018-10-08 12:05:18 -0700293message::Response::ptr executeIpmiGroupCommand(message::Request::ptr request)
294{
295 // look up the group for this request
William A. Kennington IIId10d9052019-04-24 01:57:36 -0700296 uint8_t bytes;
297 if (0 != request->payload.unpack(bytes))
Vernon Maueryf984a012018-10-08 12:05:18 -0700298 {
299 return errorResponse(request, ccReqDataLenInvalid);
300 }
William A. Kennington IIId10d9052019-04-24 01:57:36 -0700301 auto group = static_cast<Group>(bytes);
John Chung0a3f40b2025-01-22 18:07:52 -0600302 // Set defining body code
303 request->ctx->group = group;
Patrick Williams1318a5e2024-08-16 15:19:54 -0400304 message::Response::ptr response =
305 executeIpmiCommandCommon(groupHandlerMap, group, request);
William A. Kennington IIIda31f9a2019-04-25 01:36:32 -0700306 ipmi::message::Payload prefix;
307 prefix.pack(bytes);
308 response->prepend(prefix);
Vernon Maueryf984a012018-10-08 12:05:18 -0700309 return response;
310}
311
312message::Response::ptr executeIpmiOemCommand(message::Request::ptr request)
313{
314 // look up the iana for this request
William A. Kennington IIId10d9052019-04-24 01:57:36 -0700315 uint24_t bytes;
316 if (0 != request->payload.unpack(bytes))
Vernon Maueryf984a012018-10-08 12:05:18 -0700317 {
318 return errorResponse(request, ccReqDataLenInvalid);
319 }
William A. Kennington IIId10d9052019-04-24 01:57:36 -0700320 auto iana = static_cast<Iana>(bytes);
Alexander Hansen7197b342023-09-06 11:45:15 +0200321
Vernon Mauerye808bae2024-05-31 14:55:36 -0700322 lg2::debug("unpack IANA {IANA}", "IANA", lg2::hex, iana);
Alexander Hansen7197b342023-09-06 11:45:15 +0200323
Patrick Williams1318a5e2024-08-16 15:19:54 -0400324 message::Response::ptr response =
325 executeIpmiCommandCommon(oemHandlerMap, iana, request);
William A. Kennington IIIda31f9a2019-04-25 01:36:32 -0700326 ipmi::message::Payload prefix;
327 prefix.pack(bytes);
328 response->prepend(prefix);
Vernon Maueryf984a012018-10-08 12:05:18 -0700329 return response;
330}
331
Vernon Mauery240b1862018-10-08 12:05:16 -0700332message::Response::ptr executeIpmiCommand(message::Request::ptr request)
333{
334 NetFn netFn = request->ctx->netFn;
Vernon Maueryf984a012018-10-08 12:05:18 -0700335 if (netFnGroup == netFn)
336 {
337 return executeIpmiGroupCommand(request);
338 }
339 else if (netFnOem == netFn)
340 {
341 return executeIpmiOemCommand(request);
342 }
Vernon Mauery240b1862018-10-08 12:05:16 -0700343 return executeIpmiCommandCommon(handlerMap, netFn, request);
344}
345
Vernon Mauery735ee952019-02-15 13:38:52 -0800346namespace utils
347{
348template <typename AssocContainer, typename UnaryPredicate>
349void assoc_erase_if(AssocContainer& c, UnaryPredicate p)
350{
351 typename AssocContainer::iterator next = c.begin();
352 typename AssocContainer::iterator last = c.end();
353 while ((next = std::find_if(next, last, p)) != last)
354 {
355 c.erase(next++);
356 }
357}
358} // namespace utils
359
360namespace
361{
362std::unordered_map<std::string, uint8_t> uniqueNameToChannelNumber;
363
364// sdbusplus::bus::match::rules::arg0namespace() wants the prefix
365// to match without any trailing '.'
366constexpr const char ipmiDbusChannelMatch[] =
367 "xyz.openbmc_project.Ipmi.Channel";
368void updateOwners(sdbusplus::asio::connection& conn, const std::string& name)
369{
370 conn.async_method_call(
371 [name](const boost::system::error_code ec,
372 const std::string& nameOwner) {
Patrick Williams1318a5e2024-08-16 15:19:54 -0400373 if (ec)
374 {
375 lg2::error("Error getting dbus owner for {INTERFACE}",
376 "INTERFACE", name);
377 return;
378 }
379 // start after ipmiDbusChannelPrefix (after the '.')
380 std::string chName =
381 name.substr(std::strlen(ipmiDbusChannelMatch) + 1);
382 try
383 {
384 uint8_t channel = getChannelByName(chName);
385 uniqueNameToChannelNumber[nameOwner] = channel;
386 lg2::info(
387 "New interface mapping: {INTERFACE} -> channel {CHANNEL}",
388 "INTERFACE", name, "CHANNEL", channel);
389 }
390 catch (const std::exception& e)
391 {
392 lg2::info("Failed interface mapping, no such name: {INTERFACE}",
393 "INTERFACE", name);
394 }
395 },
Vernon Mauery735ee952019-02-15 13:38:52 -0800396 "org.freedesktop.DBus", "/", "org.freedesktop.DBus", "GetNameOwner",
397 name);
398}
399
Jayanth Othayoth9f3073a2024-12-08 09:29:43 -0600400void doListNames(sdbusplus::asio::connection& conn)
Vernon Mauery735ee952019-02-15 13:38:52 -0800401{
402 conn.async_method_call(
Jayanth Othayoth9f3073a2024-12-08 09:29:43 -0600403 [&conn](const boost::system::error_code ec,
404 std::vector<std::string> busNames) {
Patrick Williams1318a5e2024-08-16 15:19:54 -0400405 if (ec)
Vernon Mauery735ee952019-02-15 13:38:52 -0800406 {
Patrick Williams1318a5e2024-08-16 15:19:54 -0400407 lg2::error("Error getting dbus names: {ERROR}", "ERROR",
408 ec.message());
409 std::exit(EXIT_FAILURE);
410 return;
Vernon Mauery735ee952019-02-15 13:38:52 -0800411 }
Patrick Williams1318a5e2024-08-16 15:19:54 -0400412 // Try to make startup consistent
413 std::sort(busNames.begin(), busNames.end());
414
415 const std::string channelPrefix =
416 std::string(ipmiDbusChannelMatch) + ".";
417 for (const std::string& busName : busNames)
418 {
419 if (busName.find(channelPrefix) == 0)
420 {
421 updateOwners(conn, busName);
422 }
423 }
424 },
Vernon Mauery735ee952019-02-15 13:38:52 -0800425 "org.freedesktop.DBus", "/org/freedesktop/DBus", "org.freedesktop.DBus",
426 "ListNames");
427}
428
Patrick Williams5d82f472022-07-22 19:26:53 -0500429void nameChangeHandler(sdbusplus::message_t& message)
Vernon Mauery735ee952019-02-15 13:38:52 -0800430{
431 std::string name;
432 std::string oldOwner;
433 std::string newOwner;
434
435 message.read(name, oldOwner, newOwner);
436
437 if (!oldOwner.empty())
438 {
George Liuc024b392025-08-21 16:38:58 +0800439 if (oldOwner.starts_with(":"))
Vernon Mauery735ee952019-02-15 13:38:52 -0800440 {
441 // Connection removed
442 auto it = uniqueNameToChannelNumber.find(oldOwner);
443 if (it != uniqueNameToChannelNumber.end())
444 {
445 uniqueNameToChannelNumber.erase(it);
446 }
447 }
448 }
449 if (!newOwner.empty())
450 {
451 // start after ipmiDbusChannelMatch (and after the '.')
452 std::string chName = name.substr(std::strlen(ipmiDbusChannelMatch) + 1);
453 try
454 {
455 uint8_t channel = getChannelByName(chName);
456 uniqueNameToChannelNumber[newOwner] = channel;
Vernon Mauerye808bae2024-05-31 14:55:36 -0700457 lg2::info("New interface mapping: {INTERFACE} -> channel {CHANNEL}",
458 "INTERFACE", name, "CHANNEL", channel);
Vernon Mauery735ee952019-02-15 13:38:52 -0800459 }
460 catch (const std::exception& e)
461 {
Vernon Mauerye808bae2024-05-31 14:55:36 -0700462 lg2::info("Failed interface mapping, no such name: {INTERFACE}",
463 "INTERFACE", name);
Vernon Mauery735ee952019-02-15 13:38:52 -0800464 }
465 }
466};
467
468} // anonymous namespace
469
470static constexpr const char intraBmcName[] = "INTRABMC";
Patrick Williams5d82f472022-07-22 19:26:53 -0500471uint8_t channelFromMessage(sdbusplus::message_t& msg)
Vernon Mauery735ee952019-02-15 13:38:52 -0800472{
473 // channel name for ipmitool to resolve to
474 std::string sender = msg.get_sender();
475 auto chIter = uniqueNameToChannelNumber.find(sender);
476 if (chIter != uniqueNameToChannelNumber.end())
477 {
478 return chIter->second;
479 }
480 // FIXME: currently internal connections are ephemeral and hard to pin down
481 try
482 {
483 return getChannelByName(intraBmcName);
484 }
485 catch (const std::exception& e)
486 {
487 return invalidChannel;
488 }
489} // namespace ipmi
490
Vernon Mauery240b1862018-10-08 12:05:16 -0700491/* called from sdbus async server context */
Patrick Williams5d82f472022-07-22 19:26:53 -0500492auto executionEntry(boost::asio::yield_context yield, sdbusplus::message_t& m,
493 NetFn netFn, uint8_t lun, Cmd cmd, ipmi::SecureBuffer& data,
Vernon Mauery240b1862018-10-08 12:05:16 -0700494 std::map<std::string, ipmi::Value>& options)
495{
Vernon Mauery735ee952019-02-15 13:38:52 -0800496 const auto dbusResponse =
Vernon Mauery997952a2021-07-30 14:06:14 -0700497 [netFn, lun, cmd](Cc cc, const ipmi::SecureBuffer& data = {}) {
Patrick Williams1318a5e2024-08-16 15:19:54 -0400498 constexpr uint8_t netFnResponse = 0x01;
499 uint8_t retNetFn = netFn | netFnResponse;
500 return std::make_tuple(retNetFn, lun, cmd, cc, data);
501 };
Vernon Mauery735ee952019-02-15 13:38:52 -0800502 std::string sender = m.get_sender();
503 Privilege privilege = Privilege::None;
Vernon Maueryd6a2da02019-04-09 16:00:46 -0700504 int rqSA = 0;
Kumar Thangavelf7d081f2020-08-19 20:41:18 +0530505 int hostIdx = 0;
Vernon Mauery735ee952019-02-15 13:38:52 -0800506 uint8_t userId = 0; // undefined user
Rajashekar Gade Reddy4d226402019-11-13 17:13:05 +0530507 uint32_t sessionId = 0;
Vernon Mauery735ee952019-02-15 13:38:52 -0800508
509 // figure out what channel the request came in on
510 uint8_t channel = channelFromMessage(m);
511 if (channel == invalidChannel)
512 {
513 // unknown sender channel; refuse to service the request
Vernon Mauerye808bae2024-05-31 14:55:36 -0700514 lg2::error("ERROR determining source IPMI channel from "
515 "{SENDER} NetFn/Cmd {NETFN}/{CMD}",
516 "SENDER", sender, "NETFN", lg2::hex, netFn, "CMD", lg2::hex,
517 cmd);
Vernon Mauery735ee952019-02-15 13:38:52 -0800518 return dbusResponse(ipmi::ccDestinationUnavailable);
519 }
520
Rajashekar Gade Reddy4d226402019-11-13 17:13:05 +0530521 // session-based channels are required to provide userId, privilege and
522 // sessionId
Vernon Mauery735ee952019-02-15 13:38:52 -0800523 if (getChannelSessionSupport(channel) != EChannelSessSupported::none)
524 {
525 try
526 {
527 Value requestPriv = options.at("privilege");
528 Value requestUserId = options.at("userId");
Rajashekar Gade Reddy4d226402019-11-13 17:13:05 +0530529 Value requestSessionId = options.at("currentSessionId");
Vernon Mauery735ee952019-02-15 13:38:52 -0800530 privilege = static_cast<Privilege>(std::get<int>(requestPriv));
531 userId = static_cast<uint8_t>(std::get<int>(requestUserId));
Rajashekar Gade Reddy4d226402019-11-13 17:13:05 +0530532 sessionId =
533 static_cast<uint32_t>(std::get<uint32_t>(requestSessionId));
Vernon Mauery735ee952019-02-15 13:38:52 -0800534 }
535 catch (const std::exception& e)
536 {
Vernon Mauerye808bae2024-05-31 14:55:36 -0700537 lg2::error("ERROR determining IPMI session credentials on "
538 "channel {CHANNEL} for userid {USERID}",
539 "CHANNEL", channel, "USERID", userId, "NETFN", lg2::hex,
540 netFn, "CMD", lg2::hex, cmd);
Vernon Mauery735ee952019-02-15 13:38:52 -0800541 return dbusResponse(ipmi::ccUnspecifiedError);
542 }
543 }
544 else
545 {
546 // get max privilege for session-less channels
547 // For now, there is not a way to configure this, default to Admin
548 privilege = Privilege::Admin;
Vernon Maueryd6a2da02019-04-09 16:00:46 -0700549
550 // ipmb should supply rqSA
551 ChannelInfo chInfo;
552 getChannelInfo(channel, chInfo);
553 if (static_cast<EChannelMediumType>(chInfo.mediumType) ==
554 EChannelMediumType::ipmb)
555 {
556 const auto iter = options.find("rqSA");
557 if (iter != options.end())
558 {
559 if (std::holds_alternative<int>(iter->second))
560 {
561 rqSA = std::get<int>(iter->second);
562 }
563 }
Kumar Thangavelf7d081f2020-08-19 20:41:18 +0530564 const auto iteration = options.find("hostId");
565 if (iteration != options.end())
566 {
567 if (std::holds_alternative<int>(iteration->second))
568 {
569 hostIdx = std::get<int>(iteration->second);
570 }
571 }
Vernon Maueryd6a2da02019-04-09 16:00:46 -0700572 }
Vernon Mauery735ee952019-02-15 13:38:52 -0800573 }
574 // check to see if the requested priv/username is valid
Vernon Mauerye808bae2024-05-31 14:55:36 -0700575 lg2::debug("Set up ipmi context: Ch:NetFn/Cmd={CHANNEL}:{NETFN}/{CMD}",
576 "SENDER", sender, "NETFN", lg2::hex, netFn, "LUN", lg2::hex, lun,
577 "CMD", lg2::hex, cmd, "CHANNEL", channel, "USERID", userId,
578 "SESSIONID", lg2::hex, sessionId, "PRIVILEGE",
579 static_cast<uint8_t>(privilege), "RQSA", lg2::hex, rqSA);
Vernon Mauery735ee952019-02-15 13:38:52 -0800580
Patrick Williams1318a5e2024-08-16 15:19:54 -0400581 auto ctx = std::make_shared<ipmi::Context>(
582 getSdBus(), netFn, lun, cmd, channel, userId, sessionId, privilege,
583 rqSA, hostIdx, yield);
Vernon Mauery240b1862018-10-08 12:05:16 -0700584 auto request = std::make_shared<ipmi::message::Request>(
Vernon Mauery997952a2021-07-30 14:06:14 -0700585 ctx, std::forward<ipmi::SecureBuffer>(data));
Vernon Mauery240b1862018-10-08 12:05:16 -0700586 message::Response::ptr response = executeIpmiCommand(request);
587
Vernon Mauery735ee952019-02-15 13:38:52 -0800588 return dbusResponse(response->cc, response->payload.raw);
Vernon Mauery240b1862018-10-08 12:05:16 -0700589}
590
591/** @struct IpmiProvider
592 *
593 * RAII wrapper for dlopen so that dlclose gets called on exit
594 */
595struct IpmiProvider
596{
597 public:
598 /** @brief address of the opened library */
599 void* addr;
600 std::string name;
601
602 IpmiProvider() = delete;
603 IpmiProvider(const IpmiProvider&) = delete;
604 IpmiProvider& operator=(const IpmiProvider&) = delete;
605 IpmiProvider(IpmiProvider&&) = delete;
606 IpmiProvider& operator=(IpmiProvider&&) = delete;
607
608 /** @brief dlopen a shared object file by path
609 * @param[in] filename - path of shared object to open
610 */
611 explicit IpmiProvider(const char* fname) : addr(nullptr), name(fname)
612 {
Vernon Mauerye808bae2024-05-31 14:55:36 -0700613 lg2::debug("Open IPMI provider library: {PROVIDER}", "PROVIDER", name);
Vernon Mauery240b1862018-10-08 12:05:16 -0700614 try
615 {
616 addr = dlopen(name.c_str(), RTLD_NOW);
617 }
Patrick Williamsa2ad2da2021-10-06 12:21:46 -0500618 catch (const std::exception& e)
Vernon Mauery240b1862018-10-08 12:05:16 -0700619 {
Vernon Mauerye808bae2024-05-31 14:55:36 -0700620 lg2::error("ERROR opening IPMI provider {PROVIDER}: {ERROR}",
621 "PROVIDER", name, "ERROR", e);
Vernon Mauery240b1862018-10-08 12:05:16 -0700622 }
623 catch (...)
624 {
Vernon Mauery03d7a4b2021-01-19 11:22:17 -0800625 const char* what = currentExceptionType();
Vernon Mauerye808bae2024-05-31 14:55:36 -0700626 lg2::error("ERROR opening IPMI provider {PROVIDER}: {ERROR}",
627 "PROVIDER", name, "ERROR", what);
Vernon Mauery240b1862018-10-08 12:05:16 -0700628 }
629 if (!isOpen())
630 {
Vernon Mauerye808bae2024-05-31 14:55:36 -0700631 lg2::error("ERROR opening IPMI provider {PROVIDER}: {ERROR}",
632 "PROVIDER", name, "ERROR", dlerror());
Vernon Mauery240b1862018-10-08 12:05:16 -0700633 }
634 }
635
636 ~IpmiProvider()
637 {
638 if (isOpen())
639 {
640 dlclose(addr);
641 }
642 }
643 bool isOpen() const
644 {
645 return (nullptr != addr);
646 }
647};
648
649// Plugin libraries need to contain .so either at the end or in the middle
650constexpr const char ipmiPluginExtn[] = ".so";
651
652/* return a list of self-closing library handles */
653std::forward_list<IpmiProvider> loadProviders(const fs::path& ipmiLibsPath)
654{
655 std::vector<fs::path> libs;
656 for (const auto& libPath : fs::directory_iterator(ipmiLibsPath))
657 {
Vernon Maueryb0ab5fe2019-03-06 14:03:00 -0800658 std::error_code ec;
Vernon Mauery240b1862018-10-08 12:05:16 -0700659 fs::path fname = libPath.path();
Vernon Maueryb0ab5fe2019-03-06 14:03:00 -0800660 if (fs::is_symlink(fname, ec) || ec)
661 {
662 // it's a symlink or some other error; skip it
663 continue;
664 }
Vernon Mauery240b1862018-10-08 12:05:16 -0700665 while (fname.has_extension())
666 {
667 fs::path extn = fname.extension();
668 if (extn == ipmiPluginExtn)
669 {
670 libs.push_back(libPath.path());
671 break;
672 }
673 fname.replace_extension();
674 }
675 }
676 std::sort(libs.begin(), libs.end());
677
678 std::forward_list<IpmiProvider> handles;
679 for (auto& lib : libs)
680 {
681#ifdef __IPMI_DEBUG__
Vernon Mauerye808bae2024-05-31 14:55:36 -0700682 lg2::debug("Registering handler {HANDLER}", "HANDLER", lib);
Vernon Mauery240b1862018-10-08 12:05:16 -0700683#endif
684 handles.emplace_front(lib.c_str());
685 }
686 return handles;
687}
688
689} // namespace ipmi
690
Vernon Mauery240b1862018-10-08 12:05:16 -0700691#ifdef ALLOW_DEPRECATED_API
692/* legacy registration */
693void ipmi_register_callback(ipmi_netfn_t netFn, ipmi_cmd_t cmd,
694 ipmi_context_t context, ipmid_callback_t handler,
695 ipmi_cmd_privilege_t priv)
696{
Vernon Mauerybe376302019-03-21 13:02:05 -0700697 auto h = ipmi::makeLegacyHandler(handler, context);
Vernon Mauery240b1862018-10-08 12:05:16 -0700698 // translate priv from deprecated enum to current
699 ipmi::Privilege realPriv;
700 switch (priv)
701 {
702 case PRIVILEGE_CALLBACK:
703 realPriv = ipmi::Privilege::Callback;
704 break;
705 case PRIVILEGE_USER:
706 realPriv = ipmi::Privilege::User;
707 break;
708 case PRIVILEGE_OPERATOR:
709 realPriv = ipmi::Privilege::Operator;
710 break;
711 case PRIVILEGE_ADMIN:
712 realPriv = ipmi::Privilege::Admin;
713 break;
714 case PRIVILEGE_OEM:
715 realPriv = ipmi::Privilege::Oem;
716 break;
717 case SYSTEM_INTERFACE:
718 realPriv = ipmi::Privilege::Admin;
719 break;
720 default:
721 realPriv = ipmi::Privilege::Admin;
722 break;
723 }
Vernon Mauerye8d43232019-03-26 16:23:43 -0700724 // The original ipmi_register_callback allowed for group OEM handlers
725 // to be registered via this same interface. It just so happened that
726 // all the handlers were part of the DCMI group, so default to that.
George Liuae30d812025-04-03 09:56:47 +0800727 if (netFn == ipmi::netFnGroup)
Vernon Mauerye8d43232019-03-26 16:23:43 -0700728 {
Vernon Mauery82cffcc2023-07-27 10:59:20 -0700729 ipmi::impl::registerGroupHandler(ipmi::prioOpenBmcBase, ipmi::groupDCMI,
730 cmd, realPriv, h);
Vernon Mauerye8d43232019-03-26 16:23:43 -0700731 }
732 else
733 {
734 ipmi::impl::registerHandler(ipmi::prioOpenBmcBase, netFn, cmd, realPriv,
735 h);
736 }
Vernon Mauery240b1862018-10-08 12:05:16 -0700737}
738
Vernon Maueryf984a012018-10-08 12:05:18 -0700739namespace oem
740{
741
742class LegacyRouter : public oem::Router
743{
744 public:
Patrick Williamsfbc6c9d2023-05-10 07:50:16 -0500745 virtual ~LegacyRouter() {}
Vernon Maueryf984a012018-10-08 12:05:18 -0700746
747 /// Enable message routing to begin.
Patrick Williamsfbc6c9d2023-05-10 07:50:16 -0500748 void activate() override {}
Vernon Maueryf984a012018-10-08 12:05:18 -0700749
750 void registerHandler(Number oen, ipmi_cmd_t cmd, Handler handler) override
751 {
752 auto h = ipmi::makeLegacyHandler(std::forward<Handler>(handler));
753 ipmi::impl::registerOemHandler(ipmi::prioOpenBmcBase, oen, cmd,
754 ipmi::Privilege::Admin, h);
755 }
756};
757static LegacyRouter legacyRouter;
758
759Router* mutableRouter()
760{
761 return &legacyRouter;
762}
763
764} // namespace oem
765
Vernon Mauery240b1862018-10-08 12:05:16 -0700766/* legacy alternative to executionEntry */
Patrick Williams5d82f472022-07-22 19:26:53 -0500767void handleLegacyIpmiCommand(sdbusplus::message_t& m)
Vernon Mauery240b1862018-10-08 12:05:16 -0700768{
Vernon Mauery23b70212019-05-08 15:19:05 -0700769 // make a copy so the next two moves don't wreak havoc on the stack
Patrick Williams5d82f472022-07-22 19:26:53 -0500770 sdbusplus::message_t b{m};
Ed Tanous98605052025-02-13 16:57:13 -0800771 boost::asio::spawn(
Jayanth Othayoth531223f2024-11-11 07:30:15 -0600772 *getIoContext(),
773 [b = std::move(b)](boost::asio::yield_context yield) {
774 sdbusplus::message_t m{std::move(b)};
775 unsigned char seq = 0, netFn = 0, lun = 0, cmd = 0;
776 ipmi::SecureBuffer data;
Vernon Mauery240b1862018-10-08 12:05:16 -0700777
Jayanth Othayoth531223f2024-11-11 07:30:15 -0600778 m.read(seq, netFn, lun, cmd, data);
779 std::shared_ptr<sdbusplus::asio::connection> bus = getSdBus();
780 auto ctx = std::make_shared<ipmi::Context>(
781 bus, netFn, lun, cmd, 0, 0, 0, ipmi::Privilege::Admin, 0, 0,
782 yield);
783 auto request = std::make_shared<ipmi::message::Request>(
784 ctx, std::forward<ipmi::SecureBuffer>(data));
785 ipmi::message::Response::ptr response =
786 ipmi::executeIpmiCommand(request);
Vernon Mauery240b1862018-10-08 12:05:16 -0700787
Jayanth Othayoth531223f2024-11-11 07:30:15 -0600788 // Responses in IPMI require a bit set. So there ya go...
789 netFn |= 0x01;
Vernon Mauery240b1862018-10-08 12:05:16 -0700790
Jayanth Othayoth531223f2024-11-11 07:30:15 -0600791 constexpr const char* DBUS_INTF = "org.openbmc.HostIpmi";
Vernon Mauery240b1862018-10-08 12:05:16 -0700792
George Liude1420d2025-03-03 15:14:25 +0800793 std::string dest = m.get_sender();
794 std::string path = m.get_path();
795 boost::system::error_code ec = ipmi::callDbusMethod(
796 ctx, dest, path, DBUS_INTF, "sendMessage", seq, netFn, lun, cmd,
797 response->cc, response->payload.raw);
798
Jayanth Othayoth531223f2024-11-11 07:30:15 -0600799 if (ec)
800 {
801 lg2::error(
802 "Failed to send response to requestor ({NETFN}/{CMD}): {ERROR}",
803 "ERROR", ec.message(), "SENDER", dest, "NETFN", lg2::hex,
804 netFn, "CMD", lg2::hex, cmd);
805 }
806 },
Ed Tanous98605052025-02-13 16:57:13 -0800807 boost::asio::detached);
Vernon Mauery240b1862018-10-08 12:05:16 -0700808}
809
810#endif /* ALLOW_DEPRECATED_API */
811
812// Calls host command manager to do the right thing for the command
813using CommandHandler = phosphor::host::command::CommandHandler;
814std::unique_ptr<phosphor::host::command::Manager> cmdManager;
815void ipmid_send_cmd_to_host(CommandHandler&& cmd)
816{
Vernon Mauery5e096a22022-06-01 15:11:16 -0700817 cmdManager->execute(std::forward<CommandHandler>(cmd));
Vernon Mauery240b1862018-10-08 12:05:16 -0700818}
819
820std::unique_ptr<phosphor::host::command::Manager>& ipmid_get_host_cmd_manager()
821{
822 return cmdManager;
823}
824
Vernon Mauery20ff3332019-03-01 16:52:25 -0800825// These are symbols that are present in libipmid, but not expected
826// to be used except here (or maybe a unit test), so declare them here
827extern void setIoContext(std::shared_ptr<boost::asio::io_context>& newIo);
828extern void setSdBus(std::shared_ptr<sdbusplus::asio::connection>& newBus);
829
Vernon Mauery240b1862018-10-08 12:05:16 -0700830int main(int argc, char* argv[])
831{
832 // Connect to system bus
Vernon Mauery20ff3332019-03-01 16:52:25 -0800833 auto io = std::make_shared<boost::asio::io_context>();
834 setIoContext(io);
Vernon Mauery240b1862018-10-08 12:05:16 -0700835 if (argc > 1 && std::string(argv[1]) == "-session")
836 {
837 sd_bus_default_user(&bus);
838 }
839 else
840 {
841 sd_bus_default_system(&bus);
842 }
Vernon Mauery20ff3332019-03-01 16:52:25 -0800843 auto sdbusp = std::make_shared<sdbusplus::asio::connection>(*io, bus);
844 setSdBus(sdbusp);
Vernon Mauery240b1862018-10-08 12:05:16 -0700845
Patrick Williams3b301a32025-02-03 13:05:36 -0500846 // TODO: Hack to keep the sdEvents running.... Not sure why the sd_event
847 // queue stops running if we don't have a timer that keeps re-arming
848 sdbusplus::Timer t2([]() { ; });
849 t2.start(std::chrono::microseconds(500000), true);
850
851 // TODO: Remove all vestiges of sd_event from phosphor-host-ipmid
852 // until that is done, add the sd_event wrapper to the io object
853 sdbusplus::asio::sd_event_wrapper sdEvents(*io);
854
Vernon Mauery240b1862018-10-08 12:05:16 -0700855 cmdManager = std::make_unique<phosphor::host::command::Manager>(*sdbusp);
856
857 // Register all command providers and filters
Vernon Mauery4ec4e402019-03-20 13:09:27 -0700858 std::forward_list<ipmi::IpmiProvider> providers =
859 ipmi::loadProviders(HOST_IPMI_LIB_PATH);
Vernon Mauery240b1862018-10-08 12:05:16 -0700860
Vernon Mauery240b1862018-10-08 12:05:16 -0700861#ifdef ALLOW_DEPRECATED_API
862 // listen on deprecated signal interface for kcs/bt commands
863 constexpr const char* FILTER = "type='signal',interface='org.openbmc."
864 "HostIpmi',member='ReceivedMessage'";
Patrick Williams5d82f472022-07-22 19:26:53 -0500865 sdbusplus::bus::match_t oldIpmiInterface(*sdbusp, FILTER,
866 handleLegacyIpmiCommand);
Vernon Mauery240b1862018-10-08 12:05:16 -0700867#endif /* ALLOW_DEPRECATED_API */
868
Vernon Mauery735ee952019-02-15 13:38:52 -0800869 // set up bus name watching to match channels with bus names
Patrick Williams5d82f472022-07-22 19:26:53 -0500870 sdbusplus::bus::match_t nameOwnerChanged(
Vernon Mauery735ee952019-02-15 13:38:52 -0800871 *sdbusp,
872 sdbusplus::bus::match::rules::nameOwnerChanged() +
873 sdbusplus::bus::match::rules::arg0namespace(
874 ipmi::ipmiDbusChannelMatch),
875 ipmi::nameChangeHandler);
Jayanth Othayoth9f3073a2024-12-08 09:29:43 -0600876 ipmi::doListNames(*sdbusp);
Vernon Mauery735ee952019-02-15 13:38:52 -0800877
James Feistb0094a72019-11-26 09:07:15 -0800878 int exitCode = 0;
Vernon Mauery1b7f6f22019-03-13 13:11:25 -0700879 // set up boost::asio signal handling
Patrick Williams1318a5e2024-08-16 15:19:54 -0400880 std::function<SignalResponse(int)> stopAsioRunLoop = [&io, &exitCode](
881 int signalNumber) {
Vernon Mauerye808bae2024-05-31 14:55:36 -0700882 lg2::info("Received signal {SIGNAL}; quitting", "SIGNAL", signalNumber);
Patrick Williamsfbc6c9d2023-05-10 07:50:16 -0500883 io->stop();
884 exitCode = signalNumber;
885 return SignalResponse::breakExecution;
886 };
Vernon Mauery1b7f6f22019-03-13 13:11:25 -0700887 registerSignalHandler(ipmi::prioOpenBmcBase, SIGINT, stopAsioRunLoop);
888 registerSignalHandler(ipmi::prioOpenBmcBase, SIGTERM, stopAsioRunLoop);
889
Richard Marian Thomaiyar369406e2020-01-09 14:56:54 +0530890 sdbusp->request_name("xyz.openbmc_project.Ipmi.Host");
891 // Add bindings for inbound IPMI requests
892 auto server = sdbusplus::asio::object_server(sdbusp);
893 auto iface = server.add_interface("/xyz/openbmc_project/Ipmi",
894 "xyz.openbmc_project.Ipmi.Server");
895 iface->register_method("execute", ipmi::executionEntry);
896 iface->initialize();
897
Vernon Mauery240b1862018-10-08 12:05:16 -0700898 io->run();
899
Vernon Mauery1b7f6f22019-03-13 13:11:25 -0700900 // destroy all the IPMI handlers so the providers can unload safely
901 ipmi::handlerMap.clear();
902 ipmi::groupHandlerMap.clear();
903 ipmi::oemHandlerMap.clear();
904 ipmi::filterList.clear();
905 // unload the provider libraries
Vernon Mauery4ec4e402019-03-20 13:09:27 -0700906 providers.clear();
Vernon Mauery1b7f6f22019-03-13 13:11:25 -0700907
James Feistb0094a72019-11-26 09:07:15 -0800908 std::exit(exitCode);
Vernon Mauery240b1862018-10-08 12:05:16 -0700909}