blob: 2a78c68a67d1aef461fd16f41ce74719bdcf2942 [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 Mauerye8d43232019-03-26 16:23:43 -070024#include <dcmihandler.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>
Vernon Mauery240b1862018-10-08 12:05:16 -070032#include <phosphor-logging/log.hpp>
33#include <sdbusplus/asio/connection.hpp>
34#include <sdbusplus/asio/object_server.hpp>
35#include <sdbusplus/asio/sd_event.hpp>
36#include <sdbusplus/bus.hpp>
37#include <sdbusplus/bus/match.hpp>
38#include <sdbusplus/timer.hpp>
Patrick Williamsfbc6c9d2023-05-10 07:50:16 -050039
40#include <algorithm>
41#include <any>
42#include <exception>
43#include <filesystem>
44#include <forward_list>
45#include <map>
46#include <memory>
47#include <optional>
Vernon Mauery240b1862018-10-08 12:05:16 -070048#include <tuple>
Vernon Mauery240b1862018-10-08 12:05:16 -070049#include <unordered_map>
50#include <utility>
51#include <vector>
52
Vernon Mauery240b1862018-10-08 12:05:16 -070053namespace fs = std::filesystem;
54
55using namespace phosphor::logging;
56
Vernon Mauery240b1862018-10-08 12:05:16 -070057// IPMI Spec, shared Reservation ID.
58static unsigned short selReservationID = 0xFFFF;
59static bool selReservationValid = false;
60
61unsigned short reserveSel(void)
62{
63 // IPMI spec, Reservation ID, the value simply increases against each
64 // execution of the Reserve SEL command.
65 if (++selReservationID == 0)
66 {
67 selReservationID = 1;
68 }
69 selReservationValid = true;
70 return selReservationID;
71}
72
73bool checkSELReservation(unsigned short id)
74{
75 return (selReservationValid && selReservationID == id);
76}
77
78void cancelSELReservation(void)
79{
80 selReservationValid = false;
81}
82
83EInterfaceIndex getInterfaceIndex(void)
84{
85 return interfaceKCS;
86}
87
88sd_bus* bus;
89sd_event* events = nullptr;
90sd_event* ipmid_get_sd_event_connection(void)
91{
92 return events;
93}
94sd_bus* ipmid_get_sd_bus_connection(void)
95{
96 return bus;
97}
98
99namespace ipmi
100{
101
102static inline unsigned int makeCmdKey(unsigned int cluster, unsigned int cmd)
103{
104 return (cluster << 8) | cmd;
105}
106
107using HandlerTuple = std::tuple<int, /* prio */
108 Privilege, HandlerBase::ptr /* handler */
109 >;
110
111/* map to handle standard registered commands */
112static std::unordered_map<unsigned int, /* key is NetFn/Cmd */
113 HandlerTuple>
114 handlerMap;
115
Vernon Maueryf984a012018-10-08 12:05:18 -0700116/* special map for decoding Group registered commands (NetFn 2Ch) */
117static std::unordered_map<unsigned int, /* key is Group/Cmd (NetFn is 2Ch) */
118 HandlerTuple>
119 groupHandlerMap;
120
121/* special map for decoding OEM registered commands (NetFn 2Eh) */
122static std::unordered_map<unsigned int, /* key is Iana/Cmd (NetFn is 2Eh) */
123 HandlerTuple>
124 oemHandlerMap;
125
Vernon Mauery08a70aa2018-11-07 09:36:22 -0800126using FilterTuple = std::tuple<int, /* prio */
127 FilterBase::ptr /* filter */
128 >;
129
130/* list to hold all registered ipmi command filters */
131static std::forward_list<FilterTuple> filterList;
132
Vernon Mauery240b1862018-10-08 12:05:16 -0700133namespace impl
134{
135/* common function to register all standard IPMI handlers */
136bool registerHandler(int prio, NetFn netFn, Cmd cmd, Privilege priv,
137 HandlerBase::ptr handler)
138{
139 // check for valid NetFn: even; 00-0Ch, 30-3Eh
140 if (netFn & 1 || (netFn > netFnTransport && netFn < netFnGroup) ||
141 netFn > netFnOemEight)
142 {
143 return false;
144 }
145
146 // create key and value for this handler
147 unsigned int netFnCmd = makeCmdKey(netFn, cmd);
148 HandlerTuple item(prio, priv, handler);
149
150 // consult the handler map and look for a match
151 auto& mapCmd = handlerMap[netFnCmd];
152 if (!std::get<HandlerBase::ptr>(mapCmd) || std::get<int>(mapCmd) <= prio)
153 {
154 mapCmd = item;
155 return true;
156 }
157 return false;
158}
159
Vernon Maueryf984a012018-10-08 12:05:18 -0700160/* common function to register all Group IPMI handlers */
161bool registerGroupHandler(int prio, Group group, Cmd cmd, Privilege priv,
162 HandlerBase::ptr handler)
163{
164 // create key and value for this handler
165 unsigned int netFnCmd = makeCmdKey(group, cmd);
166 HandlerTuple item(prio, priv, handler);
167
168 // consult the handler map and look for a match
169 auto& mapCmd = groupHandlerMap[netFnCmd];
170 if (!std::get<HandlerBase::ptr>(mapCmd) || std::get<int>(mapCmd) <= prio)
171 {
172 mapCmd = item;
173 return true;
174 }
175 return false;
176}
177
178/* common function to register all OEM IPMI handlers */
179bool registerOemHandler(int prio, Iana iana, Cmd cmd, Privilege priv,
180 HandlerBase::ptr handler)
181{
182 // create key and value for this handler
183 unsigned int netFnCmd = makeCmdKey(iana, cmd);
184 HandlerTuple item(prio, priv, handler);
185
186 // consult the handler map and look for a match
187 auto& mapCmd = oemHandlerMap[netFnCmd];
188 if (!std::get<HandlerBase::ptr>(mapCmd) || std::get<int>(mapCmd) <= prio)
189 {
190 mapCmd = item;
191 return true;
192 }
193 return false;
194}
195
Vernon Mauery08a70aa2018-11-07 09:36:22 -0800196/* common function to register all IPMI filter handlers */
197void registerFilter(int prio, FilterBase::ptr filter)
198{
199 // check for initial placement
200 if (filterList.empty() || std::get<int>(filterList.front()) < prio)
201 {
202 filterList.emplace_front(std::make_tuple(prio, filter));
Yong Libe063232021-03-04 16:52:52 +0800203 return;
Vernon Mauery08a70aa2018-11-07 09:36:22 -0800204 }
205 // walk the list and put it in the right place
206 auto j = filterList.begin();
207 for (auto i = j; i != filterList.end() && std::get<int>(*i) > prio; i++)
208 {
209 j = i;
210 }
211 filterList.emplace_after(j, std::make_tuple(prio, filter));
212}
213
Vernon Mauery240b1862018-10-08 12:05:16 -0700214} // namespace impl
215
Vernon Mauery08a70aa2018-11-07 09:36:22 -0800216message::Response::ptr filterIpmiCommand(message::Request::ptr request)
217{
218 // pass the command through the filter mechanism
219 // This can be the firmware firewall or any OEM mechanism like
220 // whitelist filtering based on operational mode
221 for (auto& item : filterList)
222 {
223 FilterBase::ptr filter = std::get<FilterBase::ptr>(item);
224 ipmi::Cc cc = filter->call(request);
225 if (ipmi::ccSuccess != cc)
226 {
227 return errorResponse(request, cc);
228 }
229 }
230 return message::Response::ptr();
231}
232
Vernon Mauery240b1862018-10-08 12:05:16 -0700233message::Response::ptr executeIpmiCommandCommon(
234 std::unordered_map<unsigned int, HandlerTuple>& handlers,
235 unsigned int keyCommon, message::Request::ptr request)
236{
Vernon Mauery08a70aa2018-11-07 09:36:22 -0800237 // filter the command first; a non-null message::Response::ptr
238 // means that the message has been rejected for some reason
Vernon Mauery51f78142020-01-13 16:28:59 -0800239 message::Response::ptr filterResponse = filterIpmiCommand(request);
Vernon Mauery08a70aa2018-11-07 09:36:22 -0800240
Vernon Mauery240b1862018-10-08 12:05:16 -0700241 Cmd cmd = request->ctx->cmd;
242 unsigned int key = makeCmdKey(keyCommon, cmd);
243 auto cmdIter = handlers.find(key);
244 if (cmdIter != handlers.end())
245 {
Vernon Mauery51f78142020-01-13 16:28:59 -0800246 // only return the filter response if the command is found
247 if (filterResponse)
248 {
249 return filterResponse;
250 }
Vernon Mauery240b1862018-10-08 12:05:16 -0700251 HandlerTuple& chosen = cmdIter->second;
252 if (request->ctx->priv < std::get<Privilege>(chosen))
253 {
254 return errorResponse(request, ccInsufficientPrivilege);
255 }
256 return std::get<HandlerBase::ptr>(chosen)->call(request);
257 }
258 else
259 {
260 unsigned int wildcard = makeCmdKey(keyCommon, cmdWildcard);
261 cmdIter = handlers.find(wildcard);
262 if (cmdIter != handlers.end())
263 {
Vernon Mauery51f78142020-01-13 16:28:59 -0800264 // only return the filter response if the command is found
265 if (filterResponse)
266 {
267 return filterResponse;
268 }
Vernon Mauery240b1862018-10-08 12:05:16 -0700269 HandlerTuple& chosen = cmdIter->second;
270 if (request->ctx->priv < std::get<Privilege>(chosen))
271 {
272 return errorResponse(request, ccInsufficientPrivilege);
273 }
274 return std::get<HandlerBase::ptr>(chosen)->call(request);
275 }
276 }
277 return errorResponse(request, ccInvalidCommand);
278}
279
Vernon Maueryf984a012018-10-08 12:05:18 -0700280message::Response::ptr executeIpmiGroupCommand(message::Request::ptr request)
281{
282 // look up the group for this request
William A. Kennington IIId10d9052019-04-24 01:57:36 -0700283 uint8_t bytes;
284 if (0 != request->payload.unpack(bytes))
Vernon Maueryf984a012018-10-08 12:05:18 -0700285 {
286 return errorResponse(request, ccReqDataLenInvalid);
287 }
William A. Kennington IIId10d9052019-04-24 01:57:36 -0700288 auto group = static_cast<Group>(bytes);
Patrick Williamsfbc6c9d2023-05-10 07:50:16 -0500289 message::Response::ptr response = executeIpmiCommandCommon(groupHandlerMap,
290 group, request);
William A. Kennington IIIda31f9a2019-04-25 01:36:32 -0700291 ipmi::message::Payload prefix;
292 prefix.pack(bytes);
293 response->prepend(prefix);
Vernon Maueryf984a012018-10-08 12:05:18 -0700294 return response;
295}
296
297message::Response::ptr executeIpmiOemCommand(message::Request::ptr request)
298{
299 // look up the iana for this request
William A. Kennington IIId10d9052019-04-24 01:57:36 -0700300 uint24_t bytes;
301 if (0 != request->payload.unpack(bytes))
Vernon Maueryf984a012018-10-08 12:05:18 -0700302 {
303 return errorResponse(request, ccReqDataLenInvalid);
304 }
William A. Kennington IIId10d9052019-04-24 01:57:36 -0700305 auto iana = static_cast<Iana>(bytes);
Patrick Williamsfbc6c9d2023-05-10 07:50:16 -0500306 message::Response::ptr response = executeIpmiCommandCommon(oemHandlerMap,
307 iana, request);
William A. Kennington IIIda31f9a2019-04-25 01:36:32 -0700308 ipmi::message::Payload prefix;
309 prefix.pack(bytes);
310 response->prepend(prefix);
Vernon Maueryf984a012018-10-08 12:05:18 -0700311 return response;
312}
313
Vernon Mauery240b1862018-10-08 12:05:16 -0700314message::Response::ptr executeIpmiCommand(message::Request::ptr request)
315{
316 NetFn netFn = request->ctx->netFn;
Vernon Maueryf984a012018-10-08 12:05:18 -0700317 if (netFnGroup == netFn)
318 {
319 return executeIpmiGroupCommand(request);
320 }
321 else if (netFnOem == netFn)
322 {
323 return executeIpmiOemCommand(request);
324 }
Vernon Mauery240b1862018-10-08 12:05:16 -0700325 return executeIpmiCommandCommon(handlerMap, netFn, request);
326}
327
Vernon Mauery735ee952019-02-15 13:38:52 -0800328namespace utils
329{
330template <typename AssocContainer, typename UnaryPredicate>
331void assoc_erase_if(AssocContainer& c, UnaryPredicate p)
332{
333 typename AssocContainer::iterator next = c.begin();
334 typename AssocContainer::iterator last = c.end();
335 while ((next = std::find_if(next, last, p)) != last)
336 {
337 c.erase(next++);
338 }
339}
340} // namespace utils
341
342namespace
343{
344std::unordered_map<std::string, uint8_t> uniqueNameToChannelNumber;
345
346// sdbusplus::bus::match::rules::arg0namespace() wants the prefix
347// to match without any trailing '.'
348constexpr const char ipmiDbusChannelMatch[] =
349 "xyz.openbmc_project.Ipmi.Channel";
350void updateOwners(sdbusplus::asio::connection& conn, const std::string& name)
351{
352 conn.async_method_call(
353 [name](const boost::system::error_code ec,
354 const std::string& nameOwner) {
Patrick Williamsfbc6c9d2023-05-10 07:50:16 -0500355 if (ec)
356 {
357 log<level::ERR>("Error getting dbus owner",
358 entry("INTERFACE=%s", name.c_str()));
359 return;
360 }
361 // start after ipmiDbusChannelPrefix (after the '.')
362 std::string chName = name.substr(std::strlen(ipmiDbusChannelMatch) + 1);
363 try
364 {
365 uint8_t channel = getChannelByName(chName);
366 uniqueNameToChannelNumber[nameOwner] = channel;
367 log<level::INFO>("New interface mapping",
368 entry("INTERFACE=%s", name.c_str()),
369 entry("CHANNEL=%u", channel));
370 }
371 catch (const std::exception& e)
372 {
373 log<level::INFO>("Failed interface mapping, no such name",
374 entry("INTERFACE=%s", name.c_str()));
375 }
Vernon Mauery735ee952019-02-15 13:38:52 -0800376 },
377 "org.freedesktop.DBus", "/", "org.freedesktop.DBus", "GetNameOwner",
378 name);
379}
380
Ed Tanous778418d2020-08-17 23:20:21 -0700381void doListNames(boost::asio::io_context& io, sdbusplus::asio::connection& conn)
Vernon Mauery735ee952019-02-15 13:38:52 -0800382{
383 conn.async_method_call(
384 [&io, &conn](const boost::system::error_code ec,
385 std::vector<std::string> busNames) {
Patrick Williamsfbc6c9d2023-05-10 07:50:16 -0500386 if (ec)
387 {
388 log<level::ERR>("Error getting dbus names");
389 std::exit(EXIT_FAILURE);
390 return;
391 }
392 // Try to make startup consistent
393 std::sort(busNames.begin(), busNames.end());
Vernon Mauery735ee952019-02-15 13:38:52 -0800394
Patrick Williamsfbc6c9d2023-05-10 07:50:16 -0500395 const std::string channelPrefix = std::string(ipmiDbusChannelMatch) +
396 ".";
397 for (const std::string& busName : busNames)
398 {
399 if (busName.find(channelPrefix) == 0)
Vernon Mauery735ee952019-02-15 13:38:52 -0800400 {
Patrick Williamsfbc6c9d2023-05-10 07:50:16 -0500401 updateOwners(conn, busName);
Vernon Mauery735ee952019-02-15 13:38:52 -0800402 }
Patrick Williamsfbc6c9d2023-05-10 07:50:16 -0500403 }
Vernon Mauery735ee952019-02-15 13:38:52 -0800404 },
405 "org.freedesktop.DBus", "/org/freedesktop/DBus", "org.freedesktop.DBus",
406 "ListNames");
407}
408
Patrick Williams5d82f472022-07-22 19:26:53 -0500409void nameChangeHandler(sdbusplus::message_t& message)
Vernon Mauery735ee952019-02-15 13:38:52 -0800410{
411 std::string name;
412 std::string oldOwner;
413 std::string newOwner;
414
415 message.read(name, oldOwner, newOwner);
416
417 if (!oldOwner.empty())
418 {
419 if (boost::starts_with(oldOwner, ":"))
420 {
421 // Connection removed
422 auto it = uniqueNameToChannelNumber.find(oldOwner);
423 if (it != uniqueNameToChannelNumber.end())
424 {
425 uniqueNameToChannelNumber.erase(it);
426 }
427 }
428 }
429 if (!newOwner.empty())
430 {
431 // start after ipmiDbusChannelMatch (and after the '.')
432 std::string chName = name.substr(std::strlen(ipmiDbusChannelMatch) + 1);
433 try
434 {
435 uint8_t channel = getChannelByName(chName);
436 uniqueNameToChannelNumber[newOwner] = channel;
437 log<level::INFO>("New interface mapping",
438 entry("INTERFACE=%s", name.c_str()),
439 entry("CHANNEL=%u", channel));
440 }
441 catch (const std::exception& e)
442 {
443 log<level::INFO>("Failed interface mapping, no such name",
444 entry("INTERFACE=%s", name.c_str()));
445 }
446 }
447};
448
449} // anonymous namespace
450
451static constexpr const char intraBmcName[] = "INTRABMC";
Patrick Williams5d82f472022-07-22 19:26:53 -0500452uint8_t channelFromMessage(sdbusplus::message_t& msg)
Vernon Mauery735ee952019-02-15 13:38:52 -0800453{
454 // channel name for ipmitool to resolve to
455 std::string sender = msg.get_sender();
456 auto chIter = uniqueNameToChannelNumber.find(sender);
457 if (chIter != uniqueNameToChannelNumber.end())
458 {
459 return chIter->second;
460 }
461 // FIXME: currently internal connections are ephemeral and hard to pin down
462 try
463 {
464 return getChannelByName(intraBmcName);
465 }
466 catch (const std::exception& e)
467 {
468 return invalidChannel;
469 }
470} // namespace ipmi
471
Vernon Mauery240b1862018-10-08 12:05:16 -0700472/* called from sdbus async server context */
Patrick Williams5d82f472022-07-22 19:26:53 -0500473auto executionEntry(boost::asio::yield_context yield, sdbusplus::message_t& m,
474 NetFn netFn, uint8_t lun, Cmd cmd, ipmi::SecureBuffer& data,
Vernon Mauery240b1862018-10-08 12:05:16 -0700475 std::map<std::string, ipmi::Value>& options)
476{
Vernon Mauery735ee952019-02-15 13:38:52 -0800477 const auto dbusResponse =
Vernon Mauery997952a2021-07-30 14:06:14 -0700478 [netFn, lun, cmd](Cc cc, const ipmi::SecureBuffer& data = {}) {
Patrick Williamsfbc6c9d2023-05-10 07:50:16 -0500479 constexpr uint8_t netFnResponse = 0x01;
480 uint8_t retNetFn = netFn | netFnResponse;
481 return std::make_tuple(retNetFn, lun, cmd, cc, data);
482 };
Vernon Mauery735ee952019-02-15 13:38:52 -0800483 std::string sender = m.get_sender();
484 Privilege privilege = Privilege::None;
Vernon Maueryd6a2da02019-04-09 16:00:46 -0700485 int rqSA = 0;
Kumar Thangavelf7d081f2020-08-19 20:41:18 +0530486 int hostIdx = 0;
Vernon Mauery735ee952019-02-15 13:38:52 -0800487 uint8_t userId = 0; // undefined user
Rajashekar Gade Reddy4d226402019-11-13 17:13:05 +0530488 uint32_t sessionId = 0;
Vernon Mauery735ee952019-02-15 13:38:52 -0800489
490 // figure out what channel the request came in on
491 uint8_t channel = channelFromMessage(m);
492 if (channel == invalidChannel)
493 {
494 // unknown sender channel; refuse to service the request
495 log<level::ERR>("ERROR determining source IPMI channel",
496 entry("SENDER=%s", sender.c_str()),
497 entry("NETFN=0x%X", netFn), entry("CMD=0x%X", cmd));
498 return dbusResponse(ipmi::ccDestinationUnavailable);
499 }
500
Rajashekar Gade Reddy4d226402019-11-13 17:13:05 +0530501 // session-based channels are required to provide userId, privilege and
502 // sessionId
Vernon Mauery735ee952019-02-15 13:38:52 -0800503 if (getChannelSessionSupport(channel) != EChannelSessSupported::none)
504 {
505 try
506 {
507 Value requestPriv = options.at("privilege");
508 Value requestUserId = options.at("userId");
Rajashekar Gade Reddy4d226402019-11-13 17:13:05 +0530509 Value requestSessionId = options.at("currentSessionId");
Vernon Mauery735ee952019-02-15 13:38:52 -0800510 privilege = static_cast<Privilege>(std::get<int>(requestPriv));
511 userId = static_cast<uint8_t>(std::get<int>(requestUserId));
Rajashekar Gade Reddy4d226402019-11-13 17:13:05 +0530512 sessionId =
513 static_cast<uint32_t>(std::get<uint32_t>(requestSessionId));
Vernon Mauery735ee952019-02-15 13:38:52 -0800514 }
515 catch (const std::exception& e)
516 {
517 log<level::ERR>("ERROR determining IPMI session credentials",
518 entry("CHANNEL=%u", channel),
519 entry("NETFN=0x%X", netFn), entry("CMD=0x%X", cmd));
520 return dbusResponse(ipmi::ccUnspecifiedError);
521 }
522 }
523 else
524 {
525 // get max privilege for session-less channels
526 // For now, there is not a way to configure this, default to Admin
527 privilege = Privilege::Admin;
Vernon Maueryd6a2da02019-04-09 16:00:46 -0700528
529 // ipmb should supply rqSA
530 ChannelInfo chInfo;
531 getChannelInfo(channel, chInfo);
532 if (static_cast<EChannelMediumType>(chInfo.mediumType) ==
533 EChannelMediumType::ipmb)
534 {
535 const auto iter = options.find("rqSA");
536 if (iter != options.end())
537 {
538 if (std::holds_alternative<int>(iter->second))
539 {
540 rqSA = std::get<int>(iter->second);
541 }
542 }
Kumar Thangavelf7d081f2020-08-19 20:41:18 +0530543 const auto iteration = options.find("hostId");
544 if (iteration != options.end())
545 {
546 if (std::holds_alternative<int>(iteration->second))
547 {
548 hostIdx = std::get<int>(iteration->second);
549 }
550 }
Vernon Maueryd6a2da02019-04-09 16:00:46 -0700551 }
Vernon Mauery735ee952019-02-15 13:38:52 -0800552 }
553 // check to see if the requested priv/username is valid
554 log<level::DEBUG>("Set up ipmi context", entry("SENDER=%s", sender.c_str()),
Johnathan Manteyc11cc5c2020-07-22 13:52:33 -0700555 entry("NETFN=0x%X", netFn), entry("LUN=0x%X", lun),
556 entry("CMD=0x%X", cmd), entry("CHANNEL=%u", channel),
557 entry("USERID=%u", userId),
Rajashekar Gade Reddy4d226402019-11-13 17:13:05 +0530558 entry("SESSIONID=0x%X", sessionId),
Vernon Maueryd6a2da02019-04-09 16:00:46 -0700559 entry("PRIVILEGE=%u", static_cast<uint8_t>(privilege)),
560 entry("RQSA=%x", rqSA));
Vernon Mauery735ee952019-02-15 13:38:52 -0800561
Johnathan Manteyc11cc5c2020-07-22 13:52:33 -0700562 auto ctx = std::make_shared<ipmi::Context>(getSdBus(), netFn, lun, cmd,
563 channel, userId, sessionId,
Kumar Thangavelf7d081f2020-08-19 20:41:18 +0530564 privilege, rqSA, hostIdx, yield);
Vernon Mauery240b1862018-10-08 12:05:16 -0700565 auto request = std::make_shared<ipmi::message::Request>(
Vernon Mauery997952a2021-07-30 14:06:14 -0700566 ctx, std::forward<ipmi::SecureBuffer>(data));
Vernon Mauery240b1862018-10-08 12:05:16 -0700567 message::Response::ptr response = executeIpmiCommand(request);
568
Vernon Mauery735ee952019-02-15 13:38:52 -0800569 return dbusResponse(response->cc, response->payload.raw);
Vernon Mauery240b1862018-10-08 12:05:16 -0700570}
571
572/** @struct IpmiProvider
573 *
574 * RAII wrapper for dlopen so that dlclose gets called on exit
575 */
576struct IpmiProvider
577{
578 public:
579 /** @brief address of the opened library */
580 void* addr;
581 std::string name;
582
583 IpmiProvider() = delete;
584 IpmiProvider(const IpmiProvider&) = delete;
585 IpmiProvider& operator=(const IpmiProvider&) = delete;
586 IpmiProvider(IpmiProvider&&) = delete;
587 IpmiProvider& operator=(IpmiProvider&&) = delete;
588
589 /** @brief dlopen a shared object file by path
590 * @param[in] filename - path of shared object to open
591 */
592 explicit IpmiProvider(const char* fname) : addr(nullptr), name(fname)
593 {
594 log<level::DEBUG>("Open IPMI provider library",
595 entry("PROVIDER=%s", name.c_str()));
596 try
597 {
598 addr = dlopen(name.c_str(), RTLD_NOW);
599 }
Patrick Williamsa2ad2da2021-10-06 12:21:46 -0500600 catch (const std::exception& e)
Vernon Mauery240b1862018-10-08 12:05:16 -0700601 {
602 log<level::ERR>("ERROR opening IPMI provider",
603 entry("PROVIDER=%s", name.c_str()),
604 entry("ERROR=%s", e.what()));
605 }
606 catch (...)
607 {
Vernon Mauery03d7a4b2021-01-19 11:22:17 -0800608 const char* what = currentExceptionType();
609 phosphor::logging::log<phosphor::logging::level::ERR>(
610 "ERROR opening IPMI provider",
611 entry("PROVIDER=%s", name.c_str()), entry("ERROR=%s", what));
Vernon Mauery240b1862018-10-08 12:05:16 -0700612 }
613 if (!isOpen())
614 {
615 log<level::ERR>("ERROR opening IPMI provider",
616 entry("PROVIDER=%s", name.c_str()),
617 entry("ERROR=%s", dlerror()));
618 }
619 }
620
621 ~IpmiProvider()
622 {
623 if (isOpen())
624 {
625 dlclose(addr);
626 }
627 }
628 bool isOpen() const
629 {
630 return (nullptr != addr);
631 }
632};
633
634// Plugin libraries need to contain .so either at the end or in the middle
635constexpr const char ipmiPluginExtn[] = ".so";
636
637/* return a list of self-closing library handles */
638std::forward_list<IpmiProvider> loadProviders(const fs::path& ipmiLibsPath)
639{
640 std::vector<fs::path> libs;
641 for (const auto& libPath : fs::directory_iterator(ipmiLibsPath))
642 {
Vernon Maueryb0ab5fe2019-03-06 14:03:00 -0800643 std::error_code ec;
Vernon Mauery240b1862018-10-08 12:05:16 -0700644 fs::path fname = libPath.path();
Vernon Maueryb0ab5fe2019-03-06 14:03:00 -0800645 if (fs::is_symlink(fname, ec) || ec)
646 {
647 // it's a symlink or some other error; skip it
648 continue;
649 }
Vernon Mauery240b1862018-10-08 12:05:16 -0700650 while (fname.has_extension())
651 {
652 fs::path extn = fname.extension();
653 if (extn == ipmiPluginExtn)
654 {
655 libs.push_back(libPath.path());
656 break;
657 }
658 fname.replace_extension();
659 }
660 }
661 std::sort(libs.begin(), libs.end());
662
663 std::forward_list<IpmiProvider> handles;
664 for (auto& lib : libs)
665 {
666#ifdef __IPMI_DEBUG__
667 log<level::DEBUG>("Registering handler",
668 entry("HANDLER=%s", lib.c_str()));
669#endif
670 handles.emplace_front(lib.c_str());
671 }
672 return handles;
673}
674
675} // namespace ipmi
676
Vernon Mauery240b1862018-10-08 12:05:16 -0700677#ifdef ALLOW_DEPRECATED_API
678/* legacy registration */
679void ipmi_register_callback(ipmi_netfn_t netFn, ipmi_cmd_t cmd,
680 ipmi_context_t context, ipmid_callback_t handler,
681 ipmi_cmd_privilege_t priv)
682{
Vernon Mauerybe376302019-03-21 13:02:05 -0700683 auto h = ipmi::makeLegacyHandler(handler, context);
Vernon Mauery240b1862018-10-08 12:05:16 -0700684 // translate priv from deprecated enum to current
685 ipmi::Privilege realPriv;
686 switch (priv)
687 {
688 case PRIVILEGE_CALLBACK:
689 realPriv = ipmi::Privilege::Callback;
690 break;
691 case PRIVILEGE_USER:
692 realPriv = ipmi::Privilege::User;
693 break;
694 case PRIVILEGE_OPERATOR:
695 realPriv = ipmi::Privilege::Operator;
696 break;
697 case PRIVILEGE_ADMIN:
698 realPriv = ipmi::Privilege::Admin;
699 break;
700 case PRIVILEGE_OEM:
701 realPriv = ipmi::Privilege::Oem;
702 break;
703 case SYSTEM_INTERFACE:
704 realPriv = ipmi::Privilege::Admin;
705 break;
706 default:
707 realPriv = ipmi::Privilege::Admin;
708 break;
709 }
Vernon Mauerye8d43232019-03-26 16:23:43 -0700710 // The original ipmi_register_callback allowed for group OEM handlers
711 // to be registered via this same interface. It just so happened that
712 // all the handlers were part of the DCMI group, so default to that.
713 if (netFn == NETFUN_GRPEXT)
714 {
715 ipmi::impl::registerGroupHandler(ipmi::prioOpenBmcBase,
716 dcmi::groupExtId, cmd, realPriv, h);
717 }
718 else
719 {
720 ipmi::impl::registerHandler(ipmi::prioOpenBmcBase, netFn, cmd, realPriv,
721 h);
722 }
Vernon Mauery240b1862018-10-08 12:05:16 -0700723}
724
Vernon Maueryf984a012018-10-08 12:05:18 -0700725namespace oem
726{
727
728class LegacyRouter : public oem::Router
729{
730 public:
Patrick Williamsfbc6c9d2023-05-10 07:50:16 -0500731 virtual ~LegacyRouter() {}
Vernon Maueryf984a012018-10-08 12:05:18 -0700732
733 /// Enable message routing to begin.
Patrick Williamsfbc6c9d2023-05-10 07:50:16 -0500734 void activate() override {}
Vernon Maueryf984a012018-10-08 12:05:18 -0700735
736 void registerHandler(Number oen, ipmi_cmd_t cmd, Handler handler) override
737 {
738 auto h = ipmi::makeLegacyHandler(std::forward<Handler>(handler));
739 ipmi::impl::registerOemHandler(ipmi::prioOpenBmcBase, oen, cmd,
740 ipmi::Privilege::Admin, h);
741 }
742};
743static LegacyRouter legacyRouter;
744
745Router* mutableRouter()
746{
747 return &legacyRouter;
748}
749
750} // namespace oem
751
Vernon Mauery240b1862018-10-08 12:05:16 -0700752/* legacy alternative to executionEntry */
Patrick Williams5d82f472022-07-22 19:26:53 -0500753void handleLegacyIpmiCommand(sdbusplus::message_t& m)
Vernon Mauery240b1862018-10-08 12:05:16 -0700754{
Vernon Mauery23b70212019-05-08 15:19:05 -0700755 // make a copy so the next two moves don't wreak havoc on the stack
Patrick Williams5d82f472022-07-22 19:26:53 -0500756 sdbusplus::message_t b{m};
Patrick Williamsfbc6c9d2023-05-10 07:50:16 -0500757 boost::asio::spawn(*getIoContext(),
758 [b = std::move(b)](boost::asio::yield_context yield) {
Patrick Williams5d82f472022-07-22 19:26:53 -0500759 sdbusplus::message_t m{std::move(b)};
Snehalatha Venkatesh55f5d532021-07-13 11:06:36 +0000760 unsigned char seq = 0, netFn = 0, lun = 0, cmd = 0;
Vernon Mauery997952a2021-07-30 14:06:14 -0700761 ipmi::SecureBuffer data;
Vernon Mauery240b1862018-10-08 12:05:16 -0700762
Vernon Mauery23b70212019-05-08 15:19:05 -0700763 m.read(seq, netFn, lun, cmd, data);
Vernon Mauery33298af2019-05-13 15:32:37 -0700764 std::shared_ptr<sdbusplus::asio::connection> bus = getSdBus();
Vernon Mauery23b70212019-05-08 15:19:05 -0700765 auto ctx = std::make_shared<ipmi::Context>(
Kumar Thangavelf7d081f2020-08-19 20:41:18 +0530766 bus, netFn, lun, cmd, 0, 0, 0, ipmi::Privilege::Admin, 0, 0, yield);
Vernon Mauery23b70212019-05-08 15:19:05 -0700767 auto request = std::make_shared<ipmi::message::Request>(
Vernon Mauery997952a2021-07-30 14:06:14 -0700768 ctx, std::forward<ipmi::SecureBuffer>(data));
Vernon Mauery23b70212019-05-08 15:19:05 -0700769 ipmi::message::Response::ptr response =
770 ipmi::executeIpmiCommand(request);
Vernon Mauery240b1862018-10-08 12:05:16 -0700771
Vernon Mauery23b70212019-05-08 15:19:05 -0700772 // Responses in IPMI require a bit set. So there ya go...
773 netFn |= 0x01;
Vernon Mauery240b1862018-10-08 12:05:16 -0700774
Vernon Mauery23b70212019-05-08 15:19:05 -0700775 const char *dest, *path;
776 constexpr const char* DBUS_INTF = "org.openbmc.HostIpmi";
Vernon Mauery240b1862018-10-08 12:05:16 -0700777
Vernon Mauery23b70212019-05-08 15:19:05 -0700778 dest = m.get_sender();
779 path = m.get_path();
780 boost::system::error_code ec;
Vernon Mauery33298af2019-05-13 15:32:37 -0700781 bus->yield_method_call(yield, ec, dest, path, DBUS_INTF, "sendMessage",
782 seq, netFn, lun, cmd, response->cc,
783 response->payload.raw);
Vernon Mauery23b70212019-05-08 15:19:05 -0700784 if (ec)
785 {
786 log<level::ERR>("Failed to send response to requestor",
787 entry("ERROR=%s", ec.message().c_str()),
788 entry("SENDER=%s", dest),
789 entry("NETFN=0x%X", netFn), entry("CMD=0x%X", cmd));
790 }
791 });
Vernon Mauery240b1862018-10-08 12:05:16 -0700792}
793
794#endif /* ALLOW_DEPRECATED_API */
795
796// Calls host command manager to do the right thing for the command
797using CommandHandler = phosphor::host::command::CommandHandler;
798std::unique_ptr<phosphor::host::command::Manager> cmdManager;
799void ipmid_send_cmd_to_host(CommandHandler&& cmd)
800{
Vernon Mauery5e096a22022-06-01 15:11:16 -0700801 cmdManager->execute(std::forward<CommandHandler>(cmd));
Vernon Mauery240b1862018-10-08 12:05:16 -0700802}
803
804std::unique_ptr<phosphor::host::command::Manager>& ipmid_get_host_cmd_manager()
805{
806 return cmdManager;
807}
808
Vernon Mauery20ff3332019-03-01 16:52:25 -0800809// These are symbols that are present in libipmid, but not expected
810// to be used except here (or maybe a unit test), so declare them here
811extern void setIoContext(std::shared_ptr<boost::asio::io_context>& newIo);
812extern void setSdBus(std::shared_ptr<sdbusplus::asio::connection>& newBus);
813
Vernon Mauery240b1862018-10-08 12:05:16 -0700814int main(int argc, char* argv[])
815{
816 // Connect to system bus
Vernon Mauery20ff3332019-03-01 16:52:25 -0800817 auto io = std::make_shared<boost::asio::io_context>();
818 setIoContext(io);
Vernon Mauery240b1862018-10-08 12:05:16 -0700819 if (argc > 1 && std::string(argv[1]) == "-session")
820 {
821 sd_bus_default_user(&bus);
822 }
823 else
824 {
825 sd_bus_default_system(&bus);
826 }
Vernon Mauery20ff3332019-03-01 16:52:25 -0800827 auto sdbusp = std::make_shared<sdbusplus::asio::connection>(*io, bus);
828 setSdBus(sdbusp);
Vernon Mauery240b1862018-10-08 12:05:16 -0700829
830 // TODO: Hack to keep the sdEvents running.... Not sure why the sd_event
831 // queue stops running if we don't have a timer that keeps re-arming
832 phosphor::Timer t2([]() { ; });
833 t2.start(std::chrono::microseconds(500000), true);
834
835 // TODO: Remove all vestiges of sd_event from phosphor-host-ipmid
836 // until that is done, add the sd_event wrapper to the io object
837 sdbusplus::asio::sd_event_wrapper sdEvents(*io);
838
839 cmdManager = std::make_unique<phosphor::host::command::Manager>(*sdbusp);
840
841 // Register all command providers and filters
Vernon Mauery4ec4e402019-03-20 13:09:27 -0700842 std::forward_list<ipmi::IpmiProvider> providers =
843 ipmi::loadProviders(HOST_IPMI_LIB_PATH);
Vernon Mauery240b1862018-10-08 12:05:16 -0700844
Vernon Mauery240b1862018-10-08 12:05:16 -0700845#ifdef ALLOW_DEPRECATED_API
846 // listen on deprecated signal interface for kcs/bt commands
847 constexpr const char* FILTER = "type='signal',interface='org.openbmc."
848 "HostIpmi',member='ReceivedMessage'";
Patrick Williams5d82f472022-07-22 19:26:53 -0500849 sdbusplus::bus::match_t oldIpmiInterface(*sdbusp, FILTER,
850 handleLegacyIpmiCommand);
Vernon Mauery240b1862018-10-08 12:05:16 -0700851#endif /* ALLOW_DEPRECATED_API */
852
Vernon Mauery735ee952019-02-15 13:38:52 -0800853 // set up bus name watching to match channels with bus names
Patrick Williams5d82f472022-07-22 19:26:53 -0500854 sdbusplus::bus::match_t nameOwnerChanged(
Vernon Mauery735ee952019-02-15 13:38:52 -0800855 *sdbusp,
856 sdbusplus::bus::match::rules::nameOwnerChanged() +
857 sdbusplus::bus::match::rules::arg0namespace(
858 ipmi::ipmiDbusChannelMatch),
859 ipmi::nameChangeHandler);
860 ipmi::doListNames(*io, *sdbusp);
861
James Feistb0094a72019-11-26 09:07:15 -0800862 int exitCode = 0;
Vernon Mauery1b7f6f22019-03-13 13:11:25 -0700863 // set up boost::asio signal handling
864 std::function<SignalResponse(int)> stopAsioRunLoop =
James Feistb0094a72019-11-26 09:07:15 -0800865 [&io, &exitCode](int signalNumber) {
Patrick Williamsfbc6c9d2023-05-10 07:50:16 -0500866 log<level::INFO>("Received signal; quitting",
867 entry("SIGNAL=%d", signalNumber));
868 io->stop();
869 exitCode = signalNumber;
870 return SignalResponse::breakExecution;
871 };
Vernon Mauery1b7f6f22019-03-13 13:11:25 -0700872 registerSignalHandler(ipmi::prioOpenBmcBase, SIGINT, stopAsioRunLoop);
873 registerSignalHandler(ipmi::prioOpenBmcBase, SIGTERM, stopAsioRunLoop);
874
Richard Marian Thomaiyar369406e2020-01-09 14:56:54 +0530875 sdbusp->request_name("xyz.openbmc_project.Ipmi.Host");
876 // Add bindings for inbound IPMI requests
877 auto server = sdbusplus::asio::object_server(sdbusp);
878 auto iface = server.add_interface("/xyz/openbmc_project/Ipmi",
879 "xyz.openbmc_project.Ipmi.Server");
880 iface->register_method("execute", ipmi::executionEntry);
881 iface->initialize();
882
Vernon Mauery240b1862018-10-08 12:05:16 -0700883 io->run();
884
Vernon Mauery1b7f6f22019-03-13 13:11:25 -0700885 // destroy all the IPMI handlers so the providers can unload safely
886 ipmi::handlerMap.clear();
887 ipmi::groupHandlerMap.clear();
888 ipmi::oemHandlerMap.clear();
889 ipmi::filterList.clear();
890 // unload the provider libraries
Vernon Mauery4ec4e402019-03-20 13:09:27 -0700891 providers.clear();
Vernon Mauery1b7f6f22019-03-13 13:11:25 -0700892
James Feistb0094a72019-11-26 09:07:15 -0800893 std::exit(exitCode);
Vernon Mauery240b1862018-10-08 12:05:16 -0700894}