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