xref: /openbmc/pldm/pldmd/pldmd.cpp (revision b4275477)
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_pdr.hpp"
8 #include "dbus_impl_requester.hpp"
9 #include "host-bmc/dbus_to_event_handler.hpp"
10 #include "host-bmc/dbus_to_host_effecters.hpp"
11 #include "host-bmc/host_pdr_handler.hpp"
12 #include "invoker.hpp"
13 #include "libpldmresponder/base.hpp"
14 #include "libpldmresponder/bios.hpp"
15 #include "libpldmresponder/fru.hpp"
16 #include "libpldmresponder/platform.hpp"
17 #include "xyz/openbmc_project/PLDM/Event/server.hpp"
18 
19 #include <err.h>
20 #include <getopt.h>
21 #include <poll.h>
22 #include <stdlib.h>
23 #include <sys/socket.h>
24 #include <sys/types.h>
25 #include <sys/un.h>
26 #include <unistd.h>
27 
28 #include <sdeventplus/event.hpp>
29 #include <sdeventplus/source/io.hpp>
30 
31 #include <cstdio>
32 #include <cstring>
33 #include <fstream>
34 #include <iomanip>
35 #include <iostream>
36 #include <iterator>
37 #include <memory>
38 #include <sstream>
39 #include <stdexcept>
40 #include <string>
41 #include <vector>
42 
43 #ifdef OEM_IBM
44 #include "libpldmresponder/file_io.hpp"
45 #endif
46 
47 constexpr uint8_t MCTP_MSG_TYPE_PLDM = 1;
48 
49 using namespace pldm::responder;
50 using namespace pldm;
51 using namespace sdeventplus;
52 using namespace sdeventplus::source;
53 using namespace pldm::state_sensor;
54 
55 static Response processRxMsg(const std::vector<uint8_t>& requestMsg,
56                              Invoker& invoker, dbus_api::Requester& requester)
57 {
58 
59     Response response;
60     uint8_t eid = requestMsg[0];
61     uint8_t type = requestMsg[1];
62     pldm_header_info hdrFields{};
63     auto hdr = reinterpret_cast<const pldm_msg_hdr*>(
64         requestMsg.data() + sizeof(eid) + sizeof(type));
65     if (PLDM_SUCCESS != unpack_pldm_header(hdr, &hdrFields))
66     {
67         std::cerr << "Empty PLDM request header \n";
68     }
69     else if (PLDM_RESPONSE != hdrFields.msg_type)
70     {
71         auto request = reinterpret_cast<const pldm_msg*>(hdr);
72         size_t requestLen = requestMsg.size() - sizeof(struct pldm_msg_hdr) -
73                             sizeof(eid) - sizeof(type);
74         try
75         {
76             response = invoker.handle(hdrFields.pldm_type, hdrFields.command,
77                                       request, requestLen);
78         }
79         catch (const std::out_of_range& e)
80         {
81             uint8_t completion_code = PLDM_ERROR_UNSUPPORTED_PLDM_CMD;
82             response.resize(sizeof(pldm_msg_hdr));
83             auto responseHdr = reinterpret_cast<pldm_msg_hdr*>(response.data());
84             pldm_header_info header{};
85             header.msg_type = PLDM_RESPONSE;
86             header.instance = hdrFields.instance;
87             header.pldm_type = hdrFields.pldm_type;
88             header.command = hdrFields.command;
89             auto result = pack_pldm_header(&header, responseHdr);
90             if (PLDM_SUCCESS != result)
91             {
92                 std::cerr << "Failed adding response header \n";
93             }
94             response.insert(response.end(), completion_code);
95         }
96     }
97     else
98     {
99         requester.markFree(eid, hdr->instance_id);
100     }
101     return response;
102 }
103 
104 void printBuffer(const std::vector<uint8_t>& buffer)
105 {
106     std::ostringstream tempStream;
107     tempStream << "Buffer Data: ";
108     if (!buffer.empty())
109     {
110         for (int byte : buffer)
111         {
112             tempStream << std::setfill('0') << std::setw(2) << std::hex << byte
113                        << " ";
114         }
115     }
116     std::cout << tempStream.str().c_str() << std::endl;
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     std::unique_ptr<pldm_pdr, decltype(&pldm_pdr_destroy)> pdrRepo(
169         pldm_pdr_init(), pldm_pdr_destroy);
170     std::unique_ptr<pldm_entity_association_tree,
171                     decltype(&pldm_entity_association_tree_destroy)>
172         entityTree(pldm_entity_association_tree_init(),
173                    pldm_entity_association_tree_destroy);
174     auto& bus = pldm::utils::DBusHandler::getBus();
175     dbus_api::Requester dbusImplReq(bus, "/xyz/openbmc_project/pldm");
176     std::unique_ptr<HostPDRHandler> hostPDRHandler;
177     std::unique_ptr<pldm::host_effecters::HostEffecterParser>
178         hostEffecterParser;
179     std::unique_ptr<DbusToPLDMEvent> dbusToPLDMEventHandler;
180     auto dbusHandler = std::make_unique<DBusHandler>();
181     auto hostEID = pldm::utils::readHostEID();
182     if (hostEID)
183     {
184         hostPDRHandler = std::make_unique<HostPDRHandler>(
185             sockfd, hostEID, event, pdrRepo.get(), entityTree.get(),
186             dbusImplReq);
187         hostEffecterParser =
188             std::make_unique<pldm::host_effecters::HostEffecterParser>(
189                 &dbusImplReq, sockfd, pdrRepo.get(), dbusHandler.get(),
190                 HOST_JSONS_DIR, verbose);
191         dbusToPLDMEventHandler =
192             std::make_unique<DbusToPLDMEvent>(sockfd, hostEID, dbusImplReq);
193     }
194 
195     Invoker invoker{};
196     invoker.registerHandler(PLDM_BASE, std::make_unique<base::Handler>());
197     invoker.registerHandler(PLDM_BIOS, std::make_unique<bios::Handler>());
198     auto fruHandler = std::make_unique<fru::Handler>(
199         FRU_JSONS_DIR, pdrRepo.get(), entityTree.get());
200     // FRU table is built lazily when a FRU command or Get PDR command is
201     // handled. To enable building FRU table, the FRU handler is passed to the
202     // Platform handler.
203     invoker.registerHandler(PLDM_PLATFORM, std::make_unique<platform::Handler>(
204                                                dbusHandler.get(), PDR_JSONS_DIR,
205                                                EVENTS_JSONS_DIR, pdrRepo.get(),
206                                                hostPDRHandler.get(),
207                                                dbusToPLDMEventHandler.get(),
208                                                fruHandler.get(), true));
209     invoker.registerHandler(PLDM_FRU, std::move(fruHandler));
210 
211 #ifdef OEM_IBM
212     invoker.registerHandler(PLDM_OEM, std::make_unique<oem_ibm::Handler>());
213 #endif
214 
215     pldm::utils::CustomFD socketFd(sockfd);
216 
217     struct sockaddr_un addr
218     {};
219     addr.sun_family = AF_UNIX;
220     const char path[] = "\0mctp-mux";
221     memcpy(addr.sun_path, path, sizeof(path) - 1);
222     int result = connect(socketFd(), reinterpret_cast<struct sockaddr*>(&addr),
223                          sizeof(path) + sizeof(addr.sun_family) - 1);
224     if (-1 == result)
225     {
226         returnCode = -errno;
227         std::cerr << "Failed to connect to the socket, RC= " << returnCode
228                   << "\n";
229         exit(EXIT_FAILURE);
230     }
231 
232     result = write(socketFd(), &MCTP_MSG_TYPE_PLDM, sizeof(MCTP_MSG_TYPE_PLDM));
233     if (-1 == result)
234     {
235         returnCode = -errno;
236         std::cerr << "Failed to send message type as pldm to mctp, RC= "
237                   << returnCode << "\n";
238         exit(EXIT_FAILURE);
239     }
240 
241     dbus_api::Pdr dbusImplPdr(bus, "/xyz/openbmc_project/pldm", pdrRepo.get());
242     sdbusplus::xyz::openbmc_project::PLDM::server::Event dbusImplEvent(
243         bus, "/xyz/openbmc_project/pldm");
244     auto callback = [verbose, &invoker, &dbusImplReq](IO& /*io*/, int fd,
245                                                       uint32_t revents) {
246         if (!(revents & EPOLLIN))
247         {
248             return;
249         }
250 
251         // Outgoing message.
252         struct iovec iov[2]{};
253 
254         // This structure contains the parameter information for the response
255         // message.
256         struct msghdr msg
257         {};
258 
259         int returnCode = 0;
260         ssize_t peekedLength = recv(fd, nullptr, 0, MSG_PEEK | MSG_TRUNC);
261         if (0 == peekedLength)
262         {
263             std::cerr << "Socket has been closed \n";
264         }
265         else if (peekedLength <= -1)
266         {
267             returnCode = -errno;
268             std::cerr << "recv system call failed, RC= " << returnCode << "\n";
269         }
270         else
271         {
272             std::vector<uint8_t> requestMsg(peekedLength);
273             auto recvDataLength = recv(
274                 fd, static_cast<void*>(requestMsg.data()), peekedLength, 0);
275             if (recvDataLength == peekedLength)
276             {
277                 if (verbose)
278                 {
279                     std::cout << "Received Msg" << std::endl;
280                     printBuffer(requestMsg);
281                 }
282                 if (MCTP_MSG_TYPE_PLDM != requestMsg[1])
283                 {
284                     // Skip this message and continue.
285                     std::cerr << "Encountered Non-PLDM type message"
286                               << "\n";
287                 }
288                 else
289                 {
290                     // process message and send response
291                     auto response =
292                         processRxMsg(requestMsg, invoker, dbusImplReq);
293                     if (!response.empty())
294                     {
295                         if (verbose)
296                         {
297                             std::cout << "Sending Msg" << std::endl;
298                             printBuffer(response);
299                         }
300 
301                         iov[0].iov_base = &requestMsg[0];
302                         iov[0].iov_len =
303                             sizeof(requestMsg[0]) + sizeof(requestMsg[1]);
304                         iov[1].iov_base = response.data();
305                         iov[1].iov_len = response.size();
306 
307                         msg.msg_iov = iov;
308                         msg.msg_iovlen = sizeof(iov) / sizeof(iov[0]);
309 
310                         int result = sendmsg(fd, &msg, 0);
311                         if (-1 == result)
312                         {
313                             returnCode = -errno;
314                             std::cerr << "sendto system call failed, RC= "
315                                       << returnCode << "\n";
316                         }
317                     }
318                 }
319             }
320             else
321             {
322                 std::cerr
323                     << "Failure to read peeked length packet. peekedLength= "
324                     << peekedLength << " recvDataLength=" << recvDataLength
325                     << "\n";
326             }
327         }
328     };
329 
330     bus.attach_event(event.get(), SD_EVENT_PRIORITY_NORMAL);
331     bus.request_name("xyz.openbmc_project.PLDM");
332     IO io(event, socketFd(), EPOLLIN, std::move(callback));
333     event.loop();
334 
335     result = shutdown(sockfd, SHUT_RDWR);
336     if (-1 == result)
337     {
338         returnCode = -errno;
339         std::cerr << "Failed to shutdown the socket, RC=" << returnCode << "\n";
340         exit(EXIT_FAILURE);
341     }
342     exit(EXIT_FAILURE);
343 }
344