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