Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
41 changes: 26 additions & 15 deletions i3ipc/aio/connection.py
Original file line number Diff line number Diff line change
Expand Up @@ -420,6 +420,20 @@ async def do_reconnect():

return self._reconnect_future

async def _sock_recv_exact(self, sock, size: int) -> bytearray:
"""Reads exactly ``size`` bytes from the socket. A stream socket can
deliver a message in any number of pieces, so keep reading until all
of it has arrived. Returns fewer bytes only if the peer closed the
connection first.
"""
data = bytearray()
while len(data) < size:
chunk = await self._loop.sock_recv(sock, size - len(data))
if not chunk:
break
data.extend(chunk)
return data

async def _message(self, message_type: MessageType, payload: str = '') -> bytearray:
if message_type is MessageType.SUBSCRIBE:
raise Exception('cannot subscribe on the command socket')
Expand All @@ -429,7 +443,7 @@ async def _message(self, message_type: MessageType, payload: str = '') -> bytear
for tries in range(0, 5):
try:
await self._loop.sock_sendall(self._cmd_socket, _pack(message_type, payload))
buf = await self._loop.sock_recv(self._cmd_socket, _struct_header_size)
buf = await self._sock_recv_exact(self._cmd_socket, _struct_header_size)
break
except ConnectionError as e:
if not self._auto_reconnect:
Expand All @@ -441,21 +455,18 @@ async def _message(self, message_type: MessageType, payload: str = '') -> bytear
if not buf:
return bytearray()

magic, message_length, reply_type = _unpack_header(buf)
assert reply_type == message_type.value
assert magic == _MAGIC

try:
message = bytearray()
remaining_length = message_length
while remaining_length:
buf = await self._loop.sock_recv(self._cmd_socket, remaining_length)
if not buf:
logger.error('premature ending while reading message (%s bytes remaining)',
remaining_length)
break
message.extend(buf)
remaining_length -= len(buf)
if len(buf) < _struct_header_size:
raise ConnectionError('ipc socket closed in the middle of a reply header')

magic, message_length, reply_type = _unpack_header(buf)
assert reply_type == message_type.value
assert magic == _MAGIC

message = await self._sock_recv_exact(self._cmd_socket, message_length)
if len(message) < message_length:
raise ConnectionError('ipc socket closed in the middle of a reply: '
'got %d of %d bytes' % (len(message), message_length))
except ConnectionError as e:
if self._auto_reconnect:
ensure_future(self._reconnect())
Expand Down
27 changes: 23 additions & 4 deletions i3ipc/connection.py
Original file line number Diff line number Diff line change
Expand Up @@ -148,18 +148,37 @@ def _unpack_header(self, data):
"""
return struct.unpack(self._struct_header, data[:self._struct_header_size])

def _recv_exact(self, sock, size):
"""Reads exactly ``size`` bytes from the socket. A stream socket can
deliver a message in any number of pieces, so keep reading until all
of it has arrived. Returns fewer bytes only if the peer closed the
connection first.
"""
data = b''
while len(data) < size:
chunk = sock.recv(size - len(data))
if not chunk:
break
data += chunk
return data

def _ipc_recv(self, sock):
data = sock.recv(14)
data = self._recv_exact(sock, self._struct_header_size)

if len(data) == 0:
logger.info('got EOF from ipc socket')
return '', 0

if len(data) < self._struct_header_size:
raise ConnectionError('ipc socket closed in the middle of a message header')

msg_magic, msg_length, msg_type = self._unpack_header(data)
logger.info('reading ipc message: type=%s, length=%s', msg_type, msg_length)
msg_size = self._struct_header_size + msg_length
while len(data) < msg_size:
data += sock.recv(msg_length)
payload = self._recv_exact(sock, msg_length)
if len(payload) < msg_length:
raise ConnectionError('ipc socket closed in the middle of a message: '
'got %d of %d bytes' % (len(payload), msg_length))
data += payload
payload = self._unpack(data)
logger.info('message payload: %s', payload)
return payload, msg_type
Expand Down
154 changes: 154 additions & 0 deletions test/aio/test_ipc_recv.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,154 @@
"""Reading command replies that arrive in pieces or are cut off.

