blob: f3d12c6b143807761e52a15a896881682a9cfb82 [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
22#include <algorithm>
23#include <any>
Vernon Mauery735ee952019-02-15 13:38:52 -080024#include <boost/algorithm/string.hpp>
Ed Tanous778418d2020-08-17 23:20:21 -070025#include <boost/asio/io_context.hpp>
Vernon Mauerye8d43232019-03-26 16:23:43 -070026#include <dcmihandler.hpp>
Vernon Mauery240b1862018-10-08 12:05:16 -070027#include <exception>
Vernon Mauerybdda8002019-02-26 10:18:51 -080028#include <filesystem>
Vernon Mauery240b1862018-10-08 12:05:16 -070029#include <forward_list>
30#include <host-cmd-manager.hpp>
31#include <ipmid-host/cmd.hpp>
32#include <ipmid/api.hpp>
33#include <ipmid/handler.hpp>
34#include <ipmid/message.hpp>
35#include <ipmid/oemrouter.hpp>
Vernon Mauery33250242019-03-12 16:49:26 -070036#include <ipmid/types.hpp>
Vernon Mauery240b1862018-10-08 12:05:16 -070037#include <map>
38#include <memory>
39#include <optional>
40#include <phosphor-logging/log.hpp>
41#include <sdbusplus/asio/connection.hpp>
42#include <sdbusplus/asio/object_server.hpp>
43#include <sdbusplus/asio/sd_event.hpp>
44#include <sdbusplus/bus.hpp>
45#include <sdbusplus/bus/match.hpp>
46#include <sdbusplus/timer.hpp>
47#include <tuple>
Vernon Mauery240b1862018-10-08 12:05:16 -070048#include <unordered_map>
49#include <utility>
50#include <vector>
51
Vernon Mauery240b1862018-10-08 12:05:16 -070052namespace fs = std::filesystem;
53
54using namespace phosphor::logging;
55
Vernon Mauery240b1862018-10-08 12:05:16 -070056// IPMI Spec, shared Reservation ID.
57static unsigned short selReservationID = 0xFFFF;
58static bool selReservationValid = false;
59
60unsigned short reserveSel(void)
61{
62 // IPMI spec, Reservation ID, the value simply increases against each
63 // execution of the Reserve SEL command.
64 if (++selReservationID == 0)
65 {
66 selReservationID = 1;
67 }
68 selReservationValid = true;
69 return selReservationID;
70}
71
72bool checkSELReservation(unsigned short id)
73{
74 return (selReservationValid && selReservationID == id);
75}
76
77void cancelSELReservation(void)
78{
79 selReservationValid = false;
80}
81
82EInterfaceIndex getInterfaceIndex(void)
83{
84 return interfaceKCS;
85}
86
87sd_bus* bus;
88sd_event* events = nullptr;
89sd_event* ipmid_get_sd_event_connection(void)
90{
91 return events;
92}
93sd_bus* ipmid_get_sd_bus_connection(void)
94{
95 return bus;
96}
97
98namespace ipmi
99{
100
101static inline unsigned int makeCmdKey(unsigned int cluster, unsigned int cmd)
102{
103 return (cluster << 8) | cmd;
104}
105
106using HandlerTuple = std::tuple<int, /* prio */
107 Privilege, HandlerBase::ptr /* handler */
108 >;
109
110/* map to handle standard registered commands */
111static std::unordered_map<unsigned int, /* key is NetFn/Cmd */
112 HandlerTuple>
113 handlerMap;
114
Vernon Maueryf984a012018-10-08 12:05:18 -0700115/* special map for decoding Group registered commands (NetFn 2Ch) */
116static std::unordered_map<unsigned int, /* key is Group/Cmd (NetFn is 2Ch) */
117 HandlerTuple>
118 groupHandlerMap;
119
120/* special map for decoding OEM registered commands (NetFn 2Eh) */
121static std::unordered_map<unsigned int, /* key is Iana/Cmd (NetFn is 2Eh) */
122 HandlerTuple>
123 oemHandlerMap;
124
Vernon Mauery08a70aa2018-11-07 09:36:22 -0800125using FilterTuple = std::tuple<int, /* prio */
126 FilterBase::ptr /* filter */
127 >;
128
129/* list to hold all registered ipmi command filters */
130static std::forward_list<FilterTuple> filterList;
131
Vernon Mauery240b1862018-10-08 12:05:16 -0700132namespace impl
133{
134/* common function to register all standard IPMI handlers */
135bool registerHandler(int prio, NetFn netFn, Cmd cmd, Privilege priv,
136 HandlerBase::ptr handler)
137{
138 // check for valid NetFn: even; 00-0Ch, 30-3Eh
139 if (netFn & 1 || (netFn > netFnTransport && netFn < netFnGroup) ||
140 netFn > netFnOemEight)
141 {
142 return false;
143 }
144
145 // create key and value for this handler
146 unsigned int netFnCmd = makeCmdKey(netFn, cmd);
147 HandlerTuple item(prio, priv, handler);
148
149 // consult the handler map and look for a match
150 auto& mapCmd = handlerMap[netFnCmd];
151 if (!std::get<HandlerBase::ptr>(mapCmd) || std::get<int>(mapCmd) <= prio)
152 {
153 mapCmd = item;
154 return true;
155 }
156 return false;
157}
158
Vernon Maueryf984a012018-10-08 12:05:18 -0700159/* common function to register all Group IPMI handlers */
160bool registerGroupHandler(int prio, Group group, Cmd cmd, Privilege priv,
161 HandlerBase::ptr handler)
162{
163 // create key and value for this handler
164 unsigned int netFnCmd = makeCmdKey(group, cmd);
165 HandlerTuple item(prio, priv, handler);
166
167 // consult the handler map and look for a match
168 auto& mapCmd = groupHandlerMap[netFnCmd];
169 if (!std::get<HandlerBase::ptr>(mapCmd) || std::get<int>(mapCmd) <= prio)
170 {
171 mapCmd = item;
172 return true;
173 }
174 return false;
175}
176
177/* common function to register all OEM IPMI handlers */
178bool registerOemHandler(int prio, Iana iana, Cmd cmd, Privilege priv,
179 HandlerBase::ptr handler)
180{
181 // create key and value for this handler
182 unsigned int netFnCmd = makeCmdKey(iana, cmd);
183 HandlerTuple item(prio, priv, handler);
184
185 // consult the handler map and look for a match
186 auto& mapCmd = oemHandlerMap[netFnCmd];
187 if (!std::get<HandlerBase::ptr>(mapCmd) || std::get<int>(mapCmd) <= prio)
188 {
189 mapCmd = item;
190 return true;
191 }
192 return false;
193}
194
Vernon Mauery08a70aa2018-11-07 09:36:22 -0800195/* common function to register all IPMI filter handlers */
196void registerFilter(int prio, FilterBase::ptr filter)
197{
198 // check for initial placement
199 if (filterList.empty() || std::get<int>(filterList.front()) < prio)
200 {
201 filterList.emplace_front(std::make_tuple(prio, filter));
Yong Libe063232021-03-04 16:52:52 +0800202 return;
Vernon Mauery08a70aa2018-11-07 09:36:22 -0800203 }
204 // walk the list and put it in the right place
205 auto j = filterList.begin();
206 for (auto i = j; i != filterList.end() && std::get<int>(*i) > prio; i++)
207 {
208 j = i;
209 }
210 filterList.emplace_after(j, std::make_tuple(prio, filter));
211}
212
Vernon Mauery240b1862018-10-08 12:05:16 -0700213} // namespace impl
214
Vernon Mauery08a70aa2018-11-07 09:36:22 -0800215message::Response::ptr filterIpmiCommand(message::Request::ptr request)
216{
217 // pass the command through the filter mechanism
218 // This can be the firmware firewall or any OEM mechanism like
219 // whitelist filtering based on operational mode
220 for (auto& item : filterList)
221 {
222 FilterBase::ptr filter = std::get<FilterBase::ptr>(item);
223 ipmi::Cc cc = filter->call(request);
224 if (ipmi::ccSuccess != cc)
225 {
226 return errorResponse(request, cc);
227 }
228 }
229 return message::Response::ptr();
230}
231
Vernon Mauery240b1862018-10-08 12:05:16 -0700232message::Response::ptr executeIpmiCommandCommon(
233 std::unordered_map<unsigned int, HandlerTuple>& handlers,
234 unsigned int keyCommon, message::Request::ptr request)
235{
Vernon Mauery08a70aa2018-11-07 09:36:22 -0800236 // filter the command first; a non-null message::Response::ptr
237 // means that the message has been rejected for some reason
Vernon Mauery51f78142020-01-13 16:28:59 -0800238 message::Response::ptr filterResponse = filterIpmiCommand(request);
Vernon Mauery08a70aa2018-11-07 09:36:22 -0800239
Vernon Mauery240b1862018-10-08 12:05:16 -0700240 Cmd cmd = request->ctx->cmd;
241 unsigned int key = makeCmdKey(keyCommon, cmd);
242 auto cmdIter = handlers.find(key);
243 if (cmdIter != handlers.end())
244 {
Vernon Mauery51f78142020-01-13 16:28:59 -0800245 // only return the filter response if the command is found
246 if (filterResponse)
247 {
248 return filterResponse;
249 }
Vernon Mauery240b1862018-10-08 12:05:16 -0700250 HandlerTuple& chosen = cmdIter->second;
251 if (request->ctx->priv < std::get<Privilege>(chosen))
252 {
253 return errorResponse(request, ccInsufficientPrivilege);
254 }
255 return std::get<HandlerBase::ptr>(chosen)->call(request);
256 }
257 else
258 {
259 unsigned int wildcard = makeCmdKey(keyCommon, cmdWildcard);
260 cmdIter = handlers.find(wildcard);
261 if (cmdIter != handlers.end())
262 {
Vernon Mauery51f78142020-01-13 16:28:59 -0800263 // only return the filter response if the command is found
264 if (filterResponse)
265 {
266 return filterResponse;
267 }
Vernon Mauery240b1862018-10-08 12:05:16 -0700268 HandlerTuple& chosen = cmdIter->second;
269 if (request->ctx->priv < std::get<Privilege>(chosen))
270 {
271 return errorResponse(request, ccInsufficientPrivilege);
272 }
273 return std::get<HandlerBase::ptr>(chosen)->call(request);
274 }
275 }
276 return errorResponse(request, ccInvalidCommand);
277}
278
Vernon Maueryf984a012018-10-08 12:05:18 -0700279message::Response::ptr executeIpmiGroupCommand(message::Request::ptr request)
280{
281 // look up the group for this request
William A. Kennington IIId10d9052019-04-24 01:57:36 -0700282 uint8_t bytes;
283 if (0 != request->payload.unpack(bytes))
Vernon Maueryf984a012018-10-08 12:05:18 -0700284 {
285 return errorResponse(request, ccReqDataLenInvalid);
286 }
William A. Kennington IIId10d9052019-04-24 01:57:36 -0700287 auto group = static_cast<Group>(bytes);
Vernon Maueryf984a012018-10-08 12:05:18 -0700288 message::Response::ptr response =
289 executeIpmiCommandCommon(groupHandlerMap, group, request);
William A. Kennington IIIda31f9a2019-04-25 01:36:32 -0700290 ipmi::message::Payload prefix;
291 prefix.pack(bytes);
292 response->prepend(prefix);
Vernon Maueryf984a012018-10-08 12:05:18 -0700293 return response;
294}
295
296message::Response::ptr executeIpmiOemCommand(message::Request::ptr request)
297{
298 // look up the iana for this request
William A. Kennington IIId10d9052019-04-24 01:57:36 -0700299 uint24_t bytes;
300 if (0 != request->payload.unpack(bytes))
Vernon Maueryf984a012018-10-08 12:05:18 -0700301 {
302 return errorResponse(request, ccReqDataLenInvalid);
303 }
William A. Kennington IIId10d9052019-04-24 01:57:36 -0700304 auto iana = static_cast<Iana>(bytes);
Vernon Maueryf984a012018-10-08 12:05:18 -0700305 message::Response::ptr response =
306 executeIpmiCommandCommon(oemHandlerMap, iana, 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
Vernon Mauery240b1862018-10-08 12:05:16 -0700313message::Response::ptr executeIpmiCommand(message::Request::ptr request)
314{
315 NetFn netFn = request->ctx->netFn;
Vernon Maueryf984a012018-10-08 12:05:18 -0700316 if (netFnGroup == netFn)
317 {
318 return executeIpmiGroupCommand(request);
319 }
320 else if (netFnOem == netFn)
321 {
322 return executeIpmiOemCommand(request);
323 }
Vernon Mauery240b1862018-10-08 12:05:16 -0700324 return executeIpmiCommandCommon(handlerMap, netFn, request);
325}
326
Vernon Mauery735ee952019-02-15 13:38:52 -0800327namespace utils
328{
329template <typename AssocContainer, typename UnaryPredicate>
330void assoc_erase_if(AssocContainer& c, UnaryPredicate p)
331{
332 typename AssocContainer::iterator next = c.begin();
333 typename AssocContainer::iterator last = c.end();
334 while ((next = std::find_if(next, last, p)) != last)
335 {
336 c.erase(next++);
337 }
338}
339} // namespace utils
340
341namespace
342{
343std::unordered_map<std::string, uint8_t> uniqueNameToChannelNumber;
344
345// sdbusplus::bus::match::rules::arg0namespace() wants the prefix
346// to match without any trailing '.'
347constexpr const char ipmiDbusChannelMatch[] =
348 "xyz.openbmc_project.Ipmi.Channel";
349void updateOwners(sdbusplus::asio::connection& conn, const std::string& name)
350{
351 conn.async_method_call(
352 [name](const boost::system::error_code ec,
353 const std::string& nameOwner) {
354 if (ec)
355 {
356 log<level::ERR>("Error getting dbus owner",
357 entry("INTERFACE=%s", name.c_str()));
358 return;
359 }
360 // start after ipmiDbusChannelPrefix (after the '.')
361 std::string chName =
362 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 }
376 },
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) {
386 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());
394
395 const std::string channelPrefix =
396 std::string(ipmiDbusChannelMatch) + ".";
397 for (const std::string& busName : busNames)
398 {
399 if (busName.find(channelPrefix) == 0)
400 {
401 updateOwners(conn, busName);
402 }
403 }
404 },
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 = {}) {
Vernon Mauery735ee952019-02-15 13:38:52 -0800479 constexpr uint8_t netFnResponse = 0x01;
480 uint8_t retNetFn = netFn | netFnResponse;
481 return std::make_tuple(retNetFn, lun, cmd, cc, data);
482 };
483 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:
731 virtual ~LegacyRouter()
732 {
733 }
734
735 /// Enable message routing to begin.
736 void activate() override
737 {
738 }
739
740 void registerHandler(Number oen, ipmi_cmd_t cmd, Handler handler) override
741 {
742 auto h = ipmi::makeLegacyHandler(std::forward<Handler>(handler));
743 ipmi::impl::registerOemHandler(ipmi::prioOpenBmcBase, oen, cmd,
744 ipmi::Privilege::Admin, h);
745 }
746};
747static LegacyRouter legacyRouter;
748
749Router* mutableRouter()
750{
751 return &legacyRouter;
752}
753
754} // namespace oem
755
Vernon Mauery240b1862018-10-08 12:05:16 -0700756/* legacy alternative to executionEntry */
Patrick Williams5d82f472022-07-22 19:26:53 -0500757void handleLegacyIpmiCommand(sdbusplus::message_t& m)
Vernon Mauery240b1862018-10-08 12:05:16 -0700758{
Vernon Mauery23b70212019-05-08 15:19:05 -0700759 // make a copy so the next two moves don't wreak havoc on the stack
Patrick Williams5d82f472022-07-22 19:26:53 -0500760 sdbusplus::message_t b{m};
Vernon Mauery23b70212019-05-08 15:19:05 -0700761 boost::asio::spawn(*getIoContext(), [b = std::move(b)](
762 boost::asio::yield_context yield) {
Patrick Williams5d82f472022-07-22 19:26:53 -0500763 sdbusplus::message_t m{std::move(b)};
Snehalatha Venkatesh55f5d532021-07-13 11:06:36 +0000764 unsigned char seq = 0, netFn = 0, lun = 0, cmd = 0;
Vernon Mauery997952a2021-07-30 14:06:14 -0700765 ipmi::SecureBuffer data;
Vernon Mauery240b1862018-10-08 12:05:16 -0700766
Vernon Mauery23b70212019-05-08 15:19:05 -0700767 m.read(seq, netFn, lun, cmd, data);
Vernon Mauery33298af2019-05-13 15:32:37 -0700768 std::shared_ptr<sdbusplus::asio::connection> bus = getSdBus();
Vernon Mauery23b70212019-05-08 15:19:05 -0700769 auto ctx = std::make_shared<ipmi::Context>(
Kumar Thangavelf7d081f2020-08-19 20:41:18 +0530770 bus, netFn, lun, cmd, 0, 0, 0, ipmi::Privilege::Admin, 0, 0, yield);
Vernon Mauery23b70212019-05-08 15:19:05 -0700771 auto request = std::make_shared<ipmi::message::Request>(
Vernon Mauery997952a2021-07-30 14:06:14 -0700772 ctx, std::forward<ipmi::SecureBuffer>(data));
Vernon Mauery23b70212019-05-08 15:19:05 -0700773 ipmi::message::Response::ptr response =
774 ipmi::executeIpmiCommand(request);
Vernon Mauery240b1862018-10-08 12:05:16 -0700775
Vernon Mauery23b70212019-05-08 15:19:05 -0700776 // Responses in IPMI require a bit set. So there ya go...
777 netFn |= 0x01;
Vernon Mauery240b1862018-10-08 12:05:16 -0700778
Vernon Mauery23b70212019-05-08 15:19:05 -0700779 const char *dest, *path;
780 constexpr const char* DBUS_INTF = "org.openbmc.HostIpmi";
Vernon Mauery240b1862018-10-08 12:05:16 -0700781
Vernon Mauery23b70212019-05-08 15:19:05 -0700782 dest = m.get_sender();
783 path = m.get_path();
784 boost::system::error_code ec;
Vernon Mauery33298af2019-05-13 15:32:37 -0700785 bus->yield_method_call(yield, ec, dest, path, DBUS_INTF, "sendMessage",
786 seq, netFn, lun, cmd, response->cc,
787 response->payload.raw);
Vernon Mauery23b70212019-05-08 15:19:05 -0700788 if (ec)
789 {
790 log<level::ERR>("Failed to send response to requestor",
791 entry("ERROR=%s", ec.message().c_str()),
792 entry("SENDER=%s", dest),
793 entry("NETFN=0x%X", netFn), entry("CMD=0x%X", cmd));
794 }
795 });
Vernon Mauery240b1862018-10-08 12:05:16 -0700796}
797
798#endif /* ALLOW_DEPRECATED_API */
799
800// Calls host command manager to do the right thing for the command
801using CommandHandler = phosphor::host::command::CommandHandler;
802std::unique_ptr<phosphor::host::command::Manager> cmdManager;
803void ipmid_send_cmd_to_host(CommandHandler&& cmd)
804{
Vernon Mauery5e096a22022-06-01 15:11:16 -0700805 cmdManager->execute(std::forward<CommandHandler>(cmd));
Vernon Mauery240b1862018-10-08 12:05:16 -0700806}
807
808std::unique_ptr<phosphor::host::command::Manager>& ipmid_get_host_cmd_manager()
809{
810 return cmdManager;
811}
812
Vernon Mauery20ff3332019-03-01 16:52:25 -0800813// These are symbols that are present in libipmid, but not expected
814// to be used except here (or maybe a unit test), so declare them here
815extern void setIoContext(std::shared_ptr<boost::asio::io_context>& newIo);
816extern void setSdBus(std::shared_ptr<sdbusplus::asio::connection>& newBus);
817
Vernon Mauery240b1862018-10-08 12:05:16 -0700818int main(int argc, char* argv[])
819{
820 // Connect to system bus
Vernon Mauery20ff3332019-03-01 16:52:25 -0800821 auto io = std::make_shared<boost::asio::io_context>();
822 setIoContext(io);
Vernon Mauery240b1862018-10-08 12:05:16 -0700823 if (argc > 1 && std::string(argv[1]) == "-session")
824 {
825 sd_bus_default_user(&bus);
826 }
827 else
828 {
829 sd_bus_default_system(&bus);
830 }
Vernon Mauery20ff3332019-03-01 16:52:25 -0800831 auto sdbusp = std::make_shared<sdbusplus::asio::connection>(*io, bus);
832 setSdBus(sdbusp);
Vernon Mauery240b1862018-10-08 12:05:16 -0700833
834 // TODO: Hack to keep the sdEvents running.... Not sure why the sd_event
835 // queue stops running if we don't have a timer that keeps re-arming
836 phosphor::Timer t2([]() { ; });
837 t2.start(std::chrono::microseconds(500000), true);
838
839 // TODO: Remove all vestiges of sd_event from phosphor-host-ipmid
840 // until that is done, add the sd_event wrapper to the io object
841 sdbusplus::asio::sd_event_wrapper sdEvents(*io);
842
843 cmdManager = std::make_unique<phosphor::host::command::Manager>(*sdbusp);
844
845 // Register all command providers and filters
Vernon Mauery4ec4e402019-03-20 13:09:27 -0700846 std::forward_list<ipmi::IpmiProvider> providers =
847 ipmi::loadProviders(HOST_IPMI_LIB_PATH);
Vernon Mauery240b1862018-10-08 12:05:16 -0700848
Vernon Mauery240b1862018-10-08 12:05:16 -0700849#ifdef ALLOW_DEPRECATED_API
850 // listen on deprecated signal interface for kcs/bt commands
851 constexpr const char* FILTER = "type='signal',interface='org.openbmc."
852 "HostIpmi',member='ReceivedMessage'";
Patrick Williams5d82f472022-07-22 19:26:53 -0500853 sdbusplus::bus::match_t oldIpmiInterface(*sdbusp, FILTER,
854 handleLegacyIpmiCommand);
Vernon Mauery240b1862018-10-08 12:05:16 -0700855#endif /* ALLOW_DEPRECATED_API */
856
Vernon Mauery735ee952019-02-15 13:38:52 -0800857 // set up bus name watching to match channels with bus names
Patrick Williams5d82f472022-07-22 19:26:53 -0500858 sdbusplus::bus::match_t nameOwnerChanged(
Vernon Mauery735ee952019-02-15 13:38:52 -0800859 *sdbusp,
860 sdbusplus::bus::match::rules::nameOwnerChanged() +
861 sdbusplus::bus::match::rules::arg0namespace(
862 ipmi::ipmiDbusChannelMatch),
863 ipmi::nameChangeHandler);
864 ipmi::doListNames(*io, *sdbusp);
865
James Feistb0094a72019-11-26 09:07:15 -0800866 int exitCode = 0;
Vernon Mauery1b7f6f22019-03-13 13:11:25 -0700867 // set up boost::asio signal handling
868 std::function<SignalResponse(int)> stopAsioRunLoop =
James Feistb0094a72019-11-26 09:07:15 -0800869 [&io, &exitCode](int signalNumber) {
Vernon Mauery1b7f6f22019-03-13 13:11:25 -0700870 log<level::INFO>("Received signal; quitting",
871 entry("SIGNAL=%d", signalNumber));
872 io->stop();
James Feistb0094a72019-11-26 09:07:15 -0800873 exitCode = signalNumber;
Vernon Mauery1b7f6f22019-03-13 13:11:25 -0700874 return SignalResponse::breakExecution;
875 };
876 registerSignalHandler(ipmi::prioOpenBmcBase, SIGINT, stopAsioRunLoop);
877 registerSignalHandler(ipmi::prioOpenBmcBase, SIGTERM, stopAsioRunLoop);
878
Richard Marian Thomaiyar369406e2020-01-09 14:56:54 +0530879 sdbusp->request_name("xyz.openbmc_project.Ipmi.Host");
880 // Add bindings for inbound IPMI requests
881 auto server = sdbusplus::asio::object_server(sdbusp);
882 auto iface = server.add_interface("/xyz/openbmc_project/Ipmi",
883 "xyz.openbmc_project.Ipmi.Server");
884 iface->register_method("execute", ipmi::executionEntry);
885 iface->initialize();
886
Vernon Mauery240b1862018-10-08 12:05:16 -0700887 io->run();
888
Vernon Mauery1b7f6f22019-03-13 13:11:25 -0700889 // destroy all the IPMI handlers so the providers can unload safely
890 ipmi::handlerMap.clear();
891 ipmi::groupHandlerMap.clear();
892 ipmi::oemHandlerMap.clear();
893 ipmi::filterList.clear();
894 // unload the provider libraries
Vernon Mauery4ec4e402019-03-20 13:09:27 -0700895 providers.clear();
Vernon Mauery1b7f6f22019-03-13 13:11:25 -0700896
James Feistb0094a72019-11-26 09:07:15 -0800897 std::exit(exitCode);
Vernon Mauery240b1862018-10-08 12:05:16 -0700898}