xref: /openbmc/bmcweb/features/redfish/lib/update_service.hpp (revision 1e1e598df6d1d9530dde6e92d8f74f8143f60e50)
1 /*
2 // Copyright (c) 2018 Intel Corporation
3 //
4 // Licensed under the Apache License, Version 2.0 (the "License");
5 // you may not use this file except in compliance with the License.
6 // You may obtain a copy of the License at
7 //
8 //      http://www.apache.org/licenses/LICENSE-2.0
9 //
10 // Unless required by applicable law or agreed to in writing, software
11 // distributed under the License is distributed on an "AS IS" BASIS,
12 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 // See the License for the specific language governing permissions and
14 // limitations under the License.
15 */
16 #pragma once
17 
18 #include "bmcweb_config.h"
19 
20 #include <app.hpp>
21 #include <boost/container/flat_map.hpp>
22 #include <dbus_utility.hpp>
23 #include <registries/privilege_registry.hpp>
24 #include <sdbusplus/asio/property.hpp>
25 #include <utils/fw_utils.hpp>
26 
27 namespace redfish
28 {
29 
30 // Match signals added on software path
31 static std::unique_ptr<sdbusplus::bus::match::match> fwUpdateMatcher;
32 static std::unique_ptr<sdbusplus::bus::match::match> fwUpdateErrorMatcher;
33 // Only allow one update at a time
34 static bool fwUpdateInProgress = false;
35 // Timer for software available
36 static std::unique_ptr<boost::asio::steady_timer> fwAvailableTimer;
37 
38 inline static void cleanUp()
39 {
40     fwUpdateInProgress = false;
41     fwUpdateMatcher = nullptr;
42     fwUpdateErrorMatcher = nullptr;
43 }
44 inline static void activateImage(const std::string& objPath,
45                                  const std::string& service)
46 {
47     BMCWEB_LOG_DEBUG << "Activate image for " << objPath << " " << service;
48     crow::connections::systemBus->async_method_call(
49         [](const boost::system::error_code errorCode) {
50             if (errorCode)
51             {
52                 BMCWEB_LOG_DEBUG << "error_code = " << errorCode;
53                 BMCWEB_LOG_DEBUG << "error msg = " << errorCode.message();
54             }
55         },
56         service, objPath, "org.freedesktop.DBus.Properties", "Set",
57         "xyz.openbmc_project.Software.Activation", "RequestedActivation",
58         dbus::utility::DbusVariantType(
59             "xyz.openbmc_project.Software.Activation.RequestedActivations.Active"));
60 }
61 
62 // Note that asyncResp can be either a valid pointer or nullptr. If nullptr
63 // then no asyncResp updates will occur
64 static void
65     softwareInterfaceAdded(const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
66                            sdbusplus::message::message& m,
67                            task::Payload&& payload)
68 {
69     std::vector<std::pair<
70         std::string,
71         std::vector<std::pair<std::string, dbus::utility::DbusVariantType>>>>
72         interfacesProperties;
73 
74     sdbusplus::message::object_path objPath;
75 
76     m.read(objPath, interfacesProperties);
77 
78     BMCWEB_LOG_DEBUG << "obj path = " << objPath.str;
79     for (auto& interface : interfacesProperties)
80     {
81         BMCWEB_LOG_DEBUG << "interface = " << interface.first;
82 
83         if (interface.first == "xyz.openbmc_project.Software.Activation")
84         {
85             // Retrieve service and activate
86             crow::connections::systemBus->async_method_call(
87                 [objPath, asyncResp, payload(std::move(payload))](
88                     const boost::system::error_code errorCode,
89                     const std::vector<
90                         std::pair<std::string, std::vector<std::string>>>&
91                         objInfo) mutable {
92                     if (errorCode)
93                     {
94                         BMCWEB_LOG_DEBUG << "error_code = " << errorCode;
95                         BMCWEB_LOG_DEBUG << "error msg = "
96                                          << errorCode.message();
97                         if (asyncResp)
98                         {
99                             messages::internalError(asyncResp->res);
100                         }
101                         cleanUp();
102                         return;
103                     }
104                     // Ensure we only got one service back
105                     if (objInfo.size() != 1)
106                     {
107                         BMCWEB_LOG_ERROR << "Invalid Object Size "
108                                          << objInfo.size();
109                         if (asyncResp)
110                         {
111                             messages::internalError(asyncResp->res);
112                         }
113                         cleanUp();
114                         return;
115                     }
116                     // cancel timer only when
117                     // xyz.openbmc_project.Software.Activation interface
118                     // is added
119                     fwAvailableTimer = nullptr;
120 
121                     activateImage(objPath.str, objInfo[0].first);
122                     if (asyncResp)
123                     {
124                         std::shared_ptr<task::TaskData> task =
125                             task::TaskData::createTask(
126                                 [](boost::system::error_code ec,
127                                    sdbusplus::message::message& msg,
128                                    const std::shared_ptr<task::TaskData>&
129                                        taskData) {
130                                     if (ec)
131                                     {
132                                         return task::completed;
133                                     }
134 
135                                     std::string iface;
136                                     boost::container::flat_map<
137                                         std::string,
138                                         dbus::utility::DbusVariantType>
139                                         values;
140 
141                                     std::string index =
142                                         std::to_string(taskData->index);
143                                     msg.read(iface, values);
144 
145                                     if (iface ==
146                                         "xyz.openbmc_project.Software.Activation")
147                                     {
148                                         auto findActivation =
149                                             values.find("Activation");
150                                         if (findActivation == values.end())
151                                         {
152                                             return !task::completed;
153                                         }
154                                         std::string* state =
155                                             std::get_if<std::string>(
156                                                 &(findActivation->second));
157 
158                                         if (state == nullptr)
159                                         {
160                                             taskData->messages.emplace_back(
161                                                 messages::internalError());
162                                             return task::completed;
163                                         }
164 
165                                         if (boost::ends_with(*state,
166                                                              "Invalid") ||
167                                             boost::ends_with(*state, "Failed"))
168                                         {
169                                             taskData->state = "Exception";
170                                             taskData->status = "Warning";
171                                             taskData->messages.emplace_back(
172                                                 messages::taskAborted(index));
173                                             return task::completed;
174                                         }
175 
176                                         if (boost::ends_with(*state, "Staged"))
177                                         {
178                                             taskData->state = "Stopping";
179                                             taskData->messages.emplace_back(
180                                                 messages::taskPaused(index));
181 
182                                             // its staged, set a long timer to
183                                             // allow them time to complete the
184                                             // update (probably cycle the
185                                             // system) if this expires then
186                                             // task will be cancelled
187                                             taskData->extendTimer(
188                                                 std::chrono::hours(5));
189                                             return !task::completed;
190                                         }
191 
192                                         if (boost::ends_with(*state, "Active"))
193                                         {
194                                             taskData->messages.emplace_back(
195                                                 messages::taskCompletedOK(
196                                                     index));
197                                             taskData->state = "Completed";
198                                             return task::completed;
199                                         }
200                                     }
201                                     else if (
202                                         iface ==
203                                         "xyz.openbmc_project.Software.ActivationProgress")
204                                     {
205                                         auto findProgress =
206                                             values.find("Progress");
207                                         if (findProgress == values.end())
208                                         {
209                                             return !task::completed;
210                                         }
211                                         uint8_t* progress =
212                                             std::get_if<uint8_t>(
213                                                 &(findProgress->second));
214 
215                                         if (progress == nullptr)
216                                         {
217                                             taskData->messages.emplace_back(
218                                                 messages::internalError());
219                                             return task::completed;
220                                         }
221                                         taskData->percentComplete =
222                                             static_cast<int>(*progress);
223                                         taskData->messages.emplace_back(
224                                             messages::taskProgressChanged(
225                                                 index, static_cast<size_t>(
226                                                            *progress)));
227 
228                                         // if we're getting status updates it's
229                                         // still alive, update timer
230                                         taskData->extendTimer(
231                                             std::chrono::minutes(5));
232                                     }
233 
234                                     // as firmware update often results in a
235                                     // reboot, the task  may never "complete"
236                                     // unless it is an error
237 
238                                     return !task::completed;
239                                 },
240                                 "type='signal',interface='org.freedesktop.DBus.Properties',"
241                                 "member='PropertiesChanged',path='" +
242                                     objPath.str + "'");
243                         task->startTimer(std::chrono::minutes(5));
244                         task->populateResp(asyncResp->res);
245                         task->payload.emplace(std::move(payload));
246                     }
247                     fwUpdateInProgress = false;
248                 },
249                 "xyz.openbmc_project.ObjectMapper",
250                 "/xyz/openbmc_project/object_mapper",
251                 "xyz.openbmc_project.ObjectMapper", "GetObject", objPath.str,
252                 std::array<const char*, 1>{
253                     "xyz.openbmc_project.Software.Activation"});
254         }
255     }
256 }
257 
258 // Note that asyncResp can be either a valid pointer or nullptr. If nullptr
259 // then no asyncResp updates will occur
260 static void monitorForSoftwareAvailable(
261     const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
262     const crow::Request& req, const std::string& url,
263     int timeoutTimeSeconds = 10)
264 {
265     // Only allow one FW update at a time
266     if (fwUpdateInProgress != false)
267     {
268         if (asyncResp)
269         {
270             messages::serviceTemporarilyUnavailable(asyncResp->res, "30");
271         }
272         return;
273     }
274 
275     fwAvailableTimer =
276         std::make_unique<boost::asio::steady_timer>(*req.ioService);
277 
278     fwAvailableTimer->expires_after(std::chrono::seconds(timeoutTimeSeconds));
279 
280     fwAvailableTimer->async_wait(
281         [asyncResp](const boost::system::error_code& ec) {
282             cleanUp();
283             if (ec == boost::asio::error::operation_aborted)
284             {
285                 // expected, we were canceled before the timer completed.
286                 return;
287             }
288             BMCWEB_LOG_ERROR
289                 << "Timed out waiting for firmware object being created";
290             BMCWEB_LOG_ERROR
291                 << "FW image may has already been uploaded to server";
292             if (ec)
293             {
294                 BMCWEB_LOG_ERROR << "Async_wait failed" << ec;
295                 return;
296             }
297             if (asyncResp)
298             {
299                 redfish::messages::internalError(asyncResp->res);
300             }
301         });
302     task::Payload payload(req);
303     auto callback = [asyncResp,
304                      payload](sdbusplus::message::message& m) mutable {
305         BMCWEB_LOG_DEBUG << "Match fired";
306         softwareInterfaceAdded(asyncResp, m, std::move(payload));
307     };
308 
309     fwUpdateInProgress = true;
310 
311     fwUpdateMatcher = std::make_unique<sdbusplus::bus::match::match>(
312         *crow::connections::systemBus,
313         "interface='org.freedesktop.DBus.ObjectManager',type='signal',"
314         "member='InterfacesAdded',path='/xyz/openbmc_project/software'",
315         callback);
316 
317     fwUpdateErrorMatcher = std::make_unique<sdbusplus::bus::match::match>(
318         *crow::connections::systemBus,
319         "type='signal',member='PropertiesChanged',path_namespace='/xyz/"
320         "openbmc_project/logging/entry',"
321         "arg0='xyz.openbmc_project.Logging.Entry'",
322         [asyncResp, url](sdbusplus::message::message& m) {
323             BMCWEB_LOG_DEBUG << "Error Match fired";
324             boost::container::flat_map<std::string,
325                                        dbus::utility::DbusVariantType>
326                 values;
327             std::string objName;
328             m.read(objName, values);
329             auto find = values.find("Message");
330             if (find == values.end())
331             {
332                 return;
333             }
334             std::string* type = std::get_if<std::string>(&(find->second));
335             if (type == nullptr)
336             {
337                 return; // if this was our message, timeout will cover it
338             }
339             if (!boost::starts_with(*type, "xyz.openbmc_project.Software"))
340             {
341                 return;
342             }
343             if (*type ==
344                 "xyz.openbmc_project.Software.Image.Error.UnTarFailure")
345             {
346                 redfish::messages::invalidUpload(asyncResp->res, url,
347                                                  "Invalid archive");
348             }
349             else if (
350                 *type ==
351                 "xyz.openbmc_project.Software.Image.Error.ManifestFileFailure")
352             {
353                 redfish::messages::invalidUpload(asyncResp->res, url,
354                                                  "Invalid manifest");
355             }
356             else if (*type ==
357                      "xyz.openbmc_project.Software.Image.Error.ImageFailure")
358             {
359                 redfish::messages::invalidUpload(asyncResp->res, url,
360                                                  "Invalid image format");
361             }
362             else if (*type ==
363                      "xyz.openbmc_project.Software.Version.Error.AlreadyExists")
364             {
365 
366                 redfish::messages::invalidUpload(
367                     asyncResp->res, url, "Image version already exists");
368 
369                 redfish::messages::resourceAlreadyExists(
370                     asyncResp->res, "UpdateService.v1_5_0.UpdateService",
371                     "Version", "uploaded version");
372             }
373             else if (*type ==
374                      "xyz.openbmc_project.Software.Image.Error.BusyFailure")
375             {
376                 redfish::messages::resourceExhaustion(asyncResp->res, url);
377             }
378             else
379             {
380                 redfish::messages::internalError(asyncResp->res);
381             }
382             fwAvailableTimer = nullptr;
383         });
384 }
385 
386 /**
387  * UpdateServiceActionsSimpleUpdate class supports handle POST method for
388  * SimpleUpdate action.
389  */
390 inline void requestRoutesUpdateServiceActionsSimpleUpdate(App& app)
391 {
392     BMCWEB_ROUTE(
393         app, "/redfish/v1/UpdateService/Actions/UpdateService.SimpleUpdate/")
394         .privileges(redfish::privileges::postUpdateService)
395         .methods(
396             boost::beast::http::verb::
397                 post)([](const crow::Request& req,
398                          const std::shared_ptr<bmcweb::AsyncResp>& asyncResp) {
399             std::optional<std::string> transferProtocol;
400             std::string imageURI;
401 
402             BMCWEB_LOG_DEBUG << "Enter UpdateService.SimpleUpdate doPost";
403 
404             // User can pass in both TransferProtocol and ImageURI parameters or
405             // they can pass in just the ImageURI with the transfer protocol
406             // embedded within it.
407             // 1) TransferProtocol:TFTP ImageURI:1.1.1.1/myfile.bin
408             // 2) ImageURI:tftp://1.1.1.1/myfile.bin
409 
410             if (!json_util::readJson(req, asyncResp->res, "TransferProtocol",
411                                      transferProtocol, "ImageURI", imageURI))
412             {
413                 BMCWEB_LOG_DEBUG
414                     << "Missing TransferProtocol or ImageURI parameter";
415                 return;
416             }
417             if (!transferProtocol)
418             {
419                 // Must be option 2
420                 // Verify ImageURI has transfer protocol in it
421                 size_t separator = imageURI.find(':');
422                 if ((separator == std::string::npos) ||
423                     ((separator + 1) > imageURI.size()))
424                 {
425                     messages::actionParameterValueTypeError(
426                         asyncResp->res, imageURI, "ImageURI",
427                         "UpdateService.SimpleUpdate");
428                     BMCWEB_LOG_ERROR << "ImageURI missing transfer protocol: "
429                                      << imageURI;
430                     return;
431                 }
432                 transferProtocol = imageURI.substr(0, separator);
433                 // Ensure protocol is upper case for a common comparison path
434                 // below
435                 boost::to_upper(*transferProtocol);
436                 BMCWEB_LOG_DEBUG << "Encoded transfer protocol "
437                                  << *transferProtocol;
438 
439                 // Adjust imageURI to not have the protocol on it for parsing
440                 // below
441                 // ex. tftp://1.1.1.1/myfile.bin -> 1.1.1.1/myfile.bin
442                 imageURI = imageURI.substr(separator + 3);
443                 BMCWEB_LOG_DEBUG << "Adjusted imageUri " << imageURI;
444             }
445 
446             // OpenBMC currently only supports TFTP
447             if (*transferProtocol != "TFTP")
448             {
449                 messages::actionParameterNotSupported(
450                     asyncResp->res, "TransferProtocol",
451                     "UpdateService.SimpleUpdate");
452                 BMCWEB_LOG_ERROR << "Request incorrect protocol parameter: "
453                                  << *transferProtocol;
454                 return;
455             }
456 
457             // Format should be <IP or Hostname>/<file> for imageURI
458             size_t separator = imageURI.find('/');
459             if ((separator == std::string::npos) ||
460                 ((separator + 1) > imageURI.size()))
461             {
462                 messages::actionParameterValueTypeError(
463                     asyncResp->res, imageURI, "ImageURI",
464                     "UpdateService.SimpleUpdate");
465                 BMCWEB_LOG_ERROR << "Invalid ImageURI: " << imageURI;
466                 return;
467             }
468 
469             std::string tftpServer = imageURI.substr(0, separator);
470             std::string fwFile = imageURI.substr(separator + 1);
471             BMCWEB_LOG_DEBUG << "Server: " << tftpServer + " File: " << fwFile;
472 
473             // Setup callback for when new software detected
474             // Give TFTP 10 minutes to complete
475             monitorForSoftwareAvailable(
476                 asyncResp, req,
477                 "/redfish/v1/UpdateService/Actions/UpdateService.SimpleUpdate",
478                 600);
479 
480             // TFTP can take up to 10 minutes depending on image size and
481             // connection speed. Return to caller as soon as the TFTP operation
482             // has been started. The callback above will ensure the activate
483             // is started once the download has completed
484             redfish::messages::success(asyncResp->res);
485 
486             // Call TFTP service
487             crow::connections::systemBus->async_method_call(
488                 [](const boost::system::error_code ec) {
489                     if (ec)
490                     {
491                         // messages::internalError(asyncResp->res);
492                         cleanUp();
493                         BMCWEB_LOG_DEBUG << "error_code = " << ec;
494                         BMCWEB_LOG_DEBUG << "error msg = " << ec.message();
495                     }
496                     else
497                     {
498                         BMCWEB_LOG_DEBUG << "Call to DownloaViaTFTP Success";
499                     }
500                 },
501                 "xyz.openbmc_project.Software.Download",
502                 "/xyz/openbmc_project/software",
503                 "xyz.openbmc_project.Common.TFTP", "DownloadViaTFTP", fwFile,
504                 tftpServer);
505 
506             BMCWEB_LOG_DEBUG << "Exit UpdateService.SimpleUpdate doPost";
507         });
508 }
509 
510 inline void requestRoutesUpdateService(App& app)
511 {
512     BMCWEB_ROUTE(app, "/redfish/v1/UpdateService/")
513         .privileges(redfish::privileges::getUpdateService)
514         .methods(
515             boost::beast::http::verb::
516                 get)([](const crow::Request&,
517                         const std::shared_ptr<bmcweb::AsyncResp>& asyncResp) {
518             asyncResp->res.jsonValue["@odata.type"] =
519                 "#UpdateService.v1_5_0.UpdateService";
520             asyncResp->res.jsonValue["@odata.id"] = "/redfish/v1/UpdateService";
521             asyncResp->res.jsonValue["Id"] = "UpdateService";
522             asyncResp->res.jsonValue["Description"] =
523                 "Service for Software Update";
524             asyncResp->res.jsonValue["Name"] = "Update Service";
525             asyncResp->res.jsonValue["HttpPushUri"] =
526                 "/redfish/v1/UpdateService";
527             // UpdateService cannot be disabled
528             asyncResp->res.jsonValue["ServiceEnabled"] = true;
529             asyncResp->res.jsonValue["FirmwareInventory"] = {
530                 {"@odata.id", "/redfish/v1/UpdateService/FirmwareInventory"}};
531             // Get the MaxImageSizeBytes
532             asyncResp->res.jsonValue["MaxImageSizeBytes"] =
533                 bmcwebHttpReqBodyLimitMb * 1024 * 1024;
534 
535 #ifdef BMCWEB_INSECURE_ENABLE_REDFISH_FW_TFTP_UPDATE
536             // Update Actions object.
537             nlohmann::json& updateSvcSimpleUpdate =
538                 asyncResp->res
539                     .jsonValue["Actions"]["#UpdateService.SimpleUpdate"];
540             updateSvcSimpleUpdate["target"] =
541                 "/redfish/v1/UpdateService/Actions/UpdateService.SimpleUpdate";
542             updateSvcSimpleUpdate["TransferProtocol@Redfish.AllowableValues"] =
543                 {"TFTP"};
544 #endif
545             // Get the current ApplyTime value
546             sdbusplus::asio::getProperty<std::string>(
547                 *crow::connections::systemBus, "xyz.openbmc_project.Settings",
548                 "/xyz/openbmc_project/software/apply_time",
549                 "xyz.openbmc_project.Software.ApplyTime", "RequestedApplyTime",
550                 [asyncResp](const boost::system::error_code ec,
551                             const std::string& applyTime) {
552                     if (ec)
553                     {
554                         BMCWEB_LOG_DEBUG << "DBUS response error " << ec;
555                         messages::internalError(asyncResp->res);
556                         return;
557                     }
558 
559                     // Store the ApplyTime Value
560                     if (applyTime == "xyz.openbmc_project.Software.ApplyTime."
561                                      "RequestedApplyTimes.Immediate")
562                     {
563                         asyncResp->res
564                             .jsonValue["HttpPushUriOptions"]
565                                       ["HttpPushUriApplyTime"]["ApplyTime"] =
566                             "Immediate";
567                     }
568                     else if (applyTime ==
569                              "xyz.openbmc_project.Software.ApplyTime."
570                              "RequestedApplyTimes.OnReset")
571                     {
572                         asyncResp->res
573                             .jsonValue["HttpPushUriOptions"]
574                                       ["HttpPushUriApplyTime"]["ApplyTime"] =
575                             "OnReset";
576                     }
577                 });
578         });
579     BMCWEB_ROUTE(app, "/redfish/v1/UpdateService/")
580         .privileges(redfish::privileges::patchUpdateService)
581         .methods(
582             boost::beast::http::verb::
583                 patch)([](const crow::Request& req,
584                           const std::shared_ptr<bmcweb::AsyncResp>& asyncResp) {
585             BMCWEB_LOG_DEBUG << "doPatch...";
586 
587             std::optional<nlohmann::json> pushUriOptions;
588             if (!json_util::readJson(req, asyncResp->res, "HttpPushUriOptions",
589                                      pushUriOptions))
590             {
591                 return;
592             }
593 
594             if (pushUriOptions)
595             {
596                 std::optional<nlohmann::json> pushUriApplyTime;
597                 if (!json_util::readJson(*pushUriOptions, asyncResp->res,
598                                          "HttpPushUriApplyTime",
599                                          pushUriApplyTime))
600                 {
601                     return;
602                 }
603 
604                 if (pushUriApplyTime)
605                 {
606                     std::optional<std::string> applyTime;
607                     if (!json_util::readJson(*pushUriApplyTime, asyncResp->res,
608                                              "ApplyTime", applyTime))
609                     {
610                         return;
611                     }
612 
613                     if (applyTime)
614                     {
615                         std::string applyTimeNewVal;
616                         if (applyTime == "Immediate")
617                         {
618                             applyTimeNewVal =
619                                 "xyz.openbmc_project.Software.ApplyTime.RequestedApplyTimes.Immediate";
620                         }
621                         else if (applyTime == "OnReset")
622                         {
623                             applyTimeNewVal =
624                                 "xyz.openbmc_project.Software.ApplyTime.RequestedApplyTimes.OnReset";
625                         }
626                         else
627                         {
628                             BMCWEB_LOG_INFO
629                                 << "ApplyTime value is not in the list of acceptable values";
630                             messages::propertyValueNotInList(
631                                 asyncResp->res, *applyTime, "ApplyTime");
632                             return;
633                         }
634 
635                         // Set the requested image apply time value
636                         crow::connections::systemBus->async_method_call(
637                             [asyncResp](const boost::system::error_code ec) {
638                                 if (ec)
639                                 {
640                                     BMCWEB_LOG_ERROR
641                                         << "D-Bus responses error: " << ec;
642                                     messages::internalError(asyncResp->res);
643                                     return;
644                                 }
645                                 messages::success(asyncResp->res);
646                             },
647                             "xyz.openbmc_project.Settings",
648                             "/xyz/openbmc_project/software/apply_time",
649                             "org.freedesktop.DBus.Properties", "Set",
650                             "xyz.openbmc_project.Software.ApplyTime",
651                             "RequestedApplyTime",
652                             dbus::utility::DbusVariantType{applyTimeNewVal});
653                     }
654                 }
655             }
656         });
657     BMCWEB_ROUTE(app, "/redfish/v1/UpdateService/")
658         .privileges(redfish::privileges::postUpdateService)
659         .methods(boost::beast::http::verb::post)(
660             [](const crow::Request& req,
661                const std::shared_ptr<bmcweb::AsyncResp>& asyncResp) {
662                 BMCWEB_LOG_DEBUG << "doPost...";
663 
664                 // Setup callback for when new software detected
665                 monitorForSoftwareAvailable(asyncResp, req,
666                                             "/redfish/v1/UpdateService");
667 
668                 std::string filepath("/tmp/images/" +
669                                      boost::uuids::to_string(
670                                          boost::uuids::random_generator()()));
671                 BMCWEB_LOG_DEBUG << "Writing file to " << filepath;
672                 std::ofstream out(filepath, std::ofstream::out |
673                                                 std::ofstream::binary |
674                                                 std::ofstream::trunc);
675                 out << req.body;
676                 out.close();
677                 BMCWEB_LOG_DEBUG << "file upload complete!!";
678             });
679 }
680 
681 inline void requestRoutesSoftwareInventoryCollection(App& app)
682 {
683     BMCWEB_ROUTE(app, "/redfish/v1/UpdateService/FirmwareInventory/")
684         .privileges(redfish::privileges::getSoftwareInventoryCollection)
685         .methods(
686             boost::beast::http::verb::
687                 get)([](const crow::Request&,
688                         const std::shared_ptr<bmcweb::AsyncResp>& asyncResp) {
689             asyncResp->res.jsonValue["@odata.type"] =
690                 "#SoftwareInventoryCollection.SoftwareInventoryCollection";
691             asyncResp->res.jsonValue["@odata.id"] =
692                 "/redfish/v1/UpdateService/FirmwareInventory";
693             asyncResp->res.jsonValue["Name"] = "Software Inventory Collection";
694 
695             crow::connections::systemBus->async_method_call(
696                 [asyncResp](
697                     const boost::system::error_code ec,
698                     const std::vector<
699                         std::pair<std::string,
700                                   std::vector<std::pair<
701                                       std::string, std::vector<std::string>>>>>&
702                         subtree) {
703                     if (ec)
704                     {
705                         messages::internalError(asyncResp->res);
706                         return;
707                     }
708                     asyncResp->res.jsonValue["Members"] =
709                         nlohmann::json::array();
710                     asyncResp->res.jsonValue["Members@odata.count"] = 0;
711 
712                     for (auto& obj : subtree)
713                     {
714                         sdbusplus::message::object_path path(obj.first);
715                         std::string swId = path.filename();
716                         if (swId.empty())
717                         {
718                             messages::internalError(asyncResp->res);
719                             BMCWEB_LOG_DEBUG << "Can't parse firmware ID!!";
720                             return;
721                         }
722 
723                         nlohmann::json& members =
724                             asyncResp->res.jsonValue["Members"];
725                         members.push_back(
726                             {{"@odata.id",
727                               "/redfish/v1/UpdateService/FirmwareInventory/" +
728                                   swId}});
729                         asyncResp->res.jsonValue["Members@odata.count"] =
730                             members.size();
731                     }
732                 },
733                 // Note that only firmware levels associated with a device
734                 // are stored under /xyz/openbmc_project/software therefore
735                 // to ensure only real FirmwareInventory items are returned,
736                 // this full object path must be used here as input to
737                 // mapper
738                 "xyz.openbmc_project.ObjectMapper",
739                 "/xyz/openbmc_project/object_mapper",
740                 "xyz.openbmc_project.ObjectMapper", "GetSubTree",
741                 "/xyz/openbmc_project/software", static_cast<int32_t>(0),
742                 std::array<const char*, 1>{
743                     "xyz.openbmc_project.Software.Version"});
744         });
745 }
746 /* Fill related item links (i.e. bmc, bios) in for inventory */
747 inline static void
748     getRelatedItems(const std::shared_ptr<bmcweb::AsyncResp>& aResp,
749                     const std::string& purpose)
750 {
751     if (purpose == fw_util::bmcPurpose)
752     {
753         nlohmann::json& relatedItem = aResp->res.jsonValue["RelatedItem"];
754         relatedItem.push_back({{"@odata.id", "/redfish/v1/Managers/bmc"}});
755         aResp->res.jsonValue["RelatedItem@odata.count"] = relatedItem.size();
756     }
757     else if (purpose == fw_util::biosPurpose)
758     {
759         nlohmann::json& relatedItem = aResp->res.jsonValue["RelatedItem"];
760         relatedItem.push_back(
761             {{"@odata.id", "/redfish/v1/Systems/system/Bios"}});
762         aResp->res.jsonValue["Members@odata.count"] = relatedItem.size();
763     }
764     else
765     {
766         BMCWEB_LOG_ERROR << "Unknown software purpose " << purpose;
767     }
768 }
769 
770 inline void requestRoutesSoftwareInventory(App& app)
771 {
772     BMCWEB_ROUTE(app, "/redfish/v1/UpdateService/FirmwareInventory/<str>/")
773         .privileges(redfish::privileges::getSoftwareInventory)
774         .methods(
775             boost::beast::http::verb::get)([](const crow::Request&,
776                                               const std::shared_ptr<
777                                                   bmcweb::AsyncResp>& asyncResp,
778                                               const std::string& param) {
779             std::shared_ptr<std::string> swId =
780                 std::make_shared<std::string>(param);
781 
782             asyncResp->res.jsonValue["@odata.id"] =
783                 "/redfish/v1/UpdateService/FirmwareInventory/" + *swId;
784 
785             crow::connections::systemBus->async_method_call(
786                 [asyncResp, swId](
787                     const boost::system::error_code ec,
788                     const std::vector<
789                         std::pair<std::string,
790                                   std::vector<std::pair<
791                                       std::string, std::vector<std::string>>>>>&
792                         subtree) {
793                     BMCWEB_LOG_DEBUG << "doGet callback...";
794                     if (ec)
795                     {
796                         messages::internalError(asyncResp->res);
797                         return;
798                     }
799 
800                     // Ensure we find our input swId, otherwise return an error
801                     bool found = false;
802                     for (const std::pair<
803                              std::string,
804                              std::vector<std::pair<
805                                  std::string, std::vector<std::string>>>>& obj :
806                          subtree)
807                     {
808                         if (boost::ends_with(obj.first, *swId) != true)
809                         {
810                             continue;
811                         }
812 
813                         if (obj.second.size() < 1)
814                         {
815                             continue;
816                         }
817 
818                         found = true;
819                         fw_util::getFwStatus(asyncResp, swId,
820                                              obj.second[0].first);
821 
822                         crow::connections::systemBus->async_method_call(
823                             [asyncResp,
824                              swId](const boost::system::error_code errorCode,
825                                    const boost::container::flat_map<
826                                        std::string,
827                                        dbus::utility::DbusVariantType>&
828                                        propertiesList) {
829                                 if (errorCode)
830                                 {
831                                     messages::internalError(asyncResp->res);
832                                     return;
833                                 }
834                                 boost::container::flat_map<
835                                     std::string,
836                                     dbus::utility::DbusVariantType>::
837                                     const_iterator it =
838                                         propertiesList.find("Purpose");
839                                 if (it == propertiesList.end())
840                                 {
841                                     BMCWEB_LOG_DEBUG
842                                         << "Can't find property \"Purpose\"!";
843                                     messages::propertyMissing(asyncResp->res,
844                                                               "Purpose");
845                                     return;
846                                 }
847                                 const std::string* swInvPurpose =
848                                     std::get_if<std::string>(&it->second);
849                                 if (swInvPurpose == nullptr)
850                                 {
851                                     BMCWEB_LOG_DEBUG
852                                         << "wrong types for property\"Purpose\"!";
853                                     messages::propertyValueTypeError(
854                                         asyncResp->res, "", "Purpose");
855                                     return;
856                                 }
857 
858                                 BMCWEB_LOG_DEBUG << "swInvPurpose = "
859                                                  << *swInvPurpose;
860                                 it = propertiesList.find("Version");
861                                 if (it == propertiesList.end())
862                                 {
863                                     BMCWEB_LOG_DEBUG
864                                         << "Can't find property \"Version\"!";
865                                     messages::propertyMissing(asyncResp->res,
866                                                               "Version");
867                                     return;
868                                 }
869 
870                                 BMCWEB_LOG_DEBUG << "Version found!";
871 
872                                 const std::string* version =
873                                     std::get_if<std::string>(&it->second);
874 
875                                 if (version == nullptr)
876                                 {
877                                     BMCWEB_LOG_DEBUG
878                                         << "Can't find property \"Version\"!";
879 
880                                     messages::propertyValueTypeError(
881                                         asyncResp->res, "", "Version");
882                                     return;
883                                 }
884                                 asyncResp->res.jsonValue["Version"] = *version;
885                                 asyncResp->res.jsonValue["Id"] = *swId;
886 
887                                 // swInvPurpose is of format:
888                                 // xyz.openbmc_project.Software.Version.VersionPurpose.ABC
889                                 // Translate this to "ABC image"
890                                 size_t endDesc = swInvPurpose->rfind('.');
891                                 if (endDesc == std::string::npos)
892                                 {
893                                     messages::internalError(asyncResp->res);
894                                     return;
895                                 }
896                                 endDesc++;
897                                 if (endDesc >= swInvPurpose->size())
898                                 {
899                                     messages::internalError(asyncResp->res);
900                                     return;
901                                 }
902 
903                                 std::string formatDesc =
904                                     swInvPurpose->substr(endDesc);
905                                 asyncResp->res.jsonValue["Description"] =
906                                     formatDesc + " image";
907                                 getRelatedItems(asyncResp, *swInvPurpose);
908                             },
909                             obj.second[0].first, obj.first,
910                             "org.freedesktop.DBus.Properties", "GetAll",
911                             "xyz.openbmc_project.Software.Version");
912                     }
913                     if (!found)
914                     {
915                         BMCWEB_LOG_ERROR
916                             << "Input swID " + *swId + " not found!";
917                         messages::resourceMissingAtURI(
918                             asyncResp->res,
919                             "/redfish/v1/UpdateService/FirmwareInventory/" +
920                                 *swId);
921                         return;
922                     }
923                     asyncResp->res.jsonValue["@odata.type"] =
924                         "#SoftwareInventory.v1_1_0.SoftwareInventory";
925                     asyncResp->res.jsonValue["Name"] = "Software Inventory";
926                     asyncResp->res.jsonValue["Status"]["HealthRollup"] = "OK";
927 
928                     asyncResp->res.jsonValue["Updateable"] = false;
929                     fw_util::getFwUpdateableStatus(asyncResp, swId);
930                 },
931                 "xyz.openbmc_project.ObjectMapper",
932                 "/xyz/openbmc_project/object_mapper",
933                 "xyz.openbmc_project.ObjectMapper", "GetSubTree", "/",
934                 static_cast<int32_t>(0),
935                 std::array<const char*, 1>{
936                     "xyz.openbmc_project.Software.Version"});
937         });
938 }
939 
940 } // namespace redfish
941