mirror of
https://github.com/curl/curl.git
synced 2026-08-04 15:16:14 +03:00
This started out as regression tests for the `curl_ws_recv()` and
`curl_ws_send()` implementation and ended up with a bugfix, additional
protocol validation and minor logging improvements.
- Fix reset of fragmented message decoder state when a PING/PONG is
received in between message fragments.
- Fix undefined behavior (applying zero offset to null pointer) in
curl_ws_send() when the given buffer is NULL.
- Detect invalid overlong PING/PONG/CLOSE frames.
- Detect invalid fragmented PING/PONG/CLOSE frames.
- Detect invalid sequences of fragmented frames.
- a) A continuation frame (0x80...) is received without any ongoing
fragmented message.
- b) A new fragmented message is started (0x81/0x01/0x82/0x02...)
before the ongoing fragmented message has terminated.
- Made logs for invalid opcodes easier to understand.
- Moved noisy logs to the `CURL_TRC_WS` log level.
- Unified the prefixes for WebSocket log messages: `[WS] ...`
- Add env var `CURL_WS_FORCE_ZERO_MASK` in debug builds.
- If set, it forces the bit mask applied to outgoing payloads to
0x00000000, which effectively means the payload is not masked at
all. This drastically simplifies defining the expected `<protocol>`
data in test cases.
- 2700: Frame types
- 2701: Invalid opcode 0x3
- 2702: Invalid opcode 0xB
- 2703: Invalid reserved bit RSV1 _(replaces 2310)_
- 2704: Invalid reserved bit RSV2
- 2705: Invalid reserved bit RSV3
- 2706: Invalid masked server message
- 2707: Peculiar frame sizes _(part. replaces 2311)_
- 2708: Automatic PONG
- 2709: No automatic PONG _(replaces 2312)_
- 2710: Unsolicited PONG
- 2711: Empty PING/PONG/CLOSE
- 2712: Max sized PING/PONG/CLOSE
- 2713: Invalid oversized PING _(replaces 2307)_
- 2714: Invalid oversized PONG
- 2715: Invalid oversized CLOSE
- 2716: Invalid fragmented PING
- 2717: Invalid fragmented PONG
- 2718: Invalid fragmented CLOSE
- 2719: Fragmented messages _(part. replaces 2311)_
- 2720: Fragmented messages with empty fragments
- 2721: Fragmented messages with interleaved pong
- 2722: Invalid fragmented message without initial frame
- 2723: Invalid fragmented message without final frame
- 2305: curl_ws_recv() loop reading three larger frames
- This test involuntarily sent an invalid sequence of opcodes (0x01...,0x01...,0x81...) , but neither libcurl nor the test caught this! The correct sequence was tested in 2311 (0x01...,0x00...,0x80...). See below for 2311.
- Validation of the opcode sequence was added to libcurl and is now tested in 2723.
- Superseded by 2719 (fragmented message) and 2707 (large frames).
- 2307: overlong PING payload
- The tested PING payload length check was actually missing, but the test didn't catch this since it involuntarily sent an invalid opcode (0x19... instead of 0x89...) so that the expected error occurred, but for the wrong reason.
- Superseded by 2713.
- 2310: unknown reserved bit set in frame header
- Superseded by 2703 and extended by 2704 and 2705.
- 2311: curl_ws_recv() read fragmented message
- Superseded by 2719 (fragmented message) and 2707 (large frames).
- 2312: WebSockets no auto ping
- Superseded by 2709.
- No tests for `CURLOPT_WRITEFUNCTION`.
- No tests for sending of invalid frames/fragments.
Closes #17136
175 lines
6.6 KiB
Python
175 lines
6.6 KiB
Python
#!/usr/bin/env python3
|
|
# -*- coding: utf-8 -*-
|
|
#***************************************************************************
|
|
# _ _ ____ _
|
|
# Project ___| | | | _ \| |
|
|
# / __| | | | |_) | |
|
|
# | (__| |_| | _ <| |___
|
|
# \___|\___/|_| \_\_____|
|
|
#
|
|
# Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al.
|
|
#
|
|
# This software is licensed as described in the file COPYING, which
|
|
# you should have received as part of this distribution. The terms
|
|
# are also available at https://curl.se/docs/copyright.html.
|
|
#
|
|
# You may opt to use, copy, modify, merge, publish, distribute and/or sell
|
|
# copies of the Software, and permit persons to whom the Software is
|
|
# furnished to do so, under the terms of the COPYING file.
|
|
#
|
|
# This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
|
|
# KIND, either express or implied.
|
|
#
|
|
# SPDX-License-Identifier: curl
|
|
#
|
|
###########################################################################
|
|
#
|
|
import logging
|
|
import os
|
|
import shutil
|
|
import socket
|
|
import subprocess
|
|
import time
|
|
from datetime import datetime, timedelta
|
|
from typing import Dict
|
|
import pytest
|
|
|
|
from testenv import Env, CurlClient, LocalClient
|
|
from testenv.ports import alloc_ports_and_do
|
|
|
|
|
|
log = logging.getLogger(__name__)
|
|
|
|
|
|
@pytest.mark.skipif(condition=not Env.curl_has_protocol('ws'),
|
|
reason='curl lacks ws protocol support')
|
|
class TestWebsockets:
|
|
|
|
PORT_SPECS = {
|
|
'ws': socket.SOCK_STREAM,
|
|
}
|
|
|
|
def check_alive(self, env, port, timeout=Env.SERVER_TIMEOUT):
|
|
curl = CurlClient(env=env)
|
|
url = f'http://localhost:{port}/'
|
|
end = datetime.now() + timedelta(seconds=timeout)
|
|
while datetime.now() < end:
|
|
r = curl.http_download(urls=[url])
|
|
if r.exit_code == 0:
|
|
return True
|
|
time.sleep(.1)
|
|
return False
|
|
|
|
def _mkpath(self, path):
|
|
if not os.path.exists(path):
|
|
return os.makedirs(path)
|
|
|
|
def _rmrf(self, path):
|
|
if os.path.exists(path):
|
|
return shutil.rmtree(path)
|
|
|
|
@pytest.fixture(autouse=True, scope='class')
|
|
def ws_echo(self, env):
|
|
self.run_dir = os.path.join(env.gen_dir, 'ws-echo-server')
|
|
err_file = os.path.join(self.run_dir, 'stderr')
|
|
self._rmrf(self.run_dir)
|
|
self._mkpath(self.run_dir)
|
|
self.cmd = os.path.join(env.project_dir,
|
|
'tests/http/testenv/ws_echo_server.py')
|
|
self.wsproc = None
|
|
self.cerr = None
|
|
|
|
def startup(ports: Dict[str, int]) -> bool:
|
|
wargs = [self.cmd, '--port', str(ports['ws'])]
|
|
log.info(f'start_ {wargs}')
|
|
self.wsproc = subprocess.Popen(args=wargs,
|
|
cwd=self.run_dir,
|
|
stderr=self.cerr,
|
|
stdout=self.cerr)
|
|
if self.check_alive(env, ports['ws']):
|
|
env.update_ports(ports)
|
|
return True
|
|
log.error(f'not alive {wargs}')
|
|
self.wsproc.terminate()
|
|
self.wsproc = None
|
|
return False
|
|
|
|
with open(err_file, 'w') as self.cerr:
|
|
assert alloc_ports_and_do(TestWebsockets.PORT_SPECS, startup,
|
|
env.gen_root, max_tries=3)
|
|
assert self.wsproc
|
|
yield
|
|
self.wsproc.terminate()
|
|
|
|
def test_20_01_basic(self, env: Env, ws_echo):
|
|
curl = CurlClient(env=env)
|
|
url = f'http://localhost:{env.ws_port}/'
|
|
r = curl.http_download(urls=[url])
|
|
r.check_response(http_status=426)
|
|
|
|
def test_20_02_pingpong_small(self, env: Env, ws_echo):
|
|
payload = 125 * "x"
|
|
client = LocalClient(env=env, name='ws-pingpong')
|
|
if not client.exists():
|
|
pytest.skip(f'example client not built: {client.name}')
|
|
url = f'ws://localhost:{env.ws_port}/'
|
|
r = client.run(args=[url, payload])
|
|
r.check_exit_code(0)
|
|
|
|
# the python websocket server does not like 'large' control frames
|
|
def test_20_03_pingpong_too_large(self, env: Env, ws_echo):
|
|
payload = 127 * "x"
|
|
client = LocalClient(env=env, name='ws-pingpong')
|
|
if not client.exists():
|
|
pytest.skip(f'example client not built: {client.name}')
|
|
url = f'ws://localhost:{env.ws_port}/'
|
|
r = client.run(args=[url, payload])
|
|
r.check_exit_code(100) # CURLE_TOO_LARGE
|
|
|
|
def test_20_04_data_small(self, env: Env, ws_echo):
|
|
client = LocalClient(env=env, name='ws-data')
|
|
if not client.exists():
|
|
pytest.skip(f'example client not built: {client.name}')
|
|
url = f'ws://localhost:{env.ws_port}/'
|
|
r = client.run(args=['-m', str(0), '-M', str(10), url])
|
|
r.check_exit_code(0)
|
|
|
|
def test_20_05_data_med(self, env: Env, ws_echo):
|
|
client = LocalClient(env=env, name='ws-data')
|
|
if not client.exists():
|
|
pytest.skip(f'example client not built: {client.name}')
|
|
url = f'ws://localhost:{env.ws_port}/'
|
|
r = client.run(args=['-m', str(120), '-M', str(130), url])
|
|
r.check_exit_code(0)
|
|
|
|
def test_20_06_data_large(self, env: Env, ws_echo):
|
|
client = LocalClient(env=env, name='ws-data')
|
|
if not client.exists():
|
|
pytest.skip(f'example client not built: {client.name}')
|
|
url = f'ws://localhost:{env.ws_port}/'
|
|
r = client.run(args=['-m', str(65535 - 5), '-M', str(65535 + 5), url])
|
|
r.check_exit_code(0)
|
|
|
|
def test_20_07_data_large_small_recv(self, env: Env, ws_echo):
|
|
run_env = os.environ.copy()
|
|
run_env['CURL_WS_CHUNK_SIZE'] = '1024'
|
|
client = LocalClient(env=env, name='ws-data', run_env=run_env)
|
|
if not client.exists():
|
|
pytest.skip(f'example client not built: {client.name}')
|
|
url = f'ws://localhost:{env.ws_port}/'
|
|
r = client.run(args=['-m', str(65535 - 5), '-M', str(65535 + 5), url])
|
|
r.check_exit_code(0)
|
|
|
|
# Send large frames and simulate send blocking on 8192 bytes chunks
|
|
# Simlates error reported in #15865
|
|
def test_20_08_data_very_large(self, env: Env, ws_echo):
|
|
run_env = os.environ.copy()
|
|
run_env['CURL_WS_CHUNK_EAGAIN'] = '8192'
|
|
client = LocalClient(env=env, name='ws-data', run_env=run_env)
|
|
if not client.exists():
|
|
pytest.skip(f'example client not built: {client.name}')
|
|
url = f'ws://localhost:{env.ws_port}/'
|
|
count = 10
|
|
large = 20000
|
|
r = client.run(args=['-c', str(count), '-m', str(large), url])
|
|
r.check_exit_code(0)
|