blob: 60ac98ce26a1a3328d6a6d71eec9839558e015b3 [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;
Przemyslaw Czarnowski250b0eb2020-02-24 10:23:56 +010037static 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
50 ~NbdProxyServer()
51 {
52 BMCWEB_LOG_DEBUG << "NbdProxyServer destructor";
Iwona Klimaszewskac0a1c8a2019-07-12 18:26:38 +020053 }
54
55 std::string getEndpointId() const
56 {
57 return endpointId;
58 }
59
60 void run()
61 {
62 acceptor.async_accept(
63 [this, self(shared_from_this())](boost::system::error_code ec,
64 stream_protocol::socket socket) {
65 if (ec)
66 {
Iwona Winiarska123e8232019-11-29 12:34:33 +010067 BMCWEB_LOG_ERROR << "UNIX socket: async_accept error = "
68 << ec.message();
Iwona Klimaszewskac0a1c8a2019-07-12 18:26:38 +020069 return;
70 }
71 if (peerSocket)
72 {
73 // Something is wrong - socket shouldn't be acquired at this
74 // point
75 BMCWEB_LOG_ERROR
76 << "Failed to open connection - socket already used";
77 return;
78 }
79
80 BMCWEB_LOG_DEBUG << "Connection opened";
81 peerSocket = std::move(socket);
82 doRead();
83
84 // Trigger Write if any data was sent from server
85 // Initially this is negotiation chunk
86 doWrite();
87 });
88
Wludzik, Jozeff6a0d632020-07-16 15:16:02 +020089 auto mountHandler = [this, self(shared_from_this())](
90 const boost::system::error_code ec,
Vikram Bodireddyf5b16f02020-08-26 14:54:51 +053091 const bool) {
Iwona Klimaszewskac0a1c8a2019-07-12 18:26:38 +020092 if (ec)
93 {
Iwona Winiarska123e8232019-11-29 12:34:33 +010094 BMCWEB_LOG_ERROR << "DBus error: cannot call mount method = "
95 << ec.message();
Wludzik, Jozeff6a0d632020-07-16 15:16:02 +020096 connection.close("Failed to mount media");
Iwona Klimaszewskac0a1c8a2019-07-12 18:26:38 +020097 return;
98 }
99 };
100
101 crow::connections::systemBus->async_method_call(
102 std::move(mountHandler), "xyz.openbmc_project.VirtualMedia", path,
103 "xyz.openbmc_project.VirtualMedia.Proxy", "Mount");
104 }
105
106 void send(const std::string_view data)
107 {
108 boost::asio::buffer_copy(ws2uxBuf.prepare(data.size()),
109 boost::asio::buffer(data));
110 ws2uxBuf.commit(data.size());
111 doWrite();
112 }
113
114 void close()
115 {
Iwona Winiarska123e8232019-11-29 12:34:33 +0100116 acceptor.close();
117 if (peerSocket)
118 {
119 BMCWEB_LOG_DEBUG << "peerSocket->close()";
120 peerSocket->close();
121 peerSocket.reset();
122 BMCWEB_LOG_DEBUG << "std::remove(" << socketId << ")";
123 std::remove(socketId.c_str());
124 }
Iwona Klimaszewskac0a1c8a2019-07-12 18:26:38 +0200125 // The reference to session should exists until unmount is
126 // called
127 auto unmountHandler = [](const boost::system::error_code ec) {
128 if (ec)
129 {
130 BMCWEB_LOG_ERROR << "DBus error: " << ec
131 << ", cannot call unmount method";
132 return;
133 }
134 };
135
136 crow::connections::systemBus->async_method_call(
137 std::move(unmountHandler), "xyz.openbmc_project.VirtualMedia", path,
138 "xyz.openbmc_project.VirtualMedia.Proxy", "Unmount");
139 }
140
141 private:
142 void doRead()
143 {
144 if (!peerSocket)
145 {
146 BMCWEB_LOG_DEBUG << "UNIX socket isn't created yet";
147 // Skip if UNIX socket is not created yet.
148 return;
149 }
150
151 // Trigger async read
152 peerSocket->async_read_some(
153 ux2wsBuf.prepare(nbdBufferSize),
154 [this, self(shared_from_this())](boost::system::error_code ec,
155 std::size_t bytesRead) {
156 if (ec)
157 {
158 BMCWEB_LOG_ERROR << "UNIX socket: async_read_some error = "
Iwona Winiarska123e8232019-11-29 12:34:33 +0100159 << ec.message();
Iwona Klimaszewskac0a1c8a2019-07-12 18:26:38 +0200160 // UNIX socket has been closed by peer, best we can do is to
161 // break all connections
162 close();
163 return;
164 }
165
166 // Fetch data from UNIX socket
167
168 ux2wsBuf.commit(bytesRead);
169
170 // Paste it to WebSocket as binary
171 connection.sendBinary(
172 boost::beast::buffers_to_string(ux2wsBuf.data()));
173 ux2wsBuf.consume(bytesRead);
174
175 // Allow further reads
176 doRead();
177 });
178 }
179
180 void doWrite()
181 {
182 if (!peerSocket)
183 {
184 BMCWEB_LOG_DEBUG << "UNIX socket isn't created yet";
185 // Skip if UNIX socket is not created yet. Collect data, and wait
186 // for nbd-client connection
187 return;
188 }
189
190 if (uxWriteInProgress)
191 {
192 BMCWEB_LOG_ERROR << "Write in progress";
193 return;
194 }
195
Jason M. Bills9c0b4e52022-02-14 07:23:30 -0800196 if (ws2uxBuf.size() == 0)
Iwona Klimaszewskac0a1c8a2019-07-12 18:26:38 +0200197 {
198 BMCWEB_LOG_ERROR << "No data to write to UNIX socket";
199 return;
200 }
201
202 uxWriteInProgress = true;
203 boost::asio::async_write(
204 *peerSocket, ws2uxBuf.data(),
205 [this, self(shared_from_this())](boost::system::error_code ec,
206 std::size_t bytesWritten) {
207 ws2uxBuf.consume(bytesWritten);
208 uxWriteInProgress = false;
209 if (ec)
210 {
Iwona Winiarska123e8232019-11-29 12:34:33 +0100211 BMCWEB_LOG_ERROR << "UNIX: async_write error = "
212 << ec.message();
Iwona Klimaszewskac0a1c8a2019-07-12 18:26:38 +0200213 return;
214 }
215 // Retrigger doWrite if there is something in buffer
Iwona Winiarska123e8232019-11-29 12:34:33 +0100216 if (ws2uxBuf.size() > 0)
217 {
218 doWrite();
219 }
Iwona Klimaszewskac0a1c8a2019-07-12 18:26:38 +0200220 });
221 }
222
223 // Keeps UNIX socket endpoint file path
224 const std::string socketId;
225 const std::string endpointId;
226 const std::string path;
227
228 bool uxWriteInProgress = false;
229
230 // UNIX => WebSocket buffer
231 boost::beast::multi_buffer ux2wsBuf;
232
233 // WebSocket <= UNIX buffer
234 boost::beast::multi_buffer ws2uxBuf;
235
236 // Default acceptor for UNIX socket
237 stream_protocol::acceptor acceptor;
238
239 // The socket used to communicate with the client.
240 std::optional<stream_protocol::socket> peerSocket;
241
242 crow::websocket::Connection& connection;
243};
244
245static boost::container::flat_map<crow::websocket::Connection*,
246 std::shared_ptr<NbdProxyServer>>
247 sessions;
248
Ed Tanous81ce6092020-12-17 16:54:55 +0000249inline void requestRoutes(App& app)
Iwona Klimaszewskac0a1c8a2019-07-12 18:26:38 +0200250{
251 BMCWEB_ROUTE(app, "/nbd/<str>")
252 .websocket()
Gunnar Millsccd584f2021-11-16 11:36:33 -0600253 .onopen([](crow::websocket::Connection& conn,
254 const std::shared_ptr<bmcweb::AsyncResp>& asyncResp) {
Iwona Klimaszewskac0a1c8a2019-07-12 18:26:38 +0200255 BMCWEB_LOG_DEBUG << "nbd-proxy.onopen(" << &conn << ")";
256
Ed Tanous168e20c2021-12-13 14:39:53 -0800257 auto getUserInfoHandler = [&conn, asyncResp](
258 const boost::system::error_code ec,
259 boost::container::flat_map<
260 std::string,
261 dbus::utility::DbusVariantType>
262 userInfo) {
263 if (ec)
264 {
265 BMCWEB_LOG_ERROR << "GetUserInfo failed...";
266 conn.close("Failed to get user information");
267 return;
268 }
Przemyslaw Czarnowski250b0eb2020-02-24 10:23:56 +0100269
Ed Tanous168e20c2021-12-13 14:39:53 -0800270 const std::string* userRolePtr = nullptr;
271 auto userInfoIter = userInfo.find("UserPrivilege");
272 if (userInfoIter != userInfo.end())
273 {
274 userRolePtr =
275 std::get_if<std::string>(&userInfoIter->second);
276 }
Przemyslaw Czarnowski250b0eb2020-02-24 10:23:56 +0100277
Ed Tanous168e20c2021-12-13 14:39:53 -0800278 std::string userRole{};
279 if (userRolePtr != nullptr)
280 {
281 userRole = *userRolePtr;
282 BMCWEB_LOG_DEBUG << "userName = " << conn.getUserName()
283 << " userRole = " << *userRolePtr;
284 }
Wludzik, Jozeff6a0d632020-07-16 15:16:02 +0200285
Ed Tanous168e20c2021-12-13 14:39:53 -0800286 // Get the user privileges from the role
287 ::redfish::Privileges userPrivileges =
288 ::redfish::getUserPrivileges(userRole);
Wludzik, Jozeff6a0d632020-07-16 15:16:02 +0200289
Ed Tanous168e20c2021-12-13 14:39:53 -0800290 const ::redfish::Privileges requiredPrivileges{
291 requiredPrivilegeString};
Wludzik, Jozeff6a0d632020-07-16 15:16:02 +0200292
Ed Tanous168e20c2021-12-13 14:39:53 -0800293 if (!userPrivileges.isSupersetOf(requiredPrivileges))
294 {
295 BMCWEB_LOG_DEBUG << "User " << conn.getUserName()
296 << " not authorized for nbd connection";
297 conn.close("Unathourized access");
298 return;
299 }
Wludzik, Jozeff6a0d632020-07-16 15:16:02 +0200300
Jason M. Bills613ea982022-02-16 14:24:30 -0800301 auto openHandler = [&conn, asyncResp](
302 const boost::system::error_code ec,
303 const dbus::utility::ManagedObjectType&
304 objects) {
305 const std::string* socketValue = nullptr;
306 const std::string* endpointValue = nullptr;
307 const std::string* endpointObjectPath = nullptr;
Wludzik, Jozeff6a0d632020-07-16 15:16:02 +0200308
Jason M. Bills613ea982022-02-16 14:24:30 -0800309 if (ec)
310 {
311 BMCWEB_LOG_ERROR << "DBus error: " << ec.message();
312 conn.close("Failed to create mount point");
313 return;
314 }
315
316 for (const auto& [objectPath, interfaces] : objects)
317 {
318 for (const auto& [interface, properties] : interfaces)
Przemyslaw Czarnowski250b0eb2020-02-24 10:23:56 +0100319 {
Jason M. Bills613ea982022-02-16 14:24:30 -0800320 if (interface !=
321 "xyz.openbmc_project.VirtualMedia.MountPoint")
Przemyslaw Czarnowski250b0eb2020-02-24 10:23:56 +0100322 {
Przemyslaw Czarnowski250b0eb2020-02-24 10:23:56 +0100323 continue;
324 }
325
Jason M. Bills613ea982022-02-16 14:24:30 -0800326 for (const auto& [name, value] : properties)
Wludzik, Jozeff6a0d632020-07-16 15:16:02 +0200327 {
Jason M. Bills613ea982022-02-16 14:24:30 -0800328 if (name == "EndpointId")
Wludzik, Jozeff6a0d632020-07-16 15:16:02 +0200329 {
Jason M. Bills613ea982022-02-16 14:24:30 -0800330 endpointValue =
331 std::get_if<std::string>(&value);
Wludzik, Jozeff6a0d632020-07-16 15:16:02 +0200332
Jason M. Bills613ea982022-02-16 14:24:30 -0800333 if (endpointValue == nullptr)
334 {
335 BMCWEB_LOG_ERROR
336 << "EndpointId property value is null";
337 }
338 }
339 if (name == "Socket")
Wludzik, Jozeff6a0d632020-07-16 15:16:02 +0200340 {
Jason M. Bills613ea982022-02-16 14:24:30 -0800341 socketValue =
342 std::get_if<std::string>(&value);
343 if (socketValue == nullptr)
344 {
345 BMCWEB_LOG_ERROR
346 << "Socket property value is null";
347 }
Wludzik, Jozeff6a0d632020-07-16 15:16:02 +0200348 }
Wludzik, Jozeff6a0d632020-07-16 15:16:02 +0200349 }
Przemyslaw Czarnowski250b0eb2020-02-24 10:23:56 +0100350 }
Przemyslaw Czarnowski250b0eb2020-02-24 10:23:56 +0100351
Jason M. Bills613ea982022-02-16 14:24:30 -0800352 if (endpointValue && socketValue &&
353 *endpointValue == conn.req.target())
354 {
355 endpointObjectPath = &objectPath.str;
356 break;
357 }
358 }
359
360 if (objects.empty() || endpointObjectPath == nullptr)
361 {
362 BMCWEB_LOG_ERROR << "Cannot find requested EndpointId";
363 conn.close("Failed to match EndpointId");
364 return;
365 }
366
367 for (const auto& session : sessions)
368 {
369 if (session.second->getEndpointId() ==
370 conn.req.target())
Wludzik, Jozeff6a0d632020-07-16 15:16:02 +0200371 {
372 BMCWEB_LOG_ERROR
Jason M. Bills613ea982022-02-16 14:24:30 -0800373 << "Cannot open new connection - socket is in use";
374 conn.close("Slot is in use");
Wludzik, Jozeff6a0d632020-07-16 15:16:02 +0200375 return;
376 }
Jason M. Bills613ea982022-02-16 14:24:30 -0800377 }
Przemyslaw Czarnowski250b0eb2020-02-24 10:23:56 +0100378
Jason M. Bills613ea982022-02-16 14:24:30 -0800379 // If the socket file exists (i.e. after bmcweb crash),
380 // we cannot reuse it.
381 std::remove((*socketValue).c_str());
Przemyslaw Czarnowski250b0eb2020-02-24 10:23:56 +0100382
Jason M. Bills613ea982022-02-16 14:24:30 -0800383 sessions[&conn] = std::make_shared<NbdProxyServer>(
384 conn, *socketValue, *endpointValue,
385 *endpointObjectPath);
Przemyslaw Czarnowski250b0eb2020-02-24 10:23:56 +0100386
Jason M. Bills613ea982022-02-16 14:24:30 -0800387 sessions[&conn]->run();
388 };
Ed Tanous168e20c2021-12-13 14:39:53 -0800389 crow::connections::systemBus->async_method_call(
390 std::move(openHandler), "xyz.openbmc_project.VirtualMedia",
391 "/xyz/openbmc_project/VirtualMedia",
392 "org.freedesktop.DBus.ObjectManager", "GetManagedObjects");
393 };
Przemyslaw Czarnowski250b0eb2020-02-24 10:23:56 +0100394
Iwona Klimaszewskac0a1c8a2019-07-12 18:26:38 +0200395 crow::connections::systemBus->async_method_call(
Przemyslaw Czarnowski250b0eb2020-02-24 10:23:56 +0100396 std::move(getUserInfoHandler),
397 "xyz.openbmc_project.User.Manager", "/xyz/openbmc_project/user",
398 "xyz.openbmc_project.User.Manager", "GetUserInfo",
399 conn.getUserName());
Iwona Klimaszewskac0a1c8a2019-07-12 18:26:38 +0200400 })
401 .onclose(
402 [](crow::websocket::Connection& conn, const std::string& reason) {
403 BMCWEB_LOG_DEBUG << "nbd-proxy.onclose(reason = '" << reason
404 << "')";
405 auto session = sessions.find(&conn);
406 if (session == sessions.end())
407 {
408 BMCWEB_LOG_DEBUG << "No session to close";
409 return;
410 }
Iwona Winiarska123e8232019-11-29 12:34:33 +0100411 // Remove reference to session in global map
Iwona Klimaszewskac0a1c8a2019-07-12 18:26:38 +0200412 sessions.erase(session);
Wludzik, Jozeff6a0d632020-07-16 15:16:02 +0200413 session->second->close();
Iwona Klimaszewskac0a1c8a2019-07-12 18:26:38 +0200414 })
415 .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