xref: /openbmc/bmcweb/redfish-core/lib/update_service.hpp (revision f88b21706f70ba70951c2876a7b41eb0ccaed361)
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 "dbus_utility.hpp"
22 #include "error_messages.hpp"
23 #include "generated/enums/update_service.hpp"
24 #include "multipart_parser.hpp"
25 #include "ossl_random.hpp"
26 #include "query.hpp"
27 #include "registries/privilege_registry.hpp"
28 #include "task.hpp"
29 #include "task_messages.hpp"
30 #include "utils/collection.hpp"
31 #include "utils/dbus_utils.hpp"
32 #include "utils/json_utils.hpp"
33 #include "utils/sw_utils.hpp"
34 
35 #include <sys/mman.h>
36 
37 #include <boost/system/error_code.hpp>
38 #include <boost/url/format.hpp>
39 #include <sdbusplus/asio/property.hpp>
40 #include <sdbusplus/bus/match.hpp>
41 #include <sdbusplus/unpack_properties.hpp>
42 
43 #include <array>
44 #include <cstddef>
45 #include <filesystem>
46 #include <functional>
47 #include <iterator>
48 #include <memory>
49 #include <optional>
50 #include <string>
51 #include <string_view>
52 #include <unordered_map>
53 #include <vector>
54 
55 namespace redfish
56 {
57 
58 // Match signals added on software path
59 // NOLINTNEXTLINE(cppcoreguidelines-avoid-non-const-global-variables)
60 static std::unique_ptr<sdbusplus::bus::match_t> fwUpdateMatcher;
61 // NOLINTNEXTLINE(cppcoreguidelines-avoid-non-const-global-variables)
62 static std::unique_ptr<sdbusplus::bus::match_t> fwUpdateErrorMatcher;
63 // Only allow one update at a time
64 // NOLINTNEXTLINE(cppcoreguidelines-avoid-non-const-global-variables)
65 static bool fwUpdateInProgress = false;
66 // Timer for software available
67 // NOLINTNEXTLINE(cppcoreguidelines-avoid-non-const-global-variables)
68 static std::unique_ptr<boost::asio::steady_timer> fwAvailableTimer;
69 
70 struct MemoryFileDescriptor
71 {
72     int fd = -1;
73 
74     explicit MemoryFileDescriptor(const std::string& filename) :
75         fd(memfd_create(filename.c_str(), 0))
76     {}
77 
78     MemoryFileDescriptor(const MemoryFileDescriptor&) = default;
79     MemoryFileDescriptor(MemoryFileDescriptor&& other) noexcept : fd(other.fd)
80     {
81         other.fd = -1;
82     }
83     MemoryFileDescriptor& operator=(const MemoryFileDescriptor&) = delete;
84     MemoryFileDescriptor& operator=(MemoryFileDescriptor&&) = default;
85 
86     ~MemoryFileDescriptor()
87     {
88         if (fd != -1)
89         {
90             close(fd);
91         }
92     }
93 
94     bool rewind() const
95     {
96         if (lseek(fd, 0, SEEK_SET) == -1)
97         {
98             BMCWEB_LOG_ERROR("Failed to seek to beginning of image memfd");
99             return false;
100         }
101         return true;
102     }
103 };
104 
105 inline void cleanUp()
106 {
107     fwUpdateInProgress = false;
108     fwUpdateMatcher = nullptr;
109     fwUpdateErrorMatcher = nullptr;
110 }
111 
112 inline void activateImage(const std::string& objPath,
113                           const std::string& service)
114 {
115     BMCWEB_LOG_DEBUG("Activate image for {} {}", objPath, service);
116     sdbusplus::asio::setProperty(
117         *crow::connections::systemBus, service, objPath,
118         "xyz.openbmc_project.Software.Activation", "RequestedActivation",
119         "xyz.openbmc_project.Software.Activation.RequestedActivations.Active",
120         [](const boost::system::error_code& ec) {
121         if (ec)
122         {
123             BMCWEB_LOG_DEBUG("error_code = {}", ec);
124             BMCWEB_LOG_DEBUG("error msg = {}", ec.message());
125         }
126     });
127 }
128 
129 inline bool handleCreateTask(const boost::system::error_code& ec2,
130                              sdbusplus::message_t& msg,
131                              const std::shared_ptr<task::TaskData>& taskData)
132 {
133     if (ec2)
134     {
135         return task::completed;
136     }
137 
138     std::string iface;
139     dbus::utility::DBusPropertiesMap values;
140 
141     std::string index = std::to_string(taskData->index);
142     msg.read(iface, values);
143 
144     if (iface == "xyz.openbmc_project.Software.Activation")
145     {
146         const std::string* state = nullptr;
147         for (const auto& property : values)
148         {
149             if (property.first == "Activation")
150             {
151                 state = std::get_if<std::string>(&property.second);
152                 if (state == nullptr)
153                 {
154                     taskData->messages.emplace_back(messages::internalError());
155                     return task::completed;
156                 }
157             }
158         }
159 
160         if (state == nullptr)
161         {
162             return !task::completed;
163         }
164 
165         if (state->ends_with("Invalid") || state->ends_with("Failed"))
166         {
167             taskData->state = "Exception";
168             taskData->status = "Warning";
169             taskData->messages.emplace_back(messages::taskAborted(index));
170             return task::completed;
171         }
172 
173         if (state->ends_with("Staged"))
174         {
175             taskData->state = "Stopping";
176             taskData->messages.emplace_back(messages::taskPaused(index));
177 
178             // its staged, set a long timer to
179             // allow them time to complete the
180             // update (probably cycle the
181             // system) if this expires then
182             // task will be canceled
183             taskData->extendTimer(std::chrono::hours(5));
184             return !task::completed;
185         }
186 
187         if (state->ends_with("Active"))
188         {
189             taskData->messages.emplace_back(messages::taskCompletedOK(index));
190             taskData->state = "Completed";
191             return task::completed;
192         }
193     }
194     else if (iface == "xyz.openbmc_project.Software.ActivationProgress")
195     {
196         const uint8_t* progress = nullptr;
197         for (const auto& property : values)
198         {
199             if (property.first == "Progress")
200             {
201                 progress = std::get_if<uint8_t>(&property.second);
202                 if (progress == nullptr)
203                 {
204                     taskData->messages.emplace_back(messages::internalError());
205                     return task::completed;
206                 }
207             }
208         }
209 
210         if (progress == nullptr)
211         {
212             return !task::completed;
213         }
214         taskData->percentComplete = *progress;
215         taskData->messages.emplace_back(
216             messages::taskProgressChanged(index, *progress));
217 
218         // if we're getting status updates it's
219         // still alive, update timer
220         taskData->extendTimer(std::chrono::minutes(5));
221     }
222 
223     // as firmware update often results in a
224     // reboot, the task  may never "complete"
225     // unless it is an error
226 
227     return !task::completed;
228 }
229 
230 inline void createTask(const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
231                        task::Payload&& payload,
232                        const sdbusplus::message::object_path& objPath)
233 {
234     std::shared_ptr<task::TaskData> task = task::TaskData::createTask(
235         std::bind_front(handleCreateTask),
236         "type='signal',interface='org.freedesktop.DBus.Properties',"
237         "member='PropertiesChanged',path='" +
238             objPath.str + "'");
239     task->startTimer(std::chrono::minutes(5));
240     task->populateResp(asyncResp->res);
241     task->payload.emplace(std::move(payload));
242 }
243 
244 // Note that asyncResp can be either a valid pointer or nullptr. If nullptr
245 // then no asyncResp updates will occur
246 static void
247     softwareInterfaceAdded(const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
248                            sdbusplus::message_t& m, task::Payload&& payload)
249 {
250     dbus::utility::DBusInterfacesMap interfacesProperties;
251 
252     sdbusplus::message::object_path objPath;
253 
254     m.read(objPath, interfacesProperties);
255 
256     BMCWEB_LOG_DEBUG("obj path = {}", objPath.str);
257     for (const auto& interface : interfacesProperties)
258     {
259         BMCWEB_LOG_DEBUG("interface = {}", interface.first);
260 
261         if (interface.first == "xyz.openbmc_project.Software.Activation")
262         {
263             // Retrieve service and activate
264             constexpr std::array<std::string_view, 1> interfaces = {
265                 "xyz.openbmc_project.Software.Activation"};
266             dbus::utility::getDbusObject(
267                 objPath.str, interfaces,
268                 [objPath, asyncResp, payload(std::move(payload))](
269                     const boost::system::error_code& ec,
270                     const std::vector<
271                         std::pair<std::string, std::vector<std::string>>>&
272                         objInfo) mutable {
273                 if (ec)
274                 {
275                     BMCWEB_LOG_DEBUG("error_code = {}", ec);
276                     BMCWEB_LOG_DEBUG("error msg = {}", ec.message());
277                     if (asyncResp)
278                     {
279                         messages::internalError(asyncResp->res);
280                     }
281                     cleanUp();
282                     return;
283                 }
284                 // Ensure we only got one service back
285                 if (objInfo.size() != 1)
286                 {
287                     BMCWEB_LOG_ERROR("Invalid Object Size {}", objInfo.size());
288                     if (asyncResp)
289                     {
290                         messages::internalError(asyncResp->res);
291                     }
292                     cleanUp();
293                     return;
294                 }
295                 // cancel timer only when
296                 // xyz.openbmc_project.Software.Activation interface
297                 // is added
298                 fwAvailableTimer = nullptr;
299 
300                 activateImage(objPath.str, objInfo[0].first);
301                 if (asyncResp)
302                 {
303                     createTask(asyncResp, std::move(payload), objPath);
304                 }
305                 fwUpdateInProgress = false;
306             });
307 
308             break;
309         }
310     }
311 }
312 
313 inline void afterAvailbleTimerAsyncWait(
314     const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
315     const boost::system::error_code& ec)
316 {
317     cleanUp();
318     if (ec == boost::asio::error::operation_aborted)
319     {
320         // expected, we were canceled before the timer completed.
321         return;
322     }
323     BMCWEB_LOG_ERROR("Timed out waiting for firmware object being created");
324     BMCWEB_LOG_ERROR("FW image may has already been uploaded to server");
325     if (ec)
326     {
327         BMCWEB_LOG_ERROR("Async_wait failed{}", ec);
328         return;
329     }
330     if (asyncResp)
331     {
332         redfish::messages::internalError(asyncResp->res);
333     }
334 }
335 
336 inline void
337     handleUpdateErrorType(const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
338                           const std::string& url, const std::string& type)
339 {
340     if (type == "xyz.openbmc_project.Software.Image.Error.UnTarFailure")
341     {
342         redfish::messages::invalidUpload(asyncResp->res, url,
343                                          "Invalid archive");
344     }
345     else if (type ==
346              "xyz.openbmc_project.Software.Image.Error.ManifestFileFailure")
347     {
348         redfish::messages::invalidUpload(asyncResp->res, url,
349                                          "Invalid manifest");
350     }
351     else if (type == "xyz.openbmc_project.Software.Image.Error.ImageFailure")
352     {
353         redfish::messages::invalidUpload(asyncResp->res, url,
354                                          "Invalid image format");
355     }
356     else if (type == "xyz.openbmc_project.Software.Version.Error.AlreadyExists")
357     {
358         redfish::messages::invalidUpload(asyncResp->res, url,
359                                          "Image version already exists");
360 
361         redfish::messages::resourceAlreadyExists(
362             asyncResp->res, "UpdateService", "Version", "uploaded version");
363     }
364     else if (type == "xyz.openbmc_project.Software.Image.Error.BusyFailure")
365     {
366         redfish::messages::resourceExhaustion(asyncResp->res, url);
367     }
368     else if (type == "xyz.openbmc_project.Software.Version.Error.Incompatible")
369     {
370         redfish::messages::invalidUpload(asyncResp->res, url,
371                                          "Incompatible image version");
372     }
373     else if (type ==
374              "xyz.openbmc_project.Software.Version.Error.ExpiredAccessKey")
375     {
376         redfish::messages::invalidUpload(asyncResp->res, url,
377                                          "Update Access Key Expired");
378     }
379     else if (type ==
380              "xyz.openbmc_project.Software.Version.Error.InvalidSignature")
381     {
382         redfish::messages::invalidUpload(asyncResp->res, url,
383                                          "Invalid image signature");
384     }
385     else if (type ==
386                  "xyz.openbmc_project.Software.Image.Error.InternalFailure" ||
387              type == "xyz.openbmc_project.Software.Version.Error.HostFile")
388     {
389         BMCWEB_LOG_ERROR("Software Image Error type={}", type);
390         redfish::messages::internalError(asyncResp->res);
391     }
392     else
393     {
394         // Unrelated error types. Ignored
395         BMCWEB_LOG_INFO("Non-Software-related Error type={}. Ignored", type);
396         return;
397     }
398     // Clear the timer
399     fwAvailableTimer = nullptr;
400 }
401 
402 inline void
403     afterUpdateErrorMatcher(const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
404                             const std::string& url, sdbusplus::message_t& m)
405 {
406     dbus::utility::DBusInterfacesMap interfacesProperties;
407     sdbusplus::message::object_path objPath;
408     m.read(objPath, interfacesProperties);
409     BMCWEB_LOG_DEBUG("obj path = {}", objPath.str);
410     for (const std::pair<std::string, dbus::utility::DBusPropertiesMap>&
411              interface : interfacesProperties)
412     {
413         if (interface.first == "xyz.openbmc_project.Logging.Entry")
414         {
415             for (const std::pair<std::string, dbus::utility::DbusVariantType>&
416                      value : interface.second)
417             {
418                 if (value.first != "Message")
419                 {
420                     continue;
421                 }
422                 const std::string* type =
423                     std::get_if<std::string>(&value.second);
424                 if (type == nullptr)
425                 {
426                     // if this was our message, timeout will cover it
427                     return;
428                 }
429                 handleUpdateErrorType(asyncResp, url, *type);
430             }
431         }
432     }
433 }
434 
435 // Note that asyncResp can be either a valid pointer or nullptr. If nullptr
436 // then no asyncResp updates will occur
437 inline void monitorForSoftwareAvailable(
438     const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
439     const crow::Request& req, const std::string& url,
440     int timeoutTimeSeconds = 25)
441 {
442     // Only allow one FW update at a time
443     if (fwUpdateInProgress)
444     {
445         if (asyncResp)
446         {
447             messages::serviceTemporarilyUnavailable(asyncResp->res, "30");
448         }
449         return;
450     }
451 
452     if (req.ioService == nullptr)
453     {
454         messages::internalError(asyncResp->res);
455         return;
456     }
457 
458     fwAvailableTimer =
459         std::make_unique<boost::asio::steady_timer>(*req.ioService);
460 
461     fwAvailableTimer->expires_after(std::chrono::seconds(timeoutTimeSeconds));
462 
463     fwAvailableTimer->async_wait(
464         std::bind_front(afterAvailbleTimerAsyncWait, asyncResp));
465 
466     task::Payload payload(req);
467     auto callback = [asyncResp, payload](sdbusplus::message_t& m) mutable {
468         BMCWEB_LOG_DEBUG("Match fired");
469         softwareInterfaceAdded(asyncResp, m, std::move(payload));
470     };
471 
472     fwUpdateInProgress = true;
473 
474     fwUpdateMatcher = std::make_unique<sdbusplus::bus::match_t>(
475         *crow::connections::systemBus,
476         "interface='org.freedesktop.DBus.ObjectManager',type='signal',"
477         "member='InterfacesAdded',path='/xyz/openbmc_project/software'",
478         callback);
479 
480     fwUpdateErrorMatcher = std::make_unique<sdbusplus::bus::match_t>(
481         *crow::connections::systemBus,
482         "interface='org.freedesktop.DBus.ObjectManager',type='signal',"
483         "member='InterfacesAdded',"
484         "path='/xyz/openbmc_project/logging'",
485         std::bind_front(afterUpdateErrorMatcher, asyncResp, url));
486 }
487 
488 inline std::optional<boost::urls::url>
489     parseSimpleUpdateUrl(std::string imageURI,
490                          std::optional<std::string> transferProtocol,
491                          crow::Response& res)
492 {
493     if (imageURI.find("://") == std::string::npos)
494     {
495         if (imageURI.starts_with("/"))
496         {
497             messages::actionParameterValueTypeError(
498                 res, imageURI, "ImageURI", "UpdateService.SimpleUpdate");
499             return std::nullopt;
500         }
501         if (!transferProtocol)
502         {
503             messages::actionParameterValueTypeError(
504                 res, imageURI, "ImageURI", "UpdateService.SimpleUpdate");
505             return std::nullopt;
506         }
507         // OpenBMC currently only supports TFTP or HTTPS
508         if (*transferProtocol == "TFTP")
509         {
510             imageURI = "tftp://" + imageURI;
511         }
512         else if (*transferProtocol == "HTTPS")
513         {
514             imageURI = "https://" + imageURI;
515         }
516         else
517         {
518             messages::actionParameterNotSupported(res, "TransferProtocol",
519                                                   *transferProtocol);
520             BMCWEB_LOG_ERROR("Request incorrect protocol parameter: {}",
521                              *transferProtocol);
522             return std::nullopt;
523         }
524     }
525 
526     boost::system::result<boost::urls::url> url =
527         boost::urls::parse_absolute_uri(imageURI);
528     if (!url)
529     {
530         messages::actionParameterValueTypeError(res, imageURI, "ImageURI",
531                                                 "UpdateService.SimpleUpdate");
532 
533         return std::nullopt;
534     }
535     url->normalize();
536 
537     if (url->scheme() == "tftp")
538     {
539         if (url->encoded_path().size() < 2)
540         {
541             messages::actionParameterNotSupported(res, "ImageURI",
542                                                   url->buffer());
543             return std::nullopt;
544         }
545     }
546     else if (url->scheme() == "https")
547     {
548         // Empty paths default to "/"
549         if (url->encoded_path().empty())
550         {
551             url->set_encoded_path("/");
552         }
553     }
554     else
555     {
556         messages::actionParameterNotSupported(res, "ImageURI", imageURI);
557         return std::nullopt;
558     }
559 
560     if (url->encoded_path().empty())
561     {
562         messages::actionParameterValueTypeError(res, imageURI, "ImageURI",
563                                                 "UpdateService.SimpleUpdate");
564         return std::nullopt;
565     }
566 
567     return *url;
568 }
569 
570 inline void doHttpsUpdate(const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
571                           const boost::urls::url_view_base& url)
572 {
573     messages::actionParameterNotSupported(asyncResp->res, "ImageURI",
574                                           url.buffer());
575 }
576 
577 inline void doTftpUpdate(const crow::Request& req,
578                          const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
579                          const boost::urls::url_view_base& url)
580 {
581     if (!BMCWEB_INSECURE_TFTP_UPDATE)
582     {
583         messages::actionParameterNotSupported(asyncResp->res, "ImageURI",
584                                               url.buffer());
585         return;
586     }
587 
588     std::string path(url.encoded_path());
589     if (path.size() < 2)
590     {
591         messages::actionParameterNotSupported(asyncResp->res, "ImageURI",
592                                               url.buffer());
593         return;
594     }
595     // TFTP expects a path without a /
596     path.erase(0, 1);
597     std::string host(url.encoded_host_and_port());
598     BMCWEB_LOG_DEBUG("Server: {} File: {}", host, path);
599 
600     // Setup callback for when new software detected
601     // Give TFTP 10 minutes to complete
602     monitorForSoftwareAvailable(
603         asyncResp, req,
604         "/redfish/v1/UpdateService/Actions/UpdateService.SimpleUpdate", 600);
605 
606     // TFTP can take up to 10 minutes depending on image size and
607     // connection speed. Return to caller as soon as the TFTP operation
608     // has been started. The callback above will ensure the activate
609     // is started once the download has completed
610     redfish::messages::success(asyncResp->res);
611 
612     // Call TFTP service
613     crow::connections::systemBus->async_method_call(
614         [](const boost::system::error_code& ec) {
615         if (ec)
616         {
617             // messages::internalError(asyncResp->res);
618             cleanUp();
619             BMCWEB_LOG_DEBUG("error_code = {}", ec);
620             BMCWEB_LOG_DEBUG("error msg = {}", ec.message());
621         }
622         else
623         {
624             BMCWEB_LOG_DEBUG("Call to DownloaViaTFTP Success");
625         }
626     },
627         "xyz.openbmc_project.Software.Download",
628         "/xyz/openbmc_project/software", "xyz.openbmc_project.Common.TFTP",
629         "DownloadViaTFTP", path, host);
630 }
631 
632 inline void handleUpdateServiceSimpleUpdateAction(
633     crow::App& app, const crow::Request& req,
634     const std::shared_ptr<bmcweb::AsyncResp>& asyncResp)
635 {
636     if (!redfish::setUpRedfishRoute(app, req, asyncResp))
637     {
638         return;
639     }
640 
641     std::optional<std::string> transferProtocol;
642     std::string imageURI;
643 
644     BMCWEB_LOG_DEBUG("Enter UpdateService.SimpleUpdate doPost");
645 
646     // User can pass in both TransferProtocol and ImageURI parameters or
647     // they can pass in just the ImageURI with the transfer protocol
648     // embedded within it.
649     // 1) TransferProtocol:TFTP ImageURI:1.1.1.1/myfile.bin
650     // 2) ImageURI:tftp://1.1.1.1/myfile.bin
651 
652     if (!json_util::readJsonAction(req, asyncResp->res, "TransferProtocol",
653                                    transferProtocol, "ImageURI", imageURI))
654     {
655         BMCWEB_LOG_DEBUG("Missing TransferProtocol or ImageURI parameter");
656         return;
657     }
658 
659     std::optional<boost::urls::url> url =
660         parseSimpleUpdateUrl(imageURI, transferProtocol, asyncResp->res);
661     if (!url)
662     {
663         return;
664     }
665     if (url->scheme() == "tftp")
666     {
667         doTftpUpdate(req, asyncResp, *url);
668     }
669     else if (url->scheme() == "https")
670     {
671         doHttpsUpdate(asyncResp, *url);
672     }
673     else
674     {
675         messages::actionParameterNotSupported(asyncResp->res, "ImageURI",
676                                               url->buffer());
677         return;
678     }
679 
680     BMCWEB_LOG_DEBUG("Exit UpdateService.SimpleUpdate doPost");
681 }
682 
683 inline void uploadImageFile(crow::Response& res, std::string_view body)
684 {
685     std::filesystem::path filepath("/tmp/images/" + bmcweb::getRandomUUID());
686 
687     BMCWEB_LOG_DEBUG("Writing file to {}", filepath.string());
688     std::ofstream out(filepath, std::ofstream::out | std::ofstream::binary |
689                                     std::ofstream::trunc);
690     // set the permission of the file to 640
691     std::filesystem::perms permission = std::filesystem::perms::owner_read |
692                                         std::filesystem::perms::group_read;
693     std::filesystem::permissions(filepath, permission);
694     out << body;
695 
696     if (out.bad())
697     {
698         messages::internalError(res);
699         cleanUp();
700     }
701 }
702 
703 // Convert the Request Apply Time to the D-Bus value
704 inline bool convertApplyTime(crow::Response& res, const std::string& applyTime,
705                              std::string& applyTimeNewVal)
706 {
707     if (applyTime == "Immediate")
708     {
709         applyTimeNewVal =
710             "xyz.openbmc_project.Software.ApplyTime.RequestedApplyTimes.Immediate";
711     }
712     else if (applyTime == "OnReset")
713     {
714         applyTimeNewVal =
715             "xyz.openbmc_project.Software.ApplyTime.RequestedApplyTimes.OnReset";
716     }
717     else
718     {
719         BMCWEB_LOG_WARNING(
720             "ApplyTime value {} is not in the list of acceptable values",
721             applyTime);
722         messages::propertyValueNotInList(res, applyTime, "ApplyTime");
723         return false;
724     }
725     return true;
726 }
727 
728 inline void setApplyTime(const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
729                          const std::string& applyTime)
730 {
731     std::string applyTimeNewVal;
732     if (!convertApplyTime(asyncResp->res, applyTime, applyTimeNewVal))
733     {
734         return;
735     }
736 
737     setDbusProperty(asyncResp, "ApplyTime", "xyz.openbmc_project.Settings",
738                     sdbusplus::message::object_path(
739                         "/xyz/openbmc_project/software/apply_time"),
740                     "xyz.openbmc_project.Software.ApplyTime",
741                     "RequestedApplyTime", applyTimeNewVal);
742 }
743 
744 struct MultiPartUpdateParameters
745 {
746     std::optional<std::string> applyTime;
747     std::string uploadData;
748     std::vector<std::string> targets;
749 };
750 
751 inline std::optional<std::string>
752     processUrl(boost::system::result<boost::urls::url_view>& url)
753 {
754     if (!url)
755     {
756         return std::nullopt;
757     }
758     if (crow::utility::readUrlSegments(*url, "redfish", "v1", "Managers",
759                                        BMCWEB_REDFISH_MANAGER_URI_NAME))
760     {
761         return std::make_optional(std::string(BMCWEB_REDFISH_MANAGER_URI_NAME));
762     }
763     if constexpr (!BMCWEB_REDFISH_UPDATESERVICE_USE_DBUS)
764     {
765         return std::nullopt;
766     }
767     std::string firmwareId;
768     if (!crow::utility::readUrlSegments(*url, "redfish", "v1", "UpdateService",
769                                         "FirmwareInventory",
770                                         std::ref(firmwareId)))
771     {
772         return std::nullopt;
773     }
774 
775     return std::make_optional(firmwareId);
776 }
777 
778 inline std::optional<MultiPartUpdateParameters>
779     extractMultipartUpdateParameters(
780         const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
781         MultipartParser parser)
782 {
783     MultiPartUpdateParameters multiRet;
784     for (FormPart& formpart : parser.mime_fields)
785     {
786         boost::beast::http::fields::const_iterator it =
787             formpart.fields.find("Content-Disposition");
788         if (it == formpart.fields.end())
789         {
790             BMCWEB_LOG_ERROR("Couldn't find Content-Disposition");
791             return std::nullopt;
792         }
793         BMCWEB_LOG_INFO("Parsing value {}", it->value());
794 
795         // The construction parameters of param_list must start with `;`
796         size_t index = it->value().find(';');
797         if (index == std::string::npos)
798         {
799             continue;
800         }
801 
802         for (const auto& param :
803              boost::beast::http::param_list{it->value().substr(index)})
804         {
805             if (param.first != "name" || param.second.empty())
806             {
807                 continue;
808             }
809 
810             if (param.second == "UpdateParameters")
811             {
812                 std::vector<std::string> tempTargets;
813                 nlohmann::json content =
814                     nlohmann::json::parse(formpart.content);
815                 nlohmann::json::object_t* obj =
816                     content.get_ptr<nlohmann::json::object_t*>();
817                 if (obj == nullptr)
818                 {
819                     messages::propertyValueTypeError(
820                         asyncResp->res, formpart.content, "UpdateParameters");
821                     return std::nullopt;
822                 }
823 
824                 if (!json_util::readJsonObject(
825                         *obj, asyncResp->res, "Targets", tempTargets,
826                         "@Redfish.OperationApplyTime", multiRet.applyTime))
827                 {
828                     return std::nullopt;
829                 }
830 
831                 for (size_t urlIndex = 0; urlIndex < tempTargets.size();
832                      urlIndex++)
833                 {
834                     const std::string& target = tempTargets[urlIndex];
835                     boost::system::result<boost::urls::url_view> url =
836                         boost::urls::parse_origin_form(target);
837                     auto res = processUrl(url);
838                     if (!res.has_value())
839                     {
840                         messages::propertyValueFormatError(
841                             asyncResp->res, target,
842                             std::format("Targets/{}", urlIndex));
843                         return std::nullopt;
844                     }
845                     multiRet.targets.emplace_back(res.value());
846                 }
847                 if (multiRet.targets.size() != 1)
848                 {
849                     messages::propertyValueFormatError(
850                         asyncResp->res, multiRet.targets, "Targets");
851                     return std::nullopt;
852                 }
853             }
854             else if (param.second == "UpdateFile")
855             {
856                 multiRet.uploadData = std::move(formpart.content);
857             }
858         }
859     }
860 
861     if (multiRet.uploadData.empty())
862     {
863         BMCWEB_LOG_ERROR("Upload data is NULL");
864         messages::propertyMissing(asyncResp->res, "UpdateFile");
865         return std::nullopt;
866     }
867     if (multiRet.targets.empty())
868     {
869         messages::propertyMissing(asyncResp->res, "Targets");
870         return std::nullopt;
871     }
872     return multiRet;
873 }
874 
875 inline void
876     handleStartUpdate(const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
877                       task::Payload payload, const std::string& objectPath,
878                       const boost::system::error_code& ec,
879                       const sdbusplus::message::object_path& retPath)
880 {
881     if (ec)
882     {
883         BMCWEB_LOG_ERROR("error_code = {}", ec);
884         BMCWEB_LOG_ERROR("error msg = {}", ec.message());
885         messages::internalError(asyncResp->res);
886         return;
887     }
888 
889     BMCWEB_LOG_INFO("Call to StartUpdate Success, retPath = {}", retPath.str);
890     createTask(asyncResp, std::move(payload), objectPath);
891 }
892 
893 inline void startUpdate(const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
894                         task::Payload payload,
895                         const MemoryFileDescriptor& memfd,
896                         const std::string& applyTime,
897                         const std::string& objectPath,
898                         const std::string& serviceName)
899 {
900     crow::connections::systemBus->async_method_call(
901         [asyncResp, payload = std::move(payload),
902          objectPath](const boost::system::error_code& ec1,
903                      const sdbusplus::message::object_path& retPath) mutable {
904         handleStartUpdate(asyncResp, std::move(payload), objectPath, ec1,
905                           retPath);
906     },
907         serviceName, objectPath, "xyz.openbmc_project.Software.Update",
908         "StartUpdate", sdbusplus::message::unix_fd(memfd.fd), applyTime);
909 }
910 
911 inline void getAssociatedUpdateInterface(
912     const std::shared_ptr<bmcweb::AsyncResp>& asyncResp, task::Payload payload,
913     const MemoryFileDescriptor& memfd, const std::string& applyTime,
914     const boost::system::error_code& ec,
915     const dbus::utility::MapperGetSubTreeResponse& subtree)
916 {
917     if (ec)
918     {
919         BMCWEB_LOG_ERROR("error_code = {}", ec);
920         BMCWEB_LOG_ERROR("error msg = {}", ec.message());
921         messages::internalError(asyncResp->res);
922         return;
923     }
924     BMCWEB_LOG_DEBUG("Found {} startUpdate subtree paths", subtree.size());
925 
926     if (subtree.size() > 1)
927     {
928         BMCWEB_LOG_ERROR("Found more than one startUpdate subtree paths");
929         messages::internalError(asyncResp->res);
930         return;
931     }
932 
933     auto objectPath = subtree[0].first;
934     auto serviceName = subtree[0].second[0].first;
935 
936     BMCWEB_LOG_DEBUG("Found objectPath {} serviceName {}", objectPath,
937                      serviceName);
938     startUpdate(asyncResp, std::move(payload), memfd, applyTime, objectPath,
939                 serviceName);
940 }
941 
942 inline void
943     getSwInfo(const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
944               task::Payload payload, MemoryFileDescriptor memfd,
945               const std::string& applyTime, const std::string& target,
946               const boost::system::error_code& ec,
947               const dbus::utility::MapperGetSubTreePathsResponse& subtree)
948 {
949     using SwInfoMap =
950         std::unordered_map<std::string, sdbusplus::message::object_path>;
951     SwInfoMap swInfoMap;
952 
953     if (ec)
954     {
955         BMCWEB_LOG_ERROR("error_code = {}", ec);
956         BMCWEB_LOG_ERROR("error msg = {}", ec.message());
957         messages::internalError(asyncResp->res);
958         return;
959     }
960     BMCWEB_LOG_DEBUG("Found {} software version paths", subtree.size());
961 
962     for (const auto& objectPath : subtree)
963     {
964         sdbusplus::message::object_path path(objectPath);
965         std::string swId = path.filename();
966         swInfoMap.emplace(swId, path);
967     }
968 
969     auto swEntry = swInfoMap.find(target);
970     if (swEntry == swInfoMap.end())
971     {
972         BMCWEB_LOG_WARNING("No valid DBus path for Target URI {}", target);
973         messages::propertyValueFormatError(asyncResp->res, target, "Targets");
974         return;
975     }
976 
977     BMCWEB_LOG_DEBUG("Found software version path {}", swEntry->second.str);
978 
979     sdbusplus::message::object_path swObjectPath = swEntry->second /
980                                                    "software_version";
981     constexpr std::array<std::string_view, 1> interfaces = {
982         "xyz.openbmc_project.Software.Update"};
983     dbus::utility::getAssociatedSubTree(
984         swObjectPath,
985         sdbusplus::message::object_path("/xyz/openbmc_project/software"), 0,
986         interfaces,
987         [asyncResp, payload = std::move(payload), memfd = std::move(memfd),
988          applyTime](
989             const boost::system::error_code& ec1,
990             const dbus::utility::MapperGetSubTreeResponse& subtree1) mutable {
991         getAssociatedUpdateInterface(asyncResp, std::move(payload), memfd,
992                                      applyTime, ec1, subtree1);
993     });
994 }
995 
996 inline void
997     processUpdateRequest(const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
998                          task::Payload&& payload, std::string_view body,
999                          const std::string& applyTime,
1000                          std::vector<std::string>& targets)
1001 {
1002     MemoryFileDescriptor memfd("update-image");
1003     if (memfd.fd == -1)
1004     {
1005         BMCWEB_LOG_ERROR("Failed to create image memfd");
1006         messages::internalError(asyncResp->res);
1007         return;
1008     }
1009     if (write(memfd.fd, body.data(), body.length()) !=
1010         static_cast<ssize_t>(body.length()))
1011     {
1012         BMCWEB_LOG_ERROR("Failed to write to image memfd");
1013         messages::internalError(asyncResp->res);
1014         return;
1015     }
1016     if (!memfd.rewind())
1017     {
1018         messages::internalError(asyncResp->res);
1019         return;
1020     }
1021 
1022     if (!targets.empty() && targets[0] == BMCWEB_REDFISH_MANAGER_URI_NAME)
1023     {
1024         startUpdate(asyncResp, std::move(payload), memfd, applyTime,
1025                     "/xyz/openbmc_project/software/bmc",
1026                     "xyz.openbmc_project.Software.Manager");
1027     }
1028     else
1029     {
1030         constexpr std::array<std::string_view, 1> interfaces = {
1031             "xyz.openbmc_project.Software.Version"};
1032         dbus::utility::getSubTreePaths(
1033             "/xyz/openbmc_project/software", 1, interfaces,
1034             [asyncResp, payload = std::move(payload), memfd = std::move(memfd),
1035              applyTime,
1036              targets](const boost::system::error_code& ec,
1037                       const dbus::utility::MapperGetSubTreePathsResponse&
1038                           subtree) mutable {
1039             getSwInfo(asyncResp, std::move(payload), std::move(memfd),
1040                       applyTime, targets[0], ec, subtree);
1041         });
1042     }
1043 }
1044 
1045 inline void
1046     updateMultipartContext(const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
1047                            const crow::Request& req, MultipartParser&& parser)
1048 {
1049     std::optional<MultiPartUpdateParameters> multipart =
1050         extractMultipartUpdateParameters(asyncResp, std::move(parser));
1051     if (!multipart)
1052     {
1053         return;
1054     }
1055     if (!multipart->applyTime)
1056     {
1057         multipart->applyTime = "OnReset";
1058     }
1059 
1060     if constexpr (BMCWEB_REDFISH_UPDATESERVICE_USE_DBUS)
1061     {
1062         std::string applyTimeNewVal;
1063         if (!convertApplyTime(asyncResp->res, *multipart->applyTime,
1064                               applyTimeNewVal))
1065         {
1066             return;
1067         }
1068         task::Payload payload(req);
1069 
1070         processUpdateRequest(asyncResp, std::move(payload),
1071                              multipart->uploadData, applyTimeNewVal,
1072                              multipart->targets);
1073     }
1074     else
1075     {
1076         setApplyTime(asyncResp, *multipart->applyTime);
1077 
1078         // Setup callback for when new software detected
1079         monitorForSoftwareAvailable(asyncResp, req,
1080                                     "/redfish/v1/UpdateService");
1081 
1082         uploadImageFile(asyncResp->res, multipart->uploadData);
1083     }
1084 }
1085 
1086 inline void doHTTPUpdate(const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
1087                          const crow::Request& req)
1088 {
1089     if constexpr (BMCWEB_REDFISH_UPDATESERVICE_USE_DBUS)
1090     {
1091         task::Payload payload(req);
1092         // HTTP push only supports BMC updates (with ApplyTime as immediate) for
1093         // backwards compatibility. Specific component updates will be handled
1094         // through Multipart form HTTP push.
1095         std::vector<std::string> targets;
1096         targets.emplace_back(BMCWEB_REDFISH_MANAGER_URI_NAME);
1097 
1098         processUpdateRequest(
1099             asyncResp, std::move(payload), req.body(),
1100             "xyz.openbmc_project.Software.ApplyTime.RequestedApplyTimes.Immediate",
1101             targets);
1102     }
1103     else
1104     {
1105         // Setup callback for when new software detected
1106         monitorForSoftwareAvailable(asyncResp, req,
1107                                     "/redfish/v1/UpdateService");
1108 
1109         uploadImageFile(asyncResp->res, req.body());
1110     }
1111 }
1112 
1113 inline void
1114     handleUpdateServicePost(App& app, const crow::Request& req,
1115                             const std::shared_ptr<bmcweb::AsyncResp>& asyncResp)
1116 {
1117     if (!redfish::setUpRedfishRoute(app, req, asyncResp))
1118     {
1119         return;
1120     }
1121     std::string_view contentType = req.getHeaderValue("Content-Type");
1122 
1123     BMCWEB_LOG_DEBUG("doPost: contentType={}", contentType);
1124 
1125     // Make sure that content type is application/octet-stream or
1126     // multipart/form-data
1127     if (bmcweb::asciiIEquals(contentType, "application/octet-stream"))
1128     {
1129         doHTTPUpdate(asyncResp, req);
1130     }
1131     else if (contentType.starts_with("multipart/form-data"))
1132     {
1133         MultipartParser parser;
1134 
1135         ParserError ec = parser.parse(req);
1136         if (ec != ParserError::PARSER_SUCCESS)
1137         {
1138             // handle error
1139             BMCWEB_LOG_ERROR("MIME parse failed, ec : {}",
1140                              static_cast<int>(ec));
1141             messages::internalError(asyncResp->res);
1142             return;
1143         }
1144 
1145         updateMultipartContext(asyncResp, req, std::move(parser));
1146     }
1147     else
1148     {
1149         BMCWEB_LOG_DEBUG("Bad content type specified:{}", contentType);
1150         asyncResp->res.result(boost::beast::http::status::bad_request);
1151     }
1152 }
1153 
1154 inline void
1155     handleUpdateServiceGet(App& app, const crow::Request& req,
1156                            const std::shared_ptr<bmcweb::AsyncResp>& asyncResp)
1157 {
1158     if (!redfish::setUpRedfishRoute(app, req, asyncResp))
1159     {
1160         return;
1161     }
1162     asyncResp->res.jsonValue["@odata.type"] =
1163         "#UpdateService.v1_11_1.UpdateService";
1164     asyncResp->res.jsonValue["@odata.id"] = "/redfish/v1/UpdateService";
1165     asyncResp->res.jsonValue["Id"] = "UpdateService";
1166     asyncResp->res.jsonValue["Description"] = "Service for Software Update";
1167     asyncResp->res.jsonValue["Name"] = "Update Service";
1168 
1169     asyncResp->res.jsonValue["HttpPushUri"] =
1170         "/redfish/v1/UpdateService/update";
1171     asyncResp->res.jsonValue["MultipartHttpPushUri"] =
1172         "/redfish/v1/UpdateService/update";
1173 
1174     // UpdateService cannot be disabled
1175     asyncResp->res.jsonValue["ServiceEnabled"] = true;
1176     asyncResp->res.jsonValue["FirmwareInventory"]["@odata.id"] =
1177         "/redfish/v1/UpdateService/FirmwareInventory";
1178     // Get the MaxImageSizeBytes
1179     asyncResp->res.jsonValue["MaxImageSizeBytes"] = BMCWEB_HTTP_BODY_LIMIT *
1180                                                     1024 * 1024;
1181 
1182     // Update Actions object.
1183     nlohmann::json& updateSvcSimpleUpdate =
1184         asyncResp->res.jsonValue["Actions"]["#UpdateService.SimpleUpdate"];
1185     updateSvcSimpleUpdate["target"] =
1186         "/redfish/v1/UpdateService/Actions/UpdateService.SimpleUpdate";
1187 
1188     nlohmann::json::array_t allowed;
1189     allowed.emplace_back(update_service::TransferProtocolType::HTTPS);
1190 
1191     if constexpr (BMCWEB_INSECURE_PUSH_STYLE_NOTIFICATION)
1192     {
1193         allowed.emplace_back(update_service::TransferProtocolType::TFTP);
1194     }
1195 
1196     updateSvcSimpleUpdate["TransferProtocol@Redfish.AllowableValues"] =
1197         std::move(allowed);
1198 
1199     asyncResp->res.jsonValue["HttpPushUriOptions"]["HttpPushUriApplyTime"]
1200                             ["ApplyTime"] = "Immediate";
1201 }
1202 
1203 inline void handleUpdateServiceFirmwareInventoryCollectionGet(
1204     App& app, const crow::Request& req,
1205     const std::shared_ptr<bmcweb::AsyncResp>& asyncResp)
1206 {
1207     if (!redfish::setUpRedfishRoute(app, req, asyncResp))
1208     {
1209         return;
1210     }
1211     asyncResp->res.jsonValue["@odata.type"] =
1212         "#SoftwareInventoryCollection.SoftwareInventoryCollection";
1213     asyncResp->res.jsonValue["@odata.id"] =
1214         "/redfish/v1/UpdateService/FirmwareInventory";
1215     asyncResp->res.jsonValue["Name"] = "Software Inventory Collection";
1216     const std::array<const std::string_view, 1> iface = {
1217         "xyz.openbmc_project.Software.Version"};
1218 
1219     redfish::collection_util::getCollectionMembers(
1220         asyncResp,
1221         boost::urls::url("/redfish/v1/UpdateService/FirmwareInventory"), iface,
1222         "/xyz/openbmc_project/software");
1223 }
1224 
1225 /* Fill related item links (i.e. bmc, bios) in for inventory */
1226 inline void getRelatedItems(const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
1227                             const std::string& purpose)
1228 {
1229     if (purpose == sw_util::bmcPurpose)
1230     {
1231         nlohmann::json& relatedItem = asyncResp->res.jsonValue["RelatedItem"];
1232         nlohmann::json::object_t item;
1233         item["@odata.id"] = boost::urls::format(
1234             "/redfish/v1/Managers/{}", BMCWEB_REDFISH_MANAGER_URI_NAME);
1235         relatedItem.emplace_back(std::move(item));
1236         asyncResp->res.jsonValue["RelatedItem@odata.count"] =
1237             relatedItem.size();
1238     }
1239     else if (purpose == sw_util::biosPurpose)
1240     {
1241         nlohmann::json& relatedItem = asyncResp->res.jsonValue["RelatedItem"];
1242         nlohmann::json::object_t item;
1243         item["@odata.id"] = std::format("/redfish/v1/Systems/{}/Bios",
1244                                         BMCWEB_REDFISH_SYSTEM_URI_NAME);
1245         relatedItem.emplace_back(std::move(item));
1246         asyncResp->res.jsonValue["RelatedItem@odata.count"] =
1247             relatedItem.size();
1248     }
1249     else
1250     {
1251         BMCWEB_LOG_DEBUG("Unknown software purpose {}", purpose);
1252     }
1253 }
1254 
1255 inline void
1256     getSoftwareVersion(const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
1257                        const std::string& service, const std::string& path,
1258                        const std::string& swId)
1259 {
1260     sdbusplus::asio::getAllProperties(
1261         *crow::connections::systemBus, service, path,
1262         "xyz.openbmc_project.Software.Version",
1263         [asyncResp,
1264          swId](const boost::system::error_code& ec,
1265                const dbus::utility::DBusPropertiesMap& propertiesList) {
1266         if (ec)
1267         {
1268             messages::internalError(asyncResp->res);
1269             return;
1270         }
1271 
1272         const std::string* swInvPurpose = nullptr;
1273         const std::string* version = nullptr;
1274 
1275         const bool success = sdbusplus::unpackPropertiesNoThrow(
1276             dbus_utils::UnpackErrorPrinter(), propertiesList, "Purpose",
1277             swInvPurpose, "Version", version);
1278 
1279         if (!success)
1280         {
1281             messages::internalError(asyncResp->res);
1282             return;
1283         }
1284 
1285         if (swInvPurpose == nullptr)
1286         {
1287             BMCWEB_LOG_DEBUG("Can't find property \"Purpose\"!");
1288             messages::internalError(asyncResp->res);
1289             return;
1290         }
1291 
1292         BMCWEB_LOG_DEBUG("swInvPurpose = {}", *swInvPurpose);
1293 
1294         if (version == nullptr)
1295         {
1296             BMCWEB_LOG_DEBUG("Can't find property \"Version\"!");
1297 
1298             messages::internalError(asyncResp->res);
1299 
1300             return;
1301         }
1302         asyncResp->res.jsonValue["Version"] = *version;
1303         asyncResp->res.jsonValue["Id"] = swId;
1304 
1305         // swInvPurpose is of format:
1306         // xyz.openbmc_project.Software.Version.VersionPurpose.ABC
1307         // Translate this to "ABC image"
1308         size_t endDesc = swInvPurpose->rfind('.');
1309         if (endDesc == std::string::npos)
1310         {
1311             messages::internalError(asyncResp->res);
1312             return;
1313         }
1314         endDesc++;
1315         if (endDesc >= swInvPurpose->size())
1316         {
1317             messages::internalError(asyncResp->res);
1318             return;
1319         }
1320 
1321         std::string formatDesc = swInvPurpose->substr(endDesc);
1322         asyncResp->res.jsonValue["Description"] = formatDesc + " image";
1323         getRelatedItems(asyncResp, *swInvPurpose);
1324     });
1325 }
1326 
1327 inline void handleUpdateServiceFirmwareInventoryGet(
1328     App& app, const crow::Request& req,
1329     const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
1330     const std::string& param)
1331 {
1332     if (!redfish::setUpRedfishRoute(app, req, asyncResp))
1333     {
1334         return;
1335     }
1336     std::shared_ptr<std::string> swId = std::make_shared<std::string>(param);
1337 
1338     asyncResp->res.jsonValue["@odata.id"] = boost::urls::format(
1339         "/redfish/v1/UpdateService/FirmwareInventory/{}", *swId);
1340 
1341     constexpr std::array<std::string_view, 1> interfaces = {
1342         "xyz.openbmc_project.Software.Version"};
1343     dbus::utility::getSubTree(
1344         "/", 0, interfaces,
1345         [asyncResp,
1346          swId](const boost::system::error_code& ec,
1347                const dbus::utility::MapperGetSubTreeResponse& subtree) {
1348         BMCWEB_LOG_DEBUG("doGet callback...");
1349         if (ec)
1350         {
1351             messages::internalError(asyncResp->res);
1352             return;
1353         }
1354 
1355         // Ensure we find our input swId, otherwise return an error
1356         bool found = false;
1357         for (const std::pair<
1358                  std::string,
1359                  std::vector<std::pair<std::string, std::vector<std::string>>>>&
1360                  obj : subtree)
1361         {
1362             if (!obj.first.ends_with(*swId))
1363             {
1364                 continue;
1365             }
1366 
1367             if (obj.second.empty())
1368             {
1369                 continue;
1370             }
1371 
1372             found = true;
1373             sw_util::getSwStatus(asyncResp, swId, obj.second[0].first);
1374             getSoftwareVersion(asyncResp, obj.second[0].first, obj.first,
1375                                *swId);
1376         }
1377         if (!found)
1378         {
1379             BMCWEB_LOG_WARNING("Input swID {} not found!", *swId);
1380             messages::resourceMissingAtURI(
1381                 asyncResp->res,
1382                 boost::urls::format(
1383                     "/redfish/v1/UpdateService/FirmwareInventory/{}", *swId));
1384             return;
1385         }
1386         asyncResp->res.jsonValue["@odata.type"] =
1387             "#SoftwareInventory.v1_1_0.SoftwareInventory";
1388         asyncResp->res.jsonValue["Name"] = "Software Inventory";
1389         asyncResp->res.jsonValue["Status"]["HealthRollup"] = "OK";
1390 
1391         asyncResp->res.jsonValue["Updateable"] = false;
1392         sw_util::getSwUpdatableStatus(asyncResp, swId);
1393     });
1394 }
1395 
1396 inline void requestRoutesUpdateService(App& app)
1397 {
1398     BMCWEB_ROUTE(
1399         app, "/redfish/v1/UpdateService/Actions/UpdateService.SimpleUpdate/")
1400         .privileges(redfish::privileges::postUpdateService)
1401         .methods(boost::beast::http::verb::post)(std::bind_front(
1402             handleUpdateServiceSimpleUpdateAction, std::ref(app)));
1403 
1404     BMCWEB_ROUTE(app, "/redfish/v1/UpdateService/FirmwareInventory/<str>/")
1405         .privileges(redfish::privileges::getSoftwareInventory)
1406         .methods(boost::beast::http::verb::get)(std::bind_front(
1407             handleUpdateServiceFirmwareInventoryGet, std::ref(app)));
1408 
1409     BMCWEB_ROUTE(app, "/redfish/v1/UpdateService/")
1410         .privileges(redfish::privileges::getUpdateService)
1411         .methods(boost::beast::http::verb::get)(
1412             std::bind_front(handleUpdateServiceGet, std::ref(app)));
1413 
1414     BMCWEB_ROUTE(app, "/redfish/v1/UpdateService/update/")
1415         .privileges(redfish::privileges::postUpdateService)
1416         .methods(boost::beast::http::verb::post)(
1417             std::bind_front(handleUpdateServicePost, std::ref(app)));
1418 
1419     BMCWEB_ROUTE(app, "/redfish/v1/UpdateService/FirmwareInventory/")
1420         .privileges(redfish::privileges::getSoftwareInventoryCollection)
1421         .methods(boost::beast::http::verb::get)(std::bind_front(
1422             handleUpdateServiceFirmwareInventoryCollectionGet, std::ref(app)));
1423 }
1424 
1425 } // namespace redfish
1426