Skip to content

Commit

Permalink
Merge pull request #33 from RTUnreal/stable_read
Browse files Browse the repository at this point in the history
Fix unstable packet reading
  • Loading branch information
romis2012 authored Jun 25, 2024
2 parents ffd330b + dbc067d commit 6a4a273
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 2 deletions.
12 changes: 11 additions & 1 deletion python_socks/_connectors/socks5_async.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
from .._abc import AsyncSocketStream, AsyncResolver
from .abc import AsyncConnector

from .._protocols.errors import ReplyError
from .._protocols import socks5
from .._helpers import is_ip_address

Expand Down Expand Up @@ -65,6 +66,15 @@ async def connect(
data = conn.send(request)
await stream.write_all(data)

data = await stream.read()
data = await stream.read_exact(4)
if data[3] == socks5.AddressType.IPV4:
data += await stream.read_exact(6)
elif data[3] == socks5.AddressType.IPV6:
data += await stream.read_exact(18)
elif data[3] == socks5.AddressType.DOMAIN:
data += await stream.read_exact(int.from_bytes(await stream.read_exact(1)) + 2)
else: # pragma: no cover
raise ReplyError(f'Invalid address type: {data[3]:#02X}')

reply: socks5.ConnectReply = conn.receive(data)
return reply
12 changes: 11 additions & 1 deletion python_socks/_connectors/socks5_sync.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
from .._abc import SyncSocketStream, SyncResolver
from .abc import SyncConnector

from .._protocols.errors import ReplyError
from .._protocols import socks5
from .._helpers import is_ip_address

Expand Down Expand Up @@ -56,6 +57,15 @@ def connect(
data = conn.send(request)
stream.write_all(data)

data = stream.read()
data = stream.read_exact(4)
if data[3] == socks5.AddressType.IPV4:
data += stream.read_exact(6)
elif data[3] == socks5.AddressType.IPV6:
data += stream.read_exact(18)
elif data[3] == socks5.AddressType.DOMAIN:
data += stream.read_exact(int.from_bytes(stream.read_exact(1)) + 2)
else: # pragma: no cover
raise ReplyError(f'Invalid address type: {data[3]:#02X}')

reply: socks5.ConnectReply = conn.receive(data)
return reply

0 comments on commit 6a4a273

Please sign in to comment.