xref: /openbmc/bmcweb/features/redfish/lib/update_service.hpp (revision d093c9961eeb6bdfcfa280b6a2bbbbef00e3fe59)
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"
223ccb3adbSEd Tanous #include "query.hpp"
233ccb3adbSEd Tanous #include "registries/privilege_registry.hpp"
24a8e884fcSEd Tanous #include "task.hpp"
253ccb3adbSEd Tanous #include "utils/dbus_utils.hpp"
263ccb3adbSEd Tanous #include "utils/sw_utils.hpp"
273ccb3adbSEd Tanous 
28*d093c996SEd Tanous #include <boost/algorithm/string/case_conv.hpp>
29e99073f5SGeorge Liu #include <boost/system/error_code.hpp>
301e1e598dSJonathan Doman #include <sdbusplus/asio/property.hpp>
313ccb3adbSEd Tanous #include <sdbusplus/bus/match.hpp>
32d1bde9e5SKrzysztof Grobelny #include <sdbusplus/unpack_properties.hpp>
331214b7e7SGunnar Mills 
342b73119cSGeorge Liu #include <array>
352b73119cSGeorge Liu #include <string_view>
362b73119cSGeorge Liu 
371abe55efSEd Tanous namespace redfish
381abe55efSEd Tanous {
3927826b5fSEd Tanous 
400e7de46fSAndrew Geissler // Match signals added on software path
41cf9e417dSEd Tanous // NOLINTNEXTLINE(cppcoreguidelines-avoid-non-const-global-variables)
4259d494eeSPatrick Williams static std::unique_ptr<sdbusplus::bus::match_t> fwUpdateMatcher;
43cf9e417dSEd Tanous // NOLINTNEXTLINE(cppcoreguidelines-avoid-non-const-global-variables)
4459d494eeSPatrick Williams static std::unique_ptr<sdbusplus::bus::match_t> fwUpdateErrorMatcher;
450e7de46fSAndrew Geissler // Only allow one update at a time
46cf9e417dSEd Tanous // NOLINTNEXTLINE(cppcoreguidelines-avoid-non-const-global-variables)
470e7de46fSAndrew Geissler static bool fwUpdateInProgress = false;
4886adcd6dSAndrew Geissler // Timer for software available
49cf9e417dSEd Tanous // NOLINTNEXTLINE(cppcoreguidelines-avoid-non-const-global-variables)
50271584abSEd Tanous static std::unique_ptr<boost::asio::steady_timer> fwAvailableTimer;
5186adcd6dSAndrew Geissler 
527e860f15SJohn Edward Broadbent inline static void cleanUp()
5386adcd6dSAndrew Geissler {
5486adcd6dSAndrew Geissler     fwUpdateInProgress = false;
5586adcd6dSAndrew Geissler     fwUpdateMatcher = nullptr;
564cde5d90SJames Feist     fwUpdateErrorMatcher = nullptr;
5786adcd6dSAndrew Geissler }
587e860f15SJohn Edward Broadbent inline static void activateImage(const std::string& objPath,
5986adcd6dSAndrew Geissler                                  const std::string& service)
6086adcd6dSAndrew Geissler {
6186adcd6dSAndrew Geissler     BMCWEB_LOG_DEBUG << "Activate image for " << objPath << " " << service;
6286adcd6dSAndrew Geissler     crow::connections::systemBus->async_method_call(
6381ce609eSEd Tanous         [](const boost::system::error_code errorCode) {
6481ce609eSEd Tanous         if (errorCode)
6586adcd6dSAndrew Geissler         {
6681ce609eSEd Tanous             BMCWEB_LOG_DEBUG << "error_code = " << errorCode;
6781ce609eSEd Tanous             BMCWEB_LOG_DEBUG << "error msg = " << errorCode.message();
6886adcd6dSAndrew Geissler         }
6986adcd6dSAndrew Geissler         },
7086adcd6dSAndrew Geissler         service, objPath, "org.freedesktop.DBus.Properties", "Set",
7186adcd6dSAndrew Geissler         "xyz.openbmc_project.Software.Activation", "RequestedActivation",
72168e20c1SEd Tanous         dbus::utility::DbusVariantType(
730fda0f12SGeorge Liu             "xyz.openbmc_project.Software.Activation.RequestedActivations.Active"));
7486adcd6dSAndrew Geissler }
750554c984SAndrew Geissler 
760554c984SAndrew Geissler // Note that asyncResp can be either a valid pointer or nullptr. If nullptr
770554c984SAndrew Geissler // then no asyncResp updates will occur
788d1b46d7Szhanghch05 static void
798d1b46d7Szhanghch05     softwareInterfaceAdded(const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
8059d494eeSPatrick Williams                            sdbusplus::message_t& m, task::Payload&& payload)
8186adcd6dSAndrew Geissler {
82b9d36b47SEd Tanous     dbus::utility::DBusInteracesMap interfacesProperties;
8386adcd6dSAndrew Geissler 
8486adcd6dSAndrew Geissler     sdbusplus::message::object_path objPath;
8586adcd6dSAndrew Geissler 
8686adcd6dSAndrew Geissler     m.read(objPath, interfacesProperties);
8786adcd6dSAndrew Geissler 
8886adcd6dSAndrew Geissler     BMCWEB_LOG_DEBUG << "obj path = " << objPath.str;
89e3eb3d63SEd Tanous     for (const auto& interface : interfacesProperties)
9086adcd6dSAndrew Geissler     {
9186adcd6dSAndrew Geissler         BMCWEB_LOG_DEBUG << "interface = " << interface.first;
9286adcd6dSAndrew Geissler 
9386adcd6dSAndrew Geissler         if (interface.first == "xyz.openbmc_project.Software.Activation")
9486adcd6dSAndrew Geissler         {
9586adcd6dSAndrew Geissler             // Retrieve service and activate
962b73119cSGeorge Liu             constexpr std::array<std::string_view, 1> interfaces = {
972b73119cSGeorge Liu                 "xyz.openbmc_project.Software.Activation"};
982b73119cSGeorge Liu             dbus::utility::getDbusObject(
992b73119cSGeorge Liu                 objPath.str, interfaces,
100a3e65892SEd Tanous                 [objPath, asyncResp, payload(std::move(payload))](
1012b73119cSGeorge Liu                     const boost::system::error_code& errorCode,
102a3e65892SEd Tanous                     const std::vector<
103a3e65892SEd Tanous                         std::pair<std::string, std::vector<std::string>>>&
104a3e65892SEd Tanous                         objInfo) mutable {
10581ce609eSEd Tanous                 if (errorCode)
10686adcd6dSAndrew Geissler                 {
10781ce609eSEd Tanous                     BMCWEB_LOG_DEBUG << "error_code = " << errorCode;
108002d39b4SEd Tanous                     BMCWEB_LOG_DEBUG << "error msg = " << errorCode.message();
1090554c984SAndrew Geissler                     if (asyncResp)
1100554c984SAndrew Geissler                     {
11186adcd6dSAndrew Geissler                         messages::internalError(asyncResp->res);
1120554c984SAndrew Geissler                     }
11386adcd6dSAndrew Geissler                     cleanUp();
11486adcd6dSAndrew Geissler                     return;
11586adcd6dSAndrew Geissler                 }
11686adcd6dSAndrew Geissler                 // Ensure we only got one service back
11786adcd6dSAndrew Geissler                 if (objInfo.size() != 1)
11886adcd6dSAndrew Geissler                 {
11986adcd6dSAndrew Geissler                     BMCWEB_LOG_ERROR << "Invalid Object Size "
12086adcd6dSAndrew Geissler                                      << objInfo.size();
1210554c984SAndrew Geissler                     if (asyncResp)
1220554c984SAndrew Geissler                     {
12386adcd6dSAndrew Geissler                         messages::internalError(asyncResp->res);
1240554c984SAndrew Geissler                     }
12586adcd6dSAndrew Geissler                     cleanUp();
12686adcd6dSAndrew Geissler                     return;
12786adcd6dSAndrew Geissler                 }
12886adcd6dSAndrew Geissler                 // cancel timer only when
12986adcd6dSAndrew Geissler                 // xyz.openbmc_project.Software.Activation interface
13086adcd6dSAndrew Geissler                 // is added
13186adcd6dSAndrew Geissler                 fwAvailableTimer = nullptr;
13286adcd6dSAndrew Geissler 
13386adcd6dSAndrew Geissler                 activateImage(objPath.str, objInfo[0].first);
1340554c984SAndrew Geissler                 if (asyncResp)
1350554c984SAndrew Geissler                 {
13632898ceaSJames Feist                     std::shared_ptr<task::TaskData> task =
13732898ceaSJames Feist                         task::TaskData::createTask(
13832898ceaSJames Feist                             [](boost::system::error_code ec,
13959d494eeSPatrick Williams                                sdbusplus::message_t& msg,
1401214b7e7SGunnar Mills                                const std::shared_ptr<task::TaskData>&
1411214b7e7SGunnar Mills                                    taskData) {
14232898ceaSJames Feist                         if (ec)
14332898ceaSJames Feist                         {
14432898ceaSJames Feist                             return task::completed;
14532898ceaSJames Feist                         }
14632898ceaSJames Feist 
14732898ceaSJames Feist                         std::string iface;
148b9d36b47SEd Tanous                         dbus::utility::DBusPropertiesMap values;
149fd9ab9e1SJames Feist 
150002d39b4SEd Tanous                         std::string index = std::to_string(taskData->index);
15132898ceaSJames Feist                         msg.read(iface, values);
152fd9ab9e1SJames Feist 
153002d39b4SEd Tanous                         if (iface == "xyz.openbmc_project.Software.Activation")
154fd9ab9e1SJames Feist                         {
1550fb5b505SGayathri Leburu                             const std::string* state = nullptr;
156b9d36b47SEd Tanous                             for (const auto& property : values)
15732898ceaSJames Feist                             {
158b9d36b47SEd Tanous                                 if (property.first == "Activation")
159b9d36b47SEd Tanous                                 {
1600fb5b505SGayathri Leburu                                     state = std::get_if<std::string>(
161b9d36b47SEd Tanous                                         &property.second);
1620fb5b505SGayathri Leburu                                     if (state == nullptr)
163b9d36b47SEd Tanous                                     {
164002d39b4SEd Tanous                                         taskData->messages.emplace_back(
165002d39b4SEd Tanous                                             messages::internalError());
166b9d36b47SEd Tanous                                         return task::completed;
167b9d36b47SEd Tanous                                     }
168b9d36b47SEd Tanous                                 }
169b9d36b47SEd Tanous                             }
17032898ceaSJames Feist 
17132898ceaSJames Feist                             if (state == nullptr)
17232898ceaSJames Feist                             {
173b9d36b47SEd Tanous                                 return !task::completed;
17432898ceaSJames Feist                             }
17532898ceaSJames Feist 
17611ba3979SEd Tanous                             if (state->ends_with("Invalid") ||
17711ba3979SEd Tanous                                 state->ends_with("Failed"))
17832898ceaSJames Feist                             {
17932898ceaSJames Feist                                 taskData->state = "Exception";
18032898ceaSJames Feist                                 taskData->status = "Warning";
18132898ceaSJames Feist                                 taskData->messages.emplace_back(
182e5d5006bSJames Feist                                     messages::taskAborted(index));
18332898ceaSJames Feist                                 return task::completed;
18432898ceaSJames Feist                             }
18532898ceaSJames Feist 
18611ba3979SEd Tanous                             if (state->ends_with("Staged"))
18732898ceaSJames Feist                             {
188fd9ab9e1SJames Feist                                 taskData->state = "Stopping";
189fd9ab9e1SJames Feist                                 taskData->messages.emplace_back(
190fd9ab9e1SJames Feist                                     messages::taskPaused(index));
191fd9ab9e1SJames Feist 
192fd9ab9e1SJames Feist                                 // its staged, set a long timer to
193fd9ab9e1SJames Feist                                 // allow them time to complete the
194fd9ab9e1SJames Feist                                 // update (probably cycle the
195fd9ab9e1SJames Feist                                 // system) if this expires then
196fd9ab9e1SJames Feist                                 // task will be cancelled
197002d39b4SEd Tanous                                 taskData->extendTimer(std::chrono::hours(5));
19832898ceaSJames Feist                                 return !task::completed;
19932898ceaSJames Feist                             }
20032898ceaSJames Feist 
20111ba3979SEd Tanous                             if (state->ends_with("Active"))
20232898ceaSJames Feist                             {
20332898ceaSJames Feist                                 taskData->messages.emplace_back(
204002d39b4SEd Tanous                                     messages::taskCompletedOK(index));
20532898ceaSJames Feist                                 taskData->state = "Completed";
20632898ceaSJames Feist                                 return task::completed;
20732898ceaSJames Feist                             }
208fd9ab9e1SJames Feist                         }
2090fda0f12SGeorge Liu                         else if (
2100fda0f12SGeorge Liu                             iface ==
2110fda0f12SGeorge Liu                             "xyz.openbmc_project.Software.ActivationProgress")
212fd9ab9e1SJames Feist                         {
213b9d36b47SEd Tanous 
214b9d36b47SEd Tanous                             const uint8_t* progress = nullptr;
215b9d36b47SEd Tanous                             for (const auto& property : values)
216fd9ab9e1SJames Feist                             {
217b9d36b47SEd Tanous                                 if (property.first == "Progress")
218b9d36b47SEd Tanous                                 {
2190fb5b505SGayathri Leburu                                     progress =
2200fb5b505SGayathri Leburu                                         std::get_if<uint8_t>(&property.second);
2210fb5b505SGayathri Leburu                                     if (progress == nullptr)
222b9d36b47SEd Tanous                                     {
223002d39b4SEd Tanous                                         taskData->messages.emplace_back(
224002d39b4SEd Tanous                                             messages::internalError());
225b9d36b47SEd Tanous                                         return task::completed;
226fd9ab9e1SJames Feist                                     }
227b9d36b47SEd Tanous                                 }
228b9d36b47SEd Tanous                             }
229fd9ab9e1SJames Feist 
230fd9ab9e1SJames Feist                             if (progress == nullptr)
231fd9ab9e1SJames Feist                             {
232b9d36b47SEd Tanous                                 return !task::completed;
233fd9ab9e1SJames Feist                             }
2340fb5b505SGayathri Leburu                             taskData->percentComplete = *progress;
235fd9ab9e1SJames Feist                             taskData->messages.emplace_back(
2360fb5b505SGayathri Leburu                                 messages::taskProgressChanged(index,
2370fb5b505SGayathri Leburu                                                               *progress));
238fd9ab9e1SJames Feist 
239fd9ab9e1SJames Feist                             // if we're getting status updates it's
240fd9ab9e1SJames Feist                             // still alive, update timer
241002d39b4SEd Tanous                             taskData->extendTimer(std::chrono::minutes(5));
242fd9ab9e1SJames Feist                         }
24332898ceaSJames Feist 
24432898ceaSJames Feist                         // as firmware update often results in a
24532898ceaSJames Feist                         // reboot, the task  may never "complete"
24632898ceaSJames Feist                         // unless it is an error
24732898ceaSJames Feist 
24832898ceaSJames Feist                         return !task::completed;
24932898ceaSJames Feist                             },
2500fda0f12SGeorge Liu                             "type='signal',interface='org.freedesktop.DBus.Properties',"
251fd9ab9e1SJames Feist                             "member='PropertiesChanged',path='" +
25232898ceaSJames Feist                                 objPath.str + "'");
25332898ceaSJames Feist                     task->startTimer(std::chrono::minutes(5));
25432898ceaSJames Feist                     task->populateResp(asyncResp->res);
255a3e65892SEd Tanous                     task->payload.emplace(std::move(payload));
2560554c984SAndrew Geissler                 }
25786adcd6dSAndrew Geissler                 fwUpdateInProgress = false;
2582b73119cSGeorge Liu                 });
25962bafc01SPatrick Williams 
26062bafc01SPatrick Williams             break;
26186adcd6dSAndrew Geissler         }
26286adcd6dSAndrew Geissler     }
26386adcd6dSAndrew Geissler }
26486adcd6dSAndrew Geissler 
2650554c984SAndrew Geissler // Note that asyncResp can be either a valid pointer or nullptr. If nullptr
2660554c984SAndrew Geissler // then no asyncResp updates will occur
267b5a76932SEd Tanous static void monitorForSoftwareAvailable(
2688d1b46d7Szhanghch05     const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
2698d1b46d7Szhanghch05     const crow::Request& req, const std::string& url,
2705d138943SGunnar Mills     int timeoutTimeSeconds = 25)
27186adcd6dSAndrew Geissler {
27286adcd6dSAndrew Geissler     // Only allow one FW update at a time
273e05aec50SEd Tanous     if (fwUpdateInProgress)
27486adcd6dSAndrew Geissler     {
2750554c984SAndrew Geissler         if (asyncResp)
2760554c984SAndrew Geissler         {
27786adcd6dSAndrew Geissler             messages::serviceTemporarilyUnavailable(asyncResp->res, "30");
2780554c984SAndrew Geissler         }
27986adcd6dSAndrew Geissler         return;
28086adcd6dSAndrew Geissler     }
28186adcd6dSAndrew Geissler 
2820554c984SAndrew Geissler     fwAvailableTimer =
283271584abSEd Tanous         std::make_unique<boost::asio::steady_timer>(*req.ioService);
28486adcd6dSAndrew Geissler 
285271584abSEd Tanous     fwAvailableTimer->expires_after(std::chrono::seconds(timeoutTimeSeconds));
28686adcd6dSAndrew Geissler 
28786adcd6dSAndrew Geissler     fwAvailableTimer->async_wait(
28886adcd6dSAndrew Geissler         [asyncResp](const boost::system::error_code& ec) {
28986adcd6dSAndrew Geissler         cleanUp();
29086adcd6dSAndrew Geissler         if (ec == boost::asio::error::operation_aborted)
29186adcd6dSAndrew Geissler         {
29286adcd6dSAndrew Geissler             // expected, we were canceled before the timer completed.
29386adcd6dSAndrew Geissler             return;
29486adcd6dSAndrew Geissler         }
29586adcd6dSAndrew Geissler         BMCWEB_LOG_ERROR
29686adcd6dSAndrew Geissler             << "Timed out waiting for firmware object being created";
297002d39b4SEd Tanous         BMCWEB_LOG_ERROR << "FW image may has already been uploaded to server";
29886adcd6dSAndrew Geissler         if (ec)
29986adcd6dSAndrew Geissler         {
30086adcd6dSAndrew Geissler             BMCWEB_LOG_ERROR << "Async_wait failed" << ec;
30186adcd6dSAndrew Geissler             return;
30286adcd6dSAndrew Geissler         }
3030554c984SAndrew Geissler         if (asyncResp)
3040554c984SAndrew Geissler         {
30586adcd6dSAndrew Geissler             redfish::messages::internalError(asyncResp->res);
3060554c984SAndrew Geissler         }
30786adcd6dSAndrew Geissler     });
308a3e65892SEd Tanous     task::Payload payload(req);
30959d494eeSPatrick Williams     auto callback = [asyncResp, payload](sdbusplus::message_t& m) mutable {
31086adcd6dSAndrew Geissler         BMCWEB_LOG_DEBUG << "Match fired";
311a3e65892SEd Tanous         softwareInterfaceAdded(asyncResp, m, std::move(payload));
31286adcd6dSAndrew Geissler     };
31386adcd6dSAndrew Geissler 
31486adcd6dSAndrew Geissler     fwUpdateInProgress = true;
31586adcd6dSAndrew Geissler 
31659d494eeSPatrick Williams     fwUpdateMatcher = std::make_unique<sdbusplus::bus::match_t>(
31786adcd6dSAndrew Geissler         *crow::connections::systemBus,
31886adcd6dSAndrew Geissler         "interface='org.freedesktop.DBus.ObjectManager',type='signal',"
31986adcd6dSAndrew Geissler         "member='InterfacesAdded',path='/xyz/openbmc_project/software'",
32086adcd6dSAndrew Geissler         callback);
3214cde5d90SJames Feist 
32259d494eeSPatrick Williams     fwUpdateErrorMatcher = std::make_unique<sdbusplus::bus::match_t>(
3234cde5d90SJames Feist         *crow::connections::systemBus,
324e1cc4828SBrian Ma         "interface='org.freedesktop.DBus.ObjectManager',type='signal',"
325e1cc4828SBrian Ma         "member='InterfacesAdded',"
326e1cc4828SBrian Ma         "path='/xyz/openbmc_project/logging'",
32759d494eeSPatrick Williams         [asyncResp, url](sdbusplus::message_t& m) {
328002d39b4SEd Tanous         std::vector<std::pair<std::string, dbus::utility::DBusPropertiesMap>>
329e1cc4828SBrian Ma             interfacesProperties;
330e1cc4828SBrian Ma         sdbusplus::message::object_path objPath;
331e1cc4828SBrian Ma         m.read(objPath, interfacesProperties);
332e1cc4828SBrian Ma         BMCWEB_LOG_DEBUG << "obj path = " << objPath.str;
333e1cc4828SBrian Ma         for (const std::pair<std::string, dbus::utility::DBusPropertiesMap>&
334e1cc4828SBrian Ma                  interface : interfacesProperties)
335e1cc4828SBrian Ma         {
336e1cc4828SBrian Ma             if (interface.first == "xyz.openbmc_project.Logging.Entry")
337e1cc4828SBrian Ma             {
338711ac7a9SEd Tanous                 for (const std::pair<std::string,
339002d39b4SEd Tanous                                      dbus::utility::DbusVariantType>& value :
340002d39b4SEd Tanous                      interface.second)
3414cde5d90SJames Feist                 {
342711ac7a9SEd Tanous                     if (value.first != "Message")
343711ac7a9SEd Tanous                     {
344711ac7a9SEd Tanous                         continue;
3454cde5d90SJames Feist                     }
346e1cc4828SBrian Ma                     const std::string* type =
347711ac7a9SEd Tanous                         std::get_if<std::string>(&value.second);
3484cde5d90SJames Feist                     if (type == nullptr)
3494cde5d90SJames Feist                     {
350e1cc4828SBrian Ma                         // if this was our message, timeout will cover it
3514cde5d90SJames Feist                         return;
3524cde5d90SJames Feist                     }
353e1cc4828SBrian Ma                     fwAvailableTimer = nullptr;
3544cde5d90SJames Feist                     if (*type ==
3554cde5d90SJames Feist                         "xyz.openbmc_project.Software.Image.Error.UnTarFailure")
3564cde5d90SJames Feist                     {
357002d39b4SEd Tanous                         redfish::messages::invalidUpload(asyncResp->res, url,
358002d39b4SEd Tanous                                                          "Invalid archive");
3594cde5d90SJames Feist                     }
360e1cc4828SBrian Ma                     else if (*type ==
361e1cc4828SBrian Ma                              "xyz.openbmc_project.Software.Image.Error."
362e1cc4828SBrian Ma                              "ManifestFileFailure")
3634cde5d90SJames Feist                     {
364002d39b4SEd Tanous                         redfish::messages::invalidUpload(asyncResp->res, url,
365002d39b4SEd Tanous                                                          "Invalid manifest");
3664cde5d90SJames Feist                     }
367e1cc4828SBrian Ma                     else if (
368e1cc4828SBrian Ma                         *type ==
3694cde5d90SJames Feist                         "xyz.openbmc_project.Software.Image.Error.ImageFailure")
3704cde5d90SJames Feist                     {
371e1cc4828SBrian Ma                         redfish::messages::invalidUpload(
372e1cc4828SBrian Ma                             asyncResp->res, url, "Invalid image format");
3734cde5d90SJames Feist                     }
374e1cc4828SBrian Ma                     else if (
375e1cc4828SBrian Ma                         *type ==
3760fda0f12SGeorge Liu                         "xyz.openbmc_project.Software.Version.Error.AlreadyExists")
37788b3dd12SGunnar Mills                     {
37888b3dd12SGunnar Mills                         redfish::messages::invalidUpload(
379e1cc4828SBrian Ma                             asyncResp->res, url,
380e1cc4828SBrian Ma                             "Image version already exists");
38188b3dd12SGunnar Mills 
38288b3dd12SGunnar Mills                         redfish::messages::resourceAlreadyExists(
383d8a5d5d8SJiaqing Zhao                             asyncResp->res, "UpdateService", "Version",
384e1cc4828SBrian Ma                             "uploaded version");
38588b3dd12SGunnar Mills                     }
386e1cc4828SBrian Ma                     else if (
387e1cc4828SBrian Ma                         *type ==
3884cde5d90SJames Feist                         "xyz.openbmc_project.Software.Image.Error.BusyFailure")
3894cde5d90SJames Feist                     {
390002d39b4SEd Tanous                         redfish::messages::resourceExhaustion(asyncResp->res,
391002d39b4SEd Tanous                                                               url);
3924cde5d90SJames Feist                     }
3934cde5d90SJames Feist                     else
3944cde5d90SJames Feist                     {
3954cde5d90SJames Feist                         redfish::messages::internalError(asyncResp->res);
3964cde5d90SJames Feist                     }
397e1cc4828SBrian Ma                 }
398e1cc4828SBrian Ma             }
399711ac7a9SEd Tanous         }
4004cde5d90SJames Feist         });
40186adcd6dSAndrew Geissler }
402729dae72SJennifer Lee 
4030554c984SAndrew Geissler /**
4040554c984SAndrew Geissler  * UpdateServiceActionsSimpleUpdate class supports handle POST method for
4050554c984SAndrew Geissler  * SimpleUpdate action.
4060554c984SAndrew Geissler  */
4077e860f15SJohn Edward Broadbent inline void requestRoutesUpdateServiceActionsSimpleUpdate(App& app)
4080554c984SAndrew Geissler {
4097e860f15SJohn Edward Broadbent     BMCWEB_ROUTE(
4107e860f15SJohn Edward Broadbent         app, "/redfish/v1/UpdateService/Actions/UpdateService.SimpleUpdate/")
411ed398213SEd Tanous         .privileges(redfish::privileges::postUpdateService)
412002d39b4SEd Tanous         .methods(boost::beast::http::verb::post)(
413002d39b4SEd Tanous             [&app](const crow::Request& req,
4147e860f15SJohn Edward Broadbent                    const std::shared_ptr<bmcweb::AsyncResp>& asyncResp) {
4153ba00073SCarson Labrado         if (!redfish::setUpRedfishRoute(app, req, asyncResp))
41645ca1b86SEd Tanous         {
41745ca1b86SEd Tanous             return;
41845ca1b86SEd Tanous         }
41945ca1b86SEd Tanous 
4200554c984SAndrew Geissler         std::optional<std::string> transferProtocol;
4210554c984SAndrew Geissler         std::string imageURI;
4220554c984SAndrew Geissler 
4230554c984SAndrew Geissler         BMCWEB_LOG_DEBUG << "Enter UpdateService.SimpleUpdate doPost";
4240554c984SAndrew Geissler 
4250554c984SAndrew Geissler         // User can pass in both TransferProtocol and ImageURI parameters or
4264e0453b1SGunnar Mills         // they can pass in just the ImageURI with the transfer protocol
4274e0453b1SGunnar Mills         // embedded within it.
4280554c984SAndrew Geissler         // 1) TransferProtocol:TFTP ImageURI:1.1.1.1/myfile.bin
4290554c984SAndrew Geissler         // 2) ImageURI:tftp://1.1.1.1/myfile.bin
4300554c984SAndrew Geissler 
431002d39b4SEd Tanous         if (!json_util::readJsonAction(req, asyncResp->res, "TransferProtocol",
432002d39b4SEd Tanous                                        transferProtocol, "ImageURI", imageURI))
4330554c984SAndrew Geissler         {
4340554c984SAndrew Geissler             BMCWEB_LOG_DEBUG
4350554c984SAndrew Geissler                 << "Missing TransferProtocol or ImageURI parameter";
4360554c984SAndrew Geissler             return;
4370554c984SAndrew Geissler         }
4380554c984SAndrew Geissler         if (!transferProtocol)
4390554c984SAndrew Geissler         {
4400554c984SAndrew Geissler             // Must be option 2
4410554c984SAndrew Geissler             // Verify ImageURI has transfer protocol in it
442f23b7296SEd Tanous             size_t separator = imageURI.find(':');
4430554c984SAndrew Geissler             if ((separator == std::string::npos) ||
4440554c984SAndrew Geissler                 ((separator + 1) > imageURI.size()))
4450554c984SAndrew Geissler             {
4460554c984SAndrew Geissler                 messages::actionParameterValueTypeError(
4470554c984SAndrew Geissler                     asyncResp->res, imageURI, "ImageURI",
4480554c984SAndrew Geissler                     "UpdateService.SimpleUpdate");
4490554c984SAndrew Geissler                 BMCWEB_LOG_ERROR << "ImageURI missing transfer protocol: "
4500554c984SAndrew Geissler                                  << imageURI;
4510554c984SAndrew Geissler                 return;
4520554c984SAndrew Geissler             }
4530554c984SAndrew Geissler             transferProtocol = imageURI.substr(0, separator);
4547e860f15SJohn Edward Broadbent             // Ensure protocol is upper case for a common comparison path
4557e860f15SJohn Edward Broadbent             // below
4560554c984SAndrew Geissler             boost::to_upper(*transferProtocol);
4570554c984SAndrew Geissler             BMCWEB_LOG_DEBUG << "Encoded transfer protocol "
4580554c984SAndrew Geissler                              << *transferProtocol;
4590554c984SAndrew Geissler 
4600554c984SAndrew Geissler             // Adjust imageURI to not have the protocol on it for parsing
4610554c984SAndrew Geissler             // below
4620554c984SAndrew Geissler             // ex. tftp://1.1.1.1/myfile.bin -> 1.1.1.1/myfile.bin
4630554c984SAndrew Geissler             imageURI = imageURI.substr(separator + 3);
4640554c984SAndrew Geissler             BMCWEB_LOG_DEBUG << "Adjusted imageUri " << imageURI;
4650554c984SAndrew Geissler         }
4660554c984SAndrew Geissler 
4670554c984SAndrew Geissler         // OpenBMC currently only supports TFTP
4680554c984SAndrew Geissler         if (*transferProtocol != "TFTP")
4690554c984SAndrew Geissler         {
470002d39b4SEd Tanous             messages::actionParameterNotSupported(asyncResp->res,
471002d39b4SEd Tanous                                                   "TransferProtocol",
4720554c984SAndrew Geissler                                                   "UpdateService.SimpleUpdate");
4730554c984SAndrew Geissler             BMCWEB_LOG_ERROR << "Request incorrect protocol parameter: "
4740554c984SAndrew Geissler                              << *transferProtocol;
4750554c984SAndrew Geissler             return;
4760554c984SAndrew Geissler         }
4770554c984SAndrew Geissler 
4780554c984SAndrew Geissler         // Format should be <IP or Hostname>/<file> for imageURI
479f23b7296SEd Tanous         size_t separator = imageURI.find('/');
4800554c984SAndrew Geissler         if ((separator == std::string::npos) ||
4810554c984SAndrew Geissler             ((separator + 1) > imageURI.size()))
4820554c984SAndrew Geissler         {
4830554c984SAndrew Geissler             messages::actionParameterValueTypeError(
4840554c984SAndrew Geissler                 asyncResp->res, imageURI, "ImageURI",
4850554c984SAndrew Geissler                 "UpdateService.SimpleUpdate");
4860554c984SAndrew Geissler             BMCWEB_LOG_ERROR << "Invalid ImageURI: " << imageURI;
4870554c984SAndrew Geissler             return;
4880554c984SAndrew Geissler         }
4890554c984SAndrew Geissler 
4900554c984SAndrew Geissler         std::string tftpServer = imageURI.substr(0, separator);
4910554c984SAndrew Geissler         std::string fwFile = imageURI.substr(separator + 1);
4920554c984SAndrew Geissler         BMCWEB_LOG_DEBUG << "Server: " << tftpServer + " File: " << fwFile;
4930554c984SAndrew Geissler 
4940554c984SAndrew Geissler         // Setup callback for when new software detected
4952618d5e3SGunnar Mills         // Give TFTP 10 minutes to complete
4964cde5d90SJames Feist         monitorForSoftwareAvailable(
497d7a596bdSAlbert Zhang             asyncResp, req,
4984cde5d90SJames Feist             "/redfish/v1/UpdateService/Actions/UpdateService.SimpleUpdate",
4992618d5e3SGunnar Mills             600);
5000554c984SAndrew Geissler 
5012618d5e3SGunnar Mills         // TFTP can take up to 10 minutes depending on image size and
5020554c984SAndrew Geissler         // connection speed. Return to caller as soon as the TFTP operation
5030554c984SAndrew Geissler         // has been started. The callback above will ensure the activate
5040554c984SAndrew Geissler         // is started once the download has completed
5050554c984SAndrew Geissler         redfish::messages::success(asyncResp->res);
5060554c984SAndrew Geissler 
5070554c984SAndrew Geissler         // Call TFTP service
5080554c984SAndrew Geissler         crow::connections::systemBus->async_method_call(
5090554c984SAndrew Geissler             [](const boost::system::error_code ec) {
5100554c984SAndrew Geissler             if (ec)
5110554c984SAndrew Geissler             {
5120554c984SAndrew Geissler                 // messages::internalError(asyncResp->res);
5130554c984SAndrew Geissler                 cleanUp();
5140554c984SAndrew Geissler                 BMCWEB_LOG_DEBUG << "error_code = " << ec;
5150554c984SAndrew Geissler                 BMCWEB_LOG_DEBUG << "error msg = " << ec.message();
5160554c984SAndrew Geissler             }
5170554c984SAndrew Geissler             else
5180554c984SAndrew Geissler             {
5190554c984SAndrew Geissler                 BMCWEB_LOG_DEBUG << "Call to DownloaViaTFTP Success";
5200554c984SAndrew Geissler             }
5210554c984SAndrew Geissler             },
5220554c984SAndrew Geissler             "xyz.openbmc_project.Software.Download",
523002d39b4SEd Tanous             "/xyz/openbmc_project/software", "xyz.openbmc_project.Common.TFTP",
524002d39b4SEd Tanous             "DownloadViaTFTP", fwFile, tftpServer);
5250554c984SAndrew Geissler 
5260554c984SAndrew Geissler         BMCWEB_LOG_DEBUG << "Exit UpdateService.SimpleUpdate doPost";
5277e860f15SJohn Edward Broadbent         });
528729dae72SJennifer Lee }
529729dae72SJennifer Lee 
530c2051d11SEd Tanous inline void
531c2051d11SEd Tanous     handleUpdateServicePost(App& app, const crow::Request& req,
532c2051d11SEd Tanous                             const std::shared_ptr<bmcweb::AsyncResp>& asyncResp)
533c2051d11SEd Tanous {
5343ba00073SCarson Labrado     if (!redfish::setUpRedfishRoute(app, req, asyncResp))
535c2051d11SEd Tanous     {
536c2051d11SEd Tanous         return;
537c2051d11SEd Tanous     }
538c2051d11SEd Tanous     BMCWEB_LOG_DEBUG << "doPost...";
539c2051d11SEd Tanous 
540c2051d11SEd Tanous     // Setup callback for when new software detected
541c2051d11SEd Tanous     monitorForSoftwareAvailable(asyncResp, req, "/redfish/v1/UpdateService");
542c2051d11SEd Tanous 
543c2051d11SEd Tanous     std::string filepath(
544c2051d11SEd Tanous         "/tmp/images/" +
545c2051d11SEd Tanous         boost::uuids::to_string(boost::uuids::random_generator()()));
546c2051d11SEd Tanous     BMCWEB_LOG_DEBUG << "Writing file to " << filepath;
547c2051d11SEd Tanous     std::ofstream out(filepath, std::ofstream::out | std::ofstream::binary |
548c2051d11SEd Tanous                                     std::ofstream::trunc);
549c2051d11SEd Tanous     out << req.body;
550c2051d11SEd Tanous     out.close();
551c2051d11SEd Tanous     BMCWEB_LOG_DEBUG << "file upload complete!!";
552c2051d11SEd Tanous }
553c2051d11SEd Tanous 
5547e860f15SJohn Edward Broadbent inline void requestRoutesUpdateService(App& app)
5551abe55efSEd Tanous {
5567e860f15SJohn Edward Broadbent     BMCWEB_ROUTE(app, "/redfish/v1/UpdateService/")
557ed398213SEd Tanous         .privileges(redfish::privileges::getUpdateService)
558002d39b4SEd Tanous         .methods(boost::beast::http::verb::get)(
559002d39b4SEd Tanous             [&app](const crow::Request& req,
560002d39b4SEd Tanous                    const std::shared_ptr<bmcweb::AsyncResp>& asyncResp) {
5613ba00073SCarson Labrado         if (!redfish::setUpRedfishRoute(app, req, asyncResp))
56245ca1b86SEd Tanous         {
56345ca1b86SEd Tanous             return;
56445ca1b86SEd Tanous         }
5658d1b46d7Szhanghch05         asyncResp->res.jsonValue["@odata.type"] =
5660588a3b9SChicago Duan             "#UpdateService.v1_5_0.UpdateService";
5678d1b46d7Szhanghch05         asyncResp->res.jsonValue["@odata.id"] = "/redfish/v1/UpdateService";
5688d1b46d7Szhanghch05         asyncResp->res.jsonValue["Id"] = "UpdateService";
569002d39b4SEd Tanous         asyncResp->res.jsonValue["Description"] = "Service for Software Update";
5708d1b46d7Szhanghch05         asyncResp->res.jsonValue["Name"] = "Update Service";
5714dc23f3fSEd Tanous 
57232ca38afSEd Tanous #ifdef BMCWEB_ENABLE_REDFISH_UPDATESERVICE_OLD_POST_URL
57332ca38afSEd Tanous         // See note about later on in this file about why this is neccesary
57432ca38afSEd Tanous         // This is "Wrong" per the standard, but is done temporarily to
57532ca38afSEd Tanous         // avoid noise in failing tests as people transition to having this
57632ca38afSEd Tanous         // option disabled
57732ca38afSEd Tanous         asyncResp->res.addHeader(boost::beast::http::field::allow,
57832ca38afSEd Tanous                                  "GET, PATCH, HEAD");
57932ca38afSEd Tanous #endif
58032ca38afSEd Tanous 
5817e860f15SJohn Edward Broadbent         asyncResp->res.jsonValue["HttpPushUri"] =
5824dc23f3fSEd Tanous             "/redfish/v1/UpdateService/update";
5834dc23f3fSEd Tanous 
5840f74e643SEd Tanous         // UpdateService cannot be disabled
5858d1b46d7Szhanghch05         asyncResp->res.jsonValue["ServiceEnabled"] = true;
5861476687dSEd Tanous         asyncResp->res.jsonValue["FirmwareInventory"]["@odata.id"] =
5871476687dSEd Tanous             "/redfish/v1/UpdateService/FirmwareInventory";
588d61e5194STejas Patil         // Get the MaxImageSizeBytes
589d61e5194STejas Patil         asyncResp->res.jsonValue["MaxImageSizeBytes"] =
590d61e5194STejas Patil             bmcwebHttpReqBodyLimitMb * 1024 * 1024;
591d61e5194STejas Patil 
5920554c984SAndrew Geissler #ifdef BMCWEB_INSECURE_ENABLE_REDFISH_FW_TFTP_UPDATE
5930554c984SAndrew Geissler         // Update Actions object.
5940554c984SAndrew Geissler         nlohmann::json& updateSvcSimpleUpdate =
595002d39b4SEd Tanous             asyncResp->res.jsonValue["Actions"]["#UpdateService.SimpleUpdate"];
5960554c984SAndrew Geissler         updateSvcSimpleUpdate["target"] =
5970554c984SAndrew Geissler             "/redfish/v1/UpdateService/Actions/UpdateService.SimpleUpdate";
598002d39b4SEd Tanous         updateSvcSimpleUpdate["TransferProtocol@Redfish.AllowableValues"] = {
599002d39b4SEd Tanous             "TFTP"};
6000554c984SAndrew Geissler #endif
601274dfe62SJayashankar Padath         // Get the current ApplyTime value
6021e1e598dSJonathan Doman         sdbusplus::asio::getProperty<std::string>(
6031e1e598dSJonathan Doman             *crow::connections::systemBus, "xyz.openbmc_project.Settings",
6041e1e598dSJonathan Doman             "/xyz/openbmc_project/software/apply_time",
6051e1e598dSJonathan Doman             "xyz.openbmc_project.Software.ApplyTime", "RequestedApplyTime",
6068d1b46d7Szhanghch05             [asyncResp](const boost::system::error_code ec,
6071e1e598dSJonathan Doman                         const std::string& applyTime) {
608274dfe62SJayashankar Padath             if (ec)
609274dfe62SJayashankar Padath             {
610274dfe62SJayashankar Padath                 BMCWEB_LOG_DEBUG << "DBUS response error " << ec;
6118d1b46d7Szhanghch05                 messages::internalError(asyncResp->res);
612274dfe62SJayashankar Padath                 return;
613274dfe62SJayashankar Padath             }
614274dfe62SJayashankar Padath 
615274dfe62SJayashankar Padath             // Store the ApplyTime Value
6161e1e598dSJonathan Doman             if (applyTime == "xyz.openbmc_project.Software.ApplyTime."
6171e1e598dSJonathan Doman                              "RequestedApplyTimes.Immediate")
618274dfe62SJayashankar Padath             {
619002d39b4SEd Tanous                 asyncResp->res.jsonValue["HttpPushUriOptions"]
6207e860f15SJohn Edward Broadbent                                         ["HttpPushUriApplyTime"]["ApplyTime"] =
6217e860f15SJohn Edward Broadbent                     "Immediate";
622274dfe62SJayashankar Padath             }
623002d39b4SEd Tanous             else if (applyTime == "xyz.openbmc_project.Software.ApplyTime."
6241e1e598dSJonathan Doman                                   "RequestedApplyTimes.OnReset")
625274dfe62SJayashankar Padath             {
626002d39b4SEd Tanous                 asyncResp->res.jsonValue["HttpPushUriOptions"]
6277e860f15SJohn Edward Broadbent                                         ["HttpPushUriApplyTime"]["ApplyTime"] =
6287e860f15SJohn Edward Broadbent                     "OnReset";
629274dfe62SJayashankar Padath             }
6301e1e598dSJonathan Doman             });
6317e860f15SJohn Edward Broadbent         });
6327e860f15SJohn Edward Broadbent     BMCWEB_ROUTE(app, "/redfish/v1/UpdateService/")
633ed398213SEd Tanous         .privileges(redfish::privileges::patchUpdateService)
634002d39b4SEd Tanous         .methods(boost::beast::http::verb::patch)(
635002d39b4SEd Tanous             [&app](const crow::Request& req,
636002d39b4SEd Tanous                    const std::shared_ptr<bmcweb::AsyncResp>& asyncResp) {
6373ba00073SCarson Labrado         if (!redfish::setUpRedfishRoute(app, req, asyncResp))
63845ca1b86SEd Tanous         {
63945ca1b86SEd Tanous             return;
64045ca1b86SEd Tanous         }
641fa1a5a38SJayashankar Padath         BMCWEB_LOG_DEBUG << "doPatch...";
642fa1a5a38SJayashankar Padath 
643274dfe62SJayashankar Padath         std::optional<nlohmann::json> pushUriOptions;
644002d39b4SEd Tanous         if (!json_util::readJsonPatch(req, asyncResp->res, "HttpPushUriOptions",
645002d39b4SEd Tanous                                       pushUriOptions))
646fa1a5a38SJayashankar Padath         {
647fa1a5a38SJayashankar Padath             return;
648fa1a5a38SJayashankar Padath         }
649fa1a5a38SJayashankar Padath 
650274dfe62SJayashankar Padath         if (pushUriOptions)
651274dfe62SJayashankar Padath         {
652274dfe62SJayashankar Padath             std::optional<nlohmann::json> pushUriApplyTime;
6538d1b46d7Szhanghch05             if (!json_util::readJson(*pushUriOptions, asyncResp->res,
654002d39b4SEd Tanous                                      "HttpPushUriApplyTime", pushUriApplyTime))
655274dfe62SJayashankar Padath             {
656274dfe62SJayashankar Padath                 return;
657274dfe62SJayashankar Padath             }
658274dfe62SJayashankar Padath 
659274dfe62SJayashankar Padath             if (pushUriApplyTime)
660274dfe62SJayashankar Padath             {
661274dfe62SJayashankar Padath                 std::optional<std::string> applyTime;
6620fda0f12SGeorge Liu                 if (!json_util::readJson(*pushUriApplyTime, asyncResp->res,
6630fda0f12SGeorge Liu                                          "ApplyTime", applyTime))
664274dfe62SJayashankar Padath                 {
665274dfe62SJayashankar Padath                     return;
666274dfe62SJayashankar Padath                 }
667274dfe62SJayashankar Padath 
668274dfe62SJayashankar Padath                 if (applyTime)
669fa1a5a38SJayashankar Padath                 {
670fa1a5a38SJayashankar Padath                     std::string applyTimeNewVal;
671fa1a5a38SJayashankar Padath                     if (applyTime == "Immediate")
672fa1a5a38SJayashankar Padath                     {
673274dfe62SJayashankar Padath                         applyTimeNewVal =
6740fda0f12SGeorge Liu                             "xyz.openbmc_project.Software.ApplyTime.RequestedApplyTimes.Immediate";
675fa1a5a38SJayashankar Padath                     }
676274dfe62SJayashankar Padath                     else if (applyTime == "OnReset")
677274dfe62SJayashankar Padath                     {
678274dfe62SJayashankar Padath                         applyTimeNewVal =
6790fda0f12SGeorge Liu                             "xyz.openbmc_project.Software.ApplyTime.RequestedApplyTimes.OnReset";
680274dfe62SJayashankar Padath                     }
681fa1a5a38SJayashankar Padath                     else
682fa1a5a38SJayashankar Padath                     {
683274dfe62SJayashankar Padath                         BMCWEB_LOG_INFO
6840fda0f12SGeorge Liu                             << "ApplyTime value is not in the list of acceptable values";
685274dfe62SJayashankar Padath                         messages::propertyValueNotInList(
686274dfe62SJayashankar Padath                             asyncResp->res, *applyTime, "ApplyTime");
687274dfe62SJayashankar Padath                         return;
688fa1a5a38SJayashankar Padath                     }
689fa1a5a38SJayashankar Padath 
690fa1a5a38SJayashankar Padath                     // Set the requested image apply time value
691fa1a5a38SJayashankar Padath                     crow::connections::systemBus->async_method_call(
6920fda0f12SGeorge Liu                         [asyncResp](const boost::system::error_code ec) {
693fa1a5a38SJayashankar Padath                         if (ec)
694fa1a5a38SJayashankar Padath                         {
695002d39b4SEd Tanous                             BMCWEB_LOG_ERROR << "D-Bus responses error: " << ec;
696fa1a5a38SJayashankar Padath                             messages::internalError(asyncResp->res);
697fa1a5a38SJayashankar Padath                             return;
698fa1a5a38SJayashankar Padath                         }
699fa1a5a38SJayashankar Padath                         messages::success(asyncResp->res);
700fa1a5a38SJayashankar Padath                         },
701fa1a5a38SJayashankar Padath                         "xyz.openbmc_project.Settings",
702fa1a5a38SJayashankar Padath                         "/xyz/openbmc_project/software/apply_time",
703fa1a5a38SJayashankar Padath                         "org.freedesktop.DBus.Properties", "Set",
704274dfe62SJayashankar Padath                         "xyz.openbmc_project.Software.ApplyTime",
705274dfe62SJayashankar Padath                         "RequestedApplyTime",
706168e20c1SEd Tanous                         dbus::utility::DbusVariantType{applyTimeNewVal});
707fa1a5a38SJayashankar Padath                 }
708274dfe62SJayashankar Padath             }
709fa1a5a38SJayashankar Padath         }
7107e860f15SJohn Edward Broadbent         });
711c2051d11SEd Tanous 
7124dc23f3fSEd Tanous // The "old" behavior of the update service URI causes redfish-service validator
7134dc23f3fSEd Tanous // failures when the Allow header is supported, given that in the spec,
7144dc23f3fSEd Tanous // UpdateService does not allow POST.  in openbmc, we unfortunately reused that
7154dc23f3fSEd Tanous // resource as our HttpPushUri as well.  A number of services, including the
7164dc23f3fSEd Tanous // openbmc tests, and documentation have hardcoded that erroneous API, instead
7174dc23f3fSEd Tanous // of relying on HttpPushUri as the spec requires.  This option will exist
7184dc23f3fSEd Tanous // temporarily to allow the old behavior until Q4 2022, at which time it will be
7194dc23f3fSEd Tanous // removed.
7204dc23f3fSEd Tanous #ifdef BMCWEB_ENABLE_REDFISH_UPDATESERVICE_OLD_POST_URL
7217e860f15SJohn Edward Broadbent     BMCWEB_ROUTE(app, "/redfish/v1/UpdateService/")
722ed398213SEd Tanous         .privileges(redfish::privileges::postUpdateService)
723002d39b4SEd Tanous         .methods(boost::beast::http::verb::post)(
724002d39b4SEd Tanous             [&app](const crow::Request& req,
7254dc23f3fSEd Tanous                    const std::shared_ptr<bmcweb::AsyncResp>& asyncResp) {
7264dc23f3fSEd Tanous         asyncResp->res.addHeader(
7274dc23f3fSEd Tanous             boost::beast::http::field::warning,
7284dc23f3fSEd Tanous             "299 - \"POST to /redfish/v1/UpdateService is deprecated. Use "
7294dc23f3fSEd Tanous             "the value contained within HttpPushUri.\"");
7304dc23f3fSEd Tanous         handleUpdateServicePost(app, req, asyncResp);
7314dc23f3fSEd Tanous         });
7324dc23f3fSEd Tanous #endif
7334dc23f3fSEd Tanous     BMCWEB_ROUTE(app, "/redfish/v1/UpdateService/update/")
7344dc23f3fSEd Tanous         .privileges(redfish::privileges::postUpdateService)
7357e860f15SJohn Edward Broadbent         .methods(boost::beast::http::verb::post)(
736c2051d11SEd Tanous             std::bind_front(handleUpdateServicePost, std::ref(app)));
737729dae72SJennifer Lee }
738729dae72SJennifer Lee 
7397e860f15SJohn Edward Broadbent inline void requestRoutesSoftwareInventoryCollection(App& app)
7401abe55efSEd Tanous {
7417e860f15SJohn Edward Broadbent     BMCWEB_ROUTE(app, "/redfish/v1/UpdateService/FirmwareInventory/")
742ed398213SEd Tanous         .privileges(redfish::privileges::getSoftwareInventoryCollection)
7431476687dSEd Tanous         .methods(boost::beast::http::verb::get)(
7441476687dSEd Tanous             [&app](const crow::Request& req,
7451476687dSEd Tanous                    const std::shared_ptr<bmcweb::AsyncResp>& asyncResp) {
7463ba00073SCarson Labrado         if (!redfish::setUpRedfishRoute(app, req, asyncResp))
74745ca1b86SEd Tanous         {
74845ca1b86SEd Tanous             return;
74945ca1b86SEd Tanous         }
7508d1b46d7Szhanghch05         asyncResp->res.jsonValue["@odata.type"] =
7510f74e643SEd Tanous             "#SoftwareInventoryCollection.SoftwareInventoryCollection";
7528d1b46d7Szhanghch05         asyncResp->res.jsonValue["@odata.id"] =
7530f74e643SEd Tanous             "/redfish/v1/UpdateService/FirmwareInventory";
754002d39b4SEd Tanous         asyncResp->res.jsonValue["Name"] = "Software Inventory Collection";
755c711bf86SEd Tanous 
756e99073f5SGeorge Liu         // Note that only firmware levels associated with a device
757e99073f5SGeorge Liu         // are stored under /xyz/openbmc_project/software therefore
758e99073f5SGeorge Liu         // to ensure only real FirmwareInventory items are returned,
759e99073f5SGeorge Liu         // this full object path must be used here as input to
760e99073f5SGeorge Liu         // mapper
761e99073f5SGeorge Liu         constexpr std::array<std::string_view, 1> interfaces = {
762e99073f5SGeorge Liu             "xyz.openbmc_project.Software.Version"};
763e99073f5SGeorge Liu         dbus::utility::getSubTree(
764e99073f5SGeorge Liu             "/xyz/openbmc_project/software", 0, interfaces,
765002d39b4SEd Tanous             [asyncResp](
766e99073f5SGeorge Liu                 const boost::system::error_code& ec,
767002d39b4SEd Tanous                 const dbus::utility::MapperGetSubTreeResponse& subtree) {
7681abe55efSEd Tanous             if (ec)
7691abe55efSEd Tanous             {
770f12894f8SJason M. Bills                 messages::internalError(asyncResp->res);
7716c4eb9deSJennifer Lee                 return;
772729dae72SJennifer Lee             }
773002d39b4SEd Tanous             asyncResp->res.jsonValue["Members"] = nlohmann::json::array();
774c711bf86SEd Tanous             asyncResp->res.jsonValue["Members@odata.count"] = 0;
7756c4eb9deSJennifer Lee 
7769eb808c1SEd Tanous             for (const auto& obj : subtree)
7771abe55efSEd Tanous             {
7782dfd18efSEd Tanous                 sdbusplus::message::object_path path(obj.first);
7792dfd18efSEd Tanous                 std::string swId = path.filename();
7802dfd18efSEd Tanous                 if (swId.empty())
781f4b65ab1SJennifer Lee                 {
782f12894f8SJason M. Bills                     messages::internalError(asyncResp->res);
783f4b65ab1SJennifer Lee                     BMCWEB_LOG_DEBUG << "Can't parse firmware ID!!";
784f4b65ab1SJennifer Lee                     return;
785f4b65ab1SJennifer Lee                 }
786f4b65ab1SJennifer Lee 
787002d39b4SEd Tanous                 nlohmann::json& members = asyncResp->res.jsonValue["Members"];
7881476687dSEd Tanous                 nlohmann::json::object_t member;
7891476687dSEd Tanous                 member["@odata.id"] =
790002d39b4SEd Tanous                     "/redfish/v1/UpdateService/FirmwareInventory/" + swId;
7911476687dSEd Tanous                 members.push_back(std::move(member));
792e0dd8057SAndrew Geissler                 asyncResp->res.jsonValue["Members@odata.count"] =
793c711bf86SEd Tanous                     members.size();
7946c4eb9deSJennifer Lee             }
795e99073f5SGeorge Liu             });
7967e860f15SJohn Edward Broadbent         });
797729dae72SJennifer Lee }
79887d84729SAndrew Geissler /* Fill related item links (i.e. bmc, bios) in for inventory */
7997e860f15SJohn Edward Broadbent inline static void
8007e860f15SJohn Edward Broadbent     getRelatedItems(const std::shared_ptr<bmcweb::AsyncResp>& aResp,
80187d84729SAndrew Geissler                     const std::string& purpose)
80287d84729SAndrew Geissler {
803eee0013eSWilly Tu     if (purpose == sw_util::bmcPurpose)
80487d84729SAndrew Geissler     {
8055af690f5SAbhishek Patel         nlohmann::json& relatedItem = aResp->res.jsonValue["RelatedItem"];
8061476687dSEd Tanous         nlohmann::json::object_t item;
8071476687dSEd Tanous         item["@odata.id"] = "/redfish/v1/Managers/bmc";
8081476687dSEd Tanous         relatedItem.push_back(std::move(item));
8097e860f15SJohn Edward Broadbent         aResp->res.jsonValue["RelatedItem@odata.count"] = relatedItem.size();
81087d84729SAndrew Geissler     }
811eee0013eSWilly Tu     else if (purpose == sw_util::biosPurpose)
81287d84729SAndrew Geissler     {
8135af690f5SAbhishek Patel         nlohmann::json& relatedItem = aResp->res.jsonValue["RelatedItem"];
8141476687dSEd Tanous         nlohmann::json::object_t item;
8151476687dSEd Tanous         item["@odata.id"] = "/redfish/v1/Systems/system/Bios";
8161476687dSEd Tanous         relatedItem.push_back(std::move(item));
8171a6e51aeSJiaqing Zhao         aResp->res.jsonValue["RelatedItem@odata.count"] = relatedItem.size();
81887d84729SAndrew Geissler     }
81987d84729SAndrew Geissler     else
82087d84729SAndrew Geissler     {
82187d84729SAndrew Geissler         BMCWEB_LOG_ERROR << "Unknown software purpose " << purpose;
82287d84729SAndrew Geissler     }
82387d84729SAndrew Geissler }
82487d84729SAndrew Geissler 
825af24660dSWilly Tu inline void
826af24660dSWilly Tu     getSoftwareVersion(const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
827af24660dSWilly Tu                        const std::string& service, const std::string& path,
828af24660dSWilly Tu                        const std::string& swId)
829af24660dSWilly Tu {
830d1bde9e5SKrzysztof Grobelny     sdbusplus::asio::getAllProperties(
831d1bde9e5SKrzysztof Grobelny         *crow::connections::systemBus, service, path,
832d1bde9e5SKrzysztof Grobelny         "xyz.openbmc_project.Software.Version",
833af24660dSWilly Tu         [asyncResp,
834af24660dSWilly Tu          swId](const boost::system::error_code errorCode,
835af24660dSWilly Tu                const dbus::utility::DBusPropertiesMap& propertiesList) {
836af24660dSWilly Tu         if (errorCode)
837af24660dSWilly Tu         {
838af24660dSWilly Tu             messages::internalError(asyncResp->res);
839af24660dSWilly Tu             return;
840af24660dSWilly Tu         }
841d1bde9e5SKrzysztof Grobelny 
842af24660dSWilly Tu         const std::string* swInvPurpose = nullptr;
843af24660dSWilly Tu         const std::string* version = nullptr;
844d1bde9e5SKrzysztof Grobelny 
845d1bde9e5SKrzysztof Grobelny         const bool success = sdbusplus::unpackPropertiesNoThrow(
846d1bde9e5SKrzysztof Grobelny             dbus_utils::UnpackErrorPrinter(), propertiesList, "Purpose",
847d1bde9e5SKrzysztof Grobelny             swInvPurpose, "Version", version);
848d1bde9e5SKrzysztof Grobelny 
849d1bde9e5SKrzysztof Grobelny         if (!success)
850af24660dSWilly Tu         {
851d1bde9e5SKrzysztof Grobelny             messages::internalError(asyncResp->res);
852d1bde9e5SKrzysztof Grobelny             return;
853af24660dSWilly Tu         }
854af24660dSWilly Tu 
855af24660dSWilly Tu         if (swInvPurpose == nullptr)
856af24660dSWilly Tu         {
857af24660dSWilly Tu             BMCWEB_LOG_DEBUG << "Can't find property \"Purpose\"!";
858af24660dSWilly Tu             messages::internalError(asyncResp->res);
859af24660dSWilly Tu             return;
860af24660dSWilly Tu         }
861af24660dSWilly Tu 
862af24660dSWilly Tu         BMCWEB_LOG_DEBUG << "swInvPurpose = " << *swInvPurpose;
863af24660dSWilly Tu 
864af24660dSWilly Tu         if (version == nullptr)
865af24660dSWilly Tu         {
866af24660dSWilly Tu             BMCWEB_LOG_DEBUG << "Can't find property \"Version\"!";
867af24660dSWilly Tu 
868af24660dSWilly Tu             messages::internalError(asyncResp->res);
869af24660dSWilly Tu 
870af24660dSWilly Tu             return;
871af24660dSWilly Tu         }
872af24660dSWilly Tu         asyncResp->res.jsonValue["Version"] = *version;
873af24660dSWilly Tu         asyncResp->res.jsonValue["Id"] = swId;
874af24660dSWilly Tu 
875af24660dSWilly Tu         // swInvPurpose is of format:
876af24660dSWilly Tu         // xyz.openbmc_project.Software.Version.VersionPurpose.ABC
877af24660dSWilly Tu         // Translate this to "ABC image"
878af24660dSWilly Tu         size_t endDesc = swInvPurpose->rfind('.');
879af24660dSWilly Tu         if (endDesc == std::string::npos)
880af24660dSWilly Tu         {
881af24660dSWilly Tu             messages::internalError(asyncResp->res);
882af24660dSWilly Tu             return;
883af24660dSWilly Tu         }
884af24660dSWilly Tu         endDesc++;
885af24660dSWilly Tu         if (endDesc >= swInvPurpose->size())
886af24660dSWilly Tu         {
887af24660dSWilly Tu             messages::internalError(asyncResp->res);
888af24660dSWilly Tu             return;
889af24660dSWilly Tu         }
890af24660dSWilly Tu 
891af24660dSWilly Tu         std::string formatDesc = swInvPurpose->substr(endDesc);
892af24660dSWilly Tu         asyncResp->res.jsonValue["Description"] = formatDesc + " image";
893af24660dSWilly Tu         getRelatedItems(asyncResp, *swInvPurpose);
894d1bde9e5SKrzysztof Grobelny         });
895af24660dSWilly Tu }
896af24660dSWilly Tu 
8977e860f15SJohn Edward Broadbent inline void requestRoutesSoftwareInventory(App& app)
8981abe55efSEd Tanous {
8997e860f15SJohn Edward Broadbent     BMCWEB_ROUTE(app, "/redfish/v1/UpdateService/FirmwareInventory/<str>/")
900ed398213SEd Tanous         .privileges(redfish::privileges::getSoftwareInventory)
901002d39b4SEd Tanous         .methods(boost::beast::http::verb::get)(
902002d39b4SEd Tanous             [&app](const crow::Request& req,
90345ca1b86SEd Tanous                    const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
9047e860f15SJohn Edward Broadbent                    const std::string& param) {
9053ba00073SCarson Labrado         if (!redfish::setUpRedfishRoute(app, req, asyncResp))
90645ca1b86SEd Tanous         {
90745ca1b86SEd Tanous             return;
90845ca1b86SEd Tanous         }
9093ae837c9SEd Tanous         std::shared_ptr<std::string> swId =
9107e860f15SJohn Edward Broadbent             std::make_shared<std::string>(param);
911c711bf86SEd Tanous 
9128d1b46d7Szhanghch05         asyncResp->res.jsonValue["@odata.id"] =
9133ae837c9SEd Tanous             "/redfish/v1/UpdateService/FirmwareInventory/" + *swId;
914c711bf86SEd Tanous 
915e99073f5SGeorge Liu         constexpr std::array<std::string_view, 1> interfaces = {
916e99073f5SGeorge Liu             "xyz.openbmc_project.Software.Version"};
917e99073f5SGeorge Liu         dbus::utility::getSubTree(
918e99073f5SGeorge Liu             "/", 0, interfaces,
919b9d36b47SEd Tanous             [asyncResp,
920e99073f5SGeorge Liu              swId](const boost::system::error_code& ec,
921b9d36b47SEd Tanous                    const dbus::utility::MapperGetSubTreeResponse& subtree) {
92255c7b7a2SEd Tanous             BMCWEB_LOG_DEBUG << "doGet callback...";
9231abe55efSEd Tanous             if (ec)
9241abe55efSEd Tanous             {
925f12894f8SJason M. Bills                 messages::internalError(asyncResp->res);
9266c4eb9deSJennifer Lee                 return;
9276c4eb9deSJennifer Lee             }
9286c4eb9deSJennifer Lee 
9296913228dSAndrew Geissler             // Ensure we find our input swId, otherwise return an error
9306913228dSAndrew Geissler             bool found = false;
931002d39b4SEd Tanous             for (const std::pair<std::string,
9327e860f15SJohn Edward Broadbent                                  std::vector<std::pair<
933002d39b4SEd Tanous                                      std::string, std::vector<std::string>>>>&
934002d39b4SEd Tanous                      obj : subtree)
9351abe55efSEd Tanous             {
93611ba3979SEd Tanous                 if (!obj.first.ends_with(*swId))
9371abe55efSEd Tanous                 {
938acb7cfb4SJennifer Lee                     continue;
939acb7cfb4SJennifer Lee                 }
940acb7cfb4SJennifer Lee 
94126f6976fSEd Tanous                 if (obj.second.empty())
9421abe55efSEd Tanous                 {
943acb7cfb4SJennifer Lee                     continue;
944acb7cfb4SJennifer Lee                 }
9456c4eb9deSJennifer Lee 
9466913228dSAndrew Geissler                 found = true;
947eee0013eSWilly Tu                 sw_util::getSwStatus(asyncResp, swId, obj.second[0].first);
948af24660dSWilly Tu                 getSoftwareVersion(asyncResp, obj.second[0].first, obj.first,
949af24660dSWilly Tu                                    *swId);
9506c4eb9deSJennifer Lee             }
9516913228dSAndrew Geissler             if (!found)
9526913228dSAndrew Geissler             {
953002d39b4SEd Tanous                 BMCWEB_LOG_ERROR << "Input swID " << *swId << " not found!";
9546913228dSAndrew Geissler                 messages::resourceMissingAtURI(
955002d39b4SEd Tanous                     asyncResp->res, crow::utility::urlFromPieces(
956ace85d60SEd Tanous                                         "redfish", "v1", "UpdateService",
957ace85d60SEd Tanous                                         "FirmwareInventory", *swId));
9586913228dSAndrew Geissler                 return;
9596913228dSAndrew Geissler             }
9604e68c45bSAyushi Smriti             asyncResp->res.jsonValue["@odata.type"] =
9614e68c45bSAyushi Smriti                 "#SoftwareInventory.v1_1_0.SoftwareInventory";
9624e68c45bSAyushi Smriti             asyncResp->res.jsonValue["Name"] = "Software Inventory";
9634e68c45bSAyushi Smriti             asyncResp->res.jsonValue["Status"]["HealthRollup"] = "OK";
9643f8a743aSAppaRao Puli 
9653f8a743aSAppaRao Puli             asyncResp->res.jsonValue["Updateable"] = false;
966eee0013eSWilly Tu             sw_util::getSwUpdatableStatus(asyncResp, swId);
967e99073f5SGeorge Liu             });
9687e860f15SJohn Edward Broadbent         });
9696c4eb9deSJennifer Lee }
970729dae72SJennifer Lee 
971729dae72SJennifer Lee } // namespace redfish
972