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