xref: /openbmc/pldm/pldmd/pldmd.cpp (revision dcdcd3b8)
1 #include "libpldm/base.h"
2 #include "libpldm/bios.h"
3 #include "libpldm/pdr.h"
4 #include "libpldm/platform.h"
5 
6 #include "common/utils.hpp"
7 #include "dbus_impl_requester.hpp"
8 #include "host-bmc/host_condition.hpp"
9 #include "invoker.hpp"
10 #include "requester/handler.hpp"
11 #include "requester/request.hpp"
12 
13 #include <err.h>
14 #include <getopt.h>
15 #include <poll.h>
16 #include <stdlib.h>
17 #include <sys/socket.h>
18 #include <sys/types.h>
19 #include <sys/un.h>
20 #include <unistd.h>
21 
22 #include <sdeventplus/event.hpp>
23 #include <sdeventplus/source/io.hpp>
24 
25 #include <cstdio>
26 #include <cstring>
27 #include <fstream>
28 #include <iomanip>
29 #include <iostream>
30 #include <iterator>
31 #include <memory>
32 #include <optional>
33 #include <sstream>
34 #include <stdexcept>
35 #include <string>
36 #include <vector>
37 
38 #ifdef LIBPLDMRESPONDER
39 #include "dbus_impl_pdr.hpp"
40 #include "host-bmc/dbus_to_event_handler.hpp"
41 #include "host-bmc/dbus_to_host_effecters.hpp"
42 #include "host-bmc/host_pdr_handler.hpp"
43 #include "libpldmresponder/base.hpp"
44 #include "libpldmresponder/bios.hpp"
45 #include "libpldmresponder/fru.hpp"
46 #include "libpldmresponder/oem_handler.hpp"
47 #include "libpldmresponder/platform.hpp"
48 #include "xyz/openbmc_project/PLDM/Event/server.hpp"
49 #endif
50 
51 #ifdef OEM_IBM
52 #include "libpldmresponder/file_io.hpp"
53 #include "libpldmresponder/oem_ibm_handler.hpp"
54 #endif
55 
56 constexpr uint8_t MCTP_MSG_TYPE_PLDM = 1;
57 
58 using namespace pldm;
59 using namespace sdeventplus;
60 using namespace sdeventplus::source;
61 using namespace pldm::responder;
62 using namespace pldm::utils;
63 
64 static std::optional<Response>
65     processRxMsg(const std::vector<uint8_t>& requestMsg, Invoker& invoker,
66                  requester::Handler<requester::Request>& handler)
67 {
68     uint8_t eid = requestMsg[0];
69     uint8_t type = requestMsg[1];
70     pldm_header_info hdrFields{};
71     auto hdr = reinterpret_cast<const pldm_msg_hdr*>(
72         requestMsg.data() + sizeof(eid) + sizeof(type));
73     if (PLDM_SUCCESS != unpack_pldm_header(hdr, &hdrFields))
74     {
75         std::cerr << "Empty PLDM request header \n";
76         return std::nullopt;
77     }
78 
79     if (PLDM_RESPONSE != hdrFields.msg_type)
80     {
81         Response response;
82         auto request = reinterpret_cast<const pldm_msg*>(hdr);
83         size_t requestLen = requestMsg.size() - sizeof(struct pldm_msg_hdr) -
84                             sizeof(eid) - sizeof(type);
85         try
86         {
87             response = invoker.handle(hdrFields.pldm_type, hdrFields.command,
88                                       request, requestLen);
89         }
90         catch (const std::out_of_range& e)
91         {
92             uint8_t completion_code = PLDM_ERROR_UNSUPPORTED_PLDM_CMD;
93             response.resize(sizeof(pldm_msg_hdr));
94             auto responseHdr = reinterpret_cast<pldm_msg_hdr*>(response.data());
95             pldm_header_info header{};
96             header.msg_type = PLDM_RESPONSE;
97             header.instance = hdrFields.instance;
98             header.pldm_type = hdrFields.pldm_type;
99             header.command = hdrFields.command;
100             if (PLDM_SUCCESS != pack_pldm_header(&header, responseHdr))
101             {
102                 std::cerr << "Failed adding response header \n";
103                 return std::nullopt;
104             }
105             response.insert(response.end(), completion_code);
106         }
107         return response;
108     }
109     else if (PLDM_RESPONSE == hdrFields.msg_type)
110     {
111         auto response = reinterpret_cast<const pldm_msg*>(hdr);
112         size_t responseLen = requestMsg.size() - sizeof(struct pldm_msg_hdr) -
113                              sizeof(eid) - sizeof(type);
114         handler.handleResponse(eid, hdrFields.instance, hdrFields.pldm_type,
115                                hdrFields.command, response, responseLen);
116     }
117     return std::nullopt;
118 }
119 
120 void optionUsage(void)
121 {
122     std::cerr << "Usage: pldmd [options]\n";
123     std::cerr << "Options:\n";
124     std::cerr
125         << "  --verbose=<0/1>  0 - Disable verbosity, 1 - Enable verbosity\n";
126     std::cerr << "Defaulted settings:  --verbose=0 \n";
127 }
128 
129 int main(int argc, char** argv)
130 {
131 
132     bool verbose = false;
133     static struct option long_options[] = {
134         {"verbose", required_argument, 0, 'v'}, {0, 0, 0, 0}};
135 
136     auto argflag = getopt_long(argc, argv, "v:", long_options, nullptr);
137     switch (argflag)
138     {
139         case 'v':
140             switch (std::stoi(optarg))
141             {
142                 case 0:
143                     verbose = false;
144                     break;
145                 case 1:
146                     verbose = true;
147                     break;
148                 default:
149                     optionUsage();
150                     break;
151             }
152             break;
153         default:
154             optionUsage();
155             break;
156     }
157 
158     /* Create local socket. */
159     int returnCode = 0;
160     int sockfd = socket(AF_UNIX, SOCK_SEQPACKET, 0);
161     if (-1 == sockfd)
162     {
163         returnCode = -errno;
164         std::cerr << "Failed to create the socket, RC= " << returnCode << "\n";
165         exit(EXIT_FAILURE);
166     }
167 
168     auto event = Event::get_default();
169     auto& bus = pldm::utils::DBusHandler::getBus();
170     dbus_api::Requester dbusImplReq(bus, "/xyz/openbmc_project/pldm");
171 
172     dbus_api::Host dbusImplHost(bus, "/xyz/openbmc_project/pldm");
173 
174     Invoker invoker{};
175     requester::Handler<requester::Request> reqHandler(sockfd, event,
176                                                       dbusImplReq);
177 
178 #ifdef LIBPLDMRESPONDER
179     using namespace pldm::state_sensor;
180     std::unique_ptr<pldm_pdr, decltype(&pldm_pdr_destroy)> pdrRepo(
181         pldm_pdr_init(), pldm_pdr_destroy);
182     std::unique_ptr<pldm_entity_association_tree,
183                     decltype(&pldm_entity_association_tree_destroy)>
184         entityTree(pldm_entity_association_tree_init(),
185                    pldm_entity_association_tree_destroy);
186     std::unique_ptr<pldm_entity_association_tree,
187                     decltype(&pldm_entity_association_tree_destroy)>
188         bmcEntityTree(pldm_entity_association_tree_init(),
189                       pldm_entity_association_tree_destroy);
190     std::shared_ptr<HostPDRHandler> hostPDRHandler;
191     std::unique_ptr<pldm::host_effecters::HostEffecterParser>
192         hostEffecterParser;
193     std::unique_ptr<DbusToPLDMEvent> dbusToPLDMEventHandler;
194     auto dbusHandler = std::make_unique<DBusHandler>();
195     auto hostEID = pldm::utils::readHostEID();
196     if (hostEID)
197     {
198         hostPDRHandler = std::make_shared<HostPDRHandler>(
199             sockfd, hostEID, event, pdrRepo.get(), EVENTS_JSONS_DIR,
200             entityTree.get(), bmcEntityTree.get(), dbusImplReq, &reqHandler,
201             verbose);
202         // HostFirmware interface needs access to hostPDR to know if host
203         // is running
204         dbusImplHost.setHostPdrObj(hostPDRHandler);
205 
206         hostEffecterParser =
207             std::make_unique<pldm::host_effecters::HostEffecterParser>(
208                 &dbusImplReq, sockfd, pdrRepo.get(), dbusHandler.get(),
209                 HOST_JSONS_DIR, &reqHandler, verbose);
210         dbusToPLDMEventHandler = std::make_unique<DbusToPLDMEvent>(
211             sockfd, hostEID, dbusImplReq, &reqHandler);
212     }
213     std::unique_ptr<oem_platform::Handler> oemPlatformHandler{};
214 
215 #ifdef OEM_IBM
216     std::unique_ptr<pldm::responder::CodeUpdate> codeUpdate =
217         std::make_unique<pldm::responder::CodeUpdate>(dbusHandler.get());
218     codeUpdate->clearDirPath(LID_STAGING_DIR);
219     oemPlatformHandler = std::make_unique<oem_ibm_platform::Handler>(
220         dbusHandler.get(), codeUpdate.get(), sockfd, hostEID, dbusImplReq,
221         event, &reqHandler);
222     codeUpdate->setOemPlatformHandler(oemPlatformHandler.get());
223     invoker.registerHandler(PLDM_OEM, std::make_unique<oem_ibm::Handler>(
224                                           oemPlatformHandler.get(), sockfd,
225                                           hostEID, &dbusImplReq, &reqHandler));
226 #endif
227     invoker.registerHandler(PLDM_BASE, std::make_unique<base::Handler>());
228     invoker.registerHandler(
229         PLDM_BIOS, std::make_unique<bios::Handler>(sockfd, hostEID,
230                                                    &dbusImplReq, &reqHandler));
231     auto fruHandler = std::make_unique<fru::Handler>(
232         FRU_JSONS_DIR, FRU_MASTER_JSON, pdrRepo.get(), entityTree.get(),
233         bmcEntityTree.get());
234     // FRU table is built lazily when a FRU command or Get PDR command is
235     // handled. To enable building FRU table, the FRU handler is passed to the
236     // Platform handler.
237     auto platformHandler = std::make_unique<platform::Handler>(
238         dbusHandler.get(), PDR_JSONS_DIR, pdrRepo.get(), hostPDRHandler.get(),
239         dbusToPLDMEventHandler.get(), fruHandler.get(),
240         oemPlatformHandler.get(), event, true);
241 #ifdef OEM_IBM
242     pldm::responder::oem_ibm_platform::Handler* oemIbmPlatformHandler =
243         dynamic_cast<pldm::responder::oem_ibm_platform::Handler*>(
244             oemPlatformHandler.get());
245     oemIbmPlatformHandler->setPlatformHandler(platformHandler.get());
246 #endif
247 
248     invoker.registerHandler(PLDM_PLATFORM, std::move(platformHandler));
249     invoker.registerHandler(PLDM_FRU, std::move(fruHandler));
250     dbus_api::Pdr dbusImplPdr(bus, "/xyz/openbmc_project/pldm", pdrRepo.get());
251     sdbusplus::xyz::openbmc_project::PLDM::server::Event dbusImplEvent(
252         bus, "/xyz/openbmc_project/pldm");
253 #endif
254 
255     pldm::utils::CustomFD socketFd(sockfd);
256 
257     struct sockaddr_un addr
258     {};
259     addr.sun_family = AF_UNIX;
260     const char path[] = "\0mctp-mux";
261     memcpy(addr.sun_path, path, sizeof(path) - 1);
262     int result = connect(socketFd(), reinterpret_cast<struct sockaddr*>(&addr),
263                          sizeof(path) + sizeof(addr.sun_family) - 1);
264     if (-1 == result)
265     {
266         returnCode = -errno;
267         std::cerr << "Failed to connect to the socket, RC= " << returnCode
268                   << "\n";
269         exit(EXIT_FAILURE);
270     }
271 
272     result = write(socketFd(), &MCTP_MSG_TYPE_PLDM, sizeof(MCTP_MSG_TYPE_PLDM));
273     if (-1 == result)
274     {
275         returnCode = -errno;
276         std::cerr << "Failed to send message type as pldm to mctp, RC= "
277                   << returnCode << "\n";
278         exit(EXIT_FAILURE);
279     }
280 
281     auto callback = [verbose, &invoker, &reqHandler](IO& io, int fd,
282                                                      uint32_t revents) {
283         if (!(revents & EPOLLIN))
284         {
285             return;
286         }
287 
288         // Outgoing message.
289         struct iovec iov[2]{};
290 
291         // This structure contains the parameter information for the response
292         // message.
293         struct msghdr msg
294         {};
295 
296         int returnCode = 0;
297         ssize_t peekedLength = recv(fd, nullptr, 0, MSG_PEEK | MSG_TRUNC);
298         if (0 == peekedLength)
299         {
300             // MCTP daemon has closed the socket this daemon is connected to.
301             // This may or may not be an error scenario, in either case the
302             // recovery mechanism for this daemon is to restart, and hence exit
303             // the event loop, that will cause this daemon to exit with a
304             // failure code.
305             io.get_event().exit(0);
306         }
307         else if (peekedLength <= -1)
308         {
309             returnCode = -errno;
310             std::cerr << "recv system call failed, RC= " << returnCode << "\n";
311         }
312         else
313         {
314             std::vector<uint8_t> requestMsg(peekedLength);
315             auto recvDataLength = recv(
316                 fd, static_cast<void*>(requestMsg.data()), peekedLength, 0);
317             if (recvDataLength == peekedLength)
318             {
319                 if (verbose)
320                 {
321                     std::cout << "Received Msg" << std::endl;
322                     printBuffer(requestMsg, verbose);
323                 }
324                 if (MCTP_MSG_TYPE_PLDM != requestMsg[1])
325                 {
326                     // Skip this message and continue.
327                     std::cerr << "Encountered Non-PLDM type message"
328                               << "\n";
329                 }
330                 else
331                 {
332                     // process message and send response
333                     auto response =
334                         processRxMsg(requestMsg, invoker, reqHandler);
335                     if (response.has_value())
336                     {
337                         if (verbose)
338                         {
339                             std::cout << "Sending Msg" << std::endl;
340                             printBuffer(*response, verbose);
341                         }
342 
343                         iov[0].iov_base = &requestMsg[0];
344                         iov[0].iov_len =
345                             sizeof(requestMsg[0]) + sizeof(requestMsg[1]);
346                         iov[1].iov_base = (*response).data();
347                         iov[1].iov_len = (*response).size();
348 
349                         msg.msg_iov = iov;
350                         msg.msg_iovlen = sizeof(iov) / sizeof(iov[0]);
351 
352                         int result = sendmsg(fd, &msg, 0);
353                         if (-1 == result)
354                         {
355                             returnCode = -errno;
356                             std::cerr << "sendto system call failed, RC= "
357                                       << returnCode << "\n";
358                         }
359                     }
360                 }
361             }
362             else
363             {
364                 std::cerr
365                     << "Failure to read peeked length packet. peekedLength= "
366                     << peekedLength << " recvDataLength=" << recvDataLength
367                     << "\n";
368             }
369         }
370     };
371 
372     bus.attach_event(event.get(), SD_EVENT_PRIORITY_NORMAL);
373     bus.request_name("xyz.openbmc_project.PLDM");
374     IO io(event, socketFd(), EPOLLIN, std::move(callback));
375     hostPDRHandler->setHostState();
376     if (hostPDRHandler->isHostUp())
377     {
378         hostPDRHandler->getHostPDR();
379     }
380     else
381     {
382         if (verbose)
383         {
384             std::cout << "Host is not running\n";
385         }
386     }
387 
388     event.loop();
389 
390     result = shutdown(sockfd, SHUT_RDWR);
391     if (-1 == result)
392     {
393         returnCode = -errno;
394         std::cerr << "Failed to shutdown the socket, RC=" << returnCode << "\n";
395         exit(EXIT_FAILURE);
396     }
397     exit(EXIT_FAILURE);
398 }
399