xref: /openbmc/bmcweb/features/redfish/lib/virtual_media.hpp (revision 914e2d5d5dbeddca9f48504256f7089efe86fc65)
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 <app.hpp>
19 #include <boost/container/flat_map.hpp>
20 #include <boost/process/async_pipe.hpp>
21 #include <boost/type_traits/has_dereference.hpp>
22 #include <utils/json_utils.hpp>
23 // for GetObjectType and ManagedObjectType
24 
25 #include <account_service.hpp>
26 #include <boost/url/url_view.hpp>
27 #include <registries/privilege_registry.hpp>
28 
29 namespace redfish
30 {
31 /**
32  * @brief Function extracts transfer protocol name from URI.
33  */
34 inline std::string getTransferProtocolTypeFromUri(const std::string& imageUri)
35 {
36     boost::urls::error_code ec;
37     boost::urls::url_view url =
38         boost::urls::parse_uri(boost::string_view(imageUri), ec);
39     if (ec)
40     {
41         return "None";
42     }
43     boost::string_view scheme = url.scheme();
44     if (scheme == "smb")
45     {
46         return "CIFS";
47     }
48     if (scheme == "https")
49     {
50         return "HTTPS";
51     }
52 
53     return "None";
54 }
55 
56 /**
57  * @brief Read all known properties from VM object interfaces
58  */
59 inline void
60     vmParseInterfaceObject(const dbus::utility::DBusInteracesMap& interface,
61                            const std::shared_ptr<bmcweb::AsyncResp>& aResp)
62 {
63     for (const auto& [interface, values] : interface)
64     {
65         if (interface == "xyz.openbmc_project.VirtualMedia.MountPoint")
66         {
67             for (const auto& [property, value] : values)
68             {
69                 if (property == "EndpointId")
70                 {
71                     const std::string* endpointIdValue =
72                         std::get_if<std::string>(&value);
73                     if (endpointIdValue == nullptr)
74                     {
75                         continue;
76                     }
77                     if (!endpointIdValue->empty())
78                     {
79                         // Proxy mode
80                         aResp->res
81                             .jsonValue["Oem"]["OpenBMC"]["WebSocketEndpoint"] =
82                             *endpointIdValue;
83                         aResp->res.jsonValue["TransferProtocolType"] = "OEM";
84                     }
85                 }
86                 if (property == "ImageURL")
87                 {
88                     const std::string* imageUrlValue =
89                         std::get_if<std::string>(&value);
90                     if (imageUrlValue && !imageUrlValue->empty())
91                     {
92                         std::filesystem::path filePath = *imageUrlValue;
93                         if (!filePath.has_filename())
94                         {
95                             // this will handle https share, which not
96                             // necessarily has to have filename given.
97                             aResp->res.jsonValue["ImageName"] = "";
98                         }
99                         else
100                         {
101                             aResp->res.jsonValue["ImageName"] =
102                                 filePath.filename();
103                         }
104 
105                         aResp->res.jsonValue["Image"] = *imageUrlValue;
106                         aResp->res.jsonValue["TransferProtocolType"] =
107                             getTransferProtocolTypeFromUri(*imageUrlValue);
108 
109                         aResp->res.jsonValue["ConnectedVia"] = "URI";
110                     }
111                 }
112                 if (property == "WriteProtected")
113                 {
114                     const bool* writeProtectedValue = std::get_if<bool>(&value);
115                     if (writeProtectedValue)
116                     {
117                         aResp->res.jsonValue["WriteProtected"] =
118                             *writeProtectedValue;
119                     }
120                 }
121             }
122         }
123         if (interface == "xyz.openbmc_project.VirtualMedia.Process")
124         {
125             for (const auto& [property, value] : values)
126             {
127                 if (property == "Active")
128                 {
129                     const bool* activeValue = std::get_if<bool>(&value);
130                     if (!activeValue)
131                     {
132                         BMCWEB_LOG_DEBUG << "Value Active not found";
133                         return;
134                     }
135                     aResp->res.jsonValue["Inserted"] = *activeValue;
136 
137                     if (*activeValue == true)
138                     {
139                         aResp->res.jsonValue["ConnectedVia"] = "Applet";
140                     }
141                 }
142             }
143         }
144     }
145 }
146 
147 /**
148  * @brief Fill template for Virtual Media Item.
149  */
150 inline nlohmann::json vmItemTemplate(const std::string& name,
151                                      const std::string& resName)
152 {
153     nlohmann::json item;
154 
155     std::string id = "/redfish/v1/Managers/";
156     id += name;
157     id += "/VirtualMedia/";
158     id += resName;
159     item["@odata.id"] = std::move(id);
160 
161     item["@odata.type"] = "#VirtualMedia.v1_3_0.VirtualMedia";
162     item["Name"] = "Virtual Removable Media";
163     item["Id"] = resName;
164     item["WriteProtected"] = true;
165     item["MediaTypes"] = {"CD", "USBStick"};
166     item["TransferMethod"] = "Stream";
167     item["Oem"]["OpenBMC"]["@odata.type"] =
168         "#OemVirtualMedia.v1_0_0.VirtualMedia";
169 
170     return item;
171 }
172 
173 /**
174  *  @brief Fills collection data
175  */
176 inline void getVmResourceList(std::shared_ptr<bmcweb::AsyncResp> aResp,
177                               const std::string& service,
178                               const std::string& name)
179 {
180     BMCWEB_LOG_DEBUG << "Get available Virtual Media resources.";
181     crow::connections::systemBus->async_method_call(
182         [name,
183          aResp{std::move(aResp)}](const boost::system::error_code ec,
184                                   dbus::utility::ManagedObjectType& subtree) {
185             if (ec)
186             {
187                 BMCWEB_LOG_DEBUG << "DBUS response error";
188                 return;
189             }
190             nlohmann::json& members = aResp->res.jsonValue["Members"];
191             members = nlohmann::json::array();
192 
193             for (const auto& object : subtree)
194             {
195                 nlohmann::json item;
196                 std::string path = object.first.filename();
197                 if (path.empty())
198                 {
199                     continue;
200                 }
201 
202                 std::string id = "/redfish/v1/Managers/";
203                 id += name;
204                 id += "/VirtualMedia/";
205                 id += path;
206 
207                 item["@odata.id"] = std::move(id);
208                 members.emplace_back(std::move(item));
209             }
210             aResp->res.jsonValue["Members@odata.count"] = members.size();
211         },
212         service, "/xyz/openbmc_project/VirtualMedia",
213         "org.freedesktop.DBus.ObjectManager", "GetManagedObjects");
214 }
215 
216 /**
217  *  @brief Fills data for specific resource
218  */
219 inline void getVmData(const std::shared_ptr<bmcweb::AsyncResp>& aResp,
220                       const std::string& service, const std::string& name,
221                       const std::string& resName)
222 {
223     BMCWEB_LOG_DEBUG << "Get Virtual Media resource data.";
224 
225     crow::connections::systemBus->async_method_call(
226         [resName, name,
227          aResp](const boost::system::error_code ec,
228                 const dbus::utility::ManagedObjectType& subtree) {
229             if (ec)
230             {
231                 BMCWEB_LOG_DEBUG << "DBUS response error";
232 
233                 return;
234             }
235 
236             for (const auto& item : subtree)
237             {
238                 std::string thispath = item.first.filename();
239                 if (thispath.empty())
240                 {
241                     continue;
242                 }
243 
244                 if (thispath != resName)
245                 {
246                     continue;
247                 }
248 
249                 // "Legacy"/"Proxy"
250                 auto mode = item.first.parent_path();
251                 // "VirtualMedia"
252                 auto type = mode.parent_path();
253                 if (mode.filename().empty() || type.filename().empty())
254                 {
255                     continue;
256                 }
257 
258                 if (type.filename() != "VirtualMedia")
259                 {
260                     continue;
261                 }
262 
263                 aResp->res.jsonValue = vmItemTemplate(name, resName);
264                 std::string actionsId = "/redfish/v1/Managers/";
265                 actionsId += name;
266                 actionsId += "/VirtualMedia/";
267                 actionsId += resName;
268                 actionsId += "/Actions";
269 
270                 // Check if dbus path is Legacy type
271                 if (mode.filename() == "Legacy")
272                 {
273                     aResp->res.jsonValue["Actions"]["#VirtualMedia.InsertMedia"]
274                                         ["target"] =
275                         actionsId + "/VirtualMedia.InsertMedia";
276                 }
277 
278                 vmParseInterfaceObject(item.second, aResp);
279 
280                 aResp->res.jsonValue["Actions"]["#VirtualMedia.EjectMedia"]
281                                     ["target"] =
282                     actionsId + "/VirtualMedia.EjectMedia";
283 
284                 return;
285             }
286 
287             messages::resourceNotFound(
288                 aResp->res, "#VirtualMedia.v1_3_0.VirtualMedia", resName);
289         },
290         service, "/xyz/openbmc_project/VirtualMedia",
291         "org.freedesktop.DBus.ObjectManager", "GetManagedObjects");
292 }
293 
294 /**
295  * @brief Transfer protocols supported for InsertMedia action.
296  *
297  */
298 enum class TransferProtocol
299 {
300     https,
301     smb,
302     invalid
303 };
304 
305 /**
306  * @brief Function extracts transfer protocol type from URI.
307  *
308  */
309 inline std::optional<TransferProtocol>
310     getTransferProtocolFromUri(const std::string& imageUri)
311 {
312     boost::urls::error_code ec;
313     boost::urls::url_view url =
314         boost::urls::parse_uri(boost::string_view(imageUri), ec);
315     if (ec)
316     {
317         return {};
318     }
319 
320     boost::string_view scheme = url.scheme();
321     if (scheme == "smb")
322     {
323         return TransferProtocol::smb;
324     }
325     if (scheme == "https")
326     {
327         return TransferProtocol::https;
328     }
329     if (!scheme.empty())
330     {
331         return TransferProtocol::invalid;
332     }
333 
334     return {};
335 }
336 
337 /**
338  * @brief Function convert transfer protocol from string param.
339  *
340  */
341 inline std::optional<TransferProtocol> getTransferProtocolFromParam(
342     const std::optional<std::string>& transferProtocolType)
343 {
344     if (transferProtocolType == std::nullopt)
345     {
346         return {};
347     }
348 
349     if (*transferProtocolType == "CIFS")
350     {
351         return TransferProtocol::smb;
352     }
353 
354     if (*transferProtocolType == "HTTPS")
355     {
356         return TransferProtocol::https;
357     }
358 
359     return TransferProtocol::invalid;
360 }
361 
362 /**
363  * @brief Function extends URI with transfer protocol type.
364  *
365  */
366 inline std::string
367     getUriWithTransferProtocol(const std::string& imageUri,
368                                const TransferProtocol& transferProtocol)
369 {
370     if (transferProtocol == TransferProtocol::smb)
371     {
372         return "smb://" + imageUri;
373     }
374 
375     if (transferProtocol == TransferProtocol::https)
376     {
377         return "https://" + imageUri;
378     }
379 
380     return imageUri;
381 }
382 
383 /**
384  * @brief Function validate parameters of insert media request.
385  *
386  */
387 inline bool
388     validateParams(crow::Response& res, std::string& imageUrl,
389                    const std::optional<bool>& inserted,
390                    const std::optional<std::string>& transferMethod,
391                    const std::optional<std::string>& transferProtocolType)
392 {
393     BMCWEB_LOG_DEBUG << "Validation started";
394     // required param imageUrl must not be empty
395     if (imageUrl.empty())
396     {
397         BMCWEB_LOG_ERROR << "Request action parameter Image is empty.";
398 
399         messages::propertyValueFormatError(res, "<empty>", "Image");
400 
401         return false;
402     }
403 
404     // optional param inserted must be true
405     if ((inserted != std::nullopt) && (*inserted != true))
406     {
407         BMCWEB_LOG_ERROR
408             << "Request action optional parameter Inserted must be true.";
409 
410         messages::actionParameterNotSupported(res, "Inserted", "InsertMedia");
411 
412         return false;
413     }
414 
415     // optional param transferMethod must be stream
416     if ((transferMethod != std::nullopt) && (*transferMethod != "Stream"))
417     {
418         BMCWEB_LOG_ERROR << "Request action optional parameter "
419                             "TransferMethod must be Stream.";
420 
421         messages::actionParameterNotSupported(res, "TransferMethod",
422                                               "InsertMedia");
423 
424         return false;
425     }
426 
427     std::optional<TransferProtocol> uriTransferProtocolType =
428         getTransferProtocolFromUri(imageUrl);
429 
430     std::optional<TransferProtocol> paramTransferProtocolType =
431         getTransferProtocolFromParam(transferProtocolType);
432 
433     // ImageUrl does not contain valid protocol type
434     if (*uriTransferProtocolType == TransferProtocol::invalid)
435     {
436         BMCWEB_LOG_ERROR << "Request action parameter ImageUrl must "
437                             "contain specified protocol type from list: "
438                             "(smb, https).";
439 
440         messages::resourceAtUriInUnknownFormat(res, imageUrl);
441 
442         return false;
443     }
444 
445     // transferProtocolType should contain value from list
446     if (*paramTransferProtocolType == TransferProtocol::invalid)
447     {
448         BMCWEB_LOG_ERROR << "Request action parameter TransferProtocolType "
449                             "must be provided with value from list: "
450                             "(CIFS, HTTPS).";
451 
452         messages::propertyValueNotInList(res, *transferProtocolType,
453                                          "TransferProtocolType");
454         return false;
455     }
456 
457     // valid transfer protocol not provided either with URI nor param
458     if ((uriTransferProtocolType == std::nullopt) &&
459         (paramTransferProtocolType == std::nullopt))
460     {
461         BMCWEB_LOG_ERROR << "Request action parameter ImageUrl must "
462                             "contain specified protocol type or param "
463                             "TransferProtocolType must be provided.";
464 
465         messages::resourceAtUriInUnknownFormat(res, imageUrl);
466 
467         return false;
468     }
469 
470     // valid transfer protocol provided both with URI and param
471     if ((paramTransferProtocolType != std::nullopt) &&
472         (uriTransferProtocolType != std::nullopt))
473     {
474         // check if protocol is the same for URI and param
475         if (*paramTransferProtocolType != *uriTransferProtocolType)
476         {
477             BMCWEB_LOG_ERROR << "Request action parameter "
478                                 "TransferProtocolType must  contain the "
479                                 "same protocol type as protocol type "
480                                 "provided with param imageUrl.";
481 
482             messages::actionParameterValueTypeError(res, *transferProtocolType,
483                                                     "TransferProtocolType",
484                                                     "InsertMedia");
485 
486             return false;
487         }
488     }
489 
490     // validation passed
491     // add protocol to URI if needed
492     if (uriTransferProtocolType == std::nullopt)
493     {
494         imageUrl =
495             getUriWithTransferProtocol(imageUrl, *paramTransferProtocolType);
496     }
497 
498     return true;
499 }
500 
501 template <typename T>
502 static void secureCleanup(T& value)
503 {
504     auto raw = const_cast<typename T::value_type*>(value.data());
505     explicit_bzero(raw, value.size() * sizeof(*raw));
506 }
507 
508 class Credentials
509 {
510   public:
511     Credentials(std::string&& user, std::string&& password) :
512         userBuf(std::move(user)), passBuf(std::move(password))
513     {}
514 
515     ~Credentials()
516     {
517         secureCleanup(userBuf);
518         secureCleanup(passBuf);
519     }
520 
521     const std::string& user()
522     {
523         return userBuf;
524     }
525 
526     const std::string& password()
527     {
528         return passBuf;
529     }
530 
531     Credentials() = delete;
532     Credentials(const Credentials&) = delete;
533     Credentials& operator=(const Credentials&) = delete;
534 
535   private:
536     std::string userBuf;
537     std::string passBuf;
538 };
539 
540 class CredentialsProvider
541 {
542   public:
543     template <typename T>
544     struct Deleter
545     {
546         void operator()(T* buff) const
547         {
548             if (buff)
549             {
550                 secureCleanup(*buff);
551                 delete buff;
552             }
553         }
554     };
555 
556     using Buffer = std::vector<char>;
557     using SecureBuffer = std::unique_ptr<Buffer, Deleter<Buffer>>;
558     // Using explicit definition instead of std::function to avoid implicit
559     // conversions eg. stack copy instead of reference
560     using FormatterFunc = void(const std::string& username,
561                                const std::string& password, Buffer& dest);
562 
563     CredentialsProvider(std::string&& user, std::string&& password) :
564         credentials(std::move(user), std::move(password))
565     {}
566 
567     const std::string& user()
568     {
569         return credentials.user();
570     }
571 
572     const std::string& password()
573     {
574         return credentials.password();
575     }
576 
577     SecureBuffer pack(FormatterFunc formatter)
578     {
579         SecureBuffer packed{new Buffer{}};
580         if (formatter)
581         {
582             formatter(credentials.user(), credentials.password(), *packed);
583         }
584 
585         return packed;
586     }
587 
588   private:
589     Credentials credentials;
590 };
591 
592 // Wrapper for boost::async_pipe ensuring proper pipe cleanup
593 template <typename Buffer>
594 class Pipe
595 {
596   public:
597     using unix_fd = sdbusplus::message::unix_fd;
598 
599     Pipe(boost::asio::io_context& io, Buffer&& buffer) :
600         impl(io), buffer{std::move(buffer)}
601     {}
602 
603     ~Pipe()
604     {
605         // Named pipe needs to be explicitly removed
606         impl.close();
607     }
608 
609     unix_fd fd()
610     {
611         return unix_fd{impl.native_source()};
612     }
613 
614     template <typename WriteHandler>
615     void asyncWrite(WriteHandler&& handler)
616     {
617         impl.async_write_some(data(), std::forward<WriteHandler>(handler));
618     }
619 
620   private:
621     // Specialization for pointer types
622     template <typename B = Buffer>
623     typename std::enable_if<boost::has_dereference<B>::value,
624                             boost::asio::const_buffer>::type
625         data()
626     {
627         return boost::asio::buffer(*buffer);
628     }
629 
630     template <typename B = Buffer>
631     typename std::enable_if<!boost::has_dereference<B>::value,
632                             boost::asio::const_buffer>::type
633         data()
634     {
635         return boost::asio::buffer(buffer);
636     }
637 
638     const std::string name;
639     boost::process::async_pipe impl;
640     Buffer buffer;
641 };
642 
643 /**
644  * @brief Function transceives data with dbus directly.
645  *
646  * All BMC state properties will be retrieved before sending reset request.
647  */
648 inline void doMountVmLegacy(const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
649                             const std::string& service, const std::string& name,
650                             const std::string& imageUrl, const bool rw,
651                             std::string&& userName, std::string&& password)
652 {
653     using SecurePipe = Pipe<CredentialsProvider::SecureBuffer>;
654     constexpr const size_t secretLimit = 1024;
655 
656     std::shared_ptr<SecurePipe> secretPipe;
657     dbus::utility::DbusVariantType unixFd = -1;
658 
659     if (!userName.empty() || !password.empty())
660     {
661         // Encapsulate in safe buffer
662         CredentialsProvider credentials(std::move(userName),
663                                         std::move(password));
664 
665         // Payload must contain data + NULL delimiters
666         if (credentials.user().size() + credentials.password().size() + 2 >
667             secretLimit)
668         {
669             BMCWEB_LOG_ERROR << "Credentials too long to handle";
670             messages::unrecognizedRequestBody(asyncResp->res);
671             return;
672         }
673 
674         // Pack secret
675         auto secret = credentials.pack(
676             [](const auto& user, const auto& pass, auto& buff) {
677                 std::copy(user.begin(), user.end(), std::back_inserter(buff));
678                 buff.push_back('\0');
679                 std::copy(pass.begin(), pass.end(), std::back_inserter(buff));
680                 buff.push_back('\0');
681             });
682 
683         // Open pipe
684         secretPipe = std::make_shared<SecurePipe>(
685             crow::connections::systemBus->get_io_context(), std::move(secret));
686         unixFd = secretPipe->fd();
687 
688         // Pass secret over pipe
689         secretPipe->asyncWrite(
690             [asyncResp](const boost::system::error_code& ec, std::size_t) {
691                 if (ec)
692                 {
693                     BMCWEB_LOG_ERROR << "Failed to pass secret: " << ec;
694                     messages::internalError(asyncResp->res);
695                 }
696             });
697     }
698 
699     crow::connections::systemBus->async_method_call(
700         [asyncResp, secretPipe](const boost::system::error_code ec,
701                                 bool success) {
702             if (ec)
703             {
704                 BMCWEB_LOG_ERROR << "Bad D-Bus request error: " << ec;
705                 messages::internalError(asyncResp->res);
706             }
707             else if (!success)
708             {
709                 BMCWEB_LOG_ERROR << "Service responded with error";
710                 messages::generalError(asyncResp->res);
711             }
712         },
713         service, "/xyz/openbmc_project/VirtualMedia/Legacy/" + name,
714         "xyz.openbmc_project.VirtualMedia.Legacy", "Mount", imageUrl, rw,
715         unixFd);
716 }
717 
718 /**
719  * @brief Function transceives data with dbus directly.
720  *
721  * All BMC state properties will be retrieved before sending reset request.
722  */
723 inline void doVmAction(const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
724                        const std::string& service, const std::string& name,
725                        bool legacy)
726 {
727 
728     // Legacy mount requires parameter with image
729     if (legacy)
730     {
731         crow::connections::systemBus->async_method_call(
732             [asyncResp](const boost::system::error_code ec) {
733                 if (ec)
734                 {
735                     BMCWEB_LOG_ERROR << "Bad D-Bus request error: " << ec;
736 
737                     messages::internalError(asyncResp->res);
738                     return;
739                 }
740             },
741             service, "/xyz/openbmc_project/VirtualMedia/Legacy/" + name,
742             "xyz.openbmc_project.VirtualMedia.Legacy", "Unmount");
743     }
744     else // proxy
745     {
746         crow::connections::systemBus->async_method_call(
747             [asyncResp](const boost::system::error_code ec) {
748                 if (ec)
749                 {
750                     BMCWEB_LOG_ERROR << "Bad D-Bus request error: " << ec;
751 
752                     messages::internalError(asyncResp->res);
753                     return;
754                 }
755             },
756             service, "/xyz/openbmc_project/VirtualMedia/Proxy/" + name,
757             "xyz.openbmc_project.VirtualMedia.Proxy", "Unmount");
758     }
759 }
760 
761 struct InsertMediaActionParams
762 {
763     std::string imageUrl;
764     std::optional<std::string> userName;
765     std::optional<std::string> password;
766     std::optional<std::string> transferMethod;
767     std::optional<std::string> transferProtocolType;
768     std::optional<bool> writeProtected = true;
769     std::optional<bool> inserted;
770 };
771 
772 inline void requestNBDVirtualMediaRoutes(App& app)
773 {
774     BMCWEB_ROUTE(
775         app,
776         "/redfish/v1/Managers/<str>/VirtualMedia/<str>/Actions/VirtualMedia.InsertMedia")
777         .privileges(redfish::privileges::postVirtualMedia)
778         .methods(boost::beast::http::verb::post)(
779             [](const crow::Request& req,
780                const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
781                const std::string& name, const std::string& resName) {
782                 if (name != "bmc")
783                 {
784                     messages::resourceNotFound(asyncResp->res,
785                                                "VirtualMedia.Insert", resName);
786 
787                     return;
788                 }
789                 InsertMediaActionParams actionParams;
790 
791                 // Read obligatory parameters (url of
792                 // image)
793                 if (!json_util::readJson(
794                         req, asyncResp->res, "Image", actionParams.imageUrl,
795                         "WriteProtected", actionParams.writeProtected,
796                         "UserName", actionParams.userName, "Password",
797                         actionParams.password, "Inserted",
798                         actionParams.inserted, "TransferMethod",
799                         actionParams.transferMethod, "TransferProtocolType",
800                         actionParams.transferProtocolType))
801                 {
802                     BMCWEB_LOG_DEBUG << "Image is not provided";
803                     return;
804                 }
805 
806                 bool paramsValid = validateParams(
807                     asyncResp->res, actionParams.imageUrl,
808                     actionParams.inserted, actionParams.transferMethod,
809                     actionParams.transferProtocolType);
810 
811                 if (paramsValid == false)
812                 {
813                     return;
814                 }
815 
816                 crow::connections::systemBus->async_method_call(
817                     [asyncResp, actionParams,
818                      resName](const boost::system::error_code ec,
819                               const GetObjectType& getObjectType) mutable {
820                         if (ec)
821                         {
822                             BMCWEB_LOG_ERROR
823                                 << "ObjectMapper::GetObject call failed: "
824                                 << ec;
825                             messages::internalError(asyncResp->res);
826 
827                             return;
828                         }
829                         std::string service = getObjectType.begin()->first;
830                         BMCWEB_LOG_DEBUG << "GetObjectType: " << service;
831 
832                         crow::connections::systemBus->async_method_call(
833                             [service, resName, actionParams,
834                              asyncResp](const boost::system::error_code ec,
835                                         dbus::utility::ManagedObjectType&
836                                             subtree) mutable {
837                                 if (ec)
838                                 {
839                                     BMCWEB_LOG_DEBUG << "DBUS response error";
840 
841                                     return;
842                                 }
843 
844                                 for (const auto& object : subtree)
845                                 {
846                                     const std::string& path =
847                                         static_cast<const std::string&>(
848                                             object.first);
849 
850                                     std::size_t lastIndex = path.rfind('/');
851                                     if (lastIndex == std::string::npos)
852                                     {
853                                         continue;
854                                     }
855 
856                                     lastIndex += 1;
857 
858                                     if (path.substr(lastIndex) == resName)
859                                     {
860                                         lastIndex = path.rfind("Proxy");
861                                         if (lastIndex != std::string::npos)
862                                         {
863                                             // Not possible in proxy mode
864                                             BMCWEB_LOG_DEBUG
865                                                 << "InsertMedia not "
866                                                    "allowed in proxy mode";
867                                             messages::resourceNotFound(
868                                                 asyncResp->res,
869                                                 "VirtualMedia.InsertMedia",
870                                                 resName);
871 
872                                             return;
873                                         }
874 
875                                         lastIndex = path.rfind("Legacy");
876                                         if (lastIndex == std::string::npos)
877                                         {
878                                             continue;
879                                         }
880 
881                                         // manager is irrelevant for
882                                         // VirtualMedia dbus calls
883                                         doMountVmLegacy(
884                                             asyncResp, service, resName,
885                                             actionParams.imageUrl,
886                                             !(*actionParams.writeProtected),
887                                             std::move(*actionParams.userName),
888                                             std::move(*actionParams.password));
889 
890                                         return;
891                                     }
892                                 }
893                                 BMCWEB_LOG_DEBUG << "Parent item not found";
894                                 messages::resourceNotFound(
895                                     asyncResp->res, "VirtualMedia", resName);
896                             },
897                             service, "/xyz/openbmc_project/VirtualMedia",
898                             "org.freedesktop.DBus.ObjectManager",
899                             "GetManagedObjects");
900                     },
901                     "xyz.openbmc_project.ObjectMapper",
902                     "/xyz/openbmc_project/object_mapper",
903                     "xyz.openbmc_project.ObjectMapper", "GetObject",
904                     "/xyz/openbmc_project/VirtualMedia",
905                     std::array<const char*, 0>());
906             });
907 
908     BMCWEB_ROUTE(
909         app,
910         "/redfish/v1/Managers/<str>/VirtualMedia/<str>/Actions/VirtualMedia.EjectMedia")
911         .privileges(redfish::privileges::postVirtualMedia)
912         .methods(boost::beast::http::verb::post)(
913             [](const crow::Request&,
914                const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
915                const std::string& name, const std::string& resName) {
916                 if (name != "bmc")
917                 {
918                     messages::resourceNotFound(asyncResp->res,
919                                                "VirtualMedia.Eject", resName);
920 
921                     return;
922                 }
923 
924                 crow::connections::systemBus->async_method_call(
925                     [asyncResp, resName](const boost::system::error_code ec,
926                                          const GetObjectType& getObjectType) {
927                         if (ec)
928                         {
929                             BMCWEB_LOG_ERROR
930                                 << "ObjectMapper::GetObject call failed: "
931                                 << ec;
932                             messages::internalError(asyncResp->res);
933 
934                             return;
935                         }
936                         std::string service = getObjectType.begin()->first;
937                         BMCWEB_LOG_DEBUG << "GetObjectType: " << service;
938 
939                         crow::connections::systemBus->async_method_call(
940                             [resName, service, asyncResp{asyncResp}](
941                                 const boost::system::error_code ec,
942                                 dbus::utility::ManagedObjectType& subtree) {
943                                 if (ec)
944                                 {
945                                     BMCWEB_LOG_DEBUG << "DBUS response error";
946 
947                                     return;
948                                 }
949 
950                                 for (const auto& object : subtree)
951                                 {
952                                     const std::string& path =
953                                         static_cast<const std::string&>(
954                                             object.first);
955 
956                                     std::size_t lastIndex = path.rfind('/');
957                                     if (lastIndex == std::string::npos)
958                                     {
959                                         continue;
960                                     }
961 
962                                     lastIndex += 1;
963 
964                                     if (path.substr(lastIndex) == resName)
965                                     {
966                                         lastIndex = path.rfind("Proxy");
967                                         if (lastIndex != std::string::npos)
968                                         {
969                                             // Proxy mode
970                                             doVmAction(asyncResp, service,
971                                                        resName, false);
972                                         }
973 
974                                         lastIndex = path.rfind("Legacy");
975                                         if (lastIndex != std::string::npos)
976                                         {
977                                             // Legacy mode
978                                             doVmAction(asyncResp, service,
979                                                        resName, true);
980                                         }
981 
982                                         return;
983                                     }
984                                 }
985                                 BMCWEB_LOG_DEBUG << "Parent item not found";
986                                 messages::resourceNotFound(
987                                     asyncResp->res, "VirtualMedia", resName);
988                             },
989                             service, "/xyz/openbmc_project/VirtualMedia",
990                             "org.freedesktop.DBus.ObjectManager",
991                             "GetManagedObjects");
992                     },
993                     "xyz.openbmc_project.ObjectMapper",
994                     "/xyz/openbmc_project/object_mapper",
995                     "xyz.openbmc_project.ObjectMapper", "GetObject",
996                     "/xyz/openbmc_project/VirtualMedia",
997                     std::array<const char*, 0>());
998             });
999     BMCWEB_ROUTE(app, "/redfish/v1/Managers/<str>/VirtualMedia/")
1000         .privileges(redfish::privileges::getVirtualMediaCollection)
1001         .methods(boost::beast::http::verb::get)(
1002             [](const crow::Request& /* req */,
1003                const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
1004                const std::string& name) {
1005                 if (name != "bmc")
1006                 {
1007                     messages::resourceNotFound(asyncResp->res, "VirtualMedia",
1008                                                name);
1009 
1010                     return;
1011                 }
1012 
1013                 asyncResp->res.jsonValue["@odata.type"] =
1014                     "#VirtualMediaCollection.VirtualMediaCollection";
1015                 asyncResp->res.jsonValue["Name"] = "Virtual Media Services";
1016                 asyncResp->res.jsonValue["@odata.id"] =
1017                     "/redfish/v1/Managers/" + name + "/VirtualMedia";
1018 
1019                 crow::connections::systemBus->async_method_call(
1020                     [asyncResp, name](const boost::system::error_code ec,
1021                                       const GetObjectType& getObjectType) {
1022                         if (ec)
1023                         {
1024                             BMCWEB_LOG_ERROR
1025                                 << "ObjectMapper::GetObject call failed: "
1026                                 << ec;
1027                             messages::internalError(asyncResp->res);
1028 
1029                             return;
1030                         }
1031                         std::string service = getObjectType.begin()->first;
1032                         BMCWEB_LOG_DEBUG << "GetObjectType: " << service;
1033 
1034                         getVmResourceList(asyncResp, service, name);
1035                     },
1036                     "xyz.openbmc_project.ObjectMapper",
1037                     "/xyz/openbmc_project/object_mapper",
1038                     "xyz.openbmc_project.ObjectMapper", "GetObject",
1039                     "/xyz/openbmc_project/VirtualMedia",
1040                     std::array<const char*, 0>());
1041             });
1042 
1043     BMCWEB_ROUTE(app, "/redfish/v1/Managers/<str>/VirtualMedia/<str>/")
1044         .privileges(redfish::privileges::getVirtualMedia)
1045         .methods(boost::beast::http::verb::get)(
1046             [](const crow::Request& /* req */,
1047                const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
1048                const std::string& name, const std::string& resName) {
1049                 if (name != "bmc")
1050                 {
1051                     messages::resourceNotFound(asyncResp->res, "VirtualMedia",
1052                                                resName);
1053 
1054                     return;
1055                 }
1056 
1057                 crow::connections::systemBus->async_method_call(
1058                     [asyncResp, name,
1059                      resName](const boost::system::error_code ec,
1060                               const GetObjectType& getObjectType) {
1061                         if (ec)
1062                         {
1063                             BMCWEB_LOG_ERROR
1064                                 << "ObjectMapper::GetObject call failed: "
1065                                 << ec;
1066                             messages::internalError(asyncResp->res);
1067 
1068                             return;
1069                         }
1070                         std::string service = getObjectType.begin()->first;
1071                         BMCWEB_LOG_DEBUG << "GetObjectType: " << service;
1072 
1073                         getVmData(asyncResp, service, name, resName);
1074                     },
1075                     "xyz.openbmc_project.ObjectMapper",
1076                     "/xyz/openbmc_project/object_mapper",
1077                     "xyz.openbmc_project.ObjectMapper", "GetObject",
1078                     "/xyz/openbmc_project/VirtualMedia",
1079                     std::array<const char*, 0>());
1080             });
1081 }
1082 
1083 } // namespace redfish
1084