1 #include "inband_code_update.hpp"
2 
3 #include "libpldmresponder/pdr.hpp"
4 #include "oem_ibm_handler.hpp"
5 #include "xyz/openbmc_project/Common/error.hpp"
6 
7 #include <arpa/inet.h>
8 #include <libpldm/entity.h>
9 
10 #include <phosphor-logging/lg2.hpp>
11 #include <sdbusplus/server.hpp>
12 #include <xyz/openbmc_project/Dump/NewDump/server.hpp>
13 
14 #include <exception>
15 #include <fstream>
16 
17 PHOSPHOR_LOG2_USING;
18 
19 namespace pldm
20 {
21 using namespace utils;
22 
23 namespace responder
24 {
25 using namespace oem_ibm_platform;
26 
27 /** @brief Directory where the lid files without a header are stored */
28 auto lidDirPath = fs::path(LID_STAGING_DIR) / "lid";
29 
30 /** @brief Directory where the image files are stored as they are built */
31 auto imageDirPath = fs::path(LID_STAGING_DIR) / "image";
32 
33 /** @brief Directory where the code update tarball files are stored */
34 auto updateDirPath = fs::path(LID_STAGING_DIR) / "update";
35 
36 /** @brief The file name of the code update tarball */
37 constexpr auto tarImageName = "image.tar";
38 
39 /** @brief The file name of the hostfw image */
40 constexpr auto hostfwImageName = "image-hostfw";
41 
42 /** @brief The path to the code update tarball file */
43 auto tarImagePath = fs::path(imageDirPath) / tarImageName;
44 
45 /** @brief The path to the hostfw image */
46 auto hostfwImagePath = fs::path(imageDirPath) / hostfwImageName;
47 
48 /** @brief The path to the tarball file expected by the phosphor software
49  *         manager */
50 auto updateImagePath = fs::path("/tmp/images") / tarImageName;
51 
52 std::string CodeUpdate::fetchCurrentBootSide()
53 {
54     return currBootSide;
55 }
56 
57 std::string CodeUpdate::fetchNextBootSide()
58 {
59     return nextBootSide;
60 }
61 
62 int CodeUpdate::setCurrentBootSide(const std::string& currSide)
63 {
64     currBootSide = currSide;
65     return PLDM_SUCCESS;
66 }
67 
68 int CodeUpdate::setNextBootSide(const std::string& nextSide)
69 {
70     nextBootSide = nextSide;
71     std::string objPath{};
72     if (nextBootSide == currBootSide)
73     {
74         objPath = runningVersion;
75     }
76     else
77     {
78         objPath = nonRunningVersion;
79     }
80     if (objPath.empty())
81     {
82         error("no nonRunningVersion present");
83         return PLDM_PLATFORM_INVALID_STATE_VALUE;
84     }
85 
86     pldm::utils::DBusMapping dbusMapping{objPath, redundancyIntf, "Priority",
87                                          "uint8_t"};
88     uint8_t val = 0;
89     pldm::utils::PropertyValue value = static_cast<uint8_t>(val);
90     try
91     {
92         dBusIntf->setDbusProperty(dbusMapping, value);
93     }
94     catch (const std::exception& e)
95     {
96         error(
97             "failed to set the next boot side to {OBJ_PATH} ERROR={ERR_EXCEP}",
98             "OBJ_PATH", objPath.c_str(), "ERR_EXCEP", e.what());
99         return PLDM_ERROR;
100     }
101     return PLDM_SUCCESS;
102 }
103 
104 int CodeUpdate::setRequestedApplyTime()
105 {
106     int rc = PLDM_SUCCESS;
107     pldm::utils::PropertyValue value =
108         "xyz.openbmc_project.Software.ApplyTime.RequestedApplyTimes.OnReset";
109     DBusMapping dbusMapping;
110     dbusMapping.objectPath = "/xyz/openbmc_project/software/apply_time";
111     dbusMapping.interface = "xyz.openbmc_project.Software.ApplyTime";
112     dbusMapping.propertyName = "RequestedApplyTime";
113     dbusMapping.propertyType = "string";
114     try
115     {
116         pldm::utils::DBusHandler().setDbusProperty(dbusMapping, value);
117     }
118     catch (const std::exception& e)
119     {
120         error("Failed To set RequestedApplyTime property ERROR={ERR_EXCEP}",
121               "ERR_EXCEP", e.what());
122         rc = PLDM_ERROR;
123     }
124     return rc;
125 }
126 
127 int CodeUpdate::setRequestedActivation()
128 {
129     int rc = PLDM_SUCCESS;
130     pldm::utils::PropertyValue value =
131         "xyz.openbmc_project.Software.Activation.RequestedActivations.Active";
132     DBusMapping dbusMapping;
133     dbusMapping.objectPath = newImageId;
134     dbusMapping.interface = "xyz.openbmc_project.Software.Activation";
135     dbusMapping.propertyName = "RequestedActivation";
136     dbusMapping.propertyType = "string";
137     try
138     {
139         pldm::utils::DBusHandler().setDbusProperty(dbusMapping, value);
140     }
141     catch (const std::exception& e)
142     {
143         error("Failed To set RequestedActivation property ERROR={ERR_EXCEP}",
144               "ERR_EXCEP", e.what());
145         rc = PLDM_ERROR;
146     }
147     return rc;
148 }
149 
150 void CodeUpdate::setVersions()
151 {
152     static constexpr auto mapperService = "xyz.openbmc_project.ObjectMapper";
153     static constexpr auto functionalObjPath =
154         "/xyz/openbmc_project/software/functional";
155     static constexpr auto activeObjPath =
156         "/xyz/openbmc_project/software/active";
157     static constexpr auto propIntf = "org.freedesktop.DBus.Properties";
158 
159     auto& bus = dBusIntf->getBus();
160     try
161     {
162         auto method = bus.new_method_call(mapperService, functionalObjPath,
163                                           propIntf, "Get");
164         method.append("xyz.openbmc_project.Association", "endpoints");
165         std::variant<std::vector<std::string>> paths;
166 
167         auto reply = bus.call(method);
168         reply.read(paths);
169 
170         runningVersion = std::get<std::vector<std::string>>(paths)[0];
171 
172         auto method1 = bus.new_method_call(mapperService, activeObjPath,
173                                            propIntf, "Get");
174         method1.append("xyz.openbmc_project.Association", "endpoints");
175 
176         auto reply1 = bus.call(method1);
177         reply1.read(paths);
178         for (const auto& path : std::get<std::vector<std::string>>(paths))
179         {
180             if (path != runningVersion)
181             {
182                 nonRunningVersion = path;
183                 break;
184             }
185         }
186     }
187     catch (const std::exception& e)
188     {
189         error(
190             "failed to make a d-bus call to Object Mapper Association, ERROR={ERR_EXCEP}",
191             "ERR_EXCEP", e.what());
192         return;
193     }
194 
195     using namespace sdbusplus::bus::match::rules;
196     captureNextBootSideChange.push_back(
197         std::make_unique<sdbusplus::bus::match_t>(
198             pldm::utils::DBusHandler::getBus(),
199             propertiesChanged(runningVersion, redundancyIntf),
200             [this](sdbusplus::message_t& msg) {
201         DbusChangedProps props;
202         std::string iface;
203         msg.read(iface, props);
204         processPriorityChangeNotification(props);
205             }));
206     fwUpdateMatcher.push_back(std::make_unique<sdbusplus::bus::match_t>(
207         pldm::utils::DBusHandler::getBus(),
208         "interface='org.freedesktop.DBus.ObjectManager',type='signal',"
209         "member='InterfacesAdded',path='/xyz/openbmc_project/software'",
210         [this](sdbusplus::message_t& msg) {
211         DBusInterfaceAdded interfaces;
212         sdbusplus::message::object_path path;
213         msg.read(path, interfaces);
214 
215         for (auto& interface : interfaces)
216         {
217             if (interface.first == "xyz.openbmc_project.Software.Activation")
218             {
219                 auto imageInterface = "xyz.openbmc_project.Software.Activation";
220                 auto imageObjPath = path.str.c_str();
221 
222                 try
223                 {
224                     auto propVal = dBusIntf->getDbusPropertyVariant(
225                         imageObjPath, "Activation", imageInterface);
226                     const auto& imageProp = std::get<std::string>(propVal);
227                     if (imageProp == "xyz.openbmc_project.Software."
228                                      "Activation.Activations.Ready" &&
229                         isCodeUpdateInProgress())
230                     {
231                         newImageId = path.str;
232                         if (!imageActivationMatch)
233                         {
234                             imageActivationMatch =
235                                 std::make_unique<sdbusplus::bus::match_t>(
236                                     pldm::utils::DBusHandler::getBus(),
237                                     propertiesChanged(newImageId,
238                                                       "xyz.openbmc_project."
239                                                       "Software.Activation"),
240                                     [this](sdbusplus::message_t& msg) {
241                                 DbusChangedProps props;
242                                 std::string iface;
243                                 msg.read(iface, props);
244                                 const auto itr = props.find("Activation");
245                                 if (itr != props.end())
246                                 {
247                                     PropertyValue value = itr->second;
248                                     auto propVal = std::get<std::string>(value);
249                                     if (propVal ==
250                                         "xyz.openbmc_project.Software."
251                                         "Activation.Activations.Active")
252                                     {
253                                         CodeUpdateState state =
254                                             CodeUpdateState::END;
255                                         setCodeUpdateProgress(false);
256                                         auto sensorId =
257                                             getFirmwareUpdateSensor();
258                                         sendStateSensorEvent(
259                                             sensorId, PLDM_STATE_SENSOR_STATE,
260                                             0, uint8_t(state),
261                                             uint8_t(CodeUpdateState::START));
262                                         newImageId.clear();
263                                     }
264                                     else if (propVal == "xyz.openbmc_project."
265                                                         "Software.Activation."
266                                                         "Activations.Failed" ||
267                                              propVal == "xyz.openbmc_"
268                                                         "project.Software."
269                                                         "Activation."
270                                                         "Activations."
271                                                         "Invalid")
272                                     {
273                                         CodeUpdateState state =
274                                             CodeUpdateState::FAIL;
275                                         setCodeUpdateProgress(false);
276                                         auto sensorId =
277                                             getFirmwareUpdateSensor();
278                                         sendStateSensorEvent(
279                                             sensorId, PLDM_STATE_SENSOR_STATE,
280                                             0, uint8_t(state),
281                                             uint8_t(CodeUpdateState::START));
282                                         newImageId.clear();
283                                     }
284                                 }
285                                     });
286                         }
287                         auto rc = setRequestedActivation();
288                         if (rc != PLDM_SUCCESS)
289                         {
290                             CodeUpdateState state = CodeUpdateState::FAIL;
291                             setCodeUpdateProgress(false);
292                             auto sensorId = getFirmwareUpdateSensor();
293                             sendStateSensorEvent(
294                                 sensorId, PLDM_STATE_SENSOR_STATE, 0,
295                                 uint8_t(state),
296                                 uint8_t(CodeUpdateState::START));
297                             error("could not set RequestedActivation");
298                         }
299                         break;
300                     }
301                 }
302                 catch (const sdbusplus::exception_t& e)
303                 {
304                     error(
305                         "Error in getting Activation status,ERROR= {ERR_EXCEP}, INTERFACE={IMG_INTERFACE}, OBJECT PATH={OBJ_PATH}",
306                         "ERR_EXCEP", e.what(), "IMG_INTERFACE", imageInterface,
307                         "OBJ_PATH", imageObjPath);
308                 }
309             }
310         }
311         }));
312 }
313 
314 void CodeUpdate::processPriorityChangeNotification(
315     const DbusChangedProps& chProperties)
316 {
317     static constexpr auto propName = "Priority";
318     const auto it = chProperties.find(propName);
319     if (it == chProperties.end())
320     {
321         return;
322     }
323     uint8_t newVal = std::get<uint8_t>(it->second);
324     nextBootSide = (newVal == 0) ? currBootSide
325                                  : ((currBootSide == Tside) ? Pside : Tside);
326 }
327 
328 void CodeUpdate::setOemPlatformHandler(
329     pldm::responder::oem_platform::Handler* handler)
330 {
331     oemPlatformHandler = handler;
332 }
333 
334 void CodeUpdate::clearDirPath(const std::string& dirPath)
335 {
336     if (!fs::is_directory(dirPath))
337     {
338         error("The directory does not exist, dirPath = {DIR_PATH}", "DIR_PATH",
339               dirPath.c_str());
340         return;
341     }
342     for (const auto& iter : fs::directory_iterator(dirPath))
343     {
344         fs::remove_all(iter);
345     }
346 }
347 
348 void CodeUpdate::sendStateSensorEvent(
349     uint16_t sensorId, enum sensor_event_class_states sensorEventClass,
350     uint8_t sensorOffset, uint8_t eventState, uint8_t prevEventState)
351 {
352     pldm::responder::oem_ibm_platform::Handler* oemIbmPlatformHandler =
353         dynamic_cast<pldm::responder::oem_ibm_platform::Handler*>(
354             oemPlatformHandler);
355     oemIbmPlatformHandler->sendStateSensorEvent(
356         sensorId, sensorEventClass, sensorOffset, eventState, prevEventState);
357 }
358 
359 void CodeUpdate::deleteImage()
360 {
361     static constexpr auto UPDATER_SERVICE =
362         "xyz.openbmc_project.Software.BMC.Updater";
363     static constexpr auto SW_OBJ_PATH = "/xyz/openbmc_project/software";
364     static constexpr auto DELETE_INTF =
365         "xyz.openbmc_project.Collection.DeleteAll";
366 
367     auto& bus = dBusIntf->getBus();
368     try
369     {
370         auto method = bus.new_method_call(UPDATER_SERVICE, SW_OBJ_PATH,
371                                           DELETE_INTF, "DeleteAll");
372         bus.call_noreply(method);
373     }
374     catch (const std::exception& e)
375     {
376         error("Failed to delete image, ERROR={ERR_EXCEP}", "ERR_EXCEP",
377               e.what());
378         return;
379     }
380 }
381 
382 uint8_t fetchBootSide(uint16_t entityInstance, CodeUpdate* codeUpdate)
383 {
384     uint8_t sensorOpState = tSideNum;
385     if (entityInstance == 0)
386     {
387         auto currSide = codeUpdate->fetchCurrentBootSide();
388         if (currSide == Pside)
389         {
390             sensorOpState = pSideNum;
391         }
392     }
393     else if (entityInstance == 1)
394     {
395         auto nextSide = codeUpdate->fetchNextBootSide();
396         if (nextSide == Pside)
397         {
398             sensorOpState = pSideNum;
399         }
400     }
401     else
402     {
403         sensorOpState = PLDM_SENSOR_UNKNOWN;
404     }
405 
406     return sensorOpState;
407 }
408 
409 int setBootSide(uint16_t entityInstance, uint8_t currState,
410                 const std::vector<set_effecter_state_field>& stateField,
411                 CodeUpdate* codeUpdate)
412 {
413     int rc = PLDM_SUCCESS;
414     auto side = (stateField[currState].effecter_state == pSideNum) ? "P" : "T";
415 
416     if (entityInstance == 0)
417     {
418         rc = codeUpdate->setCurrentBootSide(side);
419     }
420     else if (entityInstance == 1)
421     {
422         rc = codeUpdate->setNextBootSide(side);
423     }
424     else
425     {
426         rc = PLDM_PLATFORM_INVALID_STATE_VALUE;
427     }
428     return rc;
429 }
430 
431 template <typename... T>
432 int executeCmd(const T&... t)
433 {
434     std::stringstream cmd;
435     ((cmd << t << " "), ...) << std::endl;
436     FILE* pipe = popen(cmd.str().c_str(), "r");
437     if (!pipe)
438     {
439         throw std::runtime_error("popen() failed!");
440     }
441     int rc = pclose(pipe);
442     if (WEXITSTATUS(rc))
443     {
444         std::cerr << "Error executing: ";
445         ((std::cerr << " " << t), ...);
446         std::cerr << "\n";
447         return -1;
448     }
449 
450     return 0;
451 }
452 
453 int processCodeUpdateLid(const std::string& filePath)
454 {
455     struct LidHeader
456     {
457         uint16_t magicNumber;
458         uint16_t headerVersion;
459         uint32_t lidNumber;
460         uint32_t lidDate;
461         uint16_t lidTime;
462         uint16_t lidClass;
463         uint32_t lidCrc;
464         uint32_t lidSize;
465         uint32_t headerSize;
466     };
467     LidHeader header;
468 
469     std::ifstream ifs(filePath, std::ios::in | std::ios::binary);
470     if (!ifs)
471     {
472         error("ifstream open error: {DIR_PATH}", "DIR_PATH", filePath.c_str());
473         return PLDM_ERROR;
474     }
475     ifs.seekg(0);
476     ifs.read(reinterpret_cast<char*>(&header), sizeof(header));
477 
478     // File size should be the value of lid size minus the header size
479     auto fileSize = fs::file_size(filePath);
480     fileSize -= htonl(header.headerSize);
481     if (fileSize < htonl(header.lidSize))
482     {
483         // File is not completely written yet
484         ifs.close();
485         return PLDM_SUCCESS;
486     }
487 
488     constexpr auto magicNumber = 0x0222;
489     if (htons(header.magicNumber) != magicNumber)
490     {
491         error("Invalid magic number: {DIR_PATH}", "DIR_PATH", filePath.c_str());
492         ifs.close();
493         return PLDM_ERROR;
494     }
495 
496     fs::create_directories(imageDirPath);
497     fs::create_directories(lidDirPath);
498 
499     constexpr auto bmcClass = 0x2000;
500     if (htons(header.lidClass) == bmcClass)
501     {
502         // Skip the header and concatenate the BMC LIDs into a tar file
503         std::ofstream ofs(tarImagePath,
504                           std::ios::out | std::ios::binary | std::ios::app);
505         ifs.seekg(htonl(header.headerSize));
506         ofs << ifs.rdbuf();
507         ofs.flush();
508         ofs.close();
509     }
510     else
511     {
512         std::stringstream lidFileName;
513         lidFileName << std::hex << htonl(header.lidNumber) << ".lid";
514         auto lidNoHeaderPath = fs::path(lidDirPath) / lidFileName.str();
515         std::ofstream ofs(lidNoHeaderPath,
516                           std::ios::out | std::ios::binary | std::ios::trunc);
517         ifs.seekg(htonl(header.headerSize));
518         ofs << ifs.rdbuf();
519         ofs.flush();
520         ofs.close();
521     }
522 
523     ifs.close();
524     fs::remove(filePath);
525     return PLDM_SUCCESS;
526 }
527 
528 int CodeUpdate::assembleCodeUpdateImage()
529 {
530     pid_t pid = fork();
531 
532     if (pid == 0)
533     {
534         pid_t nextPid = fork();
535         if (nextPid == 0)
536         {
537             // Create the hostfw squashfs image from the LID files without
538             // header
539             auto rc = executeCmd("/usr/sbin/mksquashfs", lidDirPath.c_str(),
540                                  hostfwImagePath.c_str(), "-all-root",
541                                  "-no-recovery");
542             if (rc < 0)
543             {
544                 error("Error occurred during the mksqusquashfs call");
545                 setCodeUpdateProgress(false);
546                 auto sensorId = getFirmwareUpdateSensor();
547                 sendStateSensorEvent(sensorId, PLDM_STATE_SENSOR_STATE, 0,
548                                      uint8_t(CodeUpdateState::FAIL),
549                                      uint8_t(CodeUpdateState::START));
550                 exit(EXIT_FAILURE);
551             }
552 
553             fs::create_directories(updateDirPath);
554 
555             // Extract the BMC tarball content
556             rc = executeCmd("/bin/tar", "-xf", tarImagePath.c_str(), "-C",
557                             updateDirPath);
558             if (rc < 0)
559             {
560                 setCodeUpdateProgress(false);
561                 auto sensorId = getFirmwareUpdateSensor();
562                 sendStateSensorEvent(sensorId, PLDM_STATE_SENSOR_STATE, 0,
563                                      uint8_t(CodeUpdateState::FAIL),
564                                      uint8_t(CodeUpdateState::START));
565                 exit(EXIT_FAILURE);
566             }
567 
568             // Add the hostfw image to the directory where the contents were
569             // extracted
570             fs::copy_file(hostfwImagePath,
571                           fs::path(updateDirPath) / hostfwImageName,
572                           fs::copy_options::overwrite_existing);
573 
574             // Remove the tarball file, then re-generate it with so that the
575             // hostfw image becomes part of the tarball
576             fs::remove(tarImagePath);
577             rc = executeCmd("/bin/tar", "-cf", tarImagePath, ".", "-C",
578                             updateDirPath);
579             if (rc < 0)
580             {
581                 error("Error occurred during the generation of the tarball");
582                 setCodeUpdateProgress(false);
583                 auto sensorId = getFirmwareUpdateSensor();
584                 sendStateSensorEvent(sensorId, PLDM_STATE_SENSOR_STATE, 0,
585                                      uint8_t(CodeUpdateState::FAIL),
586                                      uint8_t(CodeUpdateState::START));
587                 exit(EXIT_FAILURE);
588             }
589 
590             // Copy the tarball to the update directory to trigger the phosphor
591             // software manager to create a version interface
592             fs::copy_file(tarImagePath, updateImagePath,
593                           fs::copy_options::overwrite_existing);
594 
595             // Cleanup
596             fs::remove_all(updateDirPath);
597             fs::remove_all(lidDirPath);
598             fs::remove_all(imageDirPath);
599 
600             exit(EXIT_SUCCESS);
601         }
602         else if (nextPid < 0)
603         {
604             error("Error occurred during fork. ERROR={ERR}", "ERR", errno);
605             exit(EXIT_FAILURE);
606         }
607 
608         // Do nothing as parent. When parent exits, child will be reparented
609         // under init and be reaped properly.
610         exit(0);
611     }
612     else if (pid > 0)
613     {
614         int status;
615         if (waitpid(pid, &status, 0) < 0)
616         {
617             error("Error occurred during waitpid. ERROR={ERR}", "ERR", errno);
618 
619             return PLDM_ERROR;
620         }
621         else if (WEXITSTATUS(status) != 0)
622         {
623             error(
624                 "Failed to execute the assembling of the image. STATUS={IMG_STATUS}",
625                 "IMG_STATUS", status);
626             return PLDM_ERROR;
627         }
628     }
629     else
630     {
631         error("Error occurred during fork. ERROR={ERR}", "ERR", errno);
632         return PLDM_ERROR;
633     }
634 
635     return PLDM_SUCCESS;
636 }
637 
638 } // namespace responder
639 } // namespace pldm
640