blob: a92d4c49f512fd943e9e601bf30e6dbbe280b30f [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>
24#include <exception>
25#include <forward_list>
26#include <host-cmd-manager.hpp>
27#include <ipmid-host/cmd.hpp>
28#include <ipmid/api.hpp>
29#include <ipmid/handler.hpp>
30#include <ipmid/message.hpp>
31#include <ipmid/oemrouter.hpp>
32#include <ipmid/registration.hpp>
33#include <map>
34#include <memory>
35#include <optional>
36#include <phosphor-logging/log.hpp>
37#include <sdbusplus/asio/connection.hpp>
38#include <sdbusplus/asio/object_server.hpp>
39#include <sdbusplus/asio/sd_event.hpp>
40#include <sdbusplus/bus.hpp>
41#include <sdbusplus/bus/match.hpp>
42#include <sdbusplus/timer.hpp>
43#include <tuple>
44#include <types.hpp>
45#include <unordered_map>
46#include <utility>
47#include <vector>
48
49#if __has_include(<filesystem>)
50#include <filesystem>
51#elif __has_include(<experimental/filesystem>)
52#include <experimental/filesystem>
53namespace std
54{
55// splice experimental::filesystem into std
56namespace filesystem = std::experimental::filesystem;
57} // namespace std
58#else
59#error filesystem not available
60#endif
61
62namespace fs = std::filesystem;
63
64using namespace phosphor::logging;
65
Vernon Mauery240b1862018-10-08 12:05:16 -070066// IPMI Spec, shared Reservation ID.
67static unsigned short selReservationID = 0xFFFF;
68static bool selReservationValid = false;
69
70unsigned short reserveSel(void)
71{
72 // IPMI spec, Reservation ID, the value simply increases against each
73 // execution of the Reserve SEL command.
74 if (++selReservationID == 0)
75 {
76 selReservationID = 1;
77 }
78 selReservationValid = true;
79 return selReservationID;
80}
81
82bool checkSELReservation(unsigned short id)
83{
84 return (selReservationValid && selReservationID == id);
85}
86
87void cancelSELReservation(void)
88{
89 selReservationValid = false;
90}
91
92EInterfaceIndex getInterfaceIndex(void)
93{
94 return interfaceKCS;
95}
96
97sd_bus* bus;
98sd_event* events = nullptr;
99sd_event* ipmid_get_sd_event_connection(void)
100{
101 return events;
102}
103sd_bus* ipmid_get_sd_bus_connection(void)
104{
105 return bus;
106}
107
108namespace ipmi
109{
110
111static inline unsigned int makeCmdKey(unsigned int cluster, unsigned int cmd)
112{
113 return (cluster << 8) | cmd;
114}
115
116using HandlerTuple = std::tuple<int, /* prio */
117 Privilege, HandlerBase::ptr /* handler */
118 >;
119
120/* map to handle standard registered commands */
121static std::unordered_map<unsigned int, /* key is NetFn/Cmd */
122 HandlerTuple>
123 handlerMap;
124
Vernon Maueryf984a012018-10-08 12:05:18 -0700125/* special map for decoding Group registered commands (NetFn 2Ch) */
126static std::unordered_map<unsigned int, /* key is Group/Cmd (NetFn is 2Ch) */
127 HandlerTuple>
128 groupHandlerMap;
129
130/* special map for decoding OEM registered commands (NetFn 2Eh) */
131static std::unordered_map<unsigned int, /* key is Iana/Cmd (NetFn is 2Eh) */
132 HandlerTuple>
133 oemHandlerMap;
134
Vernon Mauery08a70aa2018-11-07 09:36:22 -0800135using FilterTuple = std::tuple<int, /* prio */
136 FilterBase::ptr /* filter */
137 >;
138
139/* list to hold all registered ipmi command filters */
140static std::forward_list<FilterTuple> filterList;
141
Vernon Mauery240b1862018-10-08 12:05:16 -0700142namespace impl
143{
144/* common function to register all standard IPMI handlers */
145bool registerHandler(int prio, NetFn netFn, Cmd cmd, Privilege priv,
146 HandlerBase::ptr handler)
147{
148 // check for valid NetFn: even; 00-0Ch, 30-3Eh
149 if (netFn & 1 || (netFn > netFnTransport && netFn < netFnGroup) ||
150 netFn > netFnOemEight)
151 {
152 return false;
153 }
154
155 // create key and value for this handler
156 unsigned int netFnCmd = makeCmdKey(netFn, cmd);
157 HandlerTuple item(prio, priv, handler);
158
159 // consult the handler map and look for a match
160 auto& mapCmd = handlerMap[netFnCmd];
161 if (!std::get<HandlerBase::ptr>(mapCmd) || std::get<int>(mapCmd) <= prio)
162 {
163 mapCmd = item;
164 return true;
165 }
166 return false;
167}
168
Vernon Maueryf984a012018-10-08 12:05:18 -0700169/* common function to register all Group IPMI handlers */
170bool registerGroupHandler(int prio, Group group, Cmd cmd, Privilege priv,
171 HandlerBase::ptr handler)
172{
173 // create key and value for this handler
174 unsigned int netFnCmd = makeCmdKey(group, cmd);
175 HandlerTuple item(prio, priv, handler);
176
177 // consult the handler map and look for a match
178 auto& mapCmd = groupHandlerMap[netFnCmd];
179 if (!std::get<HandlerBase::ptr>(mapCmd) || std::get<int>(mapCmd) <= prio)
180 {
181 mapCmd = item;
182 return true;
183 }
184 return false;
185}
186
187/* common function to register all OEM IPMI handlers */
188bool registerOemHandler(int prio, Iana iana, Cmd cmd, Privilege priv,
189 HandlerBase::ptr handler)
190{
191 // create key and value for this handler
192 unsigned int netFnCmd = makeCmdKey(iana, cmd);
193 HandlerTuple item(prio, priv, handler);
194
195 // consult the handler map and look for a match
196 auto& mapCmd = oemHandlerMap[netFnCmd];
197 if (!std::get<HandlerBase::ptr>(mapCmd) || std::get<int>(mapCmd) <= prio)
198 {
199 mapCmd = item;
200 return true;
201 }
202 return false;
203}
204
Vernon Mauery08a70aa2018-11-07 09:36:22 -0800205/* common function to register all IPMI filter handlers */
206void registerFilter(int prio, FilterBase::ptr filter)
207{
208 // check for initial placement
209 if (filterList.empty() || std::get<int>(filterList.front()) < prio)
210 {
211 filterList.emplace_front(std::make_tuple(prio, filter));
212 }
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
247 message::Response::ptr response = filterIpmiCommand(request);
248 if (response)
249 {
250 return response;
251 }
252
Vernon Mauery240b1862018-10-08 12:05:16 -0700253 Cmd cmd = request->ctx->cmd;
254 unsigned int key = makeCmdKey(keyCommon, cmd);
255 auto cmdIter = handlers.find(key);
256 if (cmdIter != handlers.end())
257 {
258 HandlerTuple& chosen = cmdIter->second;
259 if (request->ctx->priv < std::get<Privilege>(chosen))
260 {
261 return errorResponse(request, ccInsufficientPrivilege);
262 }
263 return std::get<HandlerBase::ptr>(chosen)->call(request);
264 }
265 else
266 {
267 unsigned int wildcard = makeCmdKey(keyCommon, cmdWildcard);
268 cmdIter = handlers.find(wildcard);
269 if (cmdIter != handlers.end())
270 {
271 HandlerTuple& chosen = cmdIter->second;
272 if (request->ctx->priv < std::get<Privilege>(chosen))
273 {
274 return errorResponse(request, ccInsufficientPrivilege);
275 }
276 return std::get<HandlerBase::ptr>(chosen)->call(request);
277 }
278 }
279 return errorResponse(request, ccInvalidCommand);
280}
281
Vernon Maueryf984a012018-10-08 12:05:18 -0700282message::Response::ptr executeIpmiGroupCommand(message::Request::ptr request)
283{
284 // look up the group for this request
285 Group group;
Vernon Maueryd35dcd02019-03-13 08:54:12 -0700286 if (0 != request->payload.unpack(group))
Vernon Maueryf984a012018-10-08 12:05:18 -0700287 {
288 return errorResponse(request, ccReqDataLenInvalid);
289 }
290 // The handler will need to unpack group as well; we just need it for lookup
291 request->payload.reset();
292 message::Response::ptr response =
293 executeIpmiCommandCommon(groupHandlerMap, group, request);
294 // if the handler should add the group; executeIpmiCommandCommon does not
295 if (response->cc != ccSuccess && response->payload.size() == 0)
296 {
297 response->pack(group);
298 }
299 return response;
300}
301
302message::Response::ptr executeIpmiOemCommand(message::Request::ptr request)
303{
304 // look up the iana for this request
305 Iana iana;
Vernon Maueryd35dcd02019-03-13 08:54:12 -0700306 if (0 != request->payload.unpack(iana))
Vernon Maueryf984a012018-10-08 12:05:18 -0700307 {
308 return errorResponse(request, ccReqDataLenInvalid);
309 }
310 request->payload.reset();
311 message::Response::ptr response =
312 executeIpmiCommandCommon(oemHandlerMap, iana, request);
313 // if the handler should add the iana; executeIpmiCommandCommon does not
314 if (response->cc != ccSuccess && response->payload.size() == 0)
315 {
316 response->pack(iana);
317 }
318 return response;
319}
320
Vernon Mauery240b1862018-10-08 12:05:16 -0700321message::Response::ptr executeIpmiCommand(message::Request::ptr request)
322{
323 NetFn netFn = request->ctx->netFn;
Vernon Maueryf984a012018-10-08 12:05:18 -0700324 if (netFnGroup == netFn)
325 {
326 return executeIpmiGroupCommand(request);
327 }
328 else if (netFnOem == netFn)
329 {
330 return executeIpmiOemCommand(request);
331 }
Vernon Mauery240b1862018-10-08 12:05:16 -0700332 return executeIpmiCommandCommon(handlerMap, netFn, request);
333}
334
335/* called from sdbus async server context */
336auto executionEntry(boost::asio::yield_context yield, NetFn netFn, uint8_t lun,
337 Cmd cmd, std::vector<uint8_t>& data,
338 std::map<std::string, ipmi::Value>& options)
339{
340 auto ctx = std::make_shared<ipmi::Context>(netFn, cmd, 0, 0,
341 ipmi::Privilege::Admin, &yield);
342 auto request = std::make_shared<ipmi::message::Request>(
343 ctx, std::forward<std::vector<uint8_t>>(data));
344 message::Response::ptr response = executeIpmiCommand(request);
345
346 // Responses in IPMI require a bit set. So there ya go...
347 netFn |= 0x01;
348 return std::make_tuple(netFn, lun, cmd, response->cc,
349 response->payload.raw);
350}
351
352/** @struct IpmiProvider
353 *
354 * RAII wrapper for dlopen so that dlclose gets called on exit
355 */
356struct IpmiProvider
357{
358 public:
359 /** @brief address of the opened library */
360 void* addr;
361 std::string name;
362
363 IpmiProvider() = delete;
364 IpmiProvider(const IpmiProvider&) = delete;
365 IpmiProvider& operator=(const IpmiProvider&) = delete;
366 IpmiProvider(IpmiProvider&&) = delete;
367 IpmiProvider& operator=(IpmiProvider&&) = delete;
368
369 /** @brief dlopen a shared object file by path
370 * @param[in] filename - path of shared object to open
371 */
372 explicit IpmiProvider(const char* fname) : addr(nullptr), name(fname)
373 {
374 log<level::DEBUG>("Open IPMI provider library",
375 entry("PROVIDER=%s", name.c_str()));
376 try
377 {
378 addr = dlopen(name.c_str(), RTLD_NOW);
379 }
380 catch (std::exception& e)
381 {
382 log<level::ERR>("ERROR opening IPMI provider",
383 entry("PROVIDER=%s", name.c_str()),
384 entry("ERROR=%s", e.what()));
385 }
386 catch (...)
387 {
388 std::exception_ptr eptr = std::current_exception();
389 try
390 {
391 std::rethrow_exception(eptr);
392 }
393 catch (std::exception& e)
394 {
395 log<level::ERR>("ERROR opening IPMI provider",
396 entry("PROVIDER=%s", name.c_str()),
397 entry("ERROR=%s", e.what()));
398 }
399 }
400 if (!isOpen())
401 {
402 log<level::ERR>("ERROR opening IPMI provider",
403 entry("PROVIDER=%s", name.c_str()),
404 entry("ERROR=%s", dlerror()));
405 }
406 }
407
408 ~IpmiProvider()
409 {
410 if (isOpen())
411 {
412 dlclose(addr);
413 }
414 }
415 bool isOpen() const
416 {
417 return (nullptr != addr);
418 }
419};
420
421// Plugin libraries need to contain .so either at the end or in the middle
422constexpr const char ipmiPluginExtn[] = ".so";
423
424/* return a list of self-closing library handles */
425std::forward_list<IpmiProvider> loadProviders(const fs::path& ipmiLibsPath)
426{
427 std::vector<fs::path> libs;
428 for (const auto& libPath : fs::directory_iterator(ipmiLibsPath))
429 {
430 fs::path fname = libPath.path();
431 while (fname.has_extension())
432 {
433 fs::path extn = fname.extension();
434 if (extn == ipmiPluginExtn)
435 {
436 libs.push_back(libPath.path());
437 break;
438 }
439 fname.replace_extension();
440 }
441 }
442 std::sort(libs.begin(), libs.end());
443
444 std::forward_list<IpmiProvider> handles;
445 for (auto& lib : libs)
446 {
447#ifdef __IPMI_DEBUG__
448 log<level::DEBUG>("Registering handler",
449 entry("HANDLER=%s", lib.c_str()));
450#endif
451 handles.emplace_front(lib.c_str());
452 }
453 return handles;
454}
455
456} // namespace ipmi
457
Vernon Mauery240b1862018-10-08 12:05:16 -0700458#ifdef ALLOW_DEPRECATED_API
459/* legacy registration */
460void ipmi_register_callback(ipmi_netfn_t netFn, ipmi_cmd_t cmd,
461 ipmi_context_t context, ipmid_callback_t handler,
462 ipmi_cmd_privilege_t priv)
463{
Vernon Mauerybe376302019-03-21 13:02:05 -0700464 auto h = ipmi::makeLegacyHandler(handler, context);
Vernon Mauery240b1862018-10-08 12:05:16 -0700465 // translate priv from deprecated enum to current
466 ipmi::Privilege realPriv;
467 switch (priv)
468 {
469 case PRIVILEGE_CALLBACK:
470 realPriv = ipmi::Privilege::Callback;
471 break;
472 case PRIVILEGE_USER:
473 realPriv = ipmi::Privilege::User;
474 break;
475 case PRIVILEGE_OPERATOR:
476 realPriv = ipmi::Privilege::Operator;
477 break;
478 case PRIVILEGE_ADMIN:
479 realPriv = ipmi::Privilege::Admin;
480 break;
481 case PRIVILEGE_OEM:
482 realPriv = ipmi::Privilege::Oem;
483 break;
484 case SYSTEM_INTERFACE:
485 realPriv = ipmi::Privilege::Admin;
486 break;
487 default:
488 realPriv = ipmi::Privilege::Admin;
489 break;
490 }
491 ipmi::impl::registerHandler(ipmi::prioOpenBmcBase, netFn, cmd, realPriv, h);
492}
493
Vernon Maueryf984a012018-10-08 12:05:18 -0700494namespace oem
495{
496
497class LegacyRouter : public oem::Router
498{
499 public:
500 virtual ~LegacyRouter()
501 {
502 }
503
504 /// Enable message routing to begin.
505 void activate() override
506 {
507 }
508
509 void registerHandler(Number oen, ipmi_cmd_t cmd, Handler handler) override
510 {
511 auto h = ipmi::makeLegacyHandler(std::forward<Handler>(handler));
512 ipmi::impl::registerOemHandler(ipmi::prioOpenBmcBase, oen, cmd,
513 ipmi::Privilege::Admin, h);
514 }
515};
516static LegacyRouter legacyRouter;
517
518Router* mutableRouter()
519{
520 return &legacyRouter;
521}
522
523} // namespace oem
524
Vernon Mauery240b1862018-10-08 12:05:16 -0700525/* legacy alternative to executionEntry */
526void handleLegacyIpmiCommand(sdbusplus::message::message& m)
527{
528 unsigned char seq, netFn, lun, cmd;
529 std::vector<uint8_t> data;
530
531 m.read(seq, netFn, lun, cmd, data);
532
533 auto ctx = std::make_shared<ipmi::Context>(netFn, cmd, 0, 0,
534 ipmi::Privilege::Admin);
535 auto request = std::make_shared<ipmi::message::Request>(
536 ctx, std::forward<std::vector<uint8_t>>(data));
537 ipmi::message::Response::ptr response = ipmi::executeIpmiCommand(request);
538
539 // Responses in IPMI require a bit set. So there ya go...
540 netFn |= 0x01;
541
542 const char *dest, *path;
543 constexpr const char* DBUS_INTF = "org.openbmc.HostIpmi";
544
545 dest = m.get_sender();
546 path = m.get_path();
Vernon Mauery20ff3332019-03-01 16:52:25 -0800547 getSdBus()->async_method_call([](boost::system::error_code ec) {}, dest,
548 path, DBUS_INTF, "sendMessage", seq, netFn,
549 lun, cmd, response->cc,
550 response->payload.raw);
Vernon Mauery240b1862018-10-08 12:05:16 -0700551}
552
553#endif /* ALLOW_DEPRECATED_API */
554
555// Calls host command manager to do the right thing for the command
556using CommandHandler = phosphor::host::command::CommandHandler;
557std::unique_ptr<phosphor::host::command::Manager> cmdManager;
558void ipmid_send_cmd_to_host(CommandHandler&& cmd)
559{
Vernon Mauery1b7f6f22019-03-13 13:11:25 -0700560 return cmdManager->execute(std::forward<CommandHandler>(cmd));
Vernon Mauery240b1862018-10-08 12:05:16 -0700561}
562
563std::unique_ptr<phosphor::host::command::Manager>& ipmid_get_host_cmd_manager()
564{
565 return cmdManager;
566}
567
Vernon Mauery20ff3332019-03-01 16:52:25 -0800568// These are symbols that are present in libipmid, but not expected
569// to be used except here (or maybe a unit test), so declare them here
570extern void setIoContext(std::shared_ptr<boost::asio::io_context>& newIo);
571extern void setSdBus(std::shared_ptr<sdbusplus::asio::connection>& newBus);
572
Vernon Mauery240b1862018-10-08 12:05:16 -0700573int main(int argc, char* argv[])
574{
575 // Connect to system bus
Vernon Mauery20ff3332019-03-01 16:52:25 -0800576 auto io = std::make_shared<boost::asio::io_context>();
577 setIoContext(io);
Vernon Mauery240b1862018-10-08 12:05:16 -0700578 if (argc > 1 && std::string(argv[1]) == "-session")
579 {
580 sd_bus_default_user(&bus);
581 }
582 else
583 {
584 sd_bus_default_system(&bus);
585 }
Vernon Mauery20ff3332019-03-01 16:52:25 -0800586 auto sdbusp = std::make_shared<sdbusplus::asio::connection>(*io, bus);
587 setSdBus(sdbusp);
Vernon Mauery240b1862018-10-08 12:05:16 -0700588 sdbusp->request_name("xyz.openbmc_project.Ipmi.Host");
589
590 // TODO: Hack to keep the sdEvents running.... Not sure why the sd_event
591 // queue stops running if we don't have a timer that keeps re-arming
592 phosphor::Timer t2([]() { ; });
593 t2.start(std::chrono::microseconds(500000), true);
594
595 // TODO: Remove all vestiges of sd_event from phosphor-host-ipmid
596 // until that is done, add the sd_event wrapper to the io object
597 sdbusplus::asio::sd_event_wrapper sdEvents(*io);
598
599 cmdManager = std::make_unique<phosphor::host::command::Manager>(*sdbusp);
600
601 // Register all command providers and filters
Vernon Mauery4ec4e402019-03-20 13:09:27 -0700602 std::forward_list<ipmi::IpmiProvider> providers =
603 ipmi::loadProviders(HOST_IPMI_LIB_PATH);
Vernon Mauery240b1862018-10-08 12:05:16 -0700604
605 // Add bindings for inbound IPMI requests
606 auto server = sdbusplus::asio::object_server(sdbusp);
607 auto iface = server.add_interface("/xyz/openbmc_project/Ipmi",
608 "xyz.openbmc_project.Ipmi.Server");
609 iface->register_method("execute", ipmi::executionEntry);
610 iface->initialize();
611
612#ifdef ALLOW_DEPRECATED_API
613 // listen on deprecated signal interface for kcs/bt commands
614 constexpr const char* FILTER = "type='signal',interface='org.openbmc."
615 "HostIpmi',member='ReceivedMessage'";
616 sdbusplus::bus::match::match oldIpmiInterface(*sdbusp, FILTER,
617 handleLegacyIpmiCommand);
618#endif /* ALLOW_DEPRECATED_API */
619
Vernon Mauery1b7f6f22019-03-13 13:11:25 -0700620 // set up boost::asio signal handling
621 std::function<SignalResponse(int)> stopAsioRunLoop =
622 [&io](int signalNumber) {
623 log<level::INFO>("Received signal; quitting",
624 entry("SIGNAL=%d", signalNumber));
625 io->stop();
626 return SignalResponse::breakExecution;
627 };
628 registerSignalHandler(ipmi::prioOpenBmcBase, SIGINT, stopAsioRunLoop);
629 registerSignalHandler(ipmi::prioOpenBmcBase, SIGTERM, stopAsioRunLoop);
630
Vernon Mauery240b1862018-10-08 12:05:16 -0700631 io->run();
632
Vernon Mauery1b7f6f22019-03-13 13:11:25 -0700633 // destroy all the IPMI handlers so the providers can unload safely
634 ipmi::handlerMap.clear();
635 ipmi::groupHandlerMap.clear();
636 ipmi::oemHandlerMap.clear();
637 ipmi::filterList.clear();
638 // unload the provider libraries
Vernon Mauery4ec4e402019-03-20 13:09:27 -0700639 providers.clear();
Vernon Mauery1b7f6f22019-03-13 13:11:25 -0700640
Vernon Mauery240b1862018-10-08 12:05:16 -0700641 return 0;
642}