blob: 68491cb86bb00b58745ae5647abfdc82bd5e7f74 [file] [log] [blame]
Iwona Klimaszewskac0a1c8a2019-07-12 18:26:38 +02001/*
2// Copyright (c) 2019 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
Ed Tanous04e438c2020-10-03 08:06:26 -070017#include <app.hpp>
Ed Tanousd43cd0c2020-09-30 20:46:53 -070018#include <boost/asio/buffer.hpp>
19#include <boost/asio/local/stream_protocol.hpp>
20#include <boost/asio/write.hpp>
Iwona Klimaszewskac0a1c8a2019-07-12 18:26:38 +020021#include <boost/beast/core/buffers_to_string.hpp>
22#include <boost/beast/core/multi_buffer.hpp>
23#include <boost/container/flat_map.hpp>
24#include <dbus_utility.hpp>
Przemyslaw Czarnowski250b0eb2020-02-24 10:23:56 +010025#include <privileges.hpp>
Ed Tanous04e438c2020-10-03 08:06:26 -070026#include <websocket.hpp>
Iwona Klimaszewskac0a1c8a2019-07-12 18:26:38 +020027
28namespace crow
29{
30
31namespace nbd_proxy
32{
33
34using boost::asio::local::stream_protocol;
35
36static constexpr auto nbdBufferSize = 131088;
Ed Tanouscf9e4172022-12-21 09:30:16 -080037constexpr const char* requiredPrivilegeString = "ConfigureManager";
Iwona Klimaszewskac0a1c8a2019-07-12 18:26:38 +020038
39struct NbdProxyServer : std::enable_shared_from_this<NbdProxyServer>
40{
41 NbdProxyServer(crow::websocket::Connection& connIn,
42 const std::string& socketIdIn,
43 const std::string& endpointIdIn, const std::string& pathIn) :
44 socketId(socketIdIn),
45 endpointId(endpointIdIn), path(pathIn),
Ed Tanous2c70f802020-09-28 14:29:23 -070046 acceptor(connIn.getIoContext(), stream_protocol::endpoint(socketId)),
Iwona Klimaszewskac0a1c8a2019-07-12 18:26:38 +020047 connection(connIn)
Gunnar Mills1214b7e2020-06-04 10:11:30 -050048 {}
Iwona Klimaszewskac0a1c8a2019-07-12 18:26:38 +020049
Ed Tanous08e9fa92022-02-16 16:18:08 -080050 NbdProxyServer(const NbdProxyServer&) = delete;
51 NbdProxyServer(NbdProxyServer&&) = delete;
52 NbdProxyServer& operator=(const NbdProxyServer&) = delete;
53 NbdProxyServer& operator=(NbdProxyServer&&) = delete;
54
Iwona Klimaszewskac0a1c8a2019-07-12 18:26:38 +020055 ~NbdProxyServer()
56 {
57 BMCWEB_LOG_DEBUG << "NbdProxyServer destructor";
Iwona Klimaszewskac0a1c8a2019-07-12 18:26:38 +020058 }
59
60 std::string getEndpointId() const
61 {
62 return endpointId;
63 }
64
65 void run()
66 {
67 acceptor.async_accept(
68 [this, self(shared_from_this())](boost::system::error_code ec,
69 stream_protocol::socket socket) {
Ed Tanous002d39b2022-05-31 08:59:27 -070070 if (ec)
71 {
72 BMCWEB_LOG_ERROR << "UNIX socket: async_accept error = "
73 << ec.message();
74 return;
75 }
76 if (peerSocket)
77 {
78 // Something is wrong - socket shouldn't be acquired at this
79 // point
80 BMCWEB_LOG_ERROR
81 << "Failed to open connection - socket already used";
82 return;
83 }
Iwona Klimaszewskac0a1c8a2019-07-12 18:26:38 +020084
Ed Tanous002d39b2022-05-31 08:59:27 -070085 BMCWEB_LOG_DEBUG << "Connection opened";
86 peerSocket = std::move(socket);
87 doRead();
Iwona Klimaszewskac0a1c8a2019-07-12 18:26:38 +020088
Ed Tanous002d39b2022-05-31 08:59:27 -070089 // Trigger Write if any data was sent from server
90 // Initially this is negotiation chunk
91 doWrite();
92 });
Iwona Klimaszewskac0a1c8a2019-07-12 18:26:38 +020093
Ed Tanous002d39b2022-05-31 08:59:27 -070094 auto mountHandler =
95 [this, self(shared_from_this())](const boost::system::error_code ec,
96 const bool) {
Iwona Klimaszewskac0a1c8a2019-07-12 18:26:38 +020097 if (ec)
98 {
Iwona Winiarska123e8232019-11-29 12:34:33 +010099 BMCWEB_LOG_ERROR << "DBus error: cannot call mount method = "
100 << ec.message();
Wludzik, Jozeff6a0d632020-07-16 15:16:02 +0200101 connection.close("Failed to mount media");
Iwona Klimaszewskac0a1c8a2019-07-12 18:26:38 +0200102 return;
103 }
104 };
105
106 crow::connections::systemBus->async_method_call(
107 std::move(mountHandler), "xyz.openbmc_project.VirtualMedia", path,
108 "xyz.openbmc_project.VirtualMedia.Proxy", "Mount");
109 }
110
111 void send(const std::string_view data)
112 {
113 boost::asio::buffer_copy(ws2uxBuf.prepare(data.size()),
114 boost::asio::buffer(data));
115 ws2uxBuf.commit(data.size());
116 doWrite();
117 }
118
119 void close()
120 {
Iwona Winiarska123e8232019-11-29 12:34:33 +0100121 acceptor.close();
122 if (peerSocket)
123 {
124 BMCWEB_LOG_DEBUG << "peerSocket->close()";
125 peerSocket->close();
126 peerSocket.reset();
127 BMCWEB_LOG_DEBUG << "std::remove(" << socketId << ")";
128 std::remove(socketId.c_str());
129 }
Iwona Klimaszewskac0a1c8a2019-07-12 18:26:38 +0200130 // The reference to session should exists until unmount is
131 // called
132 auto unmountHandler = [](const boost::system::error_code ec) {
133 if (ec)
134 {
135 BMCWEB_LOG_ERROR << "DBus error: " << ec
136 << ", cannot call unmount method";
137 return;
138 }
139 };
140
141 crow::connections::systemBus->async_method_call(
142 std::move(unmountHandler), "xyz.openbmc_project.VirtualMedia", path,
143 "xyz.openbmc_project.VirtualMedia.Proxy", "Unmount");
144 }
145
146 private:
147 void doRead()
148 {
149 if (!peerSocket)
150 {
151 BMCWEB_LOG_DEBUG << "UNIX socket isn't created yet";
152 // Skip if UNIX socket is not created yet.
153 return;
154 }
155
156 // Trigger async read
157 peerSocket->async_read_some(
158 ux2wsBuf.prepare(nbdBufferSize),
159 [this, self(shared_from_this())](boost::system::error_code ec,
160 std::size_t bytesRead) {
Ed Tanous002d39b2022-05-31 08:59:27 -0700161 if (ec)
162 {
163 BMCWEB_LOG_ERROR << "UNIX socket: async_read_some error = "
164 << ec.message();
165 // UNIX socket has been closed by peer, best we can do is to
166 // break all connections
167 close();
168 return;
169 }
Iwona Klimaszewskac0a1c8a2019-07-12 18:26:38 +0200170
Ed Tanous002d39b2022-05-31 08:59:27 -0700171 // Fetch data from UNIX socket
Iwona Klimaszewskac0a1c8a2019-07-12 18:26:38 +0200172
Ed Tanous002d39b2022-05-31 08:59:27 -0700173 ux2wsBuf.commit(bytesRead);
Iwona Klimaszewskac0a1c8a2019-07-12 18:26:38 +0200174
Ed Tanous002d39b2022-05-31 08:59:27 -0700175 // Paste it to WebSocket as binary
176 connection.sendBinary(
177 boost::beast::buffers_to_string(ux2wsBuf.data()));
178 ux2wsBuf.consume(bytesRead);
Iwona Klimaszewskac0a1c8a2019-07-12 18:26:38 +0200179
Ed Tanous002d39b2022-05-31 08:59:27 -0700180 // Allow further reads
181 doRead();
Iwona Klimaszewskac0a1c8a2019-07-12 18:26:38 +0200182 });
183 }
184
185 void doWrite()
186 {
187 if (!peerSocket)
188 {
189 BMCWEB_LOG_DEBUG << "UNIX socket isn't created yet";
190 // Skip if UNIX socket is not created yet. Collect data, and wait
191 // for nbd-client connection
192 return;
193 }
194
195 if (uxWriteInProgress)
196 {
197 BMCWEB_LOG_ERROR << "Write in progress";
198 return;
199 }
200
Jason M. Bills9c0b4e52022-02-14 07:23:30 -0800201 if (ws2uxBuf.size() == 0)
Iwona Klimaszewskac0a1c8a2019-07-12 18:26:38 +0200202 {
203 BMCWEB_LOG_ERROR << "No data to write to UNIX socket";
204 return;
205 }
206
207 uxWriteInProgress = true;
208 boost::asio::async_write(
209 *peerSocket, ws2uxBuf.data(),
210 [this, self(shared_from_this())](boost::system::error_code ec,
211 std::size_t bytesWritten) {
Ed Tanous002d39b2022-05-31 08:59:27 -0700212 ws2uxBuf.consume(bytesWritten);
213 uxWriteInProgress = false;
214 if (ec)
215 {
216 BMCWEB_LOG_ERROR << "UNIX: async_write error = "
217 << ec.message();
218 return;
219 }
220 // Retrigger doWrite if there is something in buffer
221 if (ws2uxBuf.size() > 0)
222 {
223 doWrite();
224 }
Iwona Klimaszewskac0a1c8a2019-07-12 18:26:38 +0200225 });
226 }
227
228 // Keeps UNIX socket endpoint file path
229 const std::string socketId;
230 const std::string endpointId;
231 const std::string path;
232
233 bool uxWriteInProgress = false;
234
235 // UNIX => WebSocket buffer
236 boost::beast::multi_buffer ux2wsBuf;
237
238 // WebSocket <= UNIX buffer
239 boost::beast::multi_buffer ws2uxBuf;
240
241 // Default acceptor for UNIX socket
242 stream_protocol::acceptor acceptor;
243
244 // The socket used to communicate with the client.
245 std::optional<stream_protocol::socket> peerSocket;
246
247 crow::websocket::Connection& connection;
248};
249
Ed Tanouscf9e4172022-12-21 09:30:16 -0800250using SessionMap = boost::container::flat_map<crow::websocket::Connection*,
251 std::shared_ptr<NbdProxyServer>>;
252// NOLINTNEXTLINE(cppcoreguidelines-avoid-non-const-global-variables)
253static SessionMap sessions;
Iwona Klimaszewskac0a1c8a2019-07-12 18:26:38 +0200254
Ed Tanous81ce6092020-12-17 16:54:55 +0000255inline void requestRoutes(App& app)
Iwona Klimaszewskac0a1c8a2019-07-12 18:26:38 +0200256{
257 BMCWEB_ROUTE(app, "/nbd/<str>")
258 .websocket()
zhanghch0577726382021-10-21 14:07:57 +0800259 .onopen([](crow::websocket::Connection& conn) {
Iwona Klimaszewskac0a1c8a2019-07-12 18:26:38 +0200260 BMCWEB_LOG_DEBUG << "nbd-proxy.onopen(" << &conn << ")";
261
Ed Tanous002d39b2022-05-31 08:59:27 -0700262 auto getUserInfoHandler =
263 [&conn](const boost::system::error_code ec,
264 const dbus::utility::DBusPropertiesMap& userInfo) {
265 if (ec)
266 {
267 BMCWEB_LOG_ERROR << "GetUserInfo failed...";
268 conn.close("Failed to get user information");
269 return;
270 }
271
272 const std::string* userRolePtr = nullptr;
273 auto userInfoIter = std::find_if(userInfo.begin(), userInfo.end(),
274 [](const auto& p) {
275 return p.first == "UserPrivilege";
276 });
277 if (userInfoIter != userInfo.end())
278 {
279 userRolePtr = std::get_if<std::string>(&userInfoIter->second);
280 }
281
282 std::string userRole{};
283 if (userRolePtr != nullptr)
284 {
285 userRole = *userRolePtr;
286 BMCWEB_LOG_DEBUG << "userName = " << conn.getUserName()
287 << " userRole = " << *userRolePtr;
288 }
289
290 // Get the user privileges from the role
291 ::redfish::Privileges userPrivileges =
292 ::redfish::getUserPrivileges(userRole);
293
294 const ::redfish::Privileges requiredPrivileges{
295 requiredPrivilegeString};
296
297 if (!userPrivileges.isSupersetOf(requiredPrivileges))
298 {
299 BMCWEB_LOG_DEBUG << "User " << conn.getUserName()
300 << " not authorized for nbd connection";
301 conn.close("Unathourized access");
302 return;
303 }
304
305 auto openHandler =
Ed Tanouse3009e42022-02-16 15:42:37 -0800306 [&conn](const boost::system::error_code ec2,
Ed Tanous002d39b2022-05-31 08:59:27 -0700307 const dbus::utility::ManagedObjectType& objects) {
308 const std::string* socketValue = nullptr;
309 const std::string* endpointValue = nullptr;
310 const std::string* endpointObjectPath = nullptr;
311
Ed Tanouse3009e42022-02-16 15:42:37 -0800312 if (ec2)
Ed Tanous168e20c2021-12-13 14:39:53 -0800313 {
Ed Tanouse3009e42022-02-16 15:42:37 -0800314 BMCWEB_LOG_ERROR << "DBus error: " << ec2.message();
Ed Tanous002d39b2022-05-31 08:59:27 -0700315 conn.close("Failed to create mount point");
Ed Tanous168e20c2021-12-13 14:39:53 -0800316 return;
317 }
Przemyslaw Czarnowski250b0eb2020-02-24 10:23:56 +0100318
Ed Tanous002d39b2022-05-31 08:59:27 -0700319 for (const auto& [objectPath, interfaces] : objects)
Ed Tanous168e20c2021-12-13 14:39:53 -0800320 {
Ed Tanous002d39b2022-05-31 08:59:27 -0700321 for (const auto& [interface, properties] : interfaces)
322 {
323 if (interface !=
324 "xyz.openbmc_project.VirtualMedia.MountPoint")
325 {
326 continue;
327 }
328
329 for (const auto& [name, value] : properties)
330 {
331 if (name == "EndpointId")
332 {
333 endpointValue =
334 std::get_if<std::string>(&value);
335
336 if (endpointValue == nullptr)
337 {
338 BMCWEB_LOG_ERROR
339 << "EndpointId property value is null";
340 }
341 }
342 if (name == "Socket")
343 {
344 socketValue = std::get_if<std::string>(&value);
345 if (socketValue == nullptr)
346 {
347 BMCWEB_LOG_ERROR
348 << "Socket property value is null";
349 }
350 }
351 }
352 }
353
354 if ((endpointValue != nullptr) &&
355 (socketValue != nullptr) &&
356 *endpointValue == conn.req.target())
357 {
358 endpointObjectPath = &objectPath.str;
359 break;
360 }
Ed Tanous168e20c2021-12-13 14:39:53 -0800361 }
Przemyslaw Czarnowski250b0eb2020-02-24 10:23:56 +0100362
Ed Tanous002d39b2022-05-31 08:59:27 -0700363 if (objects.empty() || endpointObjectPath == nullptr)
Ed Tanous168e20c2021-12-13 14:39:53 -0800364 {
Ed Tanous002d39b2022-05-31 08:59:27 -0700365 BMCWEB_LOG_ERROR << "Cannot find requested EndpointId";
366 conn.close("Failed to match EndpointId");
Ed Tanous168e20c2021-12-13 14:39:53 -0800367 return;
368 }
Wludzik, Jozeff6a0d632020-07-16 15:16:02 +0200369
Ed Tanous002d39b2022-05-31 08:59:27 -0700370 for (const auto& session : sessions)
371 {
372 if (session.second->getEndpointId() == conn.req.target())
Jason M. Bills613ea982022-02-16 14:24:30 -0800373 {
Ed Tanous002d39b2022-05-31 08:59:27 -0700374 BMCWEB_LOG_ERROR
375 << "Cannot open new connection - socket is in use";
376 conn.close("Slot is in use");
Jason M. Bills613ea982022-02-16 14:24:30 -0800377 return;
378 }
Ed Tanous002d39b2022-05-31 08:59:27 -0700379 }
Jason M. Bills613ea982022-02-16 14:24:30 -0800380
Ed Tanous002d39b2022-05-31 08:59:27 -0700381 // If the socket file exists (i.e. after bmcweb crash),
382 // we cannot reuse it.
383 std::remove((*socketValue).c_str());
Przemyslaw Czarnowski250b0eb2020-02-24 10:23:56 +0100384
Ed Tanous002d39b2022-05-31 08:59:27 -0700385 sessions[&conn] = std::make_shared<NbdProxyServer>(
386 conn, *socketValue, *endpointValue, *endpointObjectPath);
Wludzik, Jozeff6a0d632020-07-16 15:16:02 +0200387
Ed Tanous002d39b2022-05-31 08:59:27 -0700388 sessions[&conn]->run();
389 };
390 crow::connections::systemBus->async_method_call(
391 std::move(openHandler), "xyz.openbmc_project.VirtualMedia",
392 "/xyz/openbmc_project/VirtualMedia",
393 "org.freedesktop.DBus.ObjectManager", "GetManagedObjects");
Ed Tanous168e20c2021-12-13 14:39:53 -0800394 };
Przemyslaw Czarnowski250b0eb2020-02-24 10:23:56 +0100395
Iwona Klimaszewskac0a1c8a2019-07-12 18:26:38 +0200396 crow::connections::systemBus->async_method_call(
Przemyslaw Czarnowski250b0eb2020-02-24 10:23:56 +0100397 std::move(getUserInfoHandler),
398 "xyz.openbmc_project.User.Manager", "/xyz/openbmc_project/user",
399 "xyz.openbmc_project.User.Manager", "GetUserInfo",
400 conn.getUserName());
Iwona Klimaszewskac0a1c8a2019-07-12 18:26:38 +0200401 })
402 .onclose(
403 [](crow::websocket::Connection& conn, const std::string& reason) {
Ed Tanous002d39b2022-05-31 08:59:27 -0700404 BMCWEB_LOG_DEBUG << "nbd-proxy.onclose(reason = '" << reason << "')";
405 auto session = sessions.find(&conn);
406 if (session == sessions.end())
407 {
408 BMCWEB_LOG_DEBUG << "No session to close";
409 return;
410 }
411 session->second->close();
412 // Remove reference to session in global map
413 sessions.erase(session);
414 })
Iwona Klimaszewskac0a1c8a2019-07-12 18:26:38 +0200415 .onmessage([](crow::websocket::Connection& conn,
Vikram Bodireddyf5b16f02020-08-26 14:54:51 +0530416 const std::string& data, bool) {
Iwona Klimaszewskac0a1c8a2019-07-12 18:26:38 +0200417 BMCWEB_LOG_DEBUG << "nbd-proxy.onmessage(len = " << data.length()
418 << ")";
419 // Acquire proxy from sessions
420 auto session = sessions.find(&conn);
421 if (session != sessions.end())
422 {
423 if (session->second)
424 {
425 session->second->send(data);
426 return;
427 }
428 }
Iwona Klimaszewskac0a1c8a2019-07-12 18:26:38 +0200429 });
430}
431} // namespace nbd_proxy
432} // namespace crow