1 /*
2 * Copyright (c) 2022 Huawei Device Co., Ltd.
3 * Licensed under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License.
5 * You may obtain a copy of the License at
6 *
7 * http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS,
11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 * See the License for the specific language governing permissions and
13 * limitations under the License.
14 */
15
16 #if defined(PANDA_TARGET_WINDOWS)
17 #include <ws2tcpip.h>
18 #else
19 #include <arpa/inet.h>
20 #endif
21
22 #include <fcntl.h>
23 #include "common/log_wrapper.h"
24 #include "frame_builder.h"
25 #include "handshake_helper.h"
26 #include "network.h"
27 #include "server/websocket_server.h"
28 #include "string_utils.h"
29
30 #include <mutex>
31 #include <thread>
32
33 namespace OHOS::ArkCompiler::Toolchain {
ValidateHandShakeMessage(const HttpRequest & req)34 static bool ValidateHandShakeMessage(const HttpRequest& req)
35 {
36 std::string upgradeHeaderValue = req.upgrade;
37 // Switch to lower case in order to support obsolete versions of WebSocket protocol.
38 ToLowerCase(upgradeHeaderValue);
39 return req.connection.find("Upgrade") != std::string::npos &&
40 upgradeHeaderValue.find("websocket") != std::string::npos &&
41 req.version.compare("HTTP/1.1") == 0;
42 }
43
~WebSocketServer()44 WebSocketServer::~WebSocketServer() noexcept
45 {
46 if (serverFd_ != -1) {
47 LOGW("WebSocket server is closed while destructing the object");
48 close(serverFd_);
49 // Reset directly in order to prevent static analyzer warnings.
50 serverFd_ = -1;
51 }
52 }
53
DecodeMessage(WebSocketFrame & wsFrame) const54 bool WebSocketServer::DecodeMessage(WebSocketFrame& wsFrame) const
55 {
56 const uint64_t msgLen = wsFrame.payloadLen;
57 if (msgLen == 0) {
58 // receiving empty data is OK
59 return true;
60 }
61 auto& buffer = wsFrame.payload;
62 buffer.resize(msgLen, 0);
63
64 if (!RecvUnderLock(wsFrame.maskingKey, sizeof(wsFrame.maskingKey))) {
65 LOGE("DecodeMessage: Recv maskingKey failed");
66 return false;
67 }
68
69 if (!RecvUnderLock(buffer)) {
70 LOGE("DecodeMessage: Recv message with mask failed");
71 return false;
72 }
73
74 for (uint64_t i = 0; i < msgLen; i++) {
75 const auto j = i % WebSocketFrame::MASK_LEN;
76 buffer[i] = static_cast<uint8_t>(buffer[i]) ^ wsFrame.maskingKey[j];
77 }
78
79 return true;
80 }
81
ProtocolUpgrade(const HttpRequest & req)82 bool WebSocketServer::ProtocolUpgrade(const HttpRequest& req)
83 {
84 unsigned char encodedKey[WebSocketKeyEncoder::ENCODED_KEY_LEN + 1];
85 if (!WebSocketKeyEncoder::EncodeKey(req.secWebSocketKey, encodedKey)) {
86 LOGE("ProtocolUpgrade: failed to encode WebSocket-Key");
87 return false;
88 }
89
90 ProtocolUpgradeBuilder requestBuilder(encodedKey);
91 if (!SendUnderLock(requestBuilder.GetUpgradeMessage(), requestBuilder.GetLength())) {
92 LOGE("ProtocolUpgrade: Send failed");
93 return false;
94 }
95 return true;
96 }
97
ResponseInvalidHandShake() const98 bool WebSocketServer::ResponseInvalidHandShake() const
99 {
100 const std::string response(BAD_REQUEST_RESPONSE);
101 return SendUnderLock(response);
102 }
103
HttpHandShake()104 bool WebSocketServer::HttpHandShake()
105 {
106 std::string msgBuf(HTTP_HANDSHAKE_MAX_LEN, 0);
107 ssize_t msgLen = 0;
108 {
109 std::shared_lock lock(GetConnectionMutex());
110 while ((msgLen = recv(GetConnectionSocket(), msgBuf.data(), HTTP_HANDSHAKE_MAX_LEN, 0)) < 0 &&
111 (errno == EINTR || errno == EAGAIN)) {
112 LOGW("HttpHandShake recv failed, errno = %{public}d", errno);
113 }
114 }
115 if (msgLen <= 0) {
116 LOGE("ReadMsg failed, msgLen = %{public}ld, errno = %{public}d", static_cast<long>(msgLen), errno);
117 return false;
118 }
119 // reduce to received size
120 msgBuf.resize(msgLen);
121
122 HttpRequest req;
123 if (!HttpRequest::Decode(msgBuf, req)) {
124 LOGE("HttpHandShake: Upgrade failed");
125 return false;
126 }
127 if (validateCb_ && !validateCb_(req)) {
128 LOGE("HttpHandShake: Validation failed");
129 return false;
130 }
131
132 if (ValidateHandShakeMessage(req)) {
133 return ProtocolUpgrade(req);
134 }
135
136 LOGE("HttpHandShake: HTTP upgrade parameters failure");
137 if (!ResponseInvalidHandShake()) {
138 LOGE("HttpHandShake: failed to send 'bad request' response");
139 }
140 return false;
141 }
142
MoveToConnectingState()143 bool WebSocketServer::MoveToConnectingState()
144 {
145 if (!serverUp_.load()) {
146 // Server `Close` happened, must not accept new connections.
147 return false;
148 }
149 auto expected = ConnectionState::CLOSED;
150 if (!CompareExchangeConnectionState(expected, ConnectionState::CONNECTING)) {
151 switch (expected) {
152 case ConnectionState::CLOSING:
153 LOGW("MoveToConnectingState during closing connection");
154 break;
155 case ConnectionState::OPEN:
156 LOGW("MoveToConnectingState during already established connection");
157 break;
158 case ConnectionState::CONNECTING:
159 LOGE("MoveToConnectingState during opening connection, which violates WebSocketServer guarantees");
160 break;
161 default:
162 break;
163 }
164 return false;
165 }
166 // Must check once again because of `Close` method implementation.
167 if (!serverUp_.load()) {
168 // Server `Close` happened, `serverFd_` was closed, new connection must not be opened.
169 expected = SetConnectionState(ConnectionState::CLOSED);
170 if (expected != ConnectionState::CONNECTING) {
171 LOGE("AcceptNewConnection: Close guarantees violated");
172 }
173 return false;
174 }
175 return true;
176 }
177
AcceptNewConnection()178 bool WebSocketServer::AcceptNewConnection()
179 {
180 if (!MoveToConnectingState()) {
181 return false;
182 }
183
184 const int newConnectionFd = accept(serverFd_, nullptr, nullptr);
185 if (newConnectionFd < SOCKET_SUCCESS) {
186 LOGI("AcceptNewConnection accept has exited");
187
188 auto expected = SetConnectionState(ConnectionState::CLOSED);
189 if (expected != ConnectionState::CONNECTING) {
190 LOGE("AcceptNewConnection: violation due to concurrent close and accept: got %{public}d",
191 EnumToNumber(expected));
192 }
193 return false;
194 }
195 {
196 std::unique_lock lock(GetConnectionMutex());
197 SetConnectionSocket(newConnectionFd);
198 }
199
200 if (!HttpHandShake()) {
201 LOGW("AcceptNewConnection HttpHandShake failed");
202
203 auto expected = SetConnectionState(ConnectionState::CLOSING);
204 if (expected != ConnectionState::CONNECTING) {
205 LOGE("AcceptNewConnection: violation due to concurrent close and accept: got %{public}d",
206 EnumToNumber(expected));
207 }
208 CloseConnectionSocket(ConnectionCloseReason::FAIL);
209 return false;
210 }
211
212 OnNewConnection();
213 return true;
214 }
215
InitTcpWebSocket(int port,uint32_t timeoutLimit)216 bool WebSocketServer::InitTcpWebSocket(int port, uint32_t timeoutLimit)
217 {
218 if (port < 0) {
219 LOGE("InitTcpWebSocket invalid port");
220 return false;
221 }
222 if (serverUp_.load()) {
223 LOGI("InitTcpWebSocket websocket has inited");
224 return true;
225 }
226 #if defined(WINDOWS_PLATFORM)
227 WORD sockVersion = MAKEWORD(2, 2); // 2: version 2.2
228 WSADATA wsaData;
229 if (WSAStartup(sockVersion, &wsaData) != 0) {
230 LOGE("InitTcpWebSocket WSA init failed");
231 return false;
232 }
233 #endif
234 serverFd_ = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
235 if (serverFd_ < SOCKET_SUCCESS) {
236 LOGE("InitTcpWebSocket socket init failed, errno = %{public}d", errno);
237 return false;
238 }
239 // allow specified port can be used at once and not wait TIME_WAIT status ending
240 int sockOptVal = 1;
241 if ((setsockopt(serverFd_, SOL_SOCKET, SO_REUSEADDR,
242 reinterpret_cast<char *>(&sockOptVal), sizeof(sockOptVal))) != SOCKET_SUCCESS) {
243 LOGE("InitTcpWebSocket setsockopt SO_REUSEADDR failed, errno = %{public}d", errno);
244 CloseServerSocket();
245 return false;
246 }
247 if (!SetWebSocketTimeOut(serverFd_, timeoutLimit)) {
248 LOGE("InitTcpWebSocket SetWebSocketTimeOut failed");
249 CloseServerSocket();
250 return false;
251 }
252 return BindAndListenTcpWebSocket(port);
253 }
254
BindAndListenTcpWebSocket(int port)255 bool WebSocketServer::BindAndListenTcpWebSocket(int port)
256 {
257 sockaddr_in addrSin = {};
258 addrSin.sin_family = AF_INET;
259 addrSin.sin_port = htons(port);
260 if (inet_pton(AF_INET, "127.0.0.1", &addrSin.sin_addr) != NET_SUCCESS) {
261 LOGE("BindAndListenTcpWebSocket inet_pton failed, error = %{public}d", errno);
262 return false;
263 }
264 if (bind(serverFd_, reinterpret_cast<struct sockaddr*>(&addrSin), sizeof(addrSin)) != SOCKET_SUCCESS ||
265 listen(serverFd_, 1) != SOCKET_SUCCESS) {
266 LOGE("BindAndListenTcpWebSocket bind/listen failed, errno = %{public}d", errno);
267 CloseServerSocket();
268 return false;
269 }
270 serverUp_.store(true);
271 return true;
272 }
273
274 #if !defined(WINDOWS_PLATFORM)
InitUnixWebSocket(const std::string & sockName,uint32_t timeoutLimit)275 bool WebSocketServer::InitUnixWebSocket(const std::string& sockName, uint32_t timeoutLimit)
276 {
277 if (serverUp_.load()) {
278 LOGI("InitUnixWebSocket websocket has inited");
279 return true;
280 }
281 serverFd_ = socket(AF_UNIX, SOCK_STREAM, 0); // 0: default protocol
282 if (serverFd_ < SOCKET_SUCCESS) {
283 LOGE("InitUnixWebSocket socket init failed, errno = %{public}d", errno);
284 return false;
285 }
286 // set send and recv timeout
287 if (!SetWebSocketTimeOut(serverFd_, timeoutLimit)) {
288 LOGE("InitUnixWebSocket SetWebSocketTimeOut failed");
289 CloseServerSocket();
290 return false;
291 }
292
293 struct sockaddr_un un;
294 if (memset_s(&un, sizeof(un), 0, sizeof(un)) != EOK) {
295 LOGE("InitUnixWebSocket memset_s failed");
296 CloseServerSocket();
297 return false;
298 }
299 un.sun_family = AF_UNIX;
300 if (strcpy_s(un.sun_path + 1, sizeof(un.sun_path) - 1, sockName.c_str()) != EOK) {
301 LOGE("InitUnixWebSocket strcpy_s failed");
302 CloseServerSocket();
303 return false;
304 }
305 un.sun_path[0] = '\0';
306 uint32_t len = offsetof(struct sockaddr_un, sun_path) + strlen(sockName.c_str()) + 1;
307 if (bind(serverFd_, reinterpret_cast<struct sockaddr*>(&un), static_cast<int32_t>(len)) != SOCKET_SUCCESS) {
308 LOGE("InitUnixWebSocket bind failed, errno = %{public}d", errno);
309 CloseServerSocket();
310 return false;
311 }
312 if (listen(serverFd_, 1) != SOCKET_SUCCESS) { // 1: connection num
313 LOGE("InitUnixWebSocket listen failed, errno = %{public}d", errno);
314 CloseServerSocket();
315 return false;
316 }
317 serverUp_.store(true);
318 return true;
319 }
320
InitUnixWebSocket(int socketfd)321 bool WebSocketServer::InitUnixWebSocket(int socketfd)
322 {
323 if (serverUp_.load()) {
324 LOGI("InitUnixWebSocket websocket has inited");
325 return true;
326 }
327 if (socketfd < SOCKET_SUCCESS) {
328 LOGE("InitUnixWebSocket socketfd is invalid");
329 return false;
330 }
331 SetConnectionSocket(socketfd);
332 const int flag = fcntl(socketfd, F_GETFL, 0);
333 if (flag == -1) {
334 LOGE("InitUnixWebSocket get client state is failed, error is %{public}s", strerror(errno));
335 return false;
336 }
337 fcntl(socketfd, F_SETFL, static_cast<size_t>(flag) & ~O_NONBLOCK);
338 serverUp_.store(true);
339 return true;
340 }
341
ConnectUnixWebSocketBySocketpair()342 bool WebSocketServer::ConnectUnixWebSocketBySocketpair()
343 {
344 if (!MoveToConnectingState()) {
345 return false;
346 }
347
348 if (!HttpHandShake()) {
349 LOGE("ConnectUnixWebSocket HttpHandShake failed");
350
351 auto expected = SetConnectionState(ConnectionState::CLOSING);
352 if (expected != ConnectionState::CONNECTING) {
353 LOGE("ConnectUnixWebSocketBySocketpair: violation due to concurrent close and accept: got %{public}d",
354 EnumToNumber(expected));
355 }
356 CloseConnectionSocket(ConnectionCloseReason::FAIL);
357 return false;
358 }
359
360 OnNewConnection();
361 return true;
362 }
363 #endif // WINDOWS_PLATFORM
364
CloseServerSocket()365 void WebSocketServer::CloseServerSocket()
366 {
367 close(serverFd_);
368 serverFd_ = -1;
369 }
370
OnNewConnection()371 void WebSocketServer::OnNewConnection()
372 {
373 LOGI("New client connected");
374 if (openCb_) {
375 openCb_();
376 }
377
378 auto expected = SetConnectionState(ConnectionState::OPEN);
379 if (expected != ConnectionState::CONNECTING) {
380 LOGE("OnNewConnection violation: expected CONNECTING, but got %{public}d",
381 EnumToNumber(expected));
382 }
383 }
384
SetValidateConnectionCallback(ValidateConnectionCallback cb)385 void WebSocketServer::SetValidateConnectionCallback(ValidateConnectionCallback cb)
386 {
387 validateCb_ = std::move(cb);
388 }
389
SetOpenConnectionCallback(OpenConnectionCallback cb)390 void WebSocketServer::SetOpenConnectionCallback(OpenConnectionCallback cb)
391 {
392 openCb_ = std::move(cb);
393 }
394
ValidateIncomingFrame(const WebSocketFrame & wsFrame) const395 bool WebSocketServer::ValidateIncomingFrame(const WebSocketFrame& wsFrame) const
396 {
397 // "The server MUST close the connection upon receiving a frame that is not masked."
398 // https://www.rfc-editor.org/rfc/rfc6455#section-5.1
399 return wsFrame.mask == 1;
400 }
401
CreateFrame(bool isLast,FrameType frameType) const402 std::string WebSocketServer::CreateFrame(bool isLast, FrameType frameType) const
403 {
404 ServerFrameBuilder builder(isLast, frameType);
405 return builder.Build();
406 }
407
CreateFrame(bool isLast,FrameType frameType,const std::string & payload) const408 std::string WebSocketServer::CreateFrame(bool isLast, FrameType frameType, const std::string& payload) const
409 {
410 ServerFrameBuilder builder(isLast, frameType);
411 return builder.SetPayload(payload).Build();
412 }
413
CreateFrame(bool isLast,FrameType frameType,std::string && payload) const414 std::string WebSocketServer::CreateFrame(bool isLast, FrameType frameType, std::string&& payload) const
415 {
416 ServerFrameBuilder builder(isLast, frameType);
417 return builder.SetPayload(std::move(payload)).Build();
418 }
419
WaitConnectingStateEnds(ConnectionState connection)420 WebSocketServer::ConnectionState WebSocketServer::WaitConnectingStateEnds(ConnectionState connection)
421 {
422 auto shutdownSocketUnderLock = [this]() {
423 auto fd = GetConnectionSocket();
424 if (fd == -1) {
425 return false;
426 }
427 int err = ShutdownSocket(fd);
428 if (err != 0) {
429 LOGW("Failed to shutdown client socket, errno = %{public}d", errno);
430 }
431 return true;
432 };
433
434 auto connectionSocketWasShutdown = false;
435 while (connection == ConnectionState::CONNECTING) {
436 if (!connectionSocketWasShutdown) {
437 // Try to shutdown the already accepted connection socket,
438 // otherwise thread can infinitely hang on handshake recv.
439 std::shared_lock lock(GetConnectionMutex());
440 connectionSocketWasShutdown = shutdownSocketUnderLock();
441 }
442
443 std::this_thread::yield();
444 connection = GetConnectionState();
445 }
446 return connection;
447 }
448
Close()449 void WebSocketServer::Close()
450 {
451 // Firstly stop accepting new connections.
452 if (!serverUp_.exchange(false)) {
453 return;
454 }
455
456 int err = ShutdownSocket(serverFd_);
457 if (err != 0) {
458 LOGW("Failed to shutdown server socket, errno = %{public}d", errno);
459 }
460
461 // If there is a concurrent call to `CloseConnection`, we can immediately close `serverFd_`.
462 // This is because new connections are already prevented, hence no reads of `serverFd_` will be done,
463 // and the connection itself will be closed by someone else.
464 auto connection = GetConnectionState();
465 if (connection == ConnectionState::CLOSING || connection == ConnectionState::CLOSED) {
466 CloseServerSocket();
467 return;
468 }
469
470 connection = WaitConnectingStateEnds(connection);
471
472 // Can safely close server socket, as there will be no more new connections attempts.
473 CloseServerSocket();
474 // Must check once again after finished `AcceptNewConnection`.
475 if (connection == ConnectionState::CLOSING || connection == ConnectionState::CLOSED) {
476 return;
477 }
478
479 // If we reached this point, connection can be `OPEN`, `CLOSING` or `CLOSED`. Try to close it anyway.
480 CloseConnection(CloseStatusCode::SERVER_GO_AWAY);
481 }
482 } // namespace OHOS::ArkCompiler::Toolchain
483