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