These tests do not need i3: a small Unix socket server stands in for the
window manager and sends its replies in whatever pieces the test asks for.
"""
import asyncio
import json
import os
import socket
import struct
import tempfile
import threading
import time

import pytest

from i3ipc.aio import Connection
from i3ipc._private import MessageType

MAGIC = b'i3-ipc'

VERSION = {
'major': 4,
'minor': 24,
'patch': 0,
'human_readable': '4.24',
'loaded_config_file_name': '/dev/null'
}


def frame(msg_type, payload):
body = json.dumps(payload).encode('utf-8')
return MAGIC + struct.pack('=II', len(body), msg_type) + body


class FakeServer:
"""Stands in for the window manager, in a thread of its own: the
connection's command socket blocks, so the server can't share the
event loop. The first connection is the command socket: after the
first request it sends each of ``chunks`` with a short pause between
them, then closes the connection if ``close`` is set. Other connections
(the event socket) stay idle."""

def __init__(self, chunks, close):
self.chunks = chunks
self.close = close
self.dir = tempfile.mkdtemp()
self.path = os.path.join(self.dir, 'ipc.sock')
self.listener = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
self.listener.bind(self.path)
self.listener.listen(4)
self.first = True
threading.Thread(target=self._accept, daemon=True).start()

def _read_exact(self, conn, size):
data = b''
while len(data) < size:
chunk = conn.recv(size - len(data))
if not chunk:
break
data += chunk
return data

def _accept(self):
while True:
try:
conn, _ = self.listener.accept()
except OSError:
return
first, self.first = self.first, False
threading.Thread(target=self._serve, args=(conn, first), daemon=True).start()

def _serve(self, conn, first):
if first:
header = self._read_exact(conn, 14)
_, length, _ = struct.unpack('=6sII', header)
self._read_exact(conn, length)
for chunk in self.chunks:
conn.sendall(chunk)
time.sleep(0.05)
if self.close:
conn.close()
return
# keep the connection open until the client closes it
while self._read_exact(conn, 1):
pass
conn.close()

def cleanup(self):
self.listener.close()
os.unlink(self.path)
os.rmdir(self.dir)


async def connect(chunks, close=False):
server = FakeServer(chunks, close)
conn = await Connection(socket_path=server.path).connect()
return server, conn


async def disconnect(server, conn):
conn._loop.remove_reader(conn._sub_fd)
conn._cmd_socket.close()
conn._sub_socket.close()
server.cleanup()


@pytest.mark.asyncio
async def test_header_split_across_reads():
msg = frame(MessageType.GET_VERSION.value, VERSION)
server, conn = await connect([msg[:3], msg[3:9], msg[9:]])
try:
reply = await asyncio.wait_for(conn.get_version(), 3)
assert reply.human_readable == '4.24'
finally:
await disconnect(server, conn)


@pytest.mark.asyncio
async def test_payload_split_does_not_swallow_next_message():
first = frame(MessageType.GET_VERSION.value, VERSION)
second = frame(MessageType.GET_VERSION.value, dict(VERSION, human_readable='second'))
# the first reply's payload arrives in two pieces, and the second piece
# comes together with the whole next reply
server, conn = await connect([first[:20], first[20:] + second])
try:
reply = await asyncio.wait_for(conn.get_version(), 3)
assert reply.human_readable == '4.24'
reply = await asyncio.wait_for(conn.get_version(), 3)
assert reply.human_readable == 'second'
finally:
await disconnect(server, conn)


@pytest.mark.asyncio
async def test_connection_closed_mid_reply_raises():
msg = frame(MessageType.GET_VERSION.value, VERSION)
server, conn = await connect([msg[:20]], close=True)
try:
with pytest.raises(ConnectionError):
await asyncio.wait_for(conn.get_version(), 3)
finally:
await disconnect(server, conn)


@pytest.mark.asyncio
async def test_connection_closed_mid_header_raises():
msg = frame(MessageType.GET_VERSION.value, VERSION)
server, conn = await connect([msg[:5]], close=True)
try:
with pytest.raises(ConnectionError):
await asyncio.wait_for(conn.get_version(), 3)
finally:
await disconnect(server, conn)
Loading