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