From 73aa11ac1636a90375c03ba63863abaac32677de Mon Sep 17 00:00:00 2001 From: Maxime Coste Date: Fri, 26 Oct 2012 13:45:32 +0200 Subject: [PATCH] remote: check read/write results, detect disconnections --- src/remote.cc | 27 ++++++++++++++++++++++----- src/remote.hh | 5 +++++ 2 files changed, 27 insertions(+), 5 deletions(-) diff --git a/src/remote.cc b/src/remote.cc index 51f1d98d..13e9ee79 100644 --- a/src/remote.cc +++ b/src/remote.cc @@ -17,11 +17,20 @@ enum class RemoteUIMsg Draw }; +struct socket_error{}; + class Message { public: Message(int sock) : m_socket(sock) {} - ~Message() { ::write(m_socket, m_stream.data(), m_stream.size()); } + ~Message() + { + if (m_stream.size() == 0) + return; + int res = ::write(m_socket, m_stream.data(), m_stream.size()); + if (res == 0) + throw peer_disconnected{}; + } void write(const char* val, size_t size) { @@ -77,12 +86,21 @@ void write(Message& msg, const DisplayBuffer& display_buffer) write(msg, display_buffer.lines()); } +void read(int socket, char* buffer, size_t size) +{ + int res = ::read(socket, buffer, size); + if (res == 0) + throw peer_disconnected{}; + if (res == -1) + throw socket_error{}; + assert(res == size); +} + template T read(int socket) { char value[sizeof(T)]; - auto res = ::read(socket, value, sizeof(T)); - assert(res == sizeof(T)); + read(socket, value, sizeof(T)); return *(T*)(value); }; @@ -92,8 +110,7 @@ String read(int socket) ByteCount length = read(socket); char buffer[2048]; assert(length < 2048); - auto res = ::read(socket, buffer, (int)length); - assert(res == (int)length); + read(socket, buffer, (int)length); return String(buffer, buffer+(int)length); }; diff --git a/src/remote.hh b/src/remote.hh index a20d09ff..19e7ce4f 100644 --- a/src/remote.hh +++ b/src/remote.hh @@ -7,6 +7,11 @@ namespace Kakoune { +struct peer_disconnected : public runtime_error +{ + peer_disconnected() : runtime_error("peer disconnected") {} +}; + class RemoteUI : public UserInterface { public: