blob: 361288476e146b1d790100a6f40181670b58c475 [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>
Vernon Mauerye8d43232019-03-26 16:23:43 -070025#include <dcmihandler.hpp>
Vernon Mauery240b1862018-10-08 12:05:16 -070026#include <exception>
Vernon Mauerybdda8002019-02-26 10:18:51 -080027#include <filesystem>
Vernon Mauery240b1862018-10-08 12:05:16 -070028#include <forward_list>
29#include <host-cmd-manager.hpp>
30#include <ipmid-host/cmd.hpp>
31#include <ipmid/api.hpp>
32#include <ipmid/handler.hpp>
33#include <ipmid/message.hpp>
34#include <ipmid/oemrouter.hpp>
Vernon Mauery33250242019-03-12 16:49:26 -070035#include <ipmid/types.hpp>
Vernon Mauery240b1862018-10-08 12:05:16 -070036#include <map>
37#include <memory>
38#include <optional>
39#include <phosphor-logging/log.hpp>
40#include <sdbusplus/asio/connection.hpp>
41#include <sdbusplus/asio/object_server.hpp>
42#include <sdbusplus/asio/sd_event.hpp>
43#include <sdbusplus/bus.hpp>
44#include <sdbusplus/bus/match.hpp>
45#include <sdbusplus/timer.hpp>
46#include <tuple>
Vernon Mauery240b1862018-10-08 12:05:16 -070047#include <unordered_map>
48#include <utility>
49#include <vector>
50
Vernon Mauery240b1862018-10-08 12:05:16 -070051namespace fs = std::filesystem;
52
53using namespace phosphor::logging;
54
Vernon Mauery240b1862018-10-08 12:05:16 -070055// IPMI Spec, shared Reservation ID.
56static unsigned short selReservationID = 0xFFFF;
57static bool selReservationValid = false;
58
59unsigned short reserveSel(void)
60{
61 // IPMI spec, Reservation ID, the value simply increases against each
62 // execution of the Reserve SEL command.
63 if (++selReservationID == 0)
64 {
65 selReservationID = 1;
66 }
67 selReservationValid = true;
68 return selReservationID;
69}
70
71bool checkSELReservation(unsigned short id)
72{
73 return (selReservationValid && selReservationID == id);
74}
75
76void cancelSELReservation(void)
77{
78 selReservationValid = false;
79}
80
81EInterfaceIndex getInterfaceIndex(void)
82{
83 return interfaceKCS;
84}
85
86sd_bus* bus;
87sd_event* events = nullptr;
88sd_event* ipmid_get_sd_event_connection(void)
89{
90 return events;
91}
92sd_bus* ipmid_get_sd_bus_connection(void)
93{
94 return bus;
95}
96
97namespace ipmi
98{
99
100static inline unsigned int makeCmdKey(unsigned int cluster, unsigned int cmd)
101{
102 return (cluster << 8) | cmd;
103}
104
105using HandlerTuple = std::tuple<int, /* prio */
106 Privilege, HandlerBase::ptr /* handler */
107 >;
108
109/* map to handle standard registered commands */
110static std::unordered_map<unsigned int, /* key is NetFn/Cmd */
111 HandlerTuple>
112 handlerMap;
113
Vernon Maueryf984a012018-10-08 12:05:18 -0700114/* special map for decoding Group registered commands (NetFn 2Ch) */
115static std::unordered_map<unsigned int, /* key is Group/Cmd (NetFn is 2Ch) */
116 HandlerTuple>
117 groupHandlerMap;
118
119/* special map for decoding OEM registered commands (NetFn 2Eh) */
120static std::unordered_map<unsigned int, /* key is Iana/Cmd (NetFn is 2Eh) */
121 HandlerTuple>
122 oemHandlerMap;
123
Vernon Mauery08a70aa2018-11-07 09:36:22 -0800124using FilterTuple = std::tuple<int, /* prio */
125 FilterBase::ptr /* filter */
126 >;
127
128/* list to hold all registered ipmi command filters */
129static std::forward_list<FilterTuple> filterList;
130
Vernon Mauery240b1862018-10-08 12:05:16 -0700131namespace impl
132{
133/* common function to register all standard IPMI handlers */
134bool registerHandler(int prio, NetFn netFn, Cmd cmd, Privilege priv,
135 HandlerBase::ptr handler)
136{
137 // check for valid NetFn: even; 00-0Ch, 30-3Eh
138 if (netFn & 1 || (netFn > netFnTransport && netFn < netFnGroup) ||
139 netFn > netFnOemEight)
140 {
141 return false;
142 }
143
144 // create key and value for this handler
145 unsigned int netFnCmd = makeCmdKey(netFn, cmd);
146 HandlerTuple item(prio, priv, handler);
147
148 // consult the handler map and look for a match
149 auto& mapCmd = handlerMap[netFnCmd];
150 if (!std::get<HandlerBase::ptr>(mapCmd) || std::get<int>(mapCmd) <= prio)
151 {
152 mapCmd = item;
153 return true;
154 }
155 return false;
156}
157
Vernon Maueryf984a012018-10-08 12:05:18 -0700158/* common function to register all Group IPMI handlers */
159bool registerGroupHandler(int prio, Group group, Cmd cmd, Privilege priv,
160 HandlerBase::ptr handler)
161{
162 // create key and value for this handler
163 unsigned int netFnCmd = makeCmdKey(group, cmd);
164 HandlerTuple item(prio, priv, handler);
165
166 // consult the handler map and look for a match
167 auto& mapCmd = groupHandlerMap[netFnCmd];
168 if (!std::get<HandlerBase::ptr>(mapCmd) || std::get<int>(mapCmd) <= prio)
169 {
170 mapCmd = item;
171 return true;
172 }
173 return false;
174}
175
176/* common function to register all OEM IPMI handlers */
177bool registerOemHandler(int prio, Iana iana, Cmd cmd, Privilege priv,
178 HandlerBase::ptr handler)
179{
180 // create key and value for this handler
181 unsigned int netFnCmd = makeCmdKey(iana, cmd);
182 HandlerTuple item(prio, priv, handler);
183
184 // consult the handler map and look for a match
185 auto& mapCmd = oemHandlerMap[netFnCmd];
186 if (!std::get<HandlerBase::ptr>(mapCmd) || std::get<int>(mapCmd) <= prio)
187 {
188 mapCmd = item;
189 return true;
190 }
191 return false;
192}
193
Vernon Mauery08a70aa2018-11-07 09:36:22 -0800194/* common function to register all IPMI filter handlers */
195void registerFilter(int prio, FilterBase::ptr filter)
196{
197 // check for initial placement
198 if (filterList.empty() || std::get<int>(filterList.front()) < prio)
199 {
200 filterList.emplace_front(std::make_tuple(prio, filter));
201 }
202 // walk the list and put it in the right place
203 auto j = filterList.begin();
204 for (auto i = j; i != filterList.end() && std::get<int>(*i) > prio; i++)
205 {
206 j = i;
207 }
208 filterList.emplace_after(j, std::make_tuple(prio, filter));
209}
210
Vernon Mauery240b1862018-10-08 12:05:16 -0700211} // namespace impl
212
Vernon Mauery08a70aa2018-11-07 09:36:22 -0800213message::Response::ptr filterIpmiCommand(message::Request::ptr request)
214{
215 // pass the command through the filter mechanism
216 // This can be the firmware firewall or any OEM mechanism like
217 // whitelist filtering based on operational mode
218 for (auto& item : filterList)
219 {
220 FilterBase::ptr filter = std::get<FilterBase::ptr>(item);
221 ipmi::Cc cc = filter->call(request);
222 if (ipmi::ccSuccess != cc)
223 {
224 return errorResponse(request, cc);
225 }
226 }
227 return message::Response::ptr();
228}
229
Vernon Mauery240b1862018-10-08 12:05:16 -0700230message::Response::ptr executeIpmiCommandCommon(
231 std::unordered_map<unsigned int, HandlerTuple>& handlers,
232 unsigned int keyCommon, message::Request::ptr request)
233{
Vernon Mauery08a70aa2018-11-07 09:36:22 -0800234 // filter the command first; a non-null message::Response::ptr
235 // means that the message has been rejected for some reason
236 message::Response::ptr response = filterIpmiCommand(request);
237 if (response)
238 {
239 return response;
240 }
241
Vernon Mauery240b1862018-10-08 12:05:16 -0700242 Cmd cmd = request->ctx->cmd;
243 unsigned int key = makeCmdKey(keyCommon, cmd);
244 auto cmdIter = handlers.find(key);
245 if (cmdIter != handlers.end())
246 {
247 HandlerTuple& chosen = cmdIter->second;
248 if (request->ctx->priv < std::get<Privilege>(chosen))
249 {
250 return errorResponse(request, ccInsufficientPrivilege);
251 }
252 return std::get<HandlerBase::ptr>(chosen)->call(request);
253 }
254 else
255 {
256 unsigned int wildcard = makeCmdKey(keyCommon, cmdWildcard);
257 cmdIter = handlers.find(wildcard);
258 if (cmdIter != handlers.end())
259 {
260 HandlerTuple& chosen = cmdIter->second;
261 if (request->ctx->priv < std::get<Privilege>(chosen))
262 {
263 return errorResponse(request, ccInsufficientPrivilege);
264 }
265 return std::get<HandlerBase::ptr>(chosen)->call(request);
266 }
267 }
268 return errorResponse(request, ccInvalidCommand);
269}
270
Vernon Maueryf984a012018-10-08 12:05:18 -0700271message::Response::ptr executeIpmiGroupCommand(message::Request::ptr request)
272{
273 // look up the group for this request
William A. Kennington IIId10d9052019-04-24 01:57:36 -0700274 uint8_t bytes;
275 if (0 != request->payload.unpack(bytes))
Vernon Maueryf984a012018-10-08 12:05:18 -0700276 {
277 return errorResponse(request, ccReqDataLenInvalid);
278 }
William A. Kennington IIId10d9052019-04-24 01:57:36 -0700279 auto group = static_cast<Group>(bytes);
Vernon Maueryf984a012018-10-08 12:05:18 -0700280 message::Response::ptr response =
281 executeIpmiCommandCommon(groupHandlerMap, group, request);
William A. Kennington IIIda31f9a2019-04-25 01:36:32 -0700282 ipmi::message::Payload prefix;
283 prefix.pack(bytes);
284 response->prepend(prefix);
Vernon Maueryf984a012018-10-08 12:05:18 -0700285 return response;
286}
287
288message::Response::ptr executeIpmiOemCommand(message::Request::ptr request)
289{
290 // look up the iana for this request
William A. Kennington IIId10d9052019-04-24 01:57:36 -0700291 uint24_t bytes;
292 if (0 != request->payload.unpack(bytes))
Vernon Maueryf984a012018-10-08 12:05:18 -0700293 {
294 return errorResponse(request, ccReqDataLenInvalid);
295 }
William A. Kennington IIId10d9052019-04-24 01:57:36 -0700296 auto iana = static_cast<Iana>(bytes);
Vernon Maueryf984a012018-10-08 12:05:18 -0700297 message::Response::ptr response =
298 executeIpmiCommandCommon(oemHandlerMap, iana, request);
William A. Kennington IIIda31f9a2019-04-25 01:36:32 -0700299 ipmi::message::Payload prefix;
300 prefix.pack(bytes);
301 response->prepend(prefix);
Vernon Maueryf984a012018-10-08 12:05:18 -0700302 return response;
303}
304
Vernon Mauery240b1862018-10-08 12:05:16 -0700305message::Response::ptr executeIpmiCommand(message::Request::ptr request)
306{
307 NetFn netFn = request->ctx->netFn;
Vernon Maueryf984a012018-10-08 12:05:18 -0700308 if (netFnGroup == netFn)
309 {
310 return executeIpmiGroupCommand(request);
311 }
312 else if (netFnOem == netFn)
313 {
314 return executeIpmiOemCommand(request);
315 }
Vernon Mauery240b1862018-10-08 12:05:16 -0700316 return executeIpmiCommandCommon(handlerMap, netFn, request);
317}
318
Vernon Mauery735ee952019-02-15 13:38:52 -0800319namespace utils
320{
321template <typename AssocContainer, typename UnaryPredicate>
322void assoc_erase_if(AssocContainer& c, UnaryPredicate p)
323{
324 typename AssocContainer::iterator next = c.begin();
325 typename AssocContainer::iterator last = c.end();
326 while ((next = std::find_if(next, last, p)) != last)
327 {
328 c.erase(next++);
329 }
330}
331} // namespace utils
332
333namespace
334{
335std::unordered_map<std::string, uint8_t> uniqueNameToChannelNumber;
336
337// sdbusplus::bus::match::rules::arg0namespace() wants the prefix
338// to match without any trailing '.'
339constexpr const char ipmiDbusChannelMatch[] =
340 "xyz.openbmc_project.Ipmi.Channel";
341void updateOwners(sdbusplus::asio::connection& conn, const std::string& name)
342{
343 conn.async_method_call(
344 [name](const boost::system::error_code ec,
345 const std::string& nameOwner) {
346 if (ec)
347 {
348 log<level::ERR>("Error getting dbus owner",
349 entry("INTERFACE=%s", name.c_str()));
350 return;
351 }
352 // start after ipmiDbusChannelPrefix (after the '.')
353 std::string chName =
354 name.substr(std::strlen(ipmiDbusChannelMatch) + 1);
355 try
356 {
357 uint8_t channel = getChannelByName(chName);
358 uniqueNameToChannelNumber[nameOwner] = channel;
359 log<level::INFO>("New interface mapping",
360 entry("INTERFACE=%s", name.c_str()),
361 entry("CHANNEL=%u", channel));
362 }
363 catch (const std::exception& e)
364 {
365 log<level::INFO>("Failed interface mapping, no such name",
366 entry("INTERFACE=%s", name.c_str()));
367 }
368 },
369 "org.freedesktop.DBus", "/", "org.freedesktop.DBus", "GetNameOwner",
370 name);
371}
372
373void doListNames(boost::asio::io_service& io, sdbusplus::asio::connection& conn)
374{
375 conn.async_method_call(
376 [&io, &conn](const boost::system::error_code ec,
377 std::vector<std::string> busNames) {
378 if (ec)
379 {
380 log<level::ERR>("Error getting dbus names");
381 std::exit(EXIT_FAILURE);
382 return;
383 }
384 // Try to make startup consistent
385 std::sort(busNames.begin(), busNames.end());
386
387 const std::string channelPrefix =
388 std::string(ipmiDbusChannelMatch) + ".";
389 for (const std::string& busName : busNames)
390 {
391 if (busName.find(channelPrefix) == 0)
392 {
393 updateOwners(conn, busName);
394 }
395 }
396 },
397 "org.freedesktop.DBus", "/org/freedesktop/DBus", "org.freedesktop.DBus",
398 "ListNames");
399}
400
401void nameChangeHandler(sdbusplus::message::message& message)
402{
403 std::string name;
404 std::string oldOwner;
405 std::string newOwner;
406
407 message.read(name, oldOwner, newOwner);
408
409 if (!oldOwner.empty())
410 {
411 if (boost::starts_with(oldOwner, ":"))
412 {
413 // Connection removed
414 auto it = uniqueNameToChannelNumber.find(oldOwner);
415 if (it != uniqueNameToChannelNumber.end())
416 {
417 uniqueNameToChannelNumber.erase(it);
418 }
419 }
420 }
421 if (!newOwner.empty())
422 {
423 // start after ipmiDbusChannelMatch (and after the '.')
424 std::string chName = name.substr(std::strlen(ipmiDbusChannelMatch) + 1);
425 try
426 {
427 uint8_t channel = getChannelByName(chName);
428 uniqueNameToChannelNumber[newOwner] = channel;
429 log<level::INFO>("New interface mapping",
430 entry("INTERFACE=%s", name.c_str()),
431 entry("CHANNEL=%u", channel));
432 }
433 catch (const std::exception& e)
434 {
435 log<level::INFO>("Failed interface mapping, no such name",
436 entry("INTERFACE=%s", name.c_str()));
437 }
438 }
439};
440
441} // anonymous namespace
442
443static constexpr const char intraBmcName[] = "INTRABMC";
444uint8_t channelFromMessage(sdbusplus::message::message& msg)
445{
446 // channel name for ipmitool to resolve to
447 std::string sender = msg.get_sender();
448 auto chIter = uniqueNameToChannelNumber.find(sender);
449 if (chIter != uniqueNameToChannelNumber.end())
450 {
451 return chIter->second;
452 }
453 // FIXME: currently internal connections are ephemeral and hard to pin down
454 try
455 {
456 return getChannelByName(intraBmcName);
457 }
458 catch (const std::exception& e)
459 {
460 return invalidChannel;
461 }
462} // namespace ipmi
463
Vernon Mauery240b1862018-10-08 12:05:16 -0700464/* called from sdbus async server context */
Vernon Mauery735ee952019-02-15 13:38:52 -0800465auto executionEntry(boost::asio::yield_context yield,
466 sdbusplus::message::message& m, NetFn netFn, uint8_t lun,
Vernon Mauery240b1862018-10-08 12:05:16 -0700467 Cmd cmd, std::vector<uint8_t>& data,
468 std::map<std::string, ipmi::Value>& options)
469{
Vernon Mauery735ee952019-02-15 13:38:52 -0800470 const auto dbusResponse =
471 [netFn, lun, cmd](Cc cc, const std::vector<uint8_t>& data = {}) {
472 constexpr uint8_t netFnResponse = 0x01;
473 uint8_t retNetFn = netFn | netFnResponse;
474 return std::make_tuple(retNetFn, lun, cmd, cc, data);
475 };
476 std::string sender = m.get_sender();
477 Privilege privilege = Privilege::None;
Vernon Maueryd6a2da02019-04-09 16:00:46 -0700478 int rqSA = 0;
Vernon Mauery735ee952019-02-15 13:38:52 -0800479 uint8_t userId = 0; // undefined user
Rajashekar Gade Reddy4d226402019-11-13 17:13:05 +0530480 uint32_t sessionId = 0;
Vernon Mauery735ee952019-02-15 13:38:52 -0800481
482 // figure out what channel the request came in on
483 uint8_t channel = channelFromMessage(m);
484 if (channel == invalidChannel)
485 {
486 // unknown sender channel; refuse to service the request
487 log<level::ERR>("ERROR determining source IPMI channel",
488 entry("SENDER=%s", sender.c_str()),
489 entry("NETFN=0x%X", netFn), entry("CMD=0x%X", cmd));
490 return dbusResponse(ipmi::ccDestinationUnavailable);
491 }
492
Rajashekar Gade Reddy4d226402019-11-13 17:13:05 +0530493 // session-based channels are required to provide userId, privilege and
494 // sessionId
Vernon Mauery735ee952019-02-15 13:38:52 -0800495 if (getChannelSessionSupport(channel) != EChannelSessSupported::none)
496 {
497 try
498 {
499 Value requestPriv = options.at("privilege");
500 Value requestUserId = options.at("userId");
Rajashekar Gade Reddy4d226402019-11-13 17:13:05 +0530501 Value requestSessionId = options.at("currentSessionId");
Vernon Mauery735ee952019-02-15 13:38:52 -0800502 privilege = static_cast<Privilege>(std::get<int>(requestPriv));
503 userId = static_cast<uint8_t>(std::get<int>(requestUserId));
Rajashekar Gade Reddy4d226402019-11-13 17:13:05 +0530504 sessionId =
505 static_cast<uint32_t>(std::get<uint32_t>(requestSessionId));
Vernon Mauery735ee952019-02-15 13:38:52 -0800506 }
507 catch (const std::exception& e)
508 {
509 log<level::ERR>("ERROR determining IPMI session credentials",
510 entry("CHANNEL=%u", channel),
511 entry("NETFN=0x%X", netFn), entry("CMD=0x%X", cmd));
512 return dbusResponse(ipmi::ccUnspecifiedError);
513 }
514 }
515 else
516 {
517 // get max privilege for session-less channels
518 // For now, there is not a way to configure this, default to Admin
519 privilege = Privilege::Admin;
Vernon Maueryd6a2da02019-04-09 16:00:46 -0700520
521 // ipmb should supply rqSA
522 ChannelInfo chInfo;
523 getChannelInfo(channel, chInfo);
524 if (static_cast<EChannelMediumType>(chInfo.mediumType) ==
525 EChannelMediumType::ipmb)
526 {
527 const auto iter = options.find("rqSA");
528 if (iter != options.end())
529 {
530 if (std::holds_alternative<int>(iter->second))
531 {
532 rqSA = std::get<int>(iter->second);
533 }
534 }
535 }
Vernon Mauery735ee952019-02-15 13:38:52 -0800536 }
537 // check to see if the requested priv/username is valid
538 log<level::DEBUG>("Set up ipmi context", entry("SENDER=%s", sender.c_str()),
539 entry("NETFN=0x%X", netFn), entry("CMD=0x%X", cmd),
540 entry("CHANNEL=%u", channel), entry("USERID=%u", userId),
Rajashekar Gade Reddy4d226402019-11-13 17:13:05 +0530541 entry("SESSIONID=0x%X", sessionId),
Vernon Maueryd6a2da02019-04-09 16:00:46 -0700542 entry("PRIVILEGE=%u", static_cast<uint8_t>(privilege)),
543 entry("RQSA=%x", rqSA));
Vernon Mauery735ee952019-02-15 13:38:52 -0800544
Rajashekar Gade Reddy4d226402019-11-13 17:13:05 +0530545 auto ctx =
546 std::make_shared<ipmi::Context>(getSdBus(), netFn, cmd, channel, userId,
547 sessionId, privilege, rqSA, yield);
Vernon Mauery240b1862018-10-08 12:05:16 -0700548 auto request = std::make_shared<ipmi::message::Request>(
549 ctx, std::forward<std::vector<uint8_t>>(data));
550 message::Response::ptr response = executeIpmiCommand(request);
551
Vernon Mauery735ee952019-02-15 13:38:52 -0800552 return dbusResponse(response->cc, response->payload.raw);
Vernon Mauery240b1862018-10-08 12:05:16 -0700553}
554
555/** @struct IpmiProvider
556 *
557 * RAII wrapper for dlopen so that dlclose gets called on exit
558 */
559struct IpmiProvider
560{
561 public:
562 /** @brief address of the opened library */
563 void* addr;
564 std::string name;
565
566 IpmiProvider() = delete;
567 IpmiProvider(const IpmiProvider&) = delete;
568 IpmiProvider& operator=(const IpmiProvider&) = delete;
569 IpmiProvider(IpmiProvider&&) = delete;
570 IpmiProvider& operator=(IpmiProvider&&) = delete;
571
572 /** @brief dlopen a shared object file by path
573 * @param[in] filename - path of shared object to open
574 */
575 explicit IpmiProvider(const char* fname) : addr(nullptr), name(fname)
576 {
577 log<level::DEBUG>("Open IPMI provider library",
578 entry("PROVIDER=%s", name.c_str()));
579 try
580 {
581 addr = dlopen(name.c_str(), RTLD_NOW);
582 }
583 catch (std::exception& e)
584 {
585 log<level::ERR>("ERROR opening IPMI provider",
586 entry("PROVIDER=%s", name.c_str()),
587 entry("ERROR=%s", e.what()));
588 }
589 catch (...)
590 {
591 std::exception_ptr eptr = std::current_exception();
592 try
593 {
594 std::rethrow_exception(eptr);
595 }
596 catch (std::exception& e)
597 {
598 log<level::ERR>("ERROR opening IPMI provider",
599 entry("PROVIDER=%s", name.c_str()),
600 entry("ERROR=%s", e.what()));
601 }
602 }
603 if (!isOpen())
604 {
605 log<level::ERR>("ERROR opening IPMI provider",
606 entry("PROVIDER=%s", name.c_str()),
607 entry("ERROR=%s", dlerror()));
608 }
609 }
610
611 ~IpmiProvider()
612 {
613 if (isOpen())
614 {
615 dlclose(addr);
616 }
617 }
618 bool isOpen() const
619 {
620 return (nullptr != addr);
621 }
622};
623
624// Plugin libraries need to contain .so either at the end or in the middle
625constexpr const char ipmiPluginExtn[] = ".so";
626
627/* return a list of self-closing library handles */
628std::forward_list<IpmiProvider> loadProviders(const fs::path& ipmiLibsPath)
629{
630 std::vector<fs::path> libs;
631 for (const auto& libPath : fs::directory_iterator(ipmiLibsPath))
632 {
Vernon Maueryb0ab5fe2019-03-06 14:03:00 -0800633 std::error_code ec;
Vernon Mauery240b1862018-10-08 12:05:16 -0700634 fs::path fname = libPath.path();
Vernon Maueryb0ab5fe2019-03-06 14:03:00 -0800635 if (fs::is_symlink(fname, ec) || ec)
636 {
637 // it's a symlink or some other error; skip it
638 continue;
639 }
Vernon Mauery240b1862018-10-08 12:05:16 -0700640 while (fname.has_extension())
641 {
642 fs::path extn = fname.extension();
643 if (extn == ipmiPluginExtn)
644 {
645 libs.push_back(libPath.path());
646 break;
647 }
648 fname.replace_extension();
649 }
650 }
651 std::sort(libs.begin(), libs.end());
652
653 std::forward_list<IpmiProvider> handles;
654 for (auto& lib : libs)
655 {
656#ifdef __IPMI_DEBUG__
657 log<level::DEBUG>("Registering handler",
658 entry("HANDLER=%s", lib.c_str()));
659#endif
660 handles.emplace_front(lib.c_str());
661 }
662 return handles;
663}
664
665} // namespace ipmi
666
Vernon Mauery240b1862018-10-08 12:05:16 -0700667#ifdef ALLOW_DEPRECATED_API
668/* legacy registration */
669void ipmi_register_callback(ipmi_netfn_t netFn, ipmi_cmd_t cmd,
670 ipmi_context_t context, ipmid_callback_t handler,
671 ipmi_cmd_privilege_t priv)
672{
Vernon Mauerybe376302019-03-21 13:02:05 -0700673 auto h = ipmi::makeLegacyHandler(handler, context);
Vernon Mauery240b1862018-10-08 12:05:16 -0700674 // translate priv from deprecated enum to current
675 ipmi::Privilege realPriv;
676 switch (priv)
677 {
678 case PRIVILEGE_CALLBACK:
679 realPriv = ipmi::Privilege::Callback;
680 break;
681 case PRIVILEGE_USER:
682 realPriv = ipmi::Privilege::User;
683 break;
684 case PRIVILEGE_OPERATOR:
685 realPriv = ipmi::Privilege::Operator;
686 break;
687 case PRIVILEGE_ADMIN:
688 realPriv = ipmi::Privilege::Admin;
689 break;
690 case PRIVILEGE_OEM:
691 realPriv = ipmi::Privilege::Oem;
692 break;
693 case SYSTEM_INTERFACE:
694 realPriv = ipmi::Privilege::Admin;
695 break;
696 default:
697 realPriv = ipmi::Privilege::Admin;
698 break;
699 }
Vernon Mauerye8d43232019-03-26 16:23:43 -0700700 // The original ipmi_register_callback allowed for group OEM handlers
701 // to be registered via this same interface. It just so happened that
702 // all the handlers were part of the DCMI group, so default to that.
703 if (netFn == NETFUN_GRPEXT)
704 {
705 ipmi::impl::registerGroupHandler(ipmi::prioOpenBmcBase,
706 dcmi::groupExtId, cmd, realPriv, h);
707 }
708 else
709 {
710 ipmi::impl::registerHandler(ipmi::prioOpenBmcBase, netFn, cmd, realPriv,
711 h);
712 }
Vernon Mauery240b1862018-10-08 12:05:16 -0700713}
714
Vernon Maueryf984a012018-10-08 12:05:18 -0700715namespace oem
716{
717
718class LegacyRouter : public oem::Router
719{
720 public:
721 virtual ~LegacyRouter()
722 {
723 }
724
725 /// Enable message routing to begin.
726 void activate() override
727 {
728 }
729
730 void registerHandler(Number oen, ipmi_cmd_t cmd, Handler handler) override
731 {
732 auto h = ipmi::makeLegacyHandler(std::forward<Handler>(handler));
733 ipmi::impl::registerOemHandler(ipmi::prioOpenBmcBase, oen, cmd,
734 ipmi::Privilege::Admin, h);
735 }
736};
737static LegacyRouter legacyRouter;
738
739Router* mutableRouter()
740{
741 return &legacyRouter;
742}
743
744} // namespace oem
745
Vernon Mauery240b1862018-10-08 12:05:16 -0700746/* legacy alternative to executionEntry */
747void handleLegacyIpmiCommand(sdbusplus::message::message& m)
748{
Vernon Mauery23b70212019-05-08 15:19:05 -0700749 // make a copy so the next two moves don't wreak havoc on the stack
750 sdbusplus::message::message b{m};
751 boost::asio::spawn(*getIoContext(), [b = std::move(b)](
752 boost::asio::yield_context yield) {
753 sdbusplus::message::message m{std::move(b)};
754 unsigned char seq, netFn, lun, cmd;
755 std::vector<uint8_t> data;
Vernon Mauery240b1862018-10-08 12:05:16 -0700756
Vernon Mauery23b70212019-05-08 15:19:05 -0700757 m.read(seq, netFn, lun, cmd, data);
Vernon Mauery33298af2019-05-13 15:32:37 -0700758 std::shared_ptr<sdbusplus::asio::connection> bus = getSdBus();
Vernon Mauery23b70212019-05-08 15:19:05 -0700759 auto ctx = std::make_shared<ipmi::Context>(
Rajashekar Gade Reddy4d226402019-11-13 17:13:05 +0530760 bus, netFn, cmd, 0, 0, 0, ipmi::Privilege::Admin, 0, yield);
Vernon Mauery23b70212019-05-08 15:19:05 -0700761 auto request = std::make_shared<ipmi::message::Request>(
762 ctx, std::forward<std::vector<uint8_t>>(data));
763 ipmi::message::Response::ptr response =
764 ipmi::executeIpmiCommand(request);
Vernon Mauery240b1862018-10-08 12:05:16 -0700765
Vernon Mauery23b70212019-05-08 15:19:05 -0700766 // Responses in IPMI require a bit set. So there ya go...
767 netFn |= 0x01;
Vernon Mauery240b1862018-10-08 12:05:16 -0700768
Vernon Mauery23b70212019-05-08 15:19:05 -0700769 const char *dest, *path;
770 constexpr const char* DBUS_INTF = "org.openbmc.HostIpmi";
Vernon Mauery240b1862018-10-08 12:05:16 -0700771
Vernon Mauery23b70212019-05-08 15:19:05 -0700772 dest = m.get_sender();
773 path = m.get_path();
774 boost::system::error_code ec;
Vernon Mauery33298af2019-05-13 15:32:37 -0700775 bus->yield_method_call(yield, ec, dest, path, DBUS_INTF, "sendMessage",
776 seq, netFn, lun, cmd, response->cc,
777 response->payload.raw);
Vernon Mauery23b70212019-05-08 15:19:05 -0700778 if (ec)
779 {
780 log<level::ERR>("Failed to send response to requestor",
781 entry("ERROR=%s", ec.message().c_str()),
782 entry("SENDER=%s", dest),
783 entry("NETFN=0x%X", netFn), entry("CMD=0x%X", cmd));
784 }
785 });
Vernon Mauery240b1862018-10-08 12:05:16 -0700786}
787
788#endif /* ALLOW_DEPRECATED_API */
789
790// Calls host command manager to do the right thing for the command
791using CommandHandler = phosphor::host::command::CommandHandler;
792std::unique_ptr<phosphor::host::command::Manager> cmdManager;
793void ipmid_send_cmd_to_host(CommandHandler&& cmd)
794{
Vernon Mauery1b7f6f22019-03-13 13:11:25 -0700795 return cmdManager->execute(std::forward<CommandHandler>(cmd));
Vernon Mauery240b1862018-10-08 12:05:16 -0700796}
797
798std::unique_ptr<phosphor::host::command::Manager>& ipmid_get_host_cmd_manager()
799{
800 return cmdManager;
801}
802
Vernon Mauery20ff3332019-03-01 16:52:25 -0800803// These are symbols that are present in libipmid, but not expected
804// to be used except here (or maybe a unit test), so declare them here
805extern void setIoContext(std::shared_ptr<boost::asio::io_context>& newIo);
806extern void setSdBus(std::shared_ptr<sdbusplus::asio::connection>& newBus);
807
Vernon Mauery240b1862018-10-08 12:05:16 -0700808int main(int argc, char* argv[])
809{
810 // Connect to system bus
Vernon Mauery20ff3332019-03-01 16:52:25 -0800811 auto io = std::make_shared<boost::asio::io_context>();
812 setIoContext(io);
Vernon Mauery240b1862018-10-08 12:05:16 -0700813 if (argc > 1 && std::string(argv[1]) == "-session")
814 {
815 sd_bus_default_user(&bus);
816 }
817 else
818 {
819 sd_bus_default_system(&bus);
820 }
Vernon Mauery20ff3332019-03-01 16:52:25 -0800821 auto sdbusp = std::make_shared<sdbusplus::asio::connection>(*io, bus);
822 setSdBus(sdbusp);
Vernon Mauery240b1862018-10-08 12:05:16 -0700823 sdbusp->request_name("xyz.openbmc_project.Ipmi.Host");
824
825 // TODO: Hack to keep the sdEvents running.... Not sure why the sd_event
826 // queue stops running if we don't have a timer that keeps re-arming
827 phosphor::Timer t2([]() { ; });
828 t2.start(std::chrono::microseconds(500000), true);
829
830 // TODO: Remove all vestiges of sd_event from phosphor-host-ipmid
831 // until that is done, add the sd_event wrapper to the io object
832 sdbusplus::asio::sd_event_wrapper sdEvents(*io);
833
834 cmdManager = std::make_unique<phosphor::host::command::Manager>(*sdbusp);
835
836 // Register all command providers and filters
Vernon Mauery4ec4e402019-03-20 13:09:27 -0700837 std::forward_list<ipmi::IpmiProvider> providers =
838 ipmi::loadProviders(HOST_IPMI_LIB_PATH);
Vernon Mauery240b1862018-10-08 12:05:16 -0700839
840 // Add bindings for inbound IPMI requests
841 auto server = sdbusplus::asio::object_server(sdbusp);
842 auto iface = server.add_interface("/xyz/openbmc_project/Ipmi",
843 "xyz.openbmc_project.Ipmi.Server");
844 iface->register_method("execute", ipmi::executionEntry);
845 iface->initialize();
846
847#ifdef ALLOW_DEPRECATED_API
848 // listen on deprecated signal interface for kcs/bt commands
849 constexpr const char* FILTER = "type='signal',interface='org.openbmc."
850 "HostIpmi',member='ReceivedMessage'";
851 sdbusplus::bus::match::match oldIpmiInterface(*sdbusp, FILTER,
852 handleLegacyIpmiCommand);
853#endif /* ALLOW_DEPRECATED_API */
854
Vernon Mauery735ee952019-02-15 13:38:52 -0800855 // set up bus name watching to match channels with bus names
856 sdbusplus::bus::match::match nameOwnerChanged(
857 *sdbusp,
858 sdbusplus::bus::match::rules::nameOwnerChanged() +
859 sdbusplus::bus::match::rules::arg0namespace(
860 ipmi::ipmiDbusChannelMatch),
861 ipmi::nameChangeHandler);
862 ipmi::doListNames(*io, *sdbusp);
863
James Feistb0094a72019-11-26 09:07:15 -0800864 int exitCode = 0;
Vernon Mauery1b7f6f22019-03-13 13:11:25 -0700865 // set up boost::asio signal handling
866 std::function<SignalResponse(int)> stopAsioRunLoop =
James Feistb0094a72019-11-26 09:07:15 -0800867 [&io, &exitCode](int signalNumber) {
Vernon Mauery1b7f6f22019-03-13 13:11:25 -0700868 log<level::INFO>("Received signal; quitting",
869 entry("SIGNAL=%d", signalNumber));
870 io->stop();
James Feistb0094a72019-11-26 09:07:15 -0800871 exitCode = signalNumber;
Vernon Mauery1b7f6f22019-03-13 13:11:25 -0700872 return SignalResponse::breakExecution;
873 };
874 registerSignalHandler(ipmi::prioOpenBmcBase, SIGINT, stopAsioRunLoop);
875 registerSignalHandler(ipmi::prioOpenBmcBase, SIGTERM, stopAsioRunLoop);
876
Vernon Mauery240b1862018-10-08 12:05:16 -0700877 io->run();
878
Vernon Mauery1b7f6f22019-03-13 13:11:25 -0700879 // destroy all the IPMI handlers so the providers can unload safely
880 ipmi::handlerMap.clear();
881 ipmi::groupHandlerMap.clear();
882 ipmi::oemHandlerMap.clear();
883 ipmi::filterList.clear();
884 // unload the provider libraries
Vernon Mauery4ec4e402019-03-20 13:09:27 -0700885 providers.clear();
Vernon Mauery1b7f6f22019-03-13 13:11:25 -0700886
James Feistb0094a72019-11-26 09:07:15 -0800887 std::exit(exitCode);
Vernon Mauery240b1862018-10-08 12:05:16 -0700888}