xref: /openbmc/bmcweb/features/redfish/lib/update_service.hpp (revision 7cb59f655a3e68b23ec720d286c71805c5c9a895)
1729dae72SJennifer Lee /*
2729dae72SJennifer Lee // Copyright (c) 2018 Intel Corporation
3729dae72SJennifer Lee //
4729dae72SJennifer Lee // Licensed under the Apache License, Version 2.0 (the "License");
5729dae72SJennifer Lee // you may not use this file except in compliance with the License.
6729dae72SJennifer Lee // You may obtain a copy of the License at
7729dae72SJennifer Lee //
8729dae72SJennifer Lee //      http://www.apache.org/licenses/LICENSE-2.0
9729dae72SJennifer Lee //
10729dae72SJennifer Lee // Unless required by applicable law or agreed to in writing, software
11729dae72SJennifer Lee // distributed under the License is distributed on an "AS IS" BASIS,
12729dae72SJennifer Lee // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13729dae72SJennifer Lee // See the License for the specific language governing permissions and
14729dae72SJennifer Lee // limitations under the License.
15729dae72SJennifer Lee */
16729dae72SJennifer Lee #pragma once
17729dae72SJennifer Lee 
18d61e5194STejas Patil #include "bmcweb_config.h"
19d61e5194STejas Patil 
203ccb3adbSEd Tanous #include "app.hpp"
213ccb3adbSEd Tanous #include "dbus_utility.hpp"
220ed80c8cSGeorge Liu #include "multipart_parser.hpp"
232c6ffdb0SEd Tanous #include "ossl_random.hpp"
243ccb3adbSEd Tanous #include "query.hpp"
253ccb3adbSEd Tanous #include "registries/privilege_registry.hpp"
26a8e884fcSEd Tanous #include "task.hpp"
2708d81adaSJohn Edward Broadbent #include "utils/collection.hpp"
283ccb3adbSEd Tanous #include "utils/dbus_utils.hpp"
293ccb3adbSEd Tanous #include "utils/sw_utils.hpp"
303ccb3adbSEd Tanous 
31e99073f5SGeorge Liu #include <boost/system/error_code.hpp>
32ef4c65b7SEd Tanous #include <boost/url/format.hpp>
331e1e598dSJonathan Doman #include <sdbusplus/asio/property.hpp>
343ccb3adbSEd Tanous #include <sdbusplus/bus/match.hpp>
35d1bde9e5SKrzysztof Grobelny #include <sdbusplus/unpack_properties.hpp>
361214b7e7SGunnar Mills 
372b73119cSGeorge Liu #include <array>
380ed80c8cSGeorge Liu #include <filesystem>
39*7cb59f65SEd Tanous #include <optional>
40*7cb59f65SEd Tanous #include <string>
412b73119cSGeorge Liu #include <string_view>
422b73119cSGeorge Liu 
431abe55efSEd Tanous namespace redfish
441abe55efSEd Tanous {
4527826b5fSEd Tanous 
460e7de46fSAndrew Geissler // Match signals added on software path
47cf9e417dSEd Tanous // NOLINTNEXTLINE(cppcoreguidelines-avoid-non-const-global-variables)
4859d494eeSPatrick Williams static std::unique_ptr<sdbusplus::bus::match_t> fwUpdateMatcher;
49cf9e417dSEd Tanous // NOLINTNEXTLINE(cppcoreguidelines-avoid-non-const-global-variables)
5059d494eeSPatrick Williams static std::unique_ptr<sdbusplus::bus::match_t> fwUpdateErrorMatcher;
510e7de46fSAndrew Geissler // Only allow one update at a time
52cf9e417dSEd Tanous // NOLINTNEXTLINE(cppcoreguidelines-avoid-non-const-global-variables)
530e7de46fSAndrew Geissler static bool fwUpdateInProgress = false;
5486adcd6dSAndrew Geissler // Timer for software available
55cf9e417dSEd Tanous // NOLINTNEXTLINE(cppcoreguidelines-avoid-non-const-global-variables)
56271584abSEd Tanous static std::unique_ptr<boost::asio::steady_timer> fwAvailableTimer;
5786adcd6dSAndrew Geissler 
587e860f15SJohn Edward Broadbent inline static void cleanUp()
5986adcd6dSAndrew Geissler {
6086adcd6dSAndrew Geissler     fwUpdateInProgress = false;
6186adcd6dSAndrew Geissler     fwUpdateMatcher = nullptr;
624cde5d90SJames Feist     fwUpdateErrorMatcher = nullptr;
6386adcd6dSAndrew Geissler }
647e860f15SJohn Edward Broadbent inline static void activateImage(const std::string& objPath,
6586adcd6dSAndrew Geissler                                  const std::string& service)
6686adcd6dSAndrew Geissler {
6762598e31SEd Tanous     BMCWEB_LOG_DEBUG("Activate image for {} {}", objPath, service);
689ae226faSGeorge Liu     sdbusplus::asio::setProperty(
699ae226faSGeorge Liu         *crow::connections::systemBus, service, objPath,
709ae226faSGeorge Liu         "xyz.openbmc_project.Software.Activation", "RequestedActivation",
719ae226faSGeorge Liu         "xyz.openbmc_project.Software.Activation.RequestedActivations.Active",
728b24275dSEd Tanous         [](const boost::system::error_code& ec) {
738b24275dSEd Tanous         if (ec)
7486adcd6dSAndrew Geissler         {
7562598e31SEd Tanous             BMCWEB_LOG_DEBUG("error_code = {}", ec);
7662598e31SEd Tanous             BMCWEB_LOG_DEBUG("error msg = {}", ec.message());
7786adcd6dSAndrew Geissler         }
789ae226faSGeorge Liu     });
7986adcd6dSAndrew Geissler }
800554c984SAndrew Geissler 
810554c984SAndrew Geissler // Note that asyncResp can be either a valid pointer or nullptr. If nullptr
820554c984SAndrew Geissler // then no asyncResp updates will occur
838d1b46d7Szhanghch05 static void
848d1b46d7Szhanghch05     softwareInterfaceAdded(const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
8559d494eeSPatrick Williams                            sdbusplus::message_t& m, task::Payload&& payload)
8686adcd6dSAndrew Geissler {
8780f79a40SMichael Shen     dbus::utility::DBusInterfacesMap interfacesProperties;
8886adcd6dSAndrew Geissler 
8986adcd6dSAndrew Geissler     sdbusplus::message::object_path objPath;
9086adcd6dSAndrew Geissler 
9186adcd6dSAndrew Geissler     m.read(objPath, interfacesProperties);
9286adcd6dSAndrew Geissler 
9362598e31SEd Tanous     BMCWEB_LOG_DEBUG("obj path = {}", objPath.str);
94e3eb3d63SEd Tanous     for (const auto& interface : interfacesProperties)
9586adcd6dSAndrew Geissler     {
9662598e31SEd Tanous         BMCWEB_LOG_DEBUG("interface = {}", interface.first);
9786adcd6dSAndrew Geissler 
9886adcd6dSAndrew Geissler         if (interface.first == "xyz.openbmc_project.Software.Activation")
9986adcd6dSAndrew Geissler         {
10086adcd6dSAndrew Geissler             // Retrieve service and activate
1012b73119cSGeorge Liu             constexpr std::array<std::string_view, 1> interfaces = {
1022b73119cSGeorge Liu                 "xyz.openbmc_project.Software.Activation"};
1032b73119cSGeorge Liu             dbus::utility::getDbusObject(
1042b73119cSGeorge Liu                 objPath.str, interfaces,
105a3e65892SEd Tanous                 [objPath, asyncResp, payload(std::move(payload))](
1068b24275dSEd Tanous                     const boost::system::error_code& ec,
107a3e65892SEd Tanous                     const std::vector<
108a3e65892SEd Tanous                         std::pair<std::string, std::vector<std::string>>>&
109a3e65892SEd Tanous                         objInfo) mutable {
1108b24275dSEd Tanous                 if (ec)
11186adcd6dSAndrew Geissler                 {
11262598e31SEd Tanous                     BMCWEB_LOG_DEBUG("error_code = {}", ec);
11362598e31SEd Tanous                     BMCWEB_LOG_DEBUG("error msg = {}", ec.message());
1140554c984SAndrew Geissler                     if (asyncResp)
1150554c984SAndrew Geissler                     {
11686adcd6dSAndrew Geissler                         messages::internalError(asyncResp->res);
1170554c984SAndrew Geissler                     }
11886adcd6dSAndrew Geissler                     cleanUp();
11986adcd6dSAndrew Geissler                     return;
12086adcd6dSAndrew Geissler                 }
12186adcd6dSAndrew Geissler                 // Ensure we only got one service back
12286adcd6dSAndrew Geissler                 if (objInfo.size() != 1)
12386adcd6dSAndrew Geissler                 {
12462598e31SEd Tanous                     BMCWEB_LOG_ERROR("Invalid Object Size {}", objInfo.size());
1250554c984SAndrew Geissler                     if (asyncResp)
1260554c984SAndrew Geissler                     {
12786adcd6dSAndrew Geissler                         messages::internalError(asyncResp->res);
1280554c984SAndrew Geissler                     }
12986adcd6dSAndrew Geissler                     cleanUp();
13086adcd6dSAndrew Geissler                     return;
13186adcd6dSAndrew Geissler                 }
13286adcd6dSAndrew Geissler                 // cancel timer only when
13386adcd6dSAndrew Geissler                 // xyz.openbmc_project.Software.Activation interface
13486adcd6dSAndrew Geissler                 // is added
13586adcd6dSAndrew Geissler                 fwAvailableTimer = nullptr;
13686adcd6dSAndrew Geissler 
13786adcd6dSAndrew Geissler                 activateImage(objPath.str, objInfo[0].first);
1380554c984SAndrew Geissler                 if (asyncResp)
1390554c984SAndrew Geissler                 {
14032898ceaSJames Feist                     std::shared_ptr<task::TaskData> task =
14132898ceaSJames Feist                         task::TaskData::createTask(
1428b24275dSEd Tanous                             [](const boost::system::error_code& ec2,
14359d494eeSPatrick Williams                                sdbusplus::message_t& msg,
1441214b7e7SGunnar Mills                                const std::shared_ptr<task::TaskData>&
1451214b7e7SGunnar Mills                                    taskData) {
1468b24275dSEd Tanous                         if (ec2)
14732898ceaSJames Feist                         {
14832898ceaSJames Feist                             return task::completed;
14932898ceaSJames Feist                         }
15032898ceaSJames Feist 
15132898ceaSJames Feist                         std::string iface;
152b9d36b47SEd Tanous                         dbus::utility::DBusPropertiesMap values;
153fd9ab9e1SJames Feist 
154002d39b4SEd Tanous                         std::string index = std::to_string(taskData->index);
15532898ceaSJames Feist                         msg.read(iface, values);
156fd9ab9e1SJames Feist 
157002d39b4SEd Tanous                         if (iface == "xyz.openbmc_project.Software.Activation")
158fd9ab9e1SJames Feist                         {
1590fb5b505SGayathri Leburu                             const std::string* state = nullptr;
160b9d36b47SEd Tanous                             for (const auto& property : values)
16132898ceaSJames Feist                             {
162b9d36b47SEd Tanous                                 if (property.first == "Activation")
163b9d36b47SEd Tanous                                 {
1640fb5b505SGayathri Leburu                                     state = std::get_if<std::string>(
165b9d36b47SEd Tanous                                         &property.second);
1660fb5b505SGayathri Leburu                                     if (state == nullptr)
167b9d36b47SEd Tanous                                     {
168002d39b4SEd Tanous                                         taskData->messages.emplace_back(
169002d39b4SEd Tanous                                             messages::internalError());
170b9d36b47SEd Tanous                                         return task::completed;
171b9d36b47SEd Tanous                                     }
172b9d36b47SEd Tanous                                 }
173b9d36b47SEd Tanous                             }
17432898ceaSJames Feist 
17532898ceaSJames Feist                             if (state == nullptr)
17632898ceaSJames Feist                             {
177b9d36b47SEd Tanous                                 return !task::completed;
17832898ceaSJames Feist                             }
17932898ceaSJames Feist 
18011ba3979SEd Tanous                             if (state->ends_with("Invalid") ||
18111ba3979SEd Tanous                                 state->ends_with("Failed"))
18232898ceaSJames Feist                             {
18332898ceaSJames Feist                                 taskData->state = "Exception";
18432898ceaSJames Feist                                 taskData->status = "Warning";
18532898ceaSJames Feist                                 taskData->messages.emplace_back(
186e5d5006bSJames Feist                                     messages::taskAborted(index));
18732898ceaSJames Feist                                 return task::completed;
18832898ceaSJames Feist                             }
18932898ceaSJames Feist 
19011ba3979SEd Tanous                             if (state->ends_with("Staged"))
19132898ceaSJames Feist                             {
192fd9ab9e1SJames Feist                                 taskData->state = "Stopping";
193fd9ab9e1SJames Feist                                 taskData->messages.emplace_back(
194fd9ab9e1SJames Feist                                     messages::taskPaused(index));
195fd9ab9e1SJames Feist 
196fd9ab9e1SJames Feist                                 // its staged, set a long timer to
197fd9ab9e1SJames Feist                                 // allow them time to complete the
198fd9ab9e1SJames Feist                                 // update (probably cycle the
199fd9ab9e1SJames Feist                                 // system) if this expires then
2008ece0e45SEd Tanous                                 // task will be canceled
201002d39b4SEd Tanous                                 taskData->extendTimer(std::chrono::hours(5));
20232898ceaSJames Feist                                 return !task::completed;
20332898ceaSJames Feist                             }
20432898ceaSJames Feist 
20511ba3979SEd Tanous                             if (state->ends_with("Active"))
20632898ceaSJames Feist                             {
20732898ceaSJames Feist                                 taskData->messages.emplace_back(
208002d39b4SEd Tanous                                     messages::taskCompletedOK(index));
20932898ceaSJames Feist                                 taskData->state = "Completed";
21032898ceaSJames Feist                                 return task::completed;
21132898ceaSJames Feist                             }
212fd9ab9e1SJames Feist                         }
2130fda0f12SGeorge Liu                         else if (
2140fda0f12SGeorge Liu                             iface ==
2150fda0f12SGeorge Liu                             "xyz.openbmc_project.Software.ActivationProgress")
216fd9ab9e1SJames Feist                         {
217b9d36b47SEd Tanous                             const uint8_t* progress = nullptr;
218b9d36b47SEd Tanous                             for (const auto& property : values)
219fd9ab9e1SJames Feist                             {
220b9d36b47SEd Tanous                                 if (property.first == "Progress")
221b9d36b47SEd Tanous                                 {
2220fb5b505SGayathri Leburu                                     progress =
2230fb5b505SGayathri Leburu                                         std::get_if<uint8_t>(&property.second);
2240fb5b505SGayathri Leburu                                     if (progress == nullptr)
225b9d36b47SEd Tanous                                     {
226002d39b4SEd Tanous                                         taskData->messages.emplace_back(
227002d39b4SEd Tanous                                             messages::internalError());
228b9d36b47SEd Tanous                                         return task::completed;
229fd9ab9e1SJames Feist                                     }
230b9d36b47SEd Tanous                                 }
231b9d36b47SEd Tanous                             }
232fd9ab9e1SJames Feist 
233fd9ab9e1SJames Feist                             if (progress == nullptr)
234fd9ab9e1SJames Feist                             {
235b9d36b47SEd Tanous                                 return !task::completed;
236fd9ab9e1SJames Feist                             }
2370fb5b505SGayathri Leburu                             taskData->percentComplete = *progress;
238fd9ab9e1SJames Feist                             taskData->messages.emplace_back(
2390fb5b505SGayathri Leburu                                 messages::taskProgressChanged(index,
2400fb5b505SGayathri Leburu                                                               *progress));
241fd9ab9e1SJames Feist 
242fd9ab9e1SJames Feist                             // if we're getting status updates it's
243fd9ab9e1SJames Feist                             // still alive, update timer
244002d39b4SEd Tanous                             taskData->extendTimer(std::chrono::minutes(5));
245fd9ab9e1SJames Feist                         }
24632898ceaSJames Feist 
24732898ceaSJames Feist                         // as firmware update often results in a
24832898ceaSJames Feist                         // reboot, the task  may never "complete"
24932898ceaSJames Feist                         // unless it is an error
25032898ceaSJames Feist 
25132898ceaSJames Feist                         return !task::completed;
25232898ceaSJames Feist                     },
2530fda0f12SGeorge Liu                             "type='signal',interface='org.freedesktop.DBus.Properties',"
254fd9ab9e1SJames Feist                             "member='PropertiesChanged',path='" +
25532898ceaSJames Feist                                 objPath.str + "'");
25632898ceaSJames Feist                     task->startTimer(std::chrono::minutes(5));
25732898ceaSJames Feist                     task->populateResp(asyncResp->res);
258a3e65892SEd Tanous                     task->payload.emplace(std::move(payload));
2590554c984SAndrew Geissler                 }
26086adcd6dSAndrew Geissler                 fwUpdateInProgress = false;
2612b73119cSGeorge Liu             });
26262bafc01SPatrick Williams 
26362bafc01SPatrick Williams             break;
26486adcd6dSAndrew Geissler         }
26586adcd6dSAndrew Geissler     }
26686adcd6dSAndrew Geissler }
26786adcd6dSAndrew Geissler 
2688549b951SMyung Bae inline void afterAvailbleTimerAsyncWait(
2698549b951SMyung Bae     const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
2708549b951SMyung Bae     const boost::system::error_code& ec)
2718549b951SMyung Bae {
2728549b951SMyung Bae     cleanUp();
2738549b951SMyung Bae     if (ec == boost::asio::error::operation_aborted)
2748549b951SMyung Bae     {
2758549b951SMyung Bae         // expected, we were canceled before the timer completed.
2768549b951SMyung Bae         return;
2778549b951SMyung Bae     }
2788549b951SMyung Bae     BMCWEB_LOG_ERROR("Timed out waiting for firmware object being created");
2798549b951SMyung Bae     BMCWEB_LOG_ERROR("FW image may has already been uploaded to server");
2808549b951SMyung Bae     if (ec)
2818549b951SMyung Bae     {
2828549b951SMyung Bae         BMCWEB_LOG_ERROR("Async_wait failed{}", ec);
2838549b951SMyung Bae         return;
2848549b951SMyung Bae     }
2858549b951SMyung Bae     if (asyncResp)
2868549b951SMyung Bae     {
2878549b951SMyung Bae         redfish::messages::internalError(asyncResp->res);
2888549b951SMyung Bae     }
2898549b951SMyung Bae }
2908549b951SMyung Bae 
2918549b951SMyung Bae inline void
2928549b951SMyung Bae     handleUpdateErrorType(const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
2938549b951SMyung Bae                           const std::string& url, const std::string& type)
2948549b951SMyung Bae {
2958549b951SMyung Bae     if (type == "xyz.openbmc_project.Software.Image.Error.UnTarFailure")
2968549b951SMyung Bae     {
2978549b951SMyung Bae         redfish::messages::invalidUpload(asyncResp->res, url,
2988549b951SMyung Bae                                          "Invalid archive");
2998549b951SMyung Bae     }
3008549b951SMyung Bae     else if (type ==
3018549b951SMyung Bae              "xyz.openbmc_project.Software.Image.Error.ManifestFileFailure")
3028549b951SMyung Bae     {
3038549b951SMyung Bae         redfish::messages::invalidUpload(asyncResp->res, url,
3048549b951SMyung Bae                                          "Invalid manifest");
3058549b951SMyung Bae     }
3068549b951SMyung Bae     else if (type == "xyz.openbmc_project.Software.Image.Error.ImageFailure")
3078549b951SMyung Bae     {
3088549b951SMyung Bae         redfish::messages::invalidUpload(asyncResp->res, url,
3098549b951SMyung Bae                                          "Invalid image format");
3108549b951SMyung Bae     }
3118549b951SMyung Bae     else if (type == "xyz.openbmc_project.Software.Version.Error.AlreadyExists")
3128549b951SMyung Bae     {
3138549b951SMyung Bae         redfish::messages::invalidUpload(asyncResp->res, url,
3148549b951SMyung Bae                                          "Image version already exists");
3158549b951SMyung Bae 
3168549b951SMyung Bae         redfish::messages::resourceAlreadyExists(
3178549b951SMyung Bae             asyncResp->res, "UpdateService", "Version", "uploaded version");
3188549b951SMyung Bae     }
3198549b951SMyung Bae     else if (type == "xyz.openbmc_project.Software.Image.Error.BusyFailure")
3208549b951SMyung Bae     {
3218549b951SMyung Bae         redfish::messages::resourceExhaustion(asyncResp->res, url);
3228549b951SMyung Bae     }
3234034a652SMyung Bae     else if (type == "xyz.openbmc_project.Software.Version.Error.Incompatible")
3248549b951SMyung Bae     {
3254034a652SMyung Bae         redfish::messages::invalidUpload(asyncResp->res, url,
3264034a652SMyung Bae                                          "Incompatible image version");
3274034a652SMyung Bae     }
3284034a652SMyung Bae     else if (type ==
3294034a652SMyung Bae              "xyz.openbmc_project.Software.Version.Error.ExpiredAccessKey")
3304034a652SMyung Bae     {
3314034a652SMyung Bae         redfish::messages::invalidUpload(asyncResp->res, url,
3324034a652SMyung Bae                                          "Update Access Key Expired");
3334034a652SMyung Bae     }
3344034a652SMyung Bae     else if (type ==
3354034a652SMyung Bae              "xyz.openbmc_project.Software.Version.Error.InvalidSignature")
3364034a652SMyung Bae     {
3374034a652SMyung Bae         redfish::messages::invalidUpload(asyncResp->res, url,
3384034a652SMyung Bae                                          "Invalid image signature");
3394034a652SMyung Bae     }
3404034a652SMyung Bae     else if (type ==
3414034a652SMyung Bae                  "xyz.openbmc_project.Software.Image.Error.InternalFailure" ||
3424034a652SMyung Bae              type == "xyz.openbmc_project.Software.Version.Error.HostFile")
3434034a652SMyung Bae     {
3444034a652SMyung Bae         BMCWEB_LOG_ERROR("Software Image Error type={}", type);
3458549b951SMyung Bae         redfish::messages::internalError(asyncResp->res);
3468549b951SMyung Bae     }
3474034a652SMyung Bae     else
3484034a652SMyung Bae     {
3494034a652SMyung Bae         // Unrelated error types. Ignored
3504034a652SMyung Bae         BMCWEB_LOG_INFO("Non-Software-related Error type={}. Ignored", type);
3514034a652SMyung Bae         return;
3524034a652SMyung Bae     }
3534034a652SMyung Bae     // Clear the timer
3544034a652SMyung Bae     fwAvailableTimer = nullptr;
3558549b951SMyung Bae }
3568549b951SMyung Bae 
3578549b951SMyung Bae inline void
3588549b951SMyung Bae     afterUpdateErrorMatcher(const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
3598549b951SMyung Bae                             const std::string& url, sdbusplus::message_t& m)
3608549b951SMyung Bae {
36180f79a40SMichael Shen     dbus::utility::DBusInterfacesMap interfacesProperties;
3628549b951SMyung Bae     sdbusplus::message::object_path objPath;
3638549b951SMyung Bae     m.read(objPath, interfacesProperties);
3648549b951SMyung Bae     BMCWEB_LOG_DEBUG("obj path = {}", objPath.str);
3658549b951SMyung Bae     for (const std::pair<std::string, dbus::utility::DBusPropertiesMap>&
3668549b951SMyung Bae              interface : interfacesProperties)
3678549b951SMyung Bae     {
3688549b951SMyung Bae         if (interface.first == "xyz.openbmc_project.Logging.Entry")
3698549b951SMyung Bae         {
3708549b951SMyung Bae             for (const std::pair<std::string, dbus::utility::DbusVariantType>&
3718549b951SMyung Bae                      value : interface.second)
3728549b951SMyung Bae             {
3738549b951SMyung Bae                 if (value.first != "Message")
3748549b951SMyung Bae                 {
3758549b951SMyung Bae                     continue;
3768549b951SMyung Bae                 }
3778549b951SMyung Bae                 const std::string* type =
3788549b951SMyung Bae                     std::get_if<std::string>(&value.second);
3798549b951SMyung Bae                 if (type == nullptr)
3808549b951SMyung Bae                 {
3818549b951SMyung Bae                     // if this was our message, timeout will cover it
3828549b951SMyung Bae                     return;
3838549b951SMyung Bae                 }
3848549b951SMyung Bae                 handleUpdateErrorType(asyncResp, url, *type);
3858549b951SMyung Bae             }
3868549b951SMyung Bae         }
3878549b951SMyung Bae     }
3888549b951SMyung Bae }
3898549b951SMyung Bae 
3900554c984SAndrew Geissler // Note that asyncResp can be either a valid pointer or nullptr. If nullptr
3910554c984SAndrew Geissler // then no asyncResp updates will occur
392b5a76932SEd Tanous static void monitorForSoftwareAvailable(
3938d1b46d7Szhanghch05     const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
3948d1b46d7Szhanghch05     const crow::Request& req, const std::string& url,
3955d138943SGunnar Mills     int timeoutTimeSeconds = 25)
39686adcd6dSAndrew Geissler {
39786adcd6dSAndrew Geissler     // Only allow one FW update at a time
398e05aec50SEd Tanous     if (fwUpdateInProgress)
39986adcd6dSAndrew Geissler     {
4000554c984SAndrew Geissler         if (asyncResp)
4010554c984SAndrew Geissler         {
40286adcd6dSAndrew Geissler             messages::serviceTemporarilyUnavailable(asyncResp->res, "30");
4030554c984SAndrew Geissler         }
40486adcd6dSAndrew Geissler         return;
40586adcd6dSAndrew Geissler     }
40686adcd6dSAndrew Geissler 
4070554c984SAndrew Geissler     fwAvailableTimer =
408271584abSEd Tanous         std::make_unique<boost::asio::steady_timer>(*req.ioService);
40986adcd6dSAndrew Geissler 
410271584abSEd Tanous     fwAvailableTimer->expires_after(std::chrono::seconds(timeoutTimeSeconds));
41186adcd6dSAndrew Geissler 
41286adcd6dSAndrew Geissler     fwAvailableTimer->async_wait(
4138549b951SMyung Bae         std::bind_front(afterAvailbleTimerAsyncWait, asyncResp));
4148549b951SMyung Bae 
415a3e65892SEd Tanous     task::Payload payload(req);
41659d494eeSPatrick Williams     auto callback = [asyncResp, payload](sdbusplus::message_t& m) mutable {
41762598e31SEd Tanous         BMCWEB_LOG_DEBUG("Match fired");
418a3e65892SEd Tanous         softwareInterfaceAdded(asyncResp, m, std::move(payload));
41986adcd6dSAndrew Geissler     };
42086adcd6dSAndrew Geissler 
42186adcd6dSAndrew Geissler     fwUpdateInProgress = true;
42286adcd6dSAndrew Geissler 
42359d494eeSPatrick Williams     fwUpdateMatcher = std::make_unique<sdbusplus::bus::match_t>(
42486adcd6dSAndrew Geissler         *crow::connections::systemBus,
42586adcd6dSAndrew Geissler         "interface='org.freedesktop.DBus.ObjectManager',type='signal',"
42686adcd6dSAndrew Geissler         "member='InterfacesAdded',path='/xyz/openbmc_project/software'",
42786adcd6dSAndrew Geissler         callback);
4284cde5d90SJames Feist 
42959d494eeSPatrick Williams     fwUpdateErrorMatcher = std::make_unique<sdbusplus::bus::match_t>(
4304cde5d90SJames Feist         *crow::connections::systemBus,
431e1cc4828SBrian Ma         "interface='org.freedesktop.DBus.ObjectManager',type='signal',"
432e1cc4828SBrian Ma         "member='InterfacesAdded',"
433e1cc4828SBrian Ma         "path='/xyz/openbmc_project/logging'",
4348549b951SMyung Bae         std::bind_front(afterUpdateErrorMatcher, asyncResp, url));
43586adcd6dSAndrew Geissler }
436729dae72SJennifer Lee 
437f86bcc87SEd Tanous struct TftpUrl
438f86bcc87SEd Tanous {
439f86bcc87SEd Tanous     std::string fwFile;
440f86bcc87SEd Tanous     std::string tftpServer;
441f86bcc87SEd Tanous };
442f86bcc87SEd Tanous 
443f86bcc87SEd Tanous inline std::optional<TftpUrl>
444f86bcc87SEd Tanous     parseTftpUrl(std::string imageURI,
445f86bcc87SEd Tanous                  std::optional<std::string> transferProtocol,
446f86bcc87SEd Tanous                  crow::Response& res)
447f86bcc87SEd Tanous {
448f86bcc87SEd Tanous     if (imageURI.find("://") == std::string::npos)
449f86bcc87SEd Tanous     {
450f86bcc87SEd Tanous         if (imageURI.starts_with("/"))
451f86bcc87SEd Tanous         {
452f86bcc87SEd Tanous             messages::actionParameterValueTypeError(
453f86bcc87SEd Tanous                 res, imageURI, "ImageURI", "UpdateService.SimpleUpdate");
454f86bcc87SEd Tanous             return std::nullopt;
455f86bcc87SEd Tanous         }
456f86bcc87SEd Tanous         if (!transferProtocol)
457f86bcc87SEd Tanous         {
458f86bcc87SEd Tanous             messages::actionParameterValueTypeError(
459f86bcc87SEd Tanous                 res, imageURI, "ImageURI", "UpdateService.SimpleUpdate");
460f86bcc87SEd Tanous             return std::nullopt;
461f86bcc87SEd Tanous         }
462f86bcc87SEd Tanous         // OpenBMC currently only supports TFTP
463f86bcc87SEd Tanous         if (*transferProtocol != "TFTP")
464f86bcc87SEd Tanous         {
465f86bcc87SEd Tanous             messages::actionParameterNotSupported(res, "TransferProtocol",
466f86bcc87SEd Tanous                                                   *transferProtocol);
467f86bcc87SEd Tanous             BMCWEB_LOG_ERROR("Request incorrect protocol parameter: {}",
468f86bcc87SEd Tanous                              *transferProtocol);
469f86bcc87SEd Tanous             return std::nullopt;
470f86bcc87SEd Tanous         }
471f86bcc87SEd Tanous         imageURI = "tftp://" + imageURI;
472f86bcc87SEd Tanous     }
473f86bcc87SEd Tanous 
474f86bcc87SEd Tanous     boost::system::result<boost::urls::url> url =
475f86bcc87SEd Tanous         boost::urls::parse_absolute_uri(imageURI);
476f86bcc87SEd Tanous     if (!url)
477f86bcc87SEd Tanous     {
478f86bcc87SEd Tanous         messages::actionParameterValueTypeError(res, imageURI, "ImageURI",
479f86bcc87SEd Tanous                                                 "UpdateService.SimpleUpdate");
480f86bcc87SEd Tanous 
481f86bcc87SEd Tanous         return std::nullopt;
482f86bcc87SEd Tanous     }
483f86bcc87SEd Tanous     url->normalize();
484f86bcc87SEd Tanous 
485f86bcc87SEd Tanous     if (url->scheme() != "tftp")
486f86bcc87SEd Tanous     {
487f86bcc87SEd Tanous         messages::actionParameterNotSupported(res, "ImageURI", imageURI);
488f86bcc87SEd Tanous         return std::nullopt;
489f86bcc87SEd Tanous     }
490f86bcc87SEd Tanous     std::string path(url->encoded_path());
491f86bcc87SEd Tanous     if (path.size() < 2)
492f86bcc87SEd Tanous     {
493f86bcc87SEd Tanous         messages::actionParameterNotSupported(res, "ImageURI", imageURI);
494f86bcc87SEd Tanous         return std::nullopt;
495f86bcc87SEd Tanous     }
496f86bcc87SEd Tanous     path.erase(0, 1);
497f86bcc87SEd Tanous     std::string host(url->encoded_host_and_port());
498f86bcc87SEd Tanous     return TftpUrl{path, host};
499f86bcc87SEd Tanous }
500f86bcc87SEd Tanous 
5010554c984SAndrew Geissler /**
5020554c984SAndrew Geissler  * UpdateServiceActionsSimpleUpdate class supports handle POST method for
5030554c984SAndrew Geissler  * SimpleUpdate action.
5040554c984SAndrew Geissler  */
5057e860f15SJohn Edward Broadbent inline void requestRoutesUpdateServiceActionsSimpleUpdate(App& app)
5060554c984SAndrew Geissler {
5077e860f15SJohn Edward Broadbent     BMCWEB_ROUTE(
5087e860f15SJohn Edward Broadbent         app, "/redfish/v1/UpdateService/Actions/UpdateService.SimpleUpdate/")
509ed398213SEd Tanous         .privileges(redfish::privileges::postUpdateService)
510002d39b4SEd Tanous         .methods(boost::beast::http::verb::post)(
511002d39b4SEd Tanous             [&app](const crow::Request& req,
5127e860f15SJohn Edward Broadbent                    const std::shared_ptr<bmcweb::AsyncResp>& asyncResp) {
5133ba00073SCarson Labrado         if (!redfish::setUpRedfishRoute(app, req, asyncResp))
51445ca1b86SEd Tanous         {
51545ca1b86SEd Tanous             return;
51645ca1b86SEd Tanous         }
51745ca1b86SEd Tanous 
5180554c984SAndrew Geissler         std::optional<std::string> transferProtocol;
5190554c984SAndrew Geissler         std::string imageURI;
5200554c984SAndrew Geissler 
52162598e31SEd Tanous         BMCWEB_LOG_DEBUG("Enter UpdateService.SimpleUpdate doPost");
5220554c984SAndrew Geissler 
5230554c984SAndrew Geissler         // User can pass in both TransferProtocol and ImageURI parameters or
5244e0453b1SGunnar Mills         // they can pass in just the ImageURI with the transfer protocol
5254e0453b1SGunnar Mills         // embedded within it.
5260554c984SAndrew Geissler         // 1) TransferProtocol:TFTP ImageURI:1.1.1.1/myfile.bin
5270554c984SAndrew Geissler         // 2) ImageURI:tftp://1.1.1.1/myfile.bin
5280554c984SAndrew Geissler 
529002d39b4SEd Tanous         if (!json_util::readJsonAction(req, asyncResp->res, "TransferProtocol",
530002d39b4SEd Tanous                                        transferProtocol, "ImageURI", imageURI))
5310554c984SAndrew Geissler         {
53262598e31SEd Tanous             BMCWEB_LOG_DEBUG("Missing TransferProtocol or ImageURI parameter");
5330554c984SAndrew Geissler             return;
5340554c984SAndrew Geissler         }
535f86bcc87SEd Tanous         std::optional<TftpUrl> ret = parseTftpUrl(imageURI, transferProtocol,
536f86bcc87SEd Tanous                                                   asyncResp->res);
537f86bcc87SEd Tanous         if (!ret)
5380554c984SAndrew Geissler         {
5390554c984SAndrew Geissler             return;
5400554c984SAndrew Geissler         }
5410554c984SAndrew Geissler 
542f86bcc87SEd Tanous         BMCWEB_LOG_DEBUG("Server: {} File: {}", ret->tftpServer, ret->fwFile);
5430554c984SAndrew Geissler 
5440554c984SAndrew Geissler         // Setup callback for when new software detected
5452618d5e3SGunnar Mills         // Give TFTP 10 minutes to complete
5464cde5d90SJames Feist         monitorForSoftwareAvailable(
547d7a596bdSAlbert Zhang             asyncResp, req,
5484cde5d90SJames Feist             "/redfish/v1/UpdateService/Actions/UpdateService.SimpleUpdate",
5492618d5e3SGunnar Mills             600);
5500554c984SAndrew Geissler 
5512618d5e3SGunnar Mills         // TFTP can take up to 10 minutes depending on image size and
5520554c984SAndrew Geissler         // connection speed. Return to caller as soon as the TFTP operation
5530554c984SAndrew Geissler         // has been started. The callback above will ensure the activate
5540554c984SAndrew Geissler         // is started once the download has completed
5550554c984SAndrew Geissler         redfish::messages::success(asyncResp->res);
5560554c984SAndrew Geissler 
5570554c984SAndrew Geissler         // Call TFTP service
5580554c984SAndrew Geissler         crow::connections::systemBus->async_method_call(
5595e7e2dc5SEd Tanous             [](const boost::system::error_code& ec) {
5600554c984SAndrew Geissler             if (ec)
5610554c984SAndrew Geissler             {
5620554c984SAndrew Geissler                 // messages::internalError(asyncResp->res);
5630554c984SAndrew Geissler                 cleanUp();
56462598e31SEd Tanous                 BMCWEB_LOG_DEBUG("error_code = {}", ec);
56562598e31SEd Tanous                 BMCWEB_LOG_DEBUG("error msg = {}", ec.message());
5660554c984SAndrew Geissler             }
5670554c984SAndrew Geissler             else
5680554c984SAndrew Geissler             {
56962598e31SEd Tanous                 BMCWEB_LOG_DEBUG("Call to DownloaViaTFTP Success");
5700554c984SAndrew Geissler             }
5710554c984SAndrew Geissler         },
5720554c984SAndrew Geissler             "xyz.openbmc_project.Software.Download",
573002d39b4SEd Tanous             "/xyz/openbmc_project/software", "xyz.openbmc_project.Common.TFTP",
574f86bcc87SEd Tanous             "DownloadViaTFTP", ret->fwFile, ret->tftpServer);
5750554c984SAndrew Geissler 
57662598e31SEd Tanous         BMCWEB_LOG_DEBUG("Exit UpdateService.SimpleUpdate doPost");
5777e860f15SJohn Edward Broadbent     });
578729dae72SJennifer Lee }
579729dae72SJennifer Lee 
5800ed80c8cSGeorge Liu inline void uploadImageFile(crow::Response& res, std::string_view body)
5810ed80c8cSGeorge Liu {
5822c6ffdb0SEd Tanous     std::filesystem::path filepath("/tmp/images/" + bmcweb::getRandomUUID());
5832c6ffdb0SEd Tanous 
58462598e31SEd Tanous     BMCWEB_LOG_DEBUG("Writing file to {}", filepath.string());
5850ed80c8cSGeorge Liu     std::ofstream out(filepath, std::ofstream::out | std::ofstream::binary |
5860ed80c8cSGeorge Liu                                     std::ofstream::trunc);
5870ed80c8cSGeorge Liu     // set the permission of the file to 640
58889492a15SPatrick Williams     std::filesystem::perms permission = std::filesystem::perms::owner_read |
58989492a15SPatrick Williams                                         std::filesystem::perms::group_read;
5900ed80c8cSGeorge Liu     std::filesystem::permissions(filepath, permission);
5910ed80c8cSGeorge Liu     out << body;
5920ed80c8cSGeorge Liu 
5930ed80c8cSGeorge Liu     if (out.bad())
5940ed80c8cSGeorge Liu     {
5950ed80c8cSGeorge Liu         messages::internalError(res);
5960ed80c8cSGeorge Liu         cleanUp();
5970ed80c8cSGeorge Liu     }
5980ed80c8cSGeorge Liu }
5990ed80c8cSGeorge Liu 
6000ed80c8cSGeorge Liu inline void setApplyTime(const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
6010ed80c8cSGeorge Liu                          const std::string& applyTime)
6020ed80c8cSGeorge Liu {
6030ed80c8cSGeorge Liu     std::string applyTimeNewVal;
6040ed80c8cSGeorge Liu     if (applyTime == "Immediate")
6050ed80c8cSGeorge Liu     {
6060ed80c8cSGeorge Liu         applyTimeNewVal =
6070ed80c8cSGeorge Liu             "xyz.openbmc_project.Software.ApplyTime.RequestedApplyTimes.Immediate";
6080ed80c8cSGeorge Liu     }
6090ed80c8cSGeorge Liu     else if (applyTime == "OnReset")
6100ed80c8cSGeorge Liu     {
6110ed80c8cSGeorge Liu         applyTimeNewVal =
6120ed80c8cSGeorge Liu             "xyz.openbmc_project.Software.ApplyTime.RequestedApplyTimes.OnReset";
6130ed80c8cSGeorge Liu     }
6140ed80c8cSGeorge Liu     else
6150ed80c8cSGeorge Liu     {
61662598e31SEd Tanous         BMCWEB_LOG_INFO(
61762598e31SEd Tanous             "ApplyTime value is not in the list of acceptable values");
6180ed80c8cSGeorge Liu         messages::propertyValueNotInList(asyncResp->res, applyTime,
6190ed80c8cSGeorge Liu                                          "ApplyTime");
6200ed80c8cSGeorge Liu         return;
6210ed80c8cSGeorge Liu     }
6220ed80c8cSGeorge Liu 
6230ed80c8cSGeorge Liu     // Set the requested image apply time value
6249ae226faSGeorge Liu     sdbusplus::asio::setProperty(
6259ae226faSGeorge Liu         *crow::connections::systemBus, "xyz.openbmc_project.Settings",
6269ae226faSGeorge Liu         "/xyz/openbmc_project/software/apply_time",
6279ae226faSGeorge Liu         "xyz.openbmc_project.Software.ApplyTime", "RequestedApplyTime",
6289ae226faSGeorge Liu         applyTimeNewVal, [asyncResp](const boost::system::error_code& ec) {
6290ed80c8cSGeorge Liu         if (ec)
6300ed80c8cSGeorge Liu         {
63162598e31SEd Tanous             BMCWEB_LOG_ERROR("D-Bus responses error: {}", ec);
6320ed80c8cSGeorge Liu             messages::internalError(asyncResp->res);
6330ed80c8cSGeorge Liu             return;
6340ed80c8cSGeorge Liu         }
6350ed80c8cSGeorge Liu         messages::success(asyncResp->res);
6369ae226faSGeorge Liu     });
6370ed80c8cSGeorge Liu }
6380ed80c8cSGeorge Liu 
6390ed80c8cSGeorge Liu inline void
6400ed80c8cSGeorge Liu     updateMultipartContext(const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
6410ed80c8cSGeorge Liu                            const MultipartParser& parser)
6420ed80c8cSGeorge Liu {
6430ed80c8cSGeorge Liu     const std::string* uploadData = nullptr;
6440ed80c8cSGeorge Liu     std::optional<std::string> applyTime = "OnReset";
6450ed80c8cSGeorge Liu     bool targetFound = false;
6460ed80c8cSGeorge Liu     for (const FormPart& formpart : parser.mime_fields)
6470ed80c8cSGeorge Liu     {
6480ed80c8cSGeorge Liu         boost::beast::http::fields::const_iterator it =
6490ed80c8cSGeorge Liu             formpart.fields.find("Content-Disposition");
6500ed80c8cSGeorge Liu         if (it == formpart.fields.end())
6510ed80c8cSGeorge Liu         {
65262598e31SEd Tanous             BMCWEB_LOG_ERROR("Couldn't find Content-Disposition");
6530ed80c8cSGeorge Liu             return;
6540ed80c8cSGeorge Liu         }
65562598e31SEd Tanous         BMCWEB_LOG_INFO("Parsing value {}", it->value());
6560ed80c8cSGeorge Liu 
6570ed80c8cSGeorge Liu         // The construction parameters of param_list must start with `;`
6580ed80c8cSGeorge Liu         size_t index = it->value().find(';');
6590ed80c8cSGeorge Liu         if (index == std::string::npos)
6600ed80c8cSGeorge Liu         {
6610ed80c8cSGeorge Liu             continue;
6620ed80c8cSGeorge Liu         }
6630ed80c8cSGeorge Liu 
66489492a15SPatrick Williams         for (const auto& param :
6650ed80c8cSGeorge Liu              boost::beast::http::param_list{it->value().substr(index)})
6660ed80c8cSGeorge Liu         {
6670ed80c8cSGeorge Liu             if (param.first != "name" || param.second.empty())
6680ed80c8cSGeorge Liu             {
6690ed80c8cSGeorge Liu                 continue;
6700ed80c8cSGeorge Liu             }
6710ed80c8cSGeorge Liu 
6720ed80c8cSGeorge Liu             if (param.second == "UpdateParameters")
6730ed80c8cSGeorge Liu             {
6740ed80c8cSGeorge Liu                 std::vector<std::string> targets;
6750ed80c8cSGeorge Liu                 nlohmann::json content =
6760ed80c8cSGeorge Liu                     nlohmann::json::parse(formpart.content);
677*7cb59f65SEd Tanous                 nlohmann::json::object_t* obj =
678*7cb59f65SEd Tanous                     content.get_ptr<nlohmann::json::object_t*>();
679*7cb59f65SEd Tanous                 if (obj == nullptr)
680*7cb59f65SEd Tanous                 {
681*7cb59f65SEd Tanous                     messages::propertyValueFormatError(asyncResp->res, targets,
682*7cb59f65SEd Tanous                                                        "UpdateParameters");
683*7cb59f65SEd Tanous                     return;
684*7cb59f65SEd Tanous                 }
685*7cb59f65SEd Tanous 
686*7cb59f65SEd Tanous                 if (!json_util::readJsonObject(
687*7cb59f65SEd Tanous                         *obj, asyncResp->res, "Targets", targets,
688*7cb59f65SEd Tanous                         "@Redfish.OperationApplyTime", applyTime))
6890ed80c8cSGeorge Liu                 {
6900ed80c8cSGeorge Liu                     return;
6910ed80c8cSGeorge Liu                 }
6920ed80c8cSGeorge Liu                 if (targets.size() != 1)
6930ed80c8cSGeorge Liu                 {
694*7cb59f65SEd Tanous                     messages::propertyValueFormatError(asyncResp->res, targets,
695*7cb59f65SEd Tanous                                                        "Targets");
6960ed80c8cSGeorge Liu                     return;
6970ed80c8cSGeorge Liu                 }
6980ed80c8cSGeorge Liu                 if (targets[0] != "/redfish/v1/Managers/bmc")
6990ed80c8cSGeorge Liu                 {
700*7cb59f65SEd Tanous                     messages::propertyValueNotInList(asyncResp->res, targets[0],
701*7cb59f65SEd Tanous                                                      "Targets/0");
7020ed80c8cSGeorge Liu                     return;
7030ed80c8cSGeorge Liu                 }
7040ed80c8cSGeorge Liu                 targetFound = true;
7050ed80c8cSGeorge Liu             }
7060ed80c8cSGeorge Liu             else if (param.second == "UpdateFile")
7070ed80c8cSGeorge Liu             {
7080ed80c8cSGeorge Liu                 uploadData = &(formpart.content);
7090ed80c8cSGeorge Liu             }
7100ed80c8cSGeorge Liu         }
7110ed80c8cSGeorge Liu     }
7120ed80c8cSGeorge Liu 
7130ed80c8cSGeorge Liu     if (uploadData == nullptr)
7140ed80c8cSGeorge Liu     {
71562598e31SEd Tanous         BMCWEB_LOG_ERROR("Upload data is NULL");
7160ed80c8cSGeorge Liu         messages::propertyMissing(asyncResp->res, "UpdateFile");
7170ed80c8cSGeorge Liu         return;
7180ed80c8cSGeorge Liu     }
7190ed80c8cSGeorge Liu     if (!targetFound)
7200ed80c8cSGeorge Liu     {
7210ed80c8cSGeorge Liu         messages::propertyMissing(asyncResp->res, "targets");
7220ed80c8cSGeorge Liu         return;
7230ed80c8cSGeorge Liu     }
7240ed80c8cSGeorge Liu 
7250ed80c8cSGeorge Liu     setApplyTime(asyncResp, *applyTime);
7260ed80c8cSGeorge Liu 
7270ed80c8cSGeorge Liu     uploadImageFile(asyncResp->res, *uploadData);
7280ed80c8cSGeorge Liu }
7290ed80c8cSGeorge Liu 
730c2051d11SEd Tanous inline void
731c2051d11SEd Tanous     handleUpdateServicePost(App& app, const crow::Request& req,
732c2051d11SEd Tanous                             const std::shared_ptr<bmcweb::AsyncResp>& asyncResp)
733c2051d11SEd Tanous {
7343ba00073SCarson Labrado     if (!redfish::setUpRedfishRoute(app, req, asyncResp))
735c2051d11SEd Tanous     {
736c2051d11SEd Tanous         return;
737c2051d11SEd Tanous     }
738b33a4327SNinad Palsule     std::string_view contentType = req.getHeaderValue("Content-Type");
739b33a4327SNinad Palsule 
74062598e31SEd Tanous     BMCWEB_LOG_DEBUG("doPost: contentType={}", contentType);
741b33a4327SNinad Palsule 
742b33a4327SNinad Palsule     // Make sure that content type is application/octet-stream or
743b33a4327SNinad Palsule     // multipart/form-data
74418f8f608SEd Tanous     if (bmcweb::asciiIEquals(contentType, "application/octet-stream"))
745b33a4327SNinad Palsule     {
746b33a4327SNinad Palsule         // Setup callback for when new software detected
747b33a4327SNinad Palsule         monitorForSoftwareAvailable(asyncResp, req,
748b33a4327SNinad Palsule                                     "/redfish/v1/UpdateService");
749b33a4327SNinad Palsule 
750b33a4327SNinad Palsule         uploadImageFile(asyncResp->res, req.body());
751b33a4327SNinad Palsule     }
752b33a4327SNinad Palsule     else if (contentType.starts_with("multipart/form-data"))
753b33a4327SNinad Palsule     {
754b33a4327SNinad Palsule         MultipartParser parser;
755c2051d11SEd Tanous 
756c2051d11SEd Tanous         // Setup callback for when new software detected
757b33a4327SNinad Palsule         monitorForSoftwareAvailable(asyncResp, req,
758b33a4327SNinad Palsule                                     "/redfish/v1/UpdateService");
759c2051d11SEd Tanous 
7600ed80c8cSGeorge Liu         ParserError ec = parser.parse(req);
7610ed80c8cSGeorge Liu         if (ec != ParserError::PARSER_SUCCESS)
7620ed80c8cSGeorge Liu         {
7630ed80c8cSGeorge Liu             // handle error
76462598e31SEd Tanous             BMCWEB_LOG_ERROR("MIME parse failed, ec : {}",
76562598e31SEd Tanous                              static_cast<int>(ec));
7660ed80c8cSGeorge Liu             messages::internalError(asyncResp->res);
7670ed80c8cSGeorge Liu             return;
7680ed80c8cSGeorge Liu         }
7690ed80c8cSGeorge Liu         updateMultipartContext(asyncResp, parser);
770c2051d11SEd Tanous     }
771b33a4327SNinad Palsule     else
772b33a4327SNinad Palsule     {
77362598e31SEd Tanous         BMCWEB_LOG_DEBUG("Bad content type specified:{}", contentType);
774b33a4327SNinad Palsule         asyncResp->res.result(boost::beast::http::status::bad_request);
775b33a4327SNinad Palsule     }
776b33a4327SNinad Palsule }
777c2051d11SEd Tanous 
7787e860f15SJohn Edward Broadbent inline void requestRoutesUpdateService(App& app)
7791abe55efSEd Tanous {
7807e860f15SJohn Edward Broadbent     BMCWEB_ROUTE(app, "/redfish/v1/UpdateService/")
781ed398213SEd Tanous         .privileges(redfish::privileges::getUpdateService)
782002d39b4SEd Tanous         .methods(boost::beast::http::verb::get)(
783002d39b4SEd Tanous             [&app](const crow::Request& req,
784002d39b4SEd Tanous                    const std::shared_ptr<bmcweb::AsyncResp>& asyncResp) {
7853ba00073SCarson Labrado         if (!redfish::setUpRedfishRoute(app, req, asyncResp))
78645ca1b86SEd Tanous         {
78745ca1b86SEd Tanous             return;
78845ca1b86SEd Tanous         }
7898d1b46d7Szhanghch05         asyncResp->res.jsonValue["@odata.type"] =
7900ed80c8cSGeorge Liu             "#UpdateService.v1_11_1.UpdateService";
7918d1b46d7Szhanghch05         asyncResp->res.jsonValue["@odata.id"] = "/redfish/v1/UpdateService";
7928d1b46d7Szhanghch05         asyncResp->res.jsonValue["Id"] = "UpdateService";
793002d39b4SEd Tanous         asyncResp->res.jsonValue["Description"] = "Service for Software Update";
7948d1b46d7Szhanghch05         asyncResp->res.jsonValue["Name"] = "Update Service";
7954dc23f3fSEd Tanous 
7967e860f15SJohn Edward Broadbent         asyncResp->res.jsonValue["HttpPushUri"] =
7974dc23f3fSEd Tanous             "/redfish/v1/UpdateService/update";
7980ed80c8cSGeorge Liu         asyncResp->res.jsonValue["MultipartHttpPushUri"] =
7990ed80c8cSGeorge Liu             "/redfish/v1/UpdateService/update";
8004dc23f3fSEd Tanous 
8010f74e643SEd Tanous         // UpdateService cannot be disabled
8028d1b46d7Szhanghch05         asyncResp->res.jsonValue["ServiceEnabled"] = true;
8031476687dSEd Tanous         asyncResp->res.jsonValue["FirmwareInventory"]["@odata.id"] =
8041476687dSEd Tanous             "/redfish/v1/UpdateService/FirmwareInventory";
805d61e5194STejas Patil         // Get the MaxImageSizeBytes
806d61e5194STejas Patil         asyncResp->res.jsonValue["MaxImageSizeBytes"] =
807d61e5194STejas Patil             bmcwebHttpReqBodyLimitMb * 1024 * 1024;
808d61e5194STejas Patil 
8090554c984SAndrew Geissler #ifdef BMCWEB_INSECURE_ENABLE_REDFISH_FW_TFTP_UPDATE
8100554c984SAndrew Geissler         // Update Actions object.
8110554c984SAndrew Geissler         nlohmann::json& updateSvcSimpleUpdate =
812002d39b4SEd Tanous             asyncResp->res.jsonValue["Actions"]["#UpdateService.SimpleUpdate"];
8130554c984SAndrew Geissler         updateSvcSimpleUpdate["target"] =
8140554c984SAndrew Geissler             "/redfish/v1/UpdateService/Actions/UpdateService.SimpleUpdate";
815002d39b4SEd Tanous         updateSvcSimpleUpdate["TransferProtocol@Redfish.AllowableValues"] = {
816002d39b4SEd Tanous             "TFTP"};
8170554c984SAndrew Geissler #endif
818274dfe62SJayashankar Padath         // Get the current ApplyTime value
8191e1e598dSJonathan Doman         sdbusplus::asio::getProperty<std::string>(
8201e1e598dSJonathan Doman             *crow::connections::systemBus, "xyz.openbmc_project.Settings",
8211e1e598dSJonathan Doman             "/xyz/openbmc_project/software/apply_time",
8221e1e598dSJonathan Doman             "xyz.openbmc_project.Software.ApplyTime", "RequestedApplyTime",
8235e7e2dc5SEd Tanous             [asyncResp](const boost::system::error_code& ec,
8241e1e598dSJonathan Doman                         const std::string& applyTime) {
825274dfe62SJayashankar Padath             if (ec)
826274dfe62SJayashankar Padath             {
82762598e31SEd Tanous                 BMCWEB_LOG_DEBUG("DBUS response error {}", ec);
8288d1b46d7Szhanghch05                 messages::internalError(asyncResp->res);
829274dfe62SJayashankar Padath                 return;
830274dfe62SJayashankar Padath             }
831274dfe62SJayashankar Padath 
832274dfe62SJayashankar Padath             // Store the ApplyTime Value
8331e1e598dSJonathan Doman             if (applyTime == "xyz.openbmc_project.Software.ApplyTime."
8341e1e598dSJonathan Doman                              "RequestedApplyTimes.Immediate")
835274dfe62SJayashankar Padath             {
836002d39b4SEd Tanous                 asyncResp->res.jsonValue["HttpPushUriOptions"]
8377e860f15SJohn Edward Broadbent                                         ["HttpPushUriApplyTime"]["ApplyTime"] =
8387e860f15SJohn Edward Broadbent                     "Immediate";
839274dfe62SJayashankar Padath             }
840002d39b4SEd Tanous             else if (applyTime == "xyz.openbmc_project.Software.ApplyTime."
8411e1e598dSJonathan Doman                                   "RequestedApplyTimes.OnReset")
842274dfe62SJayashankar Padath             {
843002d39b4SEd Tanous                 asyncResp->res.jsonValue["HttpPushUriOptions"]
8447e860f15SJohn Edward Broadbent                                         ["HttpPushUriApplyTime"]["ApplyTime"] =
8457e860f15SJohn Edward Broadbent                     "OnReset";
846274dfe62SJayashankar Padath             }
8471e1e598dSJonathan Doman         });
8487e860f15SJohn Edward Broadbent     });
8497e860f15SJohn Edward Broadbent     BMCWEB_ROUTE(app, "/redfish/v1/UpdateService/")
850ed398213SEd Tanous         .privileges(redfish::privileges::patchUpdateService)
851002d39b4SEd Tanous         .methods(boost::beast::http::verb::patch)(
852002d39b4SEd Tanous             [&app](const crow::Request& req,
853002d39b4SEd Tanous                    const std::shared_ptr<bmcweb::AsyncResp>& asyncResp) {
8543ba00073SCarson Labrado         if (!redfish::setUpRedfishRoute(app, req, asyncResp))
85545ca1b86SEd Tanous         {
85645ca1b86SEd Tanous             return;
85745ca1b86SEd Tanous         }
85862598e31SEd Tanous         BMCWEB_LOG_DEBUG("doPatch...");
859fa1a5a38SJayashankar Padath 
860274dfe62SJayashankar Padath         std::optional<std::string> applyTime;
861*7cb59f65SEd Tanous         if (!json_util::readJsonPatch(
862*7cb59f65SEd Tanous                 req, asyncResp->res,
863*7cb59f65SEd Tanous                 "HttpPushUriOptions/HttpPushUriApplyTime/ApplyTime", applyTime))
864274dfe62SJayashankar Padath         {
865274dfe62SJayashankar Padath             return;
866274dfe62SJayashankar Padath         }
867274dfe62SJayashankar Padath 
868274dfe62SJayashankar Padath         if (applyTime)
869fa1a5a38SJayashankar Padath         {
8700ed80c8cSGeorge Liu             setApplyTime(asyncResp, *applyTime);
871fa1a5a38SJayashankar Padath         }
8727e860f15SJohn Edward Broadbent     });
873c2051d11SEd Tanous 
8744dc23f3fSEd Tanous     BMCWEB_ROUTE(app, "/redfish/v1/UpdateService/update/")
8754dc23f3fSEd Tanous         .privileges(redfish::privileges::postUpdateService)
8767e860f15SJohn Edward Broadbent         .methods(boost::beast::http::verb::post)(
877c2051d11SEd Tanous             std::bind_front(handleUpdateServicePost, std::ref(app)));
878729dae72SJennifer Lee }
879729dae72SJennifer Lee 
8807e860f15SJohn Edward Broadbent inline void requestRoutesSoftwareInventoryCollection(App& app)
8811abe55efSEd Tanous {
8827e860f15SJohn Edward Broadbent     BMCWEB_ROUTE(app, "/redfish/v1/UpdateService/FirmwareInventory/")
883ed398213SEd Tanous         .privileges(redfish::privileges::getSoftwareInventoryCollection)
8841476687dSEd Tanous         .methods(boost::beast::http::verb::get)(
8851476687dSEd Tanous             [&app](const crow::Request& req,
8861476687dSEd Tanous                    const std::shared_ptr<bmcweb::AsyncResp>& asyncResp) {
8873ba00073SCarson Labrado         if (!redfish::setUpRedfishRoute(app, req, asyncResp))
88845ca1b86SEd Tanous         {
88945ca1b86SEd Tanous             return;
89045ca1b86SEd Tanous         }
8918d1b46d7Szhanghch05         asyncResp->res.jsonValue["@odata.type"] =
8920f74e643SEd Tanous             "#SoftwareInventoryCollection.SoftwareInventoryCollection";
8938d1b46d7Szhanghch05         asyncResp->res.jsonValue["@odata.id"] =
8940f74e643SEd Tanous             "/redfish/v1/UpdateService/FirmwareInventory";
895002d39b4SEd Tanous         asyncResp->res.jsonValue["Name"] = "Software Inventory Collection";
89608d81adaSJohn Edward Broadbent         const std::array<const std::string_view, 1> iface = {
897e99073f5SGeorge Liu             "xyz.openbmc_project.Software.Version"};
8986c4eb9deSJennifer Lee 
89908d81adaSJohn Edward Broadbent         redfish::collection_util::getCollectionMembers(
90008d81adaSJohn Edward Broadbent             asyncResp,
90108d81adaSJohn Edward Broadbent             boost::urls::url("/redfish/v1/UpdateService/FirmwareInventory"),
90208d81adaSJohn Edward Broadbent             iface, "/xyz/openbmc_project/software");
9037e860f15SJohn Edward Broadbent     });
904729dae72SJennifer Lee }
90587d84729SAndrew Geissler /* Fill related item links (i.e. bmc, bios) in for inventory */
9067e860f15SJohn Edward Broadbent inline static void
907ac106bf6SEd Tanous     getRelatedItems(const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
90887d84729SAndrew Geissler                     const std::string& purpose)
90987d84729SAndrew Geissler {
910eee0013eSWilly Tu     if (purpose == sw_util::bmcPurpose)
91187d84729SAndrew Geissler     {
912ac106bf6SEd Tanous         nlohmann::json& relatedItem = asyncResp->res.jsonValue["RelatedItem"];
9131476687dSEd Tanous         nlohmann::json::object_t item;
9141476687dSEd Tanous         item["@odata.id"] = "/redfish/v1/Managers/bmc";
915b2ba3072SPatrick Williams         relatedItem.emplace_back(std::move(item));
916ac106bf6SEd Tanous         asyncResp->res.jsonValue["RelatedItem@odata.count"] =
917ac106bf6SEd Tanous             relatedItem.size();
91887d84729SAndrew Geissler     }
919eee0013eSWilly Tu     else if (purpose == sw_util::biosPurpose)
92087d84729SAndrew Geissler     {
921ac106bf6SEd Tanous         nlohmann::json& relatedItem = asyncResp->res.jsonValue["RelatedItem"];
9221476687dSEd Tanous         nlohmann::json::object_t item;
9231476687dSEd Tanous         item["@odata.id"] = "/redfish/v1/Systems/system/Bios";
924b2ba3072SPatrick Williams         relatedItem.emplace_back(std::move(item));
925ac106bf6SEd Tanous         asyncResp->res.jsonValue["RelatedItem@odata.count"] =
926ac106bf6SEd Tanous             relatedItem.size();
92787d84729SAndrew Geissler     }
92887d84729SAndrew Geissler     else
92987d84729SAndrew Geissler     {
930bf2ddedeSCarson Labrado         BMCWEB_LOG_DEBUG("Unknown software purpose {}", purpose);
93187d84729SAndrew Geissler     }
93287d84729SAndrew Geissler }
93387d84729SAndrew Geissler 
934af24660dSWilly Tu inline void
935af24660dSWilly Tu     getSoftwareVersion(const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
936af24660dSWilly Tu                        const std::string& service, const std::string& path,
937af24660dSWilly Tu                        const std::string& swId)
938af24660dSWilly Tu {
939d1bde9e5SKrzysztof Grobelny     sdbusplus::asio::getAllProperties(
940d1bde9e5SKrzysztof Grobelny         *crow::connections::systemBus, service, path,
941d1bde9e5SKrzysztof Grobelny         "xyz.openbmc_project.Software.Version",
942af24660dSWilly Tu         [asyncResp,
9438b24275dSEd Tanous          swId](const boost::system::error_code& ec,
944af24660dSWilly Tu                const dbus::utility::DBusPropertiesMap& propertiesList) {
9458b24275dSEd Tanous         if (ec)
946af24660dSWilly Tu         {
947af24660dSWilly Tu             messages::internalError(asyncResp->res);
948af24660dSWilly Tu             return;
949af24660dSWilly Tu         }
950d1bde9e5SKrzysztof Grobelny 
951af24660dSWilly Tu         const std::string* swInvPurpose = nullptr;
952af24660dSWilly Tu         const std::string* version = nullptr;
953d1bde9e5SKrzysztof Grobelny 
954d1bde9e5SKrzysztof Grobelny         const bool success = sdbusplus::unpackPropertiesNoThrow(
955d1bde9e5SKrzysztof Grobelny             dbus_utils::UnpackErrorPrinter(), propertiesList, "Purpose",
956d1bde9e5SKrzysztof Grobelny             swInvPurpose, "Version", version);
957d1bde9e5SKrzysztof Grobelny 
958d1bde9e5SKrzysztof Grobelny         if (!success)
959af24660dSWilly Tu         {
960d1bde9e5SKrzysztof Grobelny             messages::internalError(asyncResp->res);
961d1bde9e5SKrzysztof Grobelny             return;
962af24660dSWilly Tu         }
963af24660dSWilly Tu 
964af24660dSWilly Tu         if (swInvPurpose == nullptr)
965af24660dSWilly Tu         {
96662598e31SEd Tanous             BMCWEB_LOG_DEBUG("Can't find property \"Purpose\"!");
967af24660dSWilly Tu             messages::internalError(asyncResp->res);
968af24660dSWilly Tu             return;
969af24660dSWilly Tu         }
970af24660dSWilly Tu 
97162598e31SEd Tanous         BMCWEB_LOG_DEBUG("swInvPurpose = {}", *swInvPurpose);
972af24660dSWilly Tu 
973af24660dSWilly Tu         if (version == nullptr)
974af24660dSWilly Tu         {
97562598e31SEd Tanous             BMCWEB_LOG_DEBUG("Can't find property \"Version\"!");
976af24660dSWilly Tu 
977af24660dSWilly Tu             messages::internalError(asyncResp->res);
978af24660dSWilly Tu 
979af24660dSWilly Tu             return;
980af24660dSWilly Tu         }
981af24660dSWilly Tu         asyncResp->res.jsonValue["Version"] = *version;
982af24660dSWilly Tu         asyncResp->res.jsonValue["Id"] = swId;
983af24660dSWilly Tu 
984af24660dSWilly Tu         // swInvPurpose is of format:
985af24660dSWilly Tu         // xyz.openbmc_project.Software.Version.VersionPurpose.ABC
986af24660dSWilly Tu         // Translate this to "ABC image"
987af24660dSWilly Tu         size_t endDesc = swInvPurpose->rfind('.');
988af24660dSWilly Tu         if (endDesc == std::string::npos)
989af24660dSWilly Tu         {
990af24660dSWilly Tu             messages::internalError(asyncResp->res);
991af24660dSWilly Tu             return;
992af24660dSWilly Tu         }
993af24660dSWilly Tu         endDesc++;
994af24660dSWilly Tu         if (endDesc >= swInvPurpose->size())
995af24660dSWilly Tu         {
996af24660dSWilly Tu             messages::internalError(asyncResp->res);
997af24660dSWilly Tu             return;
998af24660dSWilly Tu         }
999af24660dSWilly Tu 
1000af24660dSWilly Tu         std::string formatDesc = swInvPurpose->substr(endDesc);
1001af24660dSWilly Tu         asyncResp->res.jsonValue["Description"] = formatDesc + " image";
1002af24660dSWilly Tu         getRelatedItems(asyncResp, *swInvPurpose);
1003d1bde9e5SKrzysztof Grobelny     });
1004af24660dSWilly Tu }
1005af24660dSWilly Tu 
10067e860f15SJohn Edward Broadbent inline void requestRoutesSoftwareInventory(App& app)
10071abe55efSEd Tanous {
10087e860f15SJohn Edward Broadbent     BMCWEB_ROUTE(app, "/redfish/v1/UpdateService/FirmwareInventory/<str>/")
1009ed398213SEd Tanous         .privileges(redfish::privileges::getSoftwareInventory)
1010002d39b4SEd Tanous         .methods(boost::beast::http::verb::get)(
1011002d39b4SEd Tanous             [&app](const crow::Request& req,
101245ca1b86SEd Tanous                    const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
10137e860f15SJohn Edward Broadbent                    const std::string& param) {
10143ba00073SCarson Labrado         if (!redfish::setUpRedfishRoute(app, req, asyncResp))
101545ca1b86SEd Tanous         {
101645ca1b86SEd Tanous             return;
101745ca1b86SEd Tanous         }
10183ae837c9SEd Tanous         std::shared_ptr<std::string> swId =
10197e860f15SJohn Edward Broadbent             std::make_shared<std::string>(param);
1020c711bf86SEd Tanous 
1021ef4c65b7SEd Tanous         asyncResp->res.jsonValue["@odata.id"] = boost::urls::format(
1022ef4c65b7SEd Tanous             "/redfish/v1/UpdateService/FirmwareInventory/{}", *swId);
1023c711bf86SEd Tanous 
1024e99073f5SGeorge Liu         constexpr std::array<std::string_view, 1> interfaces = {
1025e99073f5SGeorge Liu             "xyz.openbmc_project.Software.Version"};
1026e99073f5SGeorge Liu         dbus::utility::getSubTree(
1027e99073f5SGeorge Liu             "/", 0, interfaces,
1028b9d36b47SEd Tanous             [asyncResp,
1029e99073f5SGeorge Liu              swId](const boost::system::error_code& ec,
1030b9d36b47SEd Tanous                    const dbus::utility::MapperGetSubTreeResponse& subtree) {
103162598e31SEd Tanous             BMCWEB_LOG_DEBUG("doGet callback...");
10321abe55efSEd Tanous             if (ec)
10331abe55efSEd Tanous             {
1034f12894f8SJason M. Bills                 messages::internalError(asyncResp->res);
10356c4eb9deSJennifer Lee                 return;
10366c4eb9deSJennifer Lee             }
10376c4eb9deSJennifer Lee 
10386913228dSAndrew Geissler             // Ensure we find our input swId, otherwise return an error
10396913228dSAndrew Geissler             bool found = false;
1040002d39b4SEd Tanous             for (const std::pair<std::string,
10417e860f15SJohn Edward Broadbent                                  std::vector<std::pair<
1042002d39b4SEd Tanous                                      std::string, std::vector<std::string>>>>&
1043002d39b4SEd Tanous                      obj : subtree)
10441abe55efSEd Tanous             {
104511ba3979SEd Tanous                 if (!obj.first.ends_with(*swId))
10461abe55efSEd Tanous                 {
1047acb7cfb4SJennifer Lee                     continue;
1048acb7cfb4SJennifer Lee                 }
1049acb7cfb4SJennifer Lee 
105026f6976fSEd Tanous                 if (obj.second.empty())
10511abe55efSEd Tanous                 {
1052acb7cfb4SJennifer Lee                     continue;
1053acb7cfb4SJennifer Lee                 }
10546c4eb9deSJennifer Lee 
10556913228dSAndrew Geissler                 found = true;
1056eee0013eSWilly Tu                 sw_util::getSwStatus(asyncResp, swId, obj.second[0].first);
1057af24660dSWilly Tu                 getSoftwareVersion(asyncResp, obj.second[0].first, obj.first,
1058af24660dSWilly Tu                                    *swId);
10596c4eb9deSJennifer Lee             }
10606913228dSAndrew Geissler             if (!found)
10616913228dSAndrew Geissler             {
106262598e31SEd Tanous                 BMCWEB_LOG_WARNING("Input swID {} not found!", *swId);
10636913228dSAndrew Geissler                 messages::resourceMissingAtURI(
1064ef4c65b7SEd Tanous                     asyncResp->res,
1065ef4c65b7SEd Tanous                     boost::urls::format(
1066ef4c65b7SEd Tanous                         "/redfish/v1/UpdateService/FirmwareInventory/{}",
1067ef4c65b7SEd Tanous                         *swId));
10686913228dSAndrew Geissler                 return;
10696913228dSAndrew Geissler             }
10704e68c45bSAyushi Smriti             asyncResp->res.jsonValue["@odata.type"] =
10714e68c45bSAyushi Smriti                 "#SoftwareInventory.v1_1_0.SoftwareInventory";
10724e68c45bSAyushi Smriti             asyncResp->res.jsonValue["Name"] = "Software Inventory";
10734e68c45bSAyushi Smriti             asyncResp->res.jsonValue["Status"]["HealthRollup"] = "OK";
10743f8a743aSAppaRao Puli 
10753f8a743aSAppaRao Puli             asyncResp->res.jsonValue["Updateable"] = false;
1076eee0013eSWilly Tu             sw_util::getSwUpdatableStatus(asyncResp, swId);
1077e99073f5SGeorge Liu         });
10787e860f15SJohn Edward Broadbent     });
10796c4eb9deSJennifer Lee }
1080729dae72SJennifer Lee 
1081729dae72SJennifer Lee } // namespace redfish
1082