Add error checking of boost::asio::[read|write] functions 76/243976/4
authorTomasz Swierczek <t.swierczek@samsung.com>
Fri, 11 Sep 2020 12:15:21 +0000 (14:15 +0200)
committerTomasz Swierczek <t.swierczek@samsung.com>
Fri, 11 Sep 2020 12:38:39 +0000 (14:38 +0200)
Acc. to documentation (https://www.boost.org/doc/libs/1_60_0/boost/asio/read.hpp),
the write function should throw an error when there is a problem in reading.

Similarly, read returns number of written bytes which should be checked.

Change-Id: I301ccd4e12661f486362a9b58f7cdd8711c9112d

src/shared/protobuf_asio.cpp

index fd8a9fd14799d154a5982060b7de3a82fd611bb8..cd5ef11af5ffa7b4e93762f2d4896f97ca37856e 100644 (file)
@@ -43,12 +43,13 @@ void protobuf_sync_message_serialization::encodeMessage(const google::protobuf::
 
 bool protobuf_sync_message_serialization::Write(const void* buffer, int size)
 {
+       std::size_t written = 0;
        try {
-               boost::asio::write(fSocket, boost::asio::buffer(buffer, size));
+               written = boost::asio::write(fSocket, boost::asio::buffer(buffer, size));
        } catch(...) {
                return false;
        }
-       return true;
+       return static_cast<int>(written) == size;
 }
 
 protobuf_sync_message_deserialization::protobuf_sync_message_deserialization(
@@ -61,7 +62,13 @@ void protobuf_sync_message_deserialization::decodeMessage(google::protobuf::Mess
 {
        google::protobuf::uint8 header[4];
        google::protobuf::uint32 length;
-       boost::asio::read(fSocket, boost::asio::buffer(header));
+
+       try {
+               boost::asio::read(fSocket, boost::asio::buffer(header));
+       } catch(...) {
+               throw std::invalid_argument("Error while reading message");
+       }
+
        google::protobuf::io::CodedInputStream::ReadLittleEndian32FromArray(header, &length);
 
        if(length < 1 || length > MESSAGE_LENGHT_MAX) {
@@ -70,7 +77,11 @@ void protobuf_sync_message_deserialization::decodeMessage(google::protobuf::Mess
 
        std::unique_ptr<char[]> local_array(new char[length]);
 
-       boost::asio::read(fSocket, boost::asio::buffer(local_array.get(), length));
+       try {
+               boost::asio::read(fSocket, boost::asio::buffer(local_array.get(), length));
+       } catch(...) {
+               throw std::invalid_argument("Error while reading message");
+       }
 
        if(!message.ParseFromArray(local_array.get(), length)) {
                throw std::invalid_argument("Invalid message format");