blob: 0356161f7546e2bbc34d3c0bf95e3aa9ffce249b [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
17#include <app.h>
18#include <websocket.h>
19
20#include <boost/asio.hpp>
21#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>
Iwona Klimaszewskac0a1c8a2019-07-12 18:26:38 +020026#include <webserver_common.hpp>
27
Gunnar Mills1214b7e2020-06-04 10:11:30 -050028#include <variant>
29
Iwona Klimaszewskac0a1c8a2019-07-12 18:26:38 +020030namespace crow
31{
32
33namespace nbd_proxy
34{
35
36using boost::asio::local::stream_protocol;
37
38static constexpr auto nbdBufferSize = 131088;
Przemyslaw Czarnowski250b0eb2020-02-24 10:23:56 +010039static const char* requiredPrivilegeString = "ConfigureManager";
Iwona Klimaszewskac0a1c8a2019-07-12 18:26:38 +020040
41struct NbdProxyServer : std::enable_shared_from_this<NbdProxyServer>
42{
43 NbdProxyServer(crow::websocket::Connection& connIn,
44 const std::string& socketIdIn,
45 const std::string& endpointIdIn, const std::string& pathIn) :
46 socketId(socketIdIn),
47 endpointId(endpointIdIn), path(pathIn),
48 acceptor(connIn.get_io_context(), stream_protocol::endpoint(socketId)),
49 connection(connIn)
Gunnar Mills1214b7e2020-06-04 10:11:30 -050050 {}
Iwona Klimaszewskac0a1c8a2019-07-12 18:26:38 +020051
52 ~NbdProxyServer()
53 {
54 BMCWEB_LOG_DEBUG << "NbdProxyServer destructor";
55 close();
Iwona Klimaszewskac0a1c8a2019-07-12 18:26:38 +020056 }
57
58 std::string getEndpointId() const
59 {
60 return endpointId;
61 }
62
63 void run()
64 {
65 acceptor.async_accept(
66 [this, self(shared_from_this())](boost::system::error_code ec,
67 stream_protocol::socket socket) {
68 if (ec)
69 {
Iwona Winiarska123e8232019-11-29 12:34:33 +010070 BMCWEB_LOG_ERROR << "UNIX socket: async_accept error = "
71 << ec.message();
Iwona Klimaszewskac0a1c8a2019-07-12 18:26:38 +020072 return;
73 }
74 if (peerSocket)
75 {
76 // Something is wrong - socket shouldn't be acquired at this
77 // point
78 BMCWEB_LOG_ERROR
79 << "Failed to open connection - socket already used";
80 return;
81 }
82
83 BMCWEB_LOG_DEBUG << "Connection opened";
84 peerSocket = std::move(socket);
85 doRead();
86
87 // Trigger Write if any data was sent from server
88 // Initially this is negotiation chunk
89 doWrite();
90 });
91
92 auto mountHandler = [](const boost::system::error_code ec,
93 const bool status) {
94 if (ec)
95 {
Iwona Winiarska123e8232019-11-29 12:34:33 +010096 BMCWEB_LOG_ERROR << "DBus error: cannot call mount method = "
97 << ec.message();
Iwona Klimaszewskac0a1c8a2019-07-12 18:26:38 +020098 return;
99 }
100 };
101
102 crow::connections::systemBus->async_method_call(
103 std::move(mountHandler), "xyz.openbmc_project.VirtualMedia", path,
104 "xyz.openbmc_project.VirtualMedia.Proxy", "Mount");
105 }
106
107 void send(const std::string_view data)
108 {
109 boost::asio::buffer_copy(ws2uxBuf.prepare(data.size()),
110 boost::asio::buffer(data));
111 ws2uxBuf.commit(data.size());
112 doWrite();
113 }
114
115 void close()
116 {
Iwona Winiarska123e8232019-11-29 12:34:33 +0100117 acceptor.close();
118 if (peerSocket)
119 {
120 BMCWEB_LOG_DEBUG << "peerSocket->close()";
121 peerSocket->close();
122 peerSocket.reset();
123 BMCWEB_LOG_DEBUG << "std::remove(" << socketId << ")";
124 std::remove(socketId.c_str());
125 }
Iwona Klimaszewskac0a1c8a2019-07-12 18:26:38 +0200126 // The reference to session should exists until unmount is
127 // called
128 auto unmountHandler = [](const boost::system::error_code ec) {
129 if (ec)
130 {
131 BMCWEB_LOG_ERROR << "DBus error: " << ec
132 << ", cannot call unmount method";
133 return;
134 }
135 };
136
137 crow::connections::systemBus->async_method_call(
138 std::move(unmountHandler), "xyz.openbmc_project.VirtualMedia", path,
139 "xyz.openbmc_project.VirtualMedia.Proxy", "Unmount");
140 }
141
142 private:
143 void doRead()
144 {
145 if (!peerSocket)
146 {
147 BMCWEB_LOG_DEBUG << "UNIX socket isn't created yet";
148 // Skip if UNIX socket is not created yet.
149 return;
150 }
151
152 // Trigger async read
153 peerSocket->async_read_some(
154 ux2wsBuf.prepare(nbdBufferSize),
155 [this, self(shared_from_this())](boost::system::error_code ec,
156 std::size_t bytesRead) {
157 if (ec)
158 {
159 BMCWEB_LOG_ERROR << "UNIX socket: async_read_some error = "
Iwona Winiarska123e8232019-11-29 12:34:33 +0100160 << ec.message();
Iwona Klimaszewskac0a1c8a2019-07-12 18:26:38 +0200161 // UNIX socket has been closed by peer, best we can do is to
162 // break all connections
163 close();
164 return;
165 }
166
167 // Fetch data from UNIX socket
168
169 ux2wsBuf.commit(bytesRead);
170
171 // Paste it to WebSocket as binary
172 connection.sendBinary(
173 boost::beast::buffers_to_string(ux2wsBuf.data()));
174 ux2wsBuf.consume(bytesRead);
175
176 // Allow further reads
177 doRead();
178 });
179 }
180
181 void doWrite()
182 {
183 if (!peerSocket)
184 {
185 BMCWEB_LOG_DEBUG << "UNIX socket isn't created yet";
186 // Skip if UNIX socket is not created yet. Collect data, and wait
187 // for nbd-client connection
188 return;
189 }
190
191 if (uxWriteInProgress)
192 {
193 BMCWEB_LOG_ERROR << "Write in progress";
194 return;
195 }
196
197 if (ws2uxBuf.size() == 0)
198 {
199 BMCWEB_LOG_ERROR << "No data to write to UNIX socket";
200 return;
201 }
202
203 uxWriteInProgress = true;
204 boost::asio::async_write(
205 *peerSocket, ws2uxBuf.data(),
206 [this, self(shared_from_this())](boost::system::error_code ec,
207 std::size_t bytesWritten) {
208 ws2uxBuf.consume(bytesWritten);
209 uxWriteInProgress = false;
210 if (ec)
211 {
Iwona Winiarska123e8232019-11-29 12:34:33 +0100212 BMCWEB_LOG_ERROR << "UNIX: async_write error = "
213 << ec.message();
Iwona Klimaszewskac0a1c8a2019-07-12 18:26:38 +0200214 return;
215 }
216 // Retrigger doWrite if there is something in buffer
Iwona Winiarska123e8232019-11-29 12:34:33 +0100217 if (ws2uxBuf.size() > 0)
218 {
219 doWrite();
220 }
Iwona Klimaszewskac0a1c8a2019-07-12 18:26:38 +0200221 });
222 }
223
224 // Keeps UNIX socket endpoint file path
225 const std::string socketId;
226 const std::string endpointId;
227 const std::string path;
228
229 bool uxWriteInProgress = false;
230
231 // UNIX => WebSocket buffer
232 boost::beast::multi_buffer ux2wsBuf;
233
234 // WebSocket <= UNIX buffer
235 boost::beast::multi_buffer ws2uxBuf;
236
237 // Default acceptor for UNIX socket
238 stream_protocol::acceptor acceptor;
239
240 // The socket used to communicate with the client.
241 std::optional<stream_protocol::socket> peerSocket;
242
243 crow::websocket::Connection& connection;
244};
245
246static boost::container::flat_map<crow::websocket::Connection*,
247 std::shared_ptr<NbdProxyServer>>
248 sessions;
249
250void requestRoutes(CrowApp& app)
251{
252 BMCWEB_ROUTE(app, "/nbd/<str>")
253 .websocket()
Przemyslaw Czarnowski250b0eb2020-02-24 10:23:56 +0100254 .onopen([](crow::websocket::Connection& conn,
255 std::shared_ptr<bmcweb::AsyncResp> asyncResp) {
Iwona Klimaszewskac0a1c8a2019-07-12 18:26:38 +0200256 BMCWEB_LOG_DEBUG << "nbd-proxy.onopen(" << &conn << ")";
257
Przemyslaw Czarnowski250b0eb2020-02-24 10:23:56 +0100258 auto getUserInfoHandler = [&conn, asyncResp{std::move(asyncResp)}](
259 const boost::system::error_code ec,
260 boost::container::flat_map<
261 std::string,
262 std::variant<
263 bool, std::string,
264 std::vector<std::string>>>
265 userInfo) {
Iwona Klimaszewskac0a1c8a2019-07-12 18:26:38 +0200266 if (ec)
267 {
Przemyslaw Czarnowski250b0eb2020-02-24 10:23:56 +0100268 BMCWEB_LOG_ERROR << "GetUserInfo failed...";
Iwona Klimaszewskac0a1c8a2019-07-12 18:26:38 +0200269 asyncResp->res.result(
Przemyslaw Czarnowski250b0eb2020-02-24 10:23:56 +0100270 boost::beast::http::status::internal_server_error);
Iwona Klimaszewskac0a1c8a2019-07-12 18:26:38 +0200271 return;
272 }
273
Przemyslaw Czarnowski250b0eb2020-02-24 10:23:56 +0100274 const std::string* userRolePtr = nullptr;
275 auto userInfoIter = userInfo.find("UserPrivilege");
276 if (userInfoIter != userInfo.end())
277 {
278 userRolePtr =
279 std::get_if<std::string>(&userInfoIter->second);
280 }
Iwona Klimaszewskac0a1c8a2019-07-12 18:26:38 +0200281
Przemyslaw Czarnowski250b0eb2020-02-24 10:23:56 +0100282 std::string userRole{};
283 if (userRolePtr != nullptr)
284 {
285 userRole = *userRolePtr;
286 BMCWEB_LOG_DEBUG << "userName = " << conn.getUserName()
287 << " userRole = " << *userRolePtr;
288 }
Iwona Klimaszewskac0a1c8a2019-07-12 18:26:38 +0200289
Przemyslaw Czarnowski250b0eb2020-02-24 10:23:56 +0100290 // Get the user privileges from the role
291 ::redfish::Privileges userPrivileges =
292 ::redfish::getUserPrivileges(userRole);
Iwona Klimaszewskac0a1c8a2019-07-12 18:26:38 +0200293
Przemyslaw Czarnowski250b0eb2020-02-24 10:23:56 +0100294 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 asyncResp->res.result(
302 boost::beast::http::status::unauthorized);
303 return;
304 }
305
306 for (const auto session : sessions)
307 {
308 if (session.second->getEndpointId() == conn.req.target())
309 {
310 BMCWEB_LOG_ERROR
311 << "Cannot open new connection - socket is in use";
312 asyncResp->res.result(
313 boost::beast::http::status::bad_request);
314 return;
315 }
316 }
317
318 auto openHandler = [asyncResp,
319 &conn](const boost::system::error_code ec,
320 dbus::utility::ManagedObjectType&
321 objects) {
322 const std::string* socketValue = nullptr;
323 const std::string* endpointValue = nullptr;
324 const std::string* endpointObjectPath = nullptr;
325
326 if (ec)
327 {
328 BMCWEB_LOG_ERROR << "DBus error: " << ec.message();
329 asyncResp->res.result(
330 boost::beast::http::status::internal_server_error);
331 return;
332 }
333
334 for (const auto& objectPath : objects)
335 {
336 const auto interfaceMap = objectPath.second.find(
337 "xyz.openbmc_project.VirtualMedia.MountPoint");
338
339 if (interfaceMap == objectPath.second.end())
340 {
341 BMCWEB_LOG_DEBUG << "Cannot find MountPoint object";
342 continue;
343 }
344
345 const auto endpoint =
346 interfaceMap->second.find("EndpointId");
347 if (endpoint == interfaceMap->second.end())
348 {
349 BMCWEB_LOG_DEBUG
350 << "Cannot find EndpointId property";
351 continue;
352 }
353
354 endpointValue =
355 std::get_if<std::string>(&endpoint->second);
356
357 if (endpointValue == nullptr)
358 {
359 BMCWEB_LOG_ERROR
360 << "EndpointId property value is null";
361 continue;
362 }
363
364 if (*endpointValue == conn.req.target())
365 {
366 const auto socket =
367 interfaceMap->second.find("Socket");
368 if (socket == interfaceMap->second.end())
369 {
370 BMCWEB_LOG_DEBUG
371 << "Cannot find Socket property";
372 continue;
373 }
374
375 socketValue =
376 std::get_if<std::string>(&socket->second);
377 if (socketValue == nullptr)
378 {
379 BMCWEB_LOG_ERROR
380 << "Socket property value is null";
381 continue;
382 }
383
384 endpointObjectPath = &objectPath.first.str;
385 break;
386 }
387 }
388
389 if (endpointObjectPath == nullptr)
390 {
391 BMCWEB_LOG_ERROR << "Cannot find requested EndpointId";
392 asyncResp->res.result(
393 boost::beast::http::status::not_found);
394 return;
395 }
396
397 // If the socket file exists (i.e. after bmcweb crash),
398 // we cannot reuse it.
399 std::remove((*socketValue).c_str());
400
401 sessions[&conn] = std::make_shared<NbdProxyServer>(
402 conn, std::move(*socketValue),
403 std::move(*endpointValue),
404 std::move(*endpointObjectPath));
405
406 sessions[&conn]->run();
407
408 asyncResp->res.result(boost::beast::http::status::ok);
409 };
410 crow::connections::systemBus->async_method_call(
411 std::move(openHandler), "xyz.openbmc_project.VirtualMedia",
412 "/xyz/openbmc_project/VirtualMedia",
413 "org.freedesktop.DBus.ObjectManager", "GetManagedObjects");
Iwona Klimaszewskac0a1c8a2019-07-12 18:26:38 +0200414 };
Przemyslaw Czarnowski250b0eb2020-02-24 10:23:56 +0100415
Iwona Klimaszewskac0a1c8a2019-07-12 18:26:38 +0200416 crow::connections::systemBus->async_method_call(
Przemyslaw Czarnowski250b0eb2020-02-24 10:23:56 +0100417 std::move(getUserInfoHandler),
418 "xyz.openbmc_project.User.Manager", "/xyz/openbmc_project/user",
419 "xyz.openbmc_project.User.Manager", "GetUserInfo",
420 conn.getUserName());
Iwona Klimaszewskac0a1c8a2019-07-12 18:26:38 +0200421 })
422 .onclose(
423 [](crow::websocket::Connection& conn, const std::string& reason) {
424 BMCWEB_LOG_DEBUG << "nbd-proxy.onclose(reason = '" << reason
425 << "')";
426 auto session = sessions.find(&conn);
427 if (session == sessions.end())
428 {
429 BMCWEB_LOG_DEBUG << "No session to close";
430 return;
431 }
Iwona Klimaszewskac0a1c8a2019-07-12 18:26:38 +0200432 session->second->close();
Iwona Winiarska123e8232019-11-29 12:34:33 +0100433 // Remove reference to session in global map
Iwona Klimaszewskac0a1c8a2019-07-12 18:26:38 +0200434 sessions.erase(session);
435 })
436 .onmessage([](crow::websocket::Connection& conn,
437 const std::string& data, bool isBinary) {
438 BMCWEB_LOG_DEBUG << "nbd-proxy.onmessage(len = " << data.length()
439 << ")";
440 // Acquire proxy from sessions
441 auto session = sessions.find(&conn);
442 if (session != sessions.end())
443 {
444 if (session->second)
445 {
446 session->second->send(data);
447 return;
448 }
449 }
450 conn.close();
451 });
452}
453} // namespace nbd_proxy
454} // namespace crow