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