xref: /openbmc/bmcweb/features/redfish/lib/update_service.hpp (revision f86bcc875a496b3c321a4ed102579a4031617800)
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 
31d093c996SEd Tanous #include <boost/algorithm/string/case_conv.hpp>
32e99073f5SGeorge Liu #include <boost/system/error_code.hpp>
33ef4c65b7SEd Tanous #include <boost/url/format.hpp>
341e1e598dSJonathan Doman #include <sdbusplus/asio/property.hpp>
353ccb3adbSEd Tanous #include <sdbusplus/bus/match.hpp>
36d1bde9e5SKrzysztof Grobelny #include <sdbusplus/unpack_properties.hpp>
371214b7e7SGunnar Mills 
382b73119cSGeorge Liu #include <array>
390ed80c8cSGeorge Liu #include <filesystem>
402b73119cSGeorge Liu #include <string_view>
412b73119cSGeorge Liu 
421abe55efSEd Tanous namespace redfish
431abe55efSEd Tanous {
4427826b5fSEd Tanous 
450e7de46fSAndrew Geissler // Match signals added on software path
46cf9e417dSEd Tanous // NOLINTNEXTLINE(cppcoreguidelines-avoid-non-const-global-variables)
4759d494eeSPatrick Williams static std::unique_ptr<sdbusplus::bus::match_t> fwUpdateMatcher;
48cf9e417dSEd Tanous // NOLINTNEXTLINE(cppcoreguidelines-avoid-non-const-global-variables)
4959d494eeSPatrick Williams static std::unique_ptr<sdbusplus::bus::match_t> fwUpdateErrorMatcher;
500e7de46fSAndrew Geissler // Only allow one update at a time
51cf9e417dSEd Tanous // NOLINTNEXTLINE(cppcoreguidelines-avoid-non-const-global-variables)
520e7de46fSAndrew Geissler static bool fwUpdateInProgress = false;
5386adcd6dSAndrew Geissler // Timer for software available
54cf9e417dSEd Tanous // NOLINTNEXTLINE(cppcoreguidelines-avoid-non-const-global-variables)
55271584abSEd Tanous static std::unique_ptr<boost::asio::steady_timer> fwAvailableTimer;
5686adcd6dSAndrew Geissler 
577e860f15SJohn Edward Broadbent inline static void cleanUp()
5886adcd6dSAndrew Geissler {
5986adcd6dSAndrew Geissler     fwUpdateInProgress = false;
6086adcd6dSAndrew Geissler     fwUpdateMatcher = nullptr;
614cde5d90SJames Feist     fwUpdateErrorMatcher = nullptr;
6286adcd6dSAndrew Geissler }
637e860f15SJohn Edward Broadbent inline static void activateImage(const std::string& objPath,
6486adcd6dSAndrew Geissler                                  const std::string& service)
6586adcd6dSAndrew Geissler {
6662598e31SEd Tanous     BMCWEB_LOG_DEBUG("Activate image for {} {}", objPath, service);
679ae226faSGeorge Liu     sdbusplus::asio::setProperty(
689ae226faSGeorge Liu         *crow::connections::systemBus, service, objPath,
699ae226faSGeorge Liu         "xyz.openbmc_project.Software.Activation", "RequestedActivation",
709ae226faSGeorge Liu         "xyz.openbmc_project.Software.Activation.RequestedActivations.Active",
718b24275dSEd Tanous         [](const boost::system::error_code& ec) {
728b24275dSEd Tanous         if (ec)
7386adcd6dSAndrew Geissler         {
7462598e31SEd Tanous             BMCWEB_LOG_DEBUG("error_code = {}", ec);
7562598e31SEd Tanous             BMCWEB_LOG_DEBUG("error msg = {}", ec.message());
7686adcd6dSAndrew Geissler         }
779ae226faSGeorge Liu     });
7886adcd6dSAndrew Geissler }
790554c984SAndrew Geissler 
800554c984SAndrew Geissler // Note that asyncResp can be either a valid pointer or nullptr. If nullptr
810554c984SAndrew Geissler // then no asyncResp updates will occur
828d1b46d7Szhanghch05 static void
838d1b46d7Szhanghch05     softwareInterfaceAdded(const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
8459d494eeSPatrick Williams                            sdbusplus::message_t& m, task::Payload&& payload)
8586adcd6dSAndrew Geissler {
8680f79a40SMichael Shen     dbus::utility::DBusInterfacesMap interfacesProperties;
8786adcd6dSAndrew Geissler 
8886adcd6dSAndrew Geissler     sdbusplus::message::object_path objPath;
8986adcd6dSAndrew Geissler 
9086adcd6dSAndrew Geissler     m.read(objPath, interfacesProperties);
9186adcd6dSAndrew Geissler 
9262598e31SEd Tanous     BMCWEB_LOG_DEBUG("obj path = {}", objPath.str);
93e3eb3d63SEd Tanous     for (const auto& interface : interfacesProperties)
9486adcd6dSAndrew Geissler     {
9562598e31SEd Tanous         BMCWEB_LOG_DEBUG("interface = {}", interface.first);
9686adcd6dSAndrew Geissler 
9786adcd6dSAndrew Geissler         if (interface.first == "xyz.openbmc_project.Software.Activation")
9886adcd6dSAndrew Geissler         {
9986adcd6dSAndrew Geissler             // Retrieve service and activate
1002b73119cSGeorge Liu             constexpr std::array<std::string_view, 1> interfaces = {
1012b73119cSGeorge Liu                 "xyz.openbmc_project.Software.Activation"};
1022b73119cSGeorge Liu             dbus::utility::getDbusObject(
1032b73119cSGeorge Liu                 objPath.str, interfaces,
104a3e65892SEd Tanous                 [objPath, asyncResp, payload(std::move(payload))](
1058b24275dSEd Tanous                     const boost::system::error_code& ec,
106a3e65892SEd Tanous                     const std::vector<
107a3e65892SEd Tanous                         std::pair<std::string, std::vector<std::string>>>&
108a3e65892SEd Tanous                         objInfo) mutable {
1098b24275dSEd Tanous                 if (ec)
11086adcd6dSAndrew Geissler                 {
11162598e31SEd Tanous                     BMCWEB_LOG_DEBUG("error_code = {}", ec);
11262598e31SEd Tanous                     BMCWEB_LOG_DEBUG("error msg = {}", ec.message());
1130554c984SAndrew Geissler                     if (asyncResp)
1140554c984SAndrew Geissler                     {
11586adcd6dSAndrew Geissler                         messages::internalError(asyncResp->res);
1160554c984SAndrew Geissler                     }
11786adcd6dSAndrew Geissler                     cleanUp();
11886adcd6dSAndrew Geissler                     return;
11986adcd6dSAndrew Geissler                 }
12086adcd6dSAndrew Geissler                 // Ensure we only got one service back
12186adcd6dSAndrew Geissler                 if (objInfo.size() != 1)
12286adcd6dSAndrew Geissler                 {
12362598e31SEd Tanous                     BMCWEB_LOG_ERROR("Invalid Object Size {}", objInfo.size());
1240554c984SAndrew Geissler                     if (asyncResp)
1250554c984SAndrew Geissler                     {
12686adcd6dSAndrew Geissler                         messages::internalError(asyncResp->res);
1270554c984SAndrew Geissler                     }
12886adcd6dSAndrew Geissler                     cleanUp();
12986adcd6dSAndrew Geissler                     return;
13086adcd6dSAndrew Geissler                 }
13186adcd6dSAndrew Geissler                 // cancel timer only when
13286adcd6dSAndrew Geissler                 // xyz.openbmc_project.Software.Activation interface
13386adcd6dSAndrew Geissler                 // is added
13486adcd6dSAndrew Geissler                 fwAvailableTimer = nullptr;
13586adcd6dSAndrew Geissler 
13686adcd6dSAndrew Geissler                 activateImage(objPath.str, objInfo[0].first);
1370554c984SAndrew Geissler                 if (asyncResp)
1380554c984SAndrew Geissler                 {
13932898ceaSJames Feist                     std::shared_ptr<task::TaskData> task =
14032898ceaSJames Feist                         task::TaskData::createTask(
1418b24275dSEd Tanous                             [](const boost::system::error_code& ec2,
14259d494eeSPatrick Williams                                sdbusplus::message_t& msg,
1431214b7e7SGunnar Mills                                const std::shared_ptr<task::TaskData>&
1441214b7e7SGunnar Mills                                    taskData) {
1458b24275dSEd Tanous                         if (ec2)
14632898ceaSJames Feist                         {
14732898ceaSJames Feist                             return task::completed;
14832898ceaSJames Feist                         }
14932898ceaSJames Feist 
15032898ceaSJames Feist                         std::string iface;
151b9d36b47SEd Tanous                         dbus::utility::DBusPropertiesMap values;
152fd9ab9e1SJames Feist 
153002d39b4SEd Tanous                         std::string index = std::to_string(taskData->index);
15432898ceaSJames Feist                         msg.read(iface, values);
155fd9ab9e1SJames Feist 
156002d39b4SEd Tanous                         if (iface == "xyz.openbmc_project.Software.Activation")
157fd9ab9e1SJames Feist                         {
1580fb5b505SGayathri Leburu                             const std::string* state = nullptr;
159b9d36b47SEd Tanous                             for (const auto& property : values)
16032898ceaSJames Feist                             {
161b9d36b47SEd Tanous                                 if (property.first == "Activation")
162b9d36b47SEd Tanous                                 {
1630fb5b505SGayathri Leburu                                     state = std::get_if<std::string>(
164b9d36b47SEd Tanous                                         &property.second);
1650fb5b505SGayathri Leburu                                     if (state == nullptr)
166b9d36b47SEd Tanous                                     {
167002d39b4SEd Tanous                                         taskData->messages.emplace_back(
168002d39b4SEd Tanous                                             messages::internalError());
169b9d36b47SEd Tanous                                         return task::completed;
170b9d36b47SEd Tanous                                     }
171b9d36b47SEd Tanous                                 }
172b9d36b47SEd Tanous                             }
17332898ceaSJames Feist 
17432898ceaSJames Feist                             if (state == nullptr)
17532898ceaSJames Feist                             {
176b9d36b47SEd Tanous                                 return !task::completed;
17732898ceaSJames Feist                             }
17832898ceaSJames Feist 
17911ba3979SEd Tanous                             if (state->ends_with("Invalid") ||
18011ba3979SEd Tanous                                 state->ends_with("Failed"))
18132898ceaSJames Feist                             {
18232898ceaSJames Feist                                 taskData->state = "Exception";
18332898ceaSJames Feist                                 taskData->status = "Warning";
18432898ceaSJames Feist                                 taskData->messages.emplace_back(
185e5d5006bSJames Feist                                     messages::taskAborted(index));
18632898ceaSJames Feist                                 return task::completed;
18732898ceaSJames Feist                             }
18832898ceaSJames Feist 
18911ba3979SEd Tanous                             if (state->ends_with("Staged"))
19032898ceaSJames Feist                             {
191fd9ab9e1SJames Feist                                 taskData->state = "Stopping";
192fd9ab9e1SJames Feist                                 taskData->messages.emplace_back(
193fd9ab9e1SJames Feist                                     messages::taskPaused(index));
194fd9ab9e1SJames Feist 
195fd9ab9e1SJames Feist                                 // its staged, set a long timer to
196fd9ab9e1SJames Feist                                 // allow them time to complete the
197fd9ab9e1SJames Feist                                 // update (probably cycle the
198fd9ab9e1SJames Feist                                 // system) if this expires then
1998ece0e45SEd Tanous                                 // task will be canceled
200002d39b4SEd Tanous                                 taskData->extendTimer(std::chrono::hours(5));
20132898ceaSJames Feist                                 return !task::completed;
20232898ceaSJames Feist                             }
20332898ceaSJames Feist 
20411ba3979SEd Tanous                             if (state->ends_with("Active"))
20532898ceaSJames Feist                             {
20632898ceaSJames Feist                                 taskData->messages.emplace_back(
207002d39b4SEd Tanous                                     messages::taskCompletedOK(index));
20832898ceaSJames Feist                                 taskData->state = "Completed";
20932898ceaSJames Feist                                 return task::completed;
21032898ceaSJames Feist                             }
211fd9ab9e1SJames Feist                         }
2120fda0f12SGeorge Liu                         else if (
2130fda0f12SGeorge Liu                             iface ==
2140fda0f12SGeorge Liu                             "xyz.openbmc_project.Software.ActivationProgress")
215fd9ab9e1SJames Feist                         {
216b9d36b47SEd Tanous                             const uint8_t* progress = nullptr;
217b9d36b47SEd Tanous                             for (const auto& property : values)
218fd9ab9e1SJames Feist                             {
219b9d36b47SEd Tanous                                 if (property.first == "Progress")
220b9d36b47SEd Tanous                                 {
2210fb5b505SGayathri Leburu                                     progress =
2220fb5b505SGayathri Leburu                                         std::get_if<uint8_t>(&property.second);
2230fb5b505SGayathri Leburu                                     if (progress == nullptr)
224b9d36b47SEd Tanous                                     {
225002d39b4SEd Tanous                                         taskData->messages.emplace_back(
226002d39b4SEd Tanous                                             messages::internalError());
227b9d36b47SEd Tanous                                         return task::completed;
228fd9ab9e1SJames Feist                                     }
229b9d36b47SEd Tanous                                 }
230b9d36b47SEd Tanous                             }
231fd9ab9e1SJames Feist 
232fd9ab9e1SJames Feist                             if (progress == nullptr)
233fd9ab9e1SJames Feist                             {
234b9d36b47SEd Tanous                                 return !task::completed;
235fd9ab9e1SJames Feist                             }
2360fb5b505SGayathri Leburu                             taskData->percentComplete = *progress;
237fd9ab9e1SJames Feist                             taskData->messages.emplace_back(
2380fb5b505SGayathri Leburu                                 messages::taskProgressChanged(index,
2390fb5b505SGayathri Leburu                                                               *progress));
240fd9ab9e1SJames Feist 
241fd9ab9e1SJames Feist                             // if we're getting status updates it's
242fd9ab9e1SJames Feist                             // still alive, update timer
243002d39b4SEd Tanous                             taskData->extendTimer(std::chrono::minutes(5));
244fd9ab9e1SJames Feist                         }
24532898ceaSJames Feist 
24632898ceaSJames Feist                         // as firmware update often results in a
24732898ceaSJames Feist                         // reboot, the task  may never "complete"
24832898ceaSJames Feist                         // unless it is an error
24932898ceaSJames Feist 
25032898ceaSJames Feist                         return !task::completed;
25132898ceaSJames Feist                     },
2520fda0f12SGeorge Liu                             "type='signal',interface='org.freedesktop.DBus.Properties',"
253fd9ab9e1SJames Feist                             "member='PropertiesChanged',path='" +
25432898ceaSJames Feist                                 objPath.str + "'");
25532898ceaSJames Feist                     task->startTimer(std::chrono::minutes(5));
25632898ceaSJames Feist                     task->populateResp(asyncResp->res);
257a3e65892SEd Tanous                     task->payload.emplace(std::move(payload));
2580554c984SAndrew Geissler                 }
25986adcd6dSAndrew Geissler                 fwUpdateInProgress = false;
2602b73119cSGeorge Liu             });
26162bafc01SPatrick Williams 
26262bafc01SPatrick Williams             break;
26386adcd6dSAndrew Geissler         }
26486adcd6dSAndrew Geissler     }
26586adcd6dSAndrew Geissler }
26686adcd6dSAndrew Geissler 
2678549b951SMyung Bae inline void afterAvailbleTimerAsyncWait(
2688549b951SMyung Bae     const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
2698549b951SMyung Bae     const boost::system::error_code& ec)
2708549b951SMyung Bae {
2718549b951SMyung Bae     cleanUp();
2728549b951SMyung Bae     if (ec == boost::asio::error::operation_aborted)
2738549b951SMyung Bae     {
2748549b951SMyung Bae         // expected, we were canceled before the timer completed.
2758549b951SMyung Bae         return;
2768549b951SMyung Bae     }
2778549b951SMyung Bae     BMCWEB_LOG_ERROR("Timed out waiting for firmware object being created");
2788549b951SMyung Bae     BMCWEB_LOG_ERROR("FW image may has already been uploaded to server");
2798549b951SMyung Bae     if (ec)
2808549b951SMyung Bae     {
2818549b951SMyung Bae         BMCWEB_LOG_ERROR("Async_wait failed{}", ec);
2828549b951SMyung Bae         return;
2838549b951SMyung Bae     }
2848549b951SMyung Bae     if (asyncResp)
2858549b951SMyung Bae     {
2868549b951SMyung Bae         redfish::messages::internalError(asyncResp->res);
2878549b951SMyung Bae     }
2888549b951SMyung Bae }
2898549b951SMyung Bae 
2908549b951SMyung Bae inline void
2918549b951SMyung Bae     handleUpdateErrorType(const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
2928549b951SMyung Bae                           const std::string& url, const std::string& type)
2938549b951SMyung Bae {
2948549b951SMyung Bae     if (type == "xyz.openbmc_project.Software.Image.Error.UnTarFailure")
2958549b951SMyung Bae     {
2968549b951SMyung Bae         redfish::messages::invalidUpload(asyncResp->res, url,
2978549b951SMyung Bae                                          "Invalid archive");
2988549b951SMyung Bae     }
2998549b951SMyung Bae     else if (type ==
3008549b951SMyung Bae              "xyz.openbmc_project.Software.Image.Error.ManifestFileFailure")
3018549b951SMyung Bae     {
3028549b951SMyung Bae         redfish::messages::invalidUpload(asyncResp->res, url,
3038549b951SMyung Bae                                          "Invalid manifest");
3048549b951SMyung Bae     }
3058549b951SMyung Bae     else if (type == "xyz.openbmc_project.Software.Image.Error.ImageFailure")
3068549b951SMyung Bae     {
3078549b951SMyung Bae         redfish::messages::invalidUpload(asyncResp->res, url,
3088549b951SMyung Bae                                          "Invalid image format");
3098549b951SMyung Bae     }
3108549b951SMyung Bae     else if (type == "xyz.openbmc_project.Software.Version.Error.AlreadyExists")
3118549b951SMyung Bae     {
3128549b951SMyung Bae         redfish::messages::invalidUpload(asyncResp->res, url,
3138549b951SMyung Bae                                          "Image version already exists");
3148549b951SMyung Bae 
3158549b951SMyung Bae         redfish::messages::resourceAlreadyExists(
3168549b951SMyung Bae             asyncResp->res, "UpdateService", "Version", "uploaded version");
3178549b951SMyung Bae     }
3188549b951SMyung Bae     else if (type == "xyz.openbmc_project.Software.Image.Error.BusyFailure")
3198549b951SMyung Bae     {
3208549b951SMyung Bae         redfish::messages::resourceExhaustion(asyncResp->res, url);
3218549b951SMyung Bae     }
3224034a652SMyung Bae     else if (type == "xyz.openbmc_project.Software.Version.Error.Incompatible")
3238549b951SMyung Bae     {
3244034a652SMyung Bae         redfish::messages::invalidUpload(asyncResp->res, url,
3254034a652SMyung Bae                                          "Incompatible image version");
3264034a652SMyung Bae     }
3274034a652SMyung Bae     else if (type ==
3284034a652SMyung Bae              "xyz.openbmc_project.Software.Version.Error.ExpiredAccessKey")
3294034a652SMyung Bae     {
3304034a652SMyung Bae         redfish::messages::invalidUpload(asyncResp->res, url,
3314034a652SMyung Bae                                          "Update Access Key Expired");
3324034a652SMyung Bae     }
3334034a652SMyung Bae     else if (type ==
3344034a652SMyung Bae              "xyz.openbmc_project.Software.Version.Error.InvalidSignature")
3354034a652SMyung Bae     {
3364034a652SMyung Bae         redfish::messages::invalidUpload(asyncResp->res, url,
3374034a652SMyung Bae                                          "Invalid image signature");
3384034a652SMyung Bae     }
3394034a652SMyung Bae     else if (type ==
3404034a652SMyung Bae                  "xyz.openbmc_project.Software.Image.Error.InternalFailure" ||
3414034a652SMyung Bae              type == "xyz.openbmc_project.Software.Version.Error.HostFile")
3424034a652SMyung Bae     {
3434034a652SMyung Bae         BMCWEB_LOG_ERROR("Software Image Error type={}", type);
3448549b951SMyung Bae         redfish::messages::internalError(asyncResp->res);
3458549b951SMyung Bae     }
3464034a652SMyung Bae     else
3474034a652SMyung Bae     {
3484034a652SMyung Bae         // Unrelated error types. Ignored
3494034a652SMyung Bae         BMCWEB_LOG_INFO("Non-Software-related Error type={}. Ignored", type);
3504034a652SMyung Bae         return;
3514034a652SMyung Bae     }
3524034a652SMyung Bae     // Clear the timer
3534034a652SMyung Bae     fwAvailableTimer = nullptr;
3548549b951SMyung Bae }
3558549b951SMyung Bae 
3568549b951SMyung Bae inline void
3578549b951SMyung Bae     afterUpdateErrorMatcher(const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
3588549b951SMyung Bae                             const std::string& url, sdbusplus::message_t& m)
3598549b951SMyung Bae {
36080f79a40SMichael Shen     dbus::utility::DBusInterfacesMap interfacesProperties;
3618549b951SMyung Bae     sdbusplus::message::object_path objPath;
3628549b951SMyung Bae     m.read(objPath, interfacesProperties);
3638549b951SMyung Bae     BMCWEB_LOG_DEBUG("obj path = {}", objPath.str);
3648549b951SMyung Bae     for (const std::pair<std::string, dbus::utility::DBusPropertiesMap>&
3658549b951SMyung Bae              interface : interfacesProperties)
3668549b951SMyung Bae     {
3678549b951SMyung Bae         if (interface.first == "xyz.openbmc_project.Logging.Entry")
3688549b951SMyung Bae         {
3698549b951SMyung Bae             for (const std::pair<std::string, dbus::utility::DbusVariantType>&
3708549b951SMyung Bae                      value : interface.second)
3718549b951SMyung Bae             {
3728549b951SMyung Bae                 if (value.first != "Message")
3738549b951SMyung Bae                 {
3748549b951SMyung Bae                     continue;
3758549b951SMyung Bae                 }
3768549b951SMyung Bae                 const std::string* type =
3778549b951SMyung Bae                     std::get_if<std::string>(&value.second);
3788549b951SMyung Bae                 if (type == nullptr)
3798549b951SMyung Bae                 {
3808549b951SMyung Bae                     // if this was our message, timeout will cover it
3818549b951SMyung Bae                     return;
3828549b951SMyung Bae                 }
3838549b951SMyung Bae                 handleUpdateErrorType(asyncResp, url, *type);
3848549b951SMyung Bae             }
3858549b951SMyung Bae         }
3868549b951SMyung Bae     }
3878549b951SMyung Bae }
3888549b951SMyung Bae 
3890554c984SAndrew Geissler // Note that asyncResp can be either a valid pointer or nullptr. If nullptr
3900554c984SAndrew Geissler // then no asyncResp updates will occur
391b5a76932SEd Tanous static void monitorForSoftwareAvailable(
3928d1b46d7Szhanghch05     const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
3938d1b46d7Szhanghch05     const crow::Request& req, const std::string& url,
3945d138943SGunnar Mills     int timeoutTimeSeconds = 25)
39586adcd6dSAndrew Geissler {
39686adcd6dSAndrew Geissler     // Only allow one FW update at a time
397e05aec50SEd Tanous     if (fwUpdateInProgress)
39886adcd6dSAndrew Geissler     {
3990554c984SAndrew Geissler         if (asyncResp)
4000554c984SAndrew Geissler         {
40186adcd6dSAndrew Geissler             messages::serviceTemporarilyUnavailable(asyncResp->res, "30");
4020554c984SAndrew Geissler         }
40386adcd6dSAndrew Geissler         return;
40486adcd6dSAndrew Geissler     }
40586adcd6dSAndrew Geissler 
4060554c984SAndrew Geissler     fwAvailableTimer =
407271584abSEd Tanous         std::make_unique<boost::asio::steady_timer>(*req.ioService);
40886adcd6dSAndrew Geissler 
409271584abSEd Tanous     fwAvailableTimer->expires_after(std::chrono::seconds(timeoutTimeSeconds));
41086adcd6dSAndrew Geissler 
41186adcd6dSAndrew Geissler     fwAvailableTimer->async_wait(
4128549b951SMyung Bae         std::bind_front(afterAvailbleTimerAsyncWait, asyncResp));
4138549b951SMyung Bae 
414a3e65892SEd Tanous     task::Payload payload(req);
41559d494eeSPatrick Williams     auto callback = [asyncResp, payload](sdbusplus::message_t& m) mutable {
41662598e31SEd Tanous         BMCWEB_LOG_DEBUG("Match fired");
417a3e65892SEd Tanous         softwareInterfaceAdded(asyncResp, m, std::move(payload));
41886adcd6dSAndrew Geissler     };
41986adcd6dSAndrew Geissler 
42086adcd6dSAndrew Geissler     fwUpdateInProgress = true;
42186adcd6dSAndrew Geissler 
42259d494eeSPatrick Williams     fwUpdateMatcher = std::make_unique<sdbusplus::bus::match_t>(
42386adcd6dSAndrew Geissler         *crow::connections::systemBus,
42486adcd6dSAndrew Geissler         "interface='org.freedesktop.DBus.ObjectManager',type='signal',"
42586adcd6dSAndrew Geissler         "member='InterfacesAdded',path='/xyz/openbmc_project/software'",
42686adcd6dSAndrew Geissler         callback);
4274cde5d90SJames Feist 
42859d494eeSPatrick Williams     fwUpdateErrorMatcher = std::make_unique<sdbusplus::bus::match_t>(
4294cde5d90SJames Feist         *crow::connections::systemBus,
430e1cc4828SBrian Ma         "interface='org.freedesktop.DBus.ObjectManager',type='signal',"
431e1cc4828SBrian Ma         "member='InterfacesAdded',"
432e1cc4828SBrian Ma         "path='/xyz/openbmc_project/logging'",
4338549b951SMyung Bae         std::bind_front(afterUpdateErrorMatcher, asyncResp, url));
43486adcd6dSAndrew Geissler }
435729dae72SJennifer Lee 
436*f86bcc87SEd Tanous struct TftpUrl
437*f86bcc87SEd Tanous {
438*f86bcc87SEd Tanous     std::string fwFile;
439*f86bcc87SEd Tanous     std::string tftpServer;
440*f86bcc87SEd Tanous };
441*f86bcc87SEd Tanous 
442*f86bcc87SEd Tanous inline std::optional<TftpUrl>
443*f86bcc87SEd Tanous     parseTftpUrl(std::string imageURI,
444*f86bcc87SEd Tanous                  std::optional<std::string> transferProtocol,
445*f86bcc87SEd Tanous                  crow::Response& res)
446*f86bcc87SEd Tanous {
447*f86bcc87SEd Tanous     if (imageURI.find("://") == std::string::npos)
448*f86bcc87SEd Tanous     {
449*f86bcc87SEd Tanous         if (imageURI.starts_with("/"))
450*f86bcc87SEd Tanous         {
451*f86bcc87SEd Tanous             messages::actionParameterValueTypeError(
452*f86bcc87SEd Tanous                 res, imageURI, "ImageURI", "UpdateService.SimpleUpdate");
453*f86bcc87SEd Tanous             return std::nullopt;
454*f86bcc87SEd Tanous         }
455*f86bcc87SEd Tanous         if (!transferProtocol)
456*f86bcc87SEd Tanous         {
457*f86bcc87SEd Tanous             messages::actionParameterValueTypeError(
458*f86bcc87SEd Tanous                 res, imageURI, "ImageURI", "UpdateService.SimpleUpdate");
459*f86bcc87SEd Tanous             return std::nullopt;
460*f86bcc87SEd Tanous         }
461*f86bcc87SEd Tanous         // OpenBMC currently only supports TFTP
462*f86bcc87SEd Tanous         if (*transferProtocol != "TFTP")
463*f86bcc87SEd Tanous         {
464*f86bcc87SEd Tanous             messages::actionParameterNotSupported(res, "TransferProtocol",
465*f86bcc87SEd Tanous                                                   *transferProtocol);
466*f86bcc87SEd Tanous             BMCWEB_LOG_ERROR("Request incorrect protocol parameter: {}",
467*f86bcc87SEd Tanous                              *transferProtocol);
468*f86bcc87SEd Tanous             return std::nullopt;
469*f86bcc87SEd Tanous         }
470*f86bcc87SEd Tanous         imageURI = "tftp://" + imageURI;
471*f86bcc87SEd Tanous     }
472*f86bcc87SEd Tanous 
473*f86bcc87SEd Tanous     boost::system::result<boost::urls::url> url =
474*f86bcc87SEd Tanous         boost::urls::parse_absolute_uri(imageURI);
475*f86bcc87SEd Tanous     if (!url)
476*f86bcc87SEd Tanous     {
477*f86bcc87SEd Tanous         messages::actionParameterValueTypeError(res, imageURI, "ImageURI",
478*f86bcc87SEd Tanous                                                 "UpdateService.SimpleUpdate");
479*f86bcc87SEd Tanous 
480*f86bcc87SEd Tanous         return std::nullopt;
481*f86bcc87SEd Tanous     }
482*f86bcc87SEd Tanous     url->normalize();
483*f86bcc87SEd Tanous 
484*f86bcc87SEd Tanous     if (url->scheme() != "tftp")
485*f86bcc87SEd Tanous     {
486*f86bcc87SEd Tanous         messages::actionParameterNotSupported(res, "ImageURI", imageURI);
487*f86bcc87SEd Tanous         return std::nullopt;
488*f86bcc87SEd Tanous     }
489*f86bcc87SEd Tanous     std::string path(url->encoded_path());
490*f86bcc87SEd Tanous     if (path.size() < 2)
491*f86bcc87SEd Tanous     {
492*f86bcc87SEd Tanous         messages::actionParameterNotSupported(res, "ImageURI", imageURI);
493*f86bcc87SEd Tanous         return std::nullopt;
494*f86bcc87SEd Tanous     }
495*f86bcc87SEd Tanous     path.erase(0, 1);
496*f86bcc87SEd Tanous     std::string host(url->encoded_host_and_port());
497*f86bcc87SEd Tanous     return TftpUrl{path, host};
498*f86bcc87SEd Tanous }
499*f86bcc87SEd Tanous 
5000554c984SAndrew Geissler /**
5010554c984SAndrew Geissler  * UpdateServiceActionsSimpleUpdate class supports handle POST method for
5020554c984SAndrew Geissler  * SimpleUpdate action.
5030554c984SAndrew Geissler  */
5047e860f15SJohn Edward Broadbent inline void requestRoutesUpdateServiceActionsSimpleUpdate(App& app)
5050554c984SAndrew Geissler {
5067e860f15SJohn Edward Broadbent     BMCWEB_ROUTE(
5077e860f15SJohn Edward Broadbent         app, "/redfish/v1/UpdateService/Actions/UpdateService.SimpleUpdate/")
508ed398213SEd Tanous         .privileges(redfish::privileges::postUpdateService)
509002d39b4SEd Tanous         .methods(boost::beast::http::verb::post)(
510002d39b4SEd Tanous             [&app](const crow::Request& req,
5117e860f15SJohn Edward Broadbent                    const std::shared_ptr<bmcweb::AsyncResp>& asyncResp) {
5123ba00073SCarson Labrado         if (!redfish::setUpRedfishRoute(app, req, asyncResp))
51345ca1b86SEd Tanous         {
51445ca1b86SEd Tanous             return;
51545ca1b86SEd Tanous         }
51645ca1b86SEd Tanous 
5170554c984SAndrew Geissler         std::optional<std::string> transferProtocol;
5180554c984SAndrew Geissler         std::string imageURI;
5190554c984SAndrew Geissler 
52062598e31SEd Tanous         BMCWEB_LOG_DEBUG("Enter UpdateService.SimpleUpdate doPost");
5210554c984SAndrew Geissler 
5220554c984SAndrew Geissler         // User can pass in both TransferProtocol and ImageURI parameters or
5234e0453b1SGunnar Mills         // they can pass in just the ImageURI with the transfer protocol
5244e0453b1SGunnar Mills         // embedded within it.
5250554c984SAndrew Geissler         // 1) TransferProtocol:TFTP ImageURI:1.1.1.1/myfile.bin
5260554c984SAndrew Geissler         // 2) ImageURI:tftp://1.1.1.1/myfile.bin
5270554c984SAndrew Geissler 
528002d39b4SEd Tanous         if (!json_util::readJsonAction(req, asyncResp->res, "TransferProtocol",
529002d39b4SEd Tanous                                        transferProtocol, "ImageURI", imageURI))
5300554c984SAndrew Geissler         {
53162598e31SEd Tanous             BMCWEB_LOG_DEBUG("Missing TransferProtocol or ImageURI parameter");
5320554c984SAndrew Geissler             return;
5330554c984SAndrew Geissler         }
534*f86bcc87SEd Tanous         std::optional<TftpUrl> ret = parseTftpUrl(imageURI, transferProtocol,
535*f86bcc87SEd Tanous                                                   asyncResp->res);
536*f86bcc87SEd Tanous         if (!ret)
5370554c984SAndrew Geissler         {
5380554c984SAndrew Geissler             return;
5390554c984SAndrew Geissler         }
5400554c984SAndrew Geissler 
541*f86bcc87SEd Tanous         BMCWEB_LOG_DEBUG("Server: {} File: {}", ret->tftpServer, ret->fwFile);
5420554c984SAndrew Geissler 
5430554c984SAndrew Geissler         // Setup callback for when new software detected
5442618d5e3SGunnar Mills         // Give TFTP 10 minutes to complete
5454cde5d90SJames Feist         monitorForSoftwareAvailable(
546d7a596bdSAlbert Zhang             asyncResp, req,
5474cde5d90SJames Feist             "/redfish/v1/UpdateService/Actions/UpdateService.SimpleUpdate",
5482618d5e3SGunnar Mills             600);
5490554c984SAndrew Geissler 
5502618d5e3SGunnar Mills         // TFTP can take up to 10 minutes depending on image size and
5510554c984SAndrew Geissler         // connection speed. Return to caller as soon as the TFTP operation
5520554c984SAndrew Geissler         // has been started. The callback above will ensure the activate
5530554c984SAndrew Geissler         // is started once the download has completed
5540554c984SAndrew Geissler         redfish::messages::success(asyncResp->res);
5550554c984SAndrew Geissler 
5560554c984SAndrew Geissler         // Call TFTP service
5570554c984SAndrew Geissler         crow::connections::systemBus->async_method_call(
5585e7e2dc5SEd Tanous             [](const boost::system::error_code& ec) {
5590554c984SAndrew Geissler             if (ec)
5600554c984SAndrew Geissler             {
5610554c984SAndrew Geissler                 // messages::internalError(asyncResp->res);
5620554c984SAndrew Geissler                 cleanUp();
56362598e31SEd Tanous                 BMCWEB_LOG_DEBUG("error_code = {}", ec);
56462598e31SEd Tanous                 BMCWEB_LOG_DEBUG("error msg = {}", ec.message());
5650554c984SAndrew Geissler             }
5660554c984SAndrew Geissler             else
5670554c984SAndrew Geissler             {
56862598e31SEd Tanous                 BMCWEB_LOG_DEBUG("Call to DownloaViaTFTP Success");
5690554c984SAndrew Geissler             }
5700554c984SAndrew Geissler         },
5710554c984SAndrew Geissler             "xyz.openbmc_project.Software.Download",
572002d39b4SEd Tanous             "/xyz/openbmc_project/software", "xyz.openbmc_project.Common.TFTP",
573*f86bcc87SEd Tanous             "DownloadViaTFTP", ret->fwFile, ret->tftpServer);
5740554c984SAndrew Geissler 
57562598e31SEd Tanous         BMCWEB_LOG_DEBUG("Exit UpdateService.SimpleUpdate doPost");
5767e860f15SJohn Edward Broadbent     });
577729dae72SJennifer Lee }
578729dae72SJennifer Lee 
5790ed80c8cSGeorge Liu inline void uploadImageFile(crow::Response& res, std::string_view body)
5800ed80c8cSGeorge Liu {
5812c6ffdb0SEd Tanous     std::filesystem::path filepath("/tmp/images/" + bmcweb::getRandomUUID());
5822c6ffdb0SEd Tanous 
58362598e31SEd Tanous     BMCWEB_LOG_DEBUG("Writing file to {}", filepath.string());
5840ed80c8cSGeorge Liu     std::ofstream out(filepath, std::ofstream::out | std::ofstream::binary |
5850ed80c8cSGeorge Liu                                     std::ofstream::trunc);
5860ed80c8cSGeorge Liu     // set the permission of the file to 640
58789492a15SPatrick Williams     std::filesystem::perms permission = std::filesystem::perms::owner_read |
58889492a15SPatrick Williams                                         std::filesystem::perms::group_read;
5890ed80c8cSGeorge Liu     std::filesystem::permissions(filepath, permission);
5900ed80c8cSGeorge Liu     out << body;
5910ed80c8cSGeorge Liu 
5920ed80c8cSGeorge Liu     if (out.bad())
5930ed80c8cSGeorge Liu     {
5940ed80c8cSGeorge Liu         messages::internalError(res);
5950ed80c8cSGeorge Liu         cleanUp();
5960ed80c8cSGeorge Liu     }
5970ed80c8cSGeorge Liu }
5980ed80c8cSGeorge Liu 
5990ed80c8cSGeorge Liu inline void setApplyTime(const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
6000ed80c8cSGeorge Liu                          const std::string& applyTime)
6010ed80c8cSGeorge Liu {
6020ed80c8cSGeorge Liu     std::string applyTimeNewVal;
6030ed80c8cSGeorge Liu     if (applyTime == "Immediate")
6040ed80c8cSGeorge Liu     {
6050ed80c8cSGeorge Liu         applyTimeNewVal =
6060ed80c8cSGeorge Liu             "xyz.openbmc_project.Software.ApplyTime.RequestedApplyTimes.Immediate";
6070ed80c8cSGeorge Liu     }
6080ed80c8cSGeorge Liu     else if (applyTime == "OnReset")
6090ed80c8cSGeorge Liu     {
6100ed80c8cSGeorge Liu         applyTimeNewVal =
6110ed80c8cSGeorge Liu             "xyz.openbmc_project.Software.ApplyTime.RequestedApplyTimes.OnReset";
6120ed80c8cSGeorge Liu     }
6130ed80c8cSGeorge Liu     else
6140ed80c8cSGeorge Liu     {
61562598e31SEd Tanous         BMCWEB_LOG_INFO(
61662598e31SEd Tanous             "ApplyTime value is not in the list of acceptable values");
6170ed80c8cSGeorge Liu         messages::propertyValueNotInList(asyncResp->res, applyTime,
6180ed80c8cSGeorge Liu                                          "ApplyTime");
6190ed80c8cSGeorge Liu         return;
6200ed80c8cSGeorge Liu     }
6210ed80c8cSGeorge Liu 
6220ed80c8cSGeorge Liu     // Set the requested image apply time value
6239ae226faSGeorge Liu     sdbusplus::asio::setProperty(
6249ae226faSGeorge Liu         *crow::connections::systemBus, "xyz.openbmc_project.Settings",
6259ae226faSGeorge Liu         "/xyz/openbmc_project/software/apply_time",
6269ae226faSGeorge Liu         "xyz.openbmc_project.Software.ApplyTime", "RequestedApplyTime",
6279ae226faSGeorge Liu         applyTimeNewVal, [asyncResp](const boost::system::error_code& ec) {
6280ed80c8cSGeorge Liu         if (ec)
6290ed80c8cSGeorge Liu         {
63062598e31SEd Tanous             BMCWEB_LOG_ERROR("D-Bus responses error: {}", ec);
6310ed80c8cSGeorge Liu             messages::internalError(asyncResp->res);
6320ed80c8cSGeorge Liu             return;
6330ed80c8cSGeorge Liu         }
6340ed80c8cSGeorge Liu         messages::success(asyncResp->res);
6359ae226faSGeorge Liu     });
6360ed80c8cSGeorge Liu }
6370ed80c8cSGeorge Liu 
6380ed80c8cSGeorge Liu inline void
6390ed80c8cSGeorge Liu     updateMultipartContext(const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
6400ed80c8cSGeorge Liu                            const MultipartParser& parser)
6410ed80c8cSGeorge Liu {
6420ed80c8cSGeorge Liu     const std::string* uploadData = nullptr;
6430ed80c8cSGeorge Liu     std::optional<std::string> applyTime = "OnReset";
6440ed80c8cSGeorge Liu     bool targetFound = false;
6450ed80c8cSGeorge Liu     for (const FormPart& formpart : parser.mime_fields)
6460ed80c8cSGeorge Liu     {
6470ed80c8cSGeorge Liu         boost::beast::http::fields::const_iterator it =
6480ed80c8cSGeorge Liu             formpart.fields.find("Content-Disposition");
6490ed80c8cSGeorge Liu         if (it == formpart.fields.end())
6500ed80c8cSGeorge Liu         {
65162598e31SEd Tanous             BMCWEB_LOG_ERROR("Couldn't find Content-Disposition");
6520ed80c8cSGeorge Liu             return;
6530ed80c8cSGeorge Liu         }
65462598e31SEd Tanous         BMCWEB_LOG_INFO("Parsing value {}", it->value());
6550ed80c8cSGeorge Liu 
6560ed80c8cSGeorge Liu         // The construction parameters of param_list must start with `;`
6570ed80c8cSGeorge Liu         size_t index = it->value().find(';');
6580ed80c8cSGeorge Liu         if (index == std::string::npos)
6590ed80c8cSGeorge Liu         {
6600ed80c8cSGeorge Liu             continue;
6610ed80c8cSGeorge Liu         }
6620ed80c8cSGeorge Liu 
66389492a15SPatrick Williams         for (const auto& param :
6640ed80c8cSGeorge Liu              boost::beast::http::param_list{it->value().substr(index)})
6650ed80c8cSGeorge Liu         {
6660ed80c8cSGeorge Liu             if (param.first != "name" || param.second.empty())
6670ed80c8cSGeorge Liu             {
6680ed80c8cSGeorge Liu                 continue;
6690ed80c8cSGeorge Liu             }
6700ed80c8cSGeorge Liu 
6710ed80c8cSGeorge Liu             if (param.second == "UpdateParameters")
6720ed80c8cSGeorge Liu             {
6730ed80c8cSGeorge Liu                 std::vector<std::string> targets;
6740ed80c8cSGeorge Liu                 nlohmann::json content =
6750ed80c8cSGeorge Liu                     nlohmann::json::parse(formpart.content);
6760ed80c8cSGeorge Liu                 if (!json_util::readJson(content, asyncResp->res, "Targets",
6770ed80c8cSGeorge Liu                                          targets, "@Redfish.OperationApplyTime",
6780ed80c8cSGeorge Liu                                          applyTime))
6790ed80c8cSGeorge Liu                 {
6800ed80c8cSGeorge Liu                     return;
6810ed80c8cSGeorge Liu                 }
6820ed80c8cSGeorge Liu                 if (targets.size() != 1)
6830ed80c8cSGeorge Liu                 {
6840ed80c8cSGeorge Liu                     messages::propertyValueFormatError(asyncResp->res,
6850ed80c8cSGeorge Liu                                                        "Targets", "");
6860ed80c8cSGeorge Liu                     return;
6870ed80c8cSGeorge Liu                 }
6880ed80c8cSGeorge Liu                 if (targets[0] != "/redfish/v1/Managers/bmc")
6890ed80c8cSGeorge Liu                 {
6900ed80c8cSGeorge Liu                     messages::propertyValueNotInList(asyncResp->res,
6910ed80c8cSGeorge Liu                                                      "Targets/0", targets[0]);
6920ed80c8cSGeorge Liu                     return;
6930ed80c8cSGeorge Liu                 }
6940ed80c8cSGeorge Liu                 targetFound = true;
6950ed80c8cSGeorge Liu             }
6960ed80c8cSGeorge Liu             else if (param.second == "UpdateFile")
6970ed80c8cSGeorge Liu             {
6980ed80c8cSGeorge Liu                 uploadData = &(formpart.content);
6990ed80c8cSGeorge Liu             }
7000ed80c8cSGeorge Liu         }
7010ed80c8cSGeorge Liu     }
7020ed80c8cSGeorge Liu 
7030ed80c8cSGeorge Liu     if (uploadData == nullptr)
7040ed80c8cSGeorge Liu     {
70562598e31SEd Tanous         BMCWEB_LOG_ERROR("Upload data is NULL");
7060ed80c8cSGeorge Liu         messages::propertyMissing(asyncResp->res, "UpdateFile");
7070ed80c8cSGeorge Liu         return;
7080ed80c8cSGeorge Liu     }
7090ed80c8cSGeorge Liu     if (!targetFound)
7100ed80c8cSGeorge Liu     {
7110ed80c8cSGeorge Liu         messages::propertyMissing(asyncResp->res, "targets");
7120ed80c8cSGeorge Liu         return;
7130ed80c8cSGeorge Liu     }
7140ed80c8cSGeorge Liu 
7150ed80c8cSGeorge Liu     setApplyTime(asyncResp, *applyTime);
7160ed80c8cSGeorge Liu 
7170ed80c8cSGeorge Liu     uploadImageFile(asyncResp->res, *uploadData);
7180ed80c8cSGeorge Liu }
7190ed80c8cSGeorge Liu 
720c2051d11SEd Tanous inline void
721c2051d11SEd Tanous     handleUpdateServicePost(App& app, const crow::Request& req,
722c2051d11SEd Tanous                             const std::shared_ptr<bmcweb::AsyncResp>& asyncResp)
723c2051d11SEd Tanous {
7243ba00073SCarson Labrado     if (!redfish::setUpRedfishRoute(app, req, asyncResp))
725c2051d11SEd Tanous     {
726c2051d11SEd Tanous         return;
727c2051d11SEd Tanous     }
728b33a4327SNinad Palsule     std::string_view contentType = req.getHeaderValue("Content-Type");
729b33a4327SNinad Palsule 
73062598e31SEd Tanous     BMCWEB_LOG_DEBUG("doPost: contentType={}", contentType);
731b33a4327SNinad Palsule 
732b33a4327SNinad Palsule     // Make sure that content type is application/octet-stream or
733b33a4327SNinad Palsule     // multipart/form-data
734b33a4327SNinad Palsule     if (boost::iequals(contentType, "application/octet-stream"))
735b33a4327SNinad Palsule     {
736b33a4327SNinad Palsule         // Setup callback for when new software detected
737b33a4327SNinad Palsule         monitorForSoftwareAvailable(asyncResp, req,
738b33a4327SNinad Palsule                                     "/redfish/v1/UpdateService");
739b33a4327SNinad Palsule 
740b33a4327SNinad Palsule         uploadImageFile(asyncResp->res, req.body());
741b33a4327SNinad Palsule     }
742b33a4327SNinad Palsule     else if (contentType.starts_with("multipart/form-data"))
743b33a4327SNinad Palsule     {
744b33a4327SNinad Palsule         MultipartParser parser;
745c2051d11SEd Tanous 
746c2051d11SEd Tanous         // Setup callback for when new software detected
747b33a4327SNinad Palsule         monitorForSoftwareAvailable(asyncResp, req,
748b33a4327SNinad Palsule                                     "/redfish/v1/UpdateService");
749c2051d11SEd Tanous 
7500ed80c8cSGeorge Liu         ParserError ec = parser.parse(req);
7510ed80c8cSGeorge Liu         if (ec != ParserError::PARSER_SUCCESS)
7520ed80c8cSGeorge Liu         {
7530ed80c8cSGeorge Liu             // handle error
75462598e31SEd Tanous             BMCWEB_LOG_ERROR("MIME parse failed, ec : {}",
75562598e31SEd Tanous                              static_cast<int>(ec));
7560ed80c8cSGeorge Liu             messages::internalError(asyncResp->res);
7570ed80c8cSGeorge Liu             return;
7580ed80c8cSGeorge Liu         }
7590ed80c8cSGeorge Liu         updateMultipartContext(asyncResp, parser);
760c2051d11SEd Tanous     }
761b33a4327SNinad Palsule     else
762b33a4327SNinad Palsule     {
76362598e31SEd Tanous         BMCWEB_LOG_DEBUG("Bad content type specified:{}", contentType);
764b33a4327SNinad Palsule         asyncResp->res.result(boost::beast::http::status::bad_request);
765b33a4327SNinad Palsule     }
766b33a4327SNinad Palsule }
767c2051d11SEd Tanous 
7687e860f15SJohn Edward Broadbent inline void requestRoutesUpdateService(App& app)
7691abe55efSEd Tanous {
7707e860f15SJohn Edward Broadbent     BMCWEB_ROUTE(app, "/redfish/v1/UpdateService/")
771ed398213SEd Tanous         .privileges(redfish::privileges::getUpdateService)
772002d39b4SEd Tanous         .methods(boost::beast::http::verb::get)(
773002d39b4SEd Tanous             [&app](const crow::Request& req,
774002d39b4SEd Tanous                    const std::shared_ptr<bmcweb::AsyncResp>& asyncResp) {
7753ba00073SCarson Labrado         if (!redfish::setUpRedfishRoute(app, req, asyncResp))
77645ca1b86SEd Tanous         {
77745ca1b86SEd Tanous             return;
77845ca1b86SEd Tanous         }
7798d1b46d7Szhanghch05         asyncResp->res.jsonValue["@odata.type"] =
7800ed80c8cSGeorge Liu             "#UpdateService.v1_11_1.UpdateService";
7818d1b46d7Szhanghch05         asyncResp->res.jsonValue["@odata.id"] = "/redfish/v1/UpdateService";
7828d1b46d7Szhanghch05         asyncResp->res.jsonValue["Id"] = "UpdateService";
783002d39b4SEd Tanous         asyncResp->res.jsonValue["Description"] = "Service for Software Update";
7848d1b46d7Szhanghch05         asyncResp->res.jsonValue["Name"] = "Update Service";
7854dc23f3fSEd Tanous 
7867e860f15SJohn Edward Broadbent         asyncResp->res.jsonValue["HttpPushUri"] =
7874dc23f3fSEd Tanous             "/redfish/v1/UpdateService/update";
7880ed80c8cSGeorge Liu         asyncResp->res.jsonValue["MultipartHttpPushUri"] =
7890ed80c8cSGeorge Liu             "/redfish/v1/UpdateService/update";
7904dc23f3fSEd Tanous 
7910f74e643SEd Tanous         // UpdateService cannot be disabled
7928d1b46d7Szhanghch05         asyncResp->res.jsonValue["ServiceEnabled"] = true;
7931476687dSEd Tanous         asyncResp->res.jsonValue["FirmwareInventory"]["@odata.id"] =
7941476687dSEd Tanous             "/redfish/v1/UpdateService/FirmwareInventory";
795d61e5194STejas Patil         // Get the MaxImageSizeBytes
796d61e5194STejas Patil         asyncResp->res.jsonValue["MaxImageSizeBytes"] =
797d61e5194STejas Patil             bmcwebHttpReqBodyLimitMb * 1024 * 1024;
798d61e5194STejas Patil 
7990554c984SAndrew Geissler #ifdef BMCWEB_INSECURE_ENABLE_REDFISH_FW_TFTP_UPDATE
8000554c984SAndrew Geissler         // Update Actions object.
8010554c984SAndrew Geissler         nlohmann::json& updateSvcSimpleUpdate =
802002d39b4SEd Tanous             asyncResp->res.jsonValue["Actions"]["#UpdateService.SimpleUpdate"];
8030554c984SAndrew Geissler         updateSvcSimpleUpdate["target"] =
8040554c984SAndrew Geissler             "/redfish/v1/UpdateService/Actions/UpdateService.SimpleUpdate";
805002d39b4SEd Tanous         updateSvcSimpleUpdate["TransferProtocol@Redfish.AllowableValues"] = {
806002d39b4SEd Tanous             "TFTP"};
8070554c984SAndrew Geissler #endif
808274dfe62SJayashankar Padath         // Get the current ApplyTime value
8091e1e598dSJonathan Doman         sdbusplus::asio::getProperty<std::string>(
8101e1e598dSJonathan Doman             *crow::connections::systemBus, "xyz.openbmc_project.Settings",
8111e1e598dSJonathan Doman             "/xyz/openbmc_project/software/apply_time",
8121e1e598dSJonathan Doman             "xyz.openbmc_project.Software.ApplyTime", "RequestedApplyTime",
8135e7e2dc5SEd Tanous             [asyncResp](const boost::system::error_code& ec,
8141e1e598dSJonathan Doman                         const std::string& applyTime) {
815274dfe62SJayashankar Padath             if (ec)
816274dfe62SJayashankar Padath             {
81762598e31SEd Tanous                 BMCWEB_LOG_DEBUG("DBUS response error {}", ec);
8188d1b46d7Szhanghch05                 messages::internalError(asyncResp->res);
819274dfe62SJayashankar Padath                 return;
820274dfe62SJayashankar Padath             }
821274dfe62SJayashankar Padath 
822274dfe62SJayashankar Padath             // Store the ApplyTime Value
8231e1e598dSJonathan Doman             if (applyTime == "xyz.openbmc_project.Software.ApplyTime."
8241e1e598dSJonathan Doman                              "RequestedApplyTimes.Immediate")
825274dfe62SJayashankar Padath             {
826002d39b4SEd Tanous                 asyncResp->res.jsonValue["HttpPushUriOptions"]
8277e860f15SJohn Edward Broadbent                                         ["HttpPushUriApplyTime"]["ApplyTime"] =
8287e860f15SJohn Edward Broadbent                     "Immediate";
829274dfe62SJayashankar Padath             }
830002d39b4SEd Tanous             else if (applyTime == "xyz.openbmc_project.Software.ApplyTime."
8311e1e598dSJonathan Doman                                   "RequestedApplyTimes.OnReset")
832274dfe62SJayashankar Padath             {
833002d39b4SEd Tanous                 asyncResp->res.jsonValue["HttpPushUriOptions"]
8347e860f15SJohn Edward Broadbent                                         ["HttpPushUriApplyTime"]["ApplyTime"] =
8357e860f15SJohn Edward Broadbent                     "OnReset";
836274dfe62SJayashankar Padath             }
8371e1e598dSJonathan Doman         });
8387e860f15SJohn Edward Broadbent     });
8397e860f15SJohn Edward Broadbent     BMCWEB_ROUTE(app, "/redfish/v1/UpdateService/")
840ed398213SEd Tanous         .privileges(redfish::privileges::patchUpdateService)
841002d39b4SEd Tanous         .methods(boost::beast::http::verb::patch)(
842002d39b4SEd Tanous             [&app](const crow::Request& req,
843002d39b4SEd Tanous                    const std::shared_ptr<bmcweb::AsyncResp>& asyncResp) {
8443ba00073SCarson Labrado         if (!redfish::setUpRedfishRoute(app, req, asyncResp))
84545ca1b86SEd Tanous         {
84645ca1b86SEd Tanous             return;
84745ca1b86SEd Tanous         }
84862598e31SEd Tanous         BMCWEB_LOG_DEBUG("doPatch...");
849fa1a5a38SJayashankar Padath 
850274dfe62SJayashankar Padath         std::optional<nlohmann::json> pushUriOptions;
851002d39b4SEd Tanous         if (!json_util::readJsonPatch(req, asyncResp->res, "HttpPushUriOptions",
852002d39b4SEd Tanous                                       pushUriOptions))
853fa1a5a38SJayashankar Padath         {
854fa1a5a38SJayashankar Padath             return;
855fa1a5a38SJayashankar Padath         }
856fa1a5a38SJayashankar Padath 
857274dfe62SJayashankar Padath         if (pushUriOptions)
858274dfe62SJayashankar Padath         {
859274dfe62SJayashankar Padath             std::optional<nlohmann::json> pushUriApplyTime;
8608d1b46d7Szhanghch05             if (!json_util::readJson(*pushUriOptions, asyncResp->res,
861002d39b4SEd Tanous                                      "HttpPushUriApplyTime", pushUriApplyTime))
862274dfe62SJayashankar Padath             {
863274dfe62SJayashankar Padath                 return;
864274dfe62SJayashankar Padath             }
865274dfe62SJayashankar Padath 
866274dfe62SJayashankar Padath             if (pushUriApplyTime)
867274dfe62SJayashankar Padath             {
868274dfe62SJayashankar Padath                 std::optional<std::string> applyTime;
8690fda0f12SGeorge Liu                 if (!json_util::readJson(*pushUriApplyTime, asyncResp->res,
8700fda0f12SGeorge Liu                                          "ApplyTime", applyTime))
871274dfe62SJayashankar Padath                 {
872274dfe62SJayashankar Padath                     return;
873274dfe62SJayashankar Padath                 }
874274dfe62SJayashankar Padath 
875274dfe62SJayashankar Padath                 if (applyTime)
876fa1a5a38SJayashankar Padath                 {
8770ed80c8cSGeorge Liu                     setApplyTime(asyncResp, *applyTime);
878fa1a5a38SJayashankar Padath                 }
879274dfe62SJayashankar Padath             }
880fa1a5a38SJayashankar Padath         }
8817e860f15SJohn Edward Broadbent     });
882c2051d11SEd Tanous 
8834dc23f3fSEd Tanous     BMCWEB_ROUTE(app, "/redfish/v1/UpdateService/update/")
8844dc23f3fSEd Tanous         .privileges(redfish::privileges::postUpdateService)
8857e860f15SJohn Edward Broadbent         .methods(boost::beast::http::verb::post)(
886c2051d11SEd Tanous             std::bind_front(handleUpdateServicePost, std::ref(app)));
887729dae72SJennifer Lee }
888729dae72SJennifer Lee 
8897e860f15SJohn Edward Broadbent inline void requestRoutesSoftwareInventoryCollection(App& app)
8901abe55efSEd Tanous {
8917e860f15SJohn Edward Broadbent     BMCWEB_ROUTE(app, "/redfish/v1/UpdateService/FirmwareInventory/")
892ed398213SEd Tanous         .privileges(redfish::privileges::getSoftwareInventoryCollection)
8931476687dSEd Tanous         .methods(boost::beast::http::verb::get)(
8941476687dSEd Tanous             [&app](const crow::Request& req,
8951476687dSEd Tanous                    const std::shared_ptr<bmcweb::AsyncResp>& asyncResp) {
8963ba00073SCarson Labrado         if (!redfish::setUpRedfishRoute(app, req, asyncResp))
89745ca1b86SEd Tanous         {
89845ca1b86SEd Tanous             return;
89945ca1b86SEd Tanous         }
9008d1b46d7Szhanghch05         asyncResp->res.jsonValue["@odata.type"] =
9010f74e643SEd Tanous             "#SoftwareInventoryCollection.SoftwareInventoryCollection";
9028d1b46d7Szhanghch05         asyncResp->res.jsonValue["@odata.id"] =
9030f74e643SEd Tanous             "/redfish/v1/UpdateService/FirmwareInventory";
904002d39b4SEd Tanous         asyncResp->res.jsonValue["Name"] = "Software Inventory Collection";
90508d81adaSJohn Edward Broadbent         const std::array<const std::string_view, 1> iface = {
906e99073f5SGeorge Liu             "xyz.openbmc_project.Software.Version"};
9076c4eb9deSJennifer Lee 
90808d81adaSJohn Edward Broadbent         redfish::collection_util::getCollectionMembers(
90908d81adaSJohn Edward Broadbent             asyncResp,
91008d81adaSJohn Edward Broadbent             boost::urls::url("/redfish/v1/UpdateService/FirmwareInventory"),
91108d81adaSJohn Edward Broadbent             iface, "/xyz/openbmc_project/software");
9127e860f15SJohn Edward Broadbent     });
913729dae72SJennifer Lee }
91487d84729SAndrew Geissler /* Fill related item links (i.e. bmc, bios) in for inventory */
9157e860f15SJohn Edward Broadbent inline static void
916ac106bf6SEd Tanous     getRelatedItems(const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
91787d84729SAndrew Geissler                     const std::string& purpose)
91887d84729SAndrew Geissler {
919eee0013eSWilly Tu     if (purpose == sw_util::bmcPurpose)
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/Managers/bmc";
924b2ba3072SPatrick Williams         relatedItem.emplace_back(std::move(item));
925ac106bf6SEd Tanous         asyncResp->res.jsonValue["RelatedItem@odata.count"] =
926ac106bf6SEd Tanous             relatedItem.size();
92787d84729SAndrew Geissler     }
928eee0013eSWilly Tu     else if (purpose == sw_util::biosPurpose)
92987d84729SAndrew Geissler     {
930ac106bf6SEd Tanous         nlohmann::json& relatedItem = asyncResp->res.jsonValue["RelatedItem"];
9311476687dSEd Tanous         nlohmann::json::object_t item;
9321476687dSEd Tanous         item["@odata.id"] = "/redfish/v1/Systems/system/Bios";
933b2ba3072SPatrick Williams         relatedItem.emplace_back(std::move(item));
934ac106bf6SEd Tanous         asyncResp->res.jsonValue["RelatedItem@odata.count"] =
935ac106bf6SEd Tanous             relatedItem.size();
93687d84729SAndrew Geissler     }
93787d84729SAndrew Geissler     else
93887d84729SAndrew Geissler     {
939bf2ddedeSCarson Labrado         BMCWEB_LOG_DEBUG("Unknown software purpose {}", purpose);
94087d84729SAndrew Geissler     }
94187d84729SAndrew Geissler }
94287d84729SAndrew Geissler 
943af24660dSWilly Tu inline void
944af24660dSWilly Tu     getSoftwareVersion(const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
945af24660dSWilly Tu                        const std::string& service, const std::string& path,
946af24660dSWilly Tu                        const std::string& swId)
947af24660dSWilly Tu {
948d1bde9e5SKrzysztof Grobelny     sdbusplus::asio::getAllProperties(
949d1bde9e5SKrzysztof Grobelny         *crow::connections::systemBus, service, path,
950d1bde9e5SKrzysztof Grobelny         "xyz.openbmc_project.Software.Version",
951af24660dSWilly Tu         [asyncResp,
9528b24275dSEd Tanous          swId](const boost::system::error_code& ec,
953af24660dSWilly Tu                const dbus::utility::DBusPropertiesMap& propertiesList) {
9548b24275dSEd Tanous         if (ec)
955af24660dSWilly Tu         {
956af24660dSWilly Tu             messages::internalError(asyncResp->res);
957af24660dSWilly Tu             return;
958af24660dSWilly Tu         }
959d1bde9e5SKrzysztof Grobelny 
960af24660dSWilly Tu         const std::string* swInvPurpose = nullptr;
961af24660dSWilly Tu         const std::string* version = nullptr;
962d1bde9e5SKrzysztof Grobelny 
963d1bde9e5SKrzysztof Grobelny         const bool success = sdbusplus::unpackPropertiesNoThrow(
964d1bde9e5SKrzysztof Grobelny             dbus_utils::UnpackErrorPrinter(), propertiesList, "Purpose",
965d1bde9e5SKrzysztof Grobelny             swInvPurpose, "Version", version);
966d1bde9e5SKrzysztof Grobelny 
967d1bde9e5SKrzysztof Grobelny         if (!success)
968af24660dSWilly Tu         {
969d1bde9e5SKrzysztof Grobelny             messages::internalError(asyncResp->res);
970d1bde9e5SKrzysztof Grobelny             return;
971af24660dSWilly Tu         }
972af24660dSWilly Tu 
973af24660dSWilly Tu         if (swInvPurpose == nullptr)
974af24660dSWilly Tu         {
97562598e31SEd Tanous             BMCWEB_LOG_DEBUG("Can't find property \"Purpose\"!");
976af24660dSWilly Tu             messages::internalError(asyncResp->res);
977af24660dSWilly Tu             return;
978af24660dSWilly Tu         }
979af24660dSWilly Tu 
98062598e31SEd Tanous         BMCWEB_LOG_DEBUG("swInvPurpose = {}", *swInvPurpose);
981af24660dSWilly Tu 
982af24660dSWilly Tu         if (version == nullptr)
983af24660dSWilly Tu         {
98462598e31SEd Tanous             BMCWEB_LOG_DEBUG("Can't find property \"Version\"!");
985af24660dSWilly Tu 
986af24660dSWilly Tu             messages::internalError(asyncResp->res);
987af24660dSWilly Tu 
988af24660dSWilly Tu             return;
989af24660dSWilly Tu         }
990af24660dSWilly Tu         asyncResp->res.jsonValue["Version"] = *version;
991af24660dSWilly Tu         asyncResp->res.jsonValue["Id"] = swId;
992af24660dSWilly Tu 
993af24660dSWilly Tu         // swInvPurpose is of format:
994af24660dSWilly Tu         // xyz.openbmc_project.Software.Version.VersionPurpose.ABC
995af24660dSWilly Tu         // Translate this to "ABC image"
996af24660dSWilly Tu         size_t endDesc = swInvPurpose->rfind('.');
997af24660dSWilly Tu         if (endDesc == std::string::npos)
998af24660dSWilly Tu         {
999af24660dSWilly Tu             messages::internalError(asyncResp->res);
1000af24660dSWilly Tu             return;
1001af24660dSWilly Tu         }
1002af24660dSWilly Tu         endDesc++;
1003af24660dSWilly Tu         if (endDesc >= swInvPurpose->size())
1004af24660dSWilly Tu         {
1005af24660dSWilly Tu             messages::internalError(asyncResp->res);
1006af24660dSWilly Tu             return;
1007af24660dSWilly Tu         }
1008af24660dSWilly Tu 
1009af24660dSWilly Tu         std::string formatDesc = swInvPurpose->substr(endDesc);
1010af24660dSWilly Tu         asyncResp->res.jsonValue["Description"] = formatDesc + " image";
1011af24660dSWilly Tu         getRelatedItems(asyncResp, *swInvPurpose);
1012d1bde9e5SKrzysztof Grobelny     });
1013af24660dSWilly Tu }
1014af24660dSWilly Tu 
10157e860f15SJohn Edward Broadbent inline void requestRoutesSoftwareInventory(App& app)
10161abe55efSEd Tanous {
10177e860f15SJohn Edward Broadbent     BMCWEB_ROUTE(app, "/redfish/v1/UpdateService/FirmwareInventory/<str>/")
1018ed398213SEd Tanous         .privileges(redfish::privileges::getSoftwareInventory)
1019002d39b4SEd Tanous         .methods(boost::beast::http::verb::get)(
1020002d39b4SEd Tanous             [&app](const crow::Request& req,
102145ca1b86SEd Tanous                    const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
10227e860f15SJohn Edward Broadbent                    const std::string& param) {
10233ba00073SCarson Labrado         if (!redfish::setUpRedfishRoute(app, req, asyncResp))
102445ca1b86SEd Tanous         {
102545ca1b86SEd Tanous             return;
102645ca1b86SEd Tanous         }
10273ae837c9SEd Tanous         std::shared_ptr<std::string> swId =
10287e860f15SJohn Edward Broadbent             std::make_shared<std::string>(param);
1029c711bf86SEd Tanous 
1030ef4c65b7SEd Tanous         asyncResp->res.jsonValue["@odata.id"] = boost::urls::format(
1031ef4c65b7SEd Tanous             "/redfish/v1/UpdateService/FirmwareInventory/{}", *swId);
1032c711bf86SEd Tanous 
1033e99073f5SGeorge Liu         constexpr std::array<std::string_view, 1> interfaces = {
1034e99073f5SGeorge Liu             "xyz.openbmc_project.Software.Version"};
1035e99073f5SGeorge Liu         dbus::utility::getSubTree(
1036e99073f5SGeorge Liu             "/", 0, interfaces,
1037b9d36b47SEd Tanous             [asyncResp,
1038e99073f5SGeorge Liu              swId](const boost::system::error_code& ec,
1039b9d36b47SEd Tanous                    const dbus::utility::MapperGetSubTreeResponse& subtree) {
104062598e31SEd Tanous             BMCWEB_LOG_DEBUG("doGet callback...");
10411abe55efSEd Tanous             if (ec)
10421abe55efSEd Tanous             {
1043f12894f8SJason M. Bills                 messages::internalError(asyncResp->res);
10446c4eb9deSJennifer Lee                 return;
10456c4eb9deSJennifer Lee             }
10466c4eb9deSJennifer Lee 
10476913228dSAndrew Geissler             // Ensure we find our input swId, otherwise return an error
10486913228dSAndrew Geissler             bool found = false;
1049002d39b4SEd Tanous             for (const std::pair<std::string,
10507e860f15SJohn Edward Broadbent                                  std::vector<std::pair<
1051002d39b4SEd Tanous                                      std::string, std::vector<std::string>>>>&
1052002d39b4SEd Tanous                      obj : subtree)
10531abe55efSEd Tanous             {
105411ba3979SEd Tanous                 if (!obj.first.ends_with(*swId))
10551abe55efSEd Tanous                 {
1056acb7cfb4SJennifer Lee                     continue;
1057acb7cfb4SJennifer Lee                 }
1058acb7cfb4SJennifer Lee 
105926f6976fSEd Tanous                 if (obj.second.empty())
10601abe55efSEd Tanous                 {
1061acb7cfb4SJennifer Lee                     continue;
1062acb7cfb4SJennifer Lee                 }
10636c4eb9deSJennifer Lee 
10646913228dSAndrew Geissler                 found = true;
1065eee0013eSWilly Tu                 sw_util::getSwStatus(asyncResp, swId, obj.second[0].first);
1066af24660dSWilly Tu                 getSoftwareVersion(asyncResp, obj.second[0].first, obj.first,
1067af24660dSWilly Tu                                    *swId);
10686c4eb9deSJennifer Lee             }
10696913228dSAndrew Geissler             if (!found)
10706913228dSAndrew Geissler             {
107162598e31SEd Tanous                 BMCWEB_LOG_WARNING("Input swID {} not found!", *swId);
10726913228dSAndrew Geissler                 messages::resourceMissingAtURI(
1073ef4c65b7SEd Tanous                     asyncResp->res,
1074ef4c65b7SEd Tanous                     boost::urls::format(
1075ef4c65b7SEd Tanous                         "/redfish/v1/UpdateService/FirmwareInventory/{}",
1076ef4c65b7SEd Tanous                         *swId));
10776913228dSAndrew Geissler                 return;
10786913228dSAndrew Geissler             }
10794e68c45bSAyushi Smriti             asyncResp->res.jsonValue["@odata.type"] =
10804e68c45bSAyushi Smriti                 "#SoftwareInventory.v1_1_0.SoftwareInventory";
10814e68c45bSAyushi Smriti             asyncResp->res.jsonValue["Name"] = "Software Inventory";
10824e68c45bSAyushi Smriti             asyncResp->res.jsonValue["Status"]["HealthRollup"] = "OK";
10833f8a743aSAppaRao Puli 
10843f8a743aSAppaRao Puli             asyncResp->res.jsonValue["Updateable"] = false;
1085eee0013eSWilly Tu             sw_util::getSwUpdatableStatus(asyncResp, swId);
1086e99073f5SGeorge Liu         });
10877e860f15SJohn Edward Broadbent     });
10886c4eb9deSJennifer Lee }
1089729dae72SJennifer Lee 
1090729dae72SJennifer Lee } // namespace redfish
1091