diff options
author | Brian Orr <brian.orr@gmail.com> | 2017-08-09 17:35:21 -0700 |
---|---|---|
committer | Brian Orr <brian.orr@gmail.com> | 2017-08-09 17:35:21 -0700 |
commit | ff794c230e8f5215f5347b2d6903779fe8a2a9b3 (patch) | |
tree | 25dbc389565c97f89a638813293916382e002b28 /gr-blocks/lib/tcp_connection.cc | |
parent | 811bee8c54bdca5c53c2ccbc6ef6d1bbca55eaae (diff) |
Fix invalid Asio buffer usage in tcp_connection
Asio requires that the underlying buffer passed to `async_write()`
remain valid valid until the handler was called. The previous version
was allocating a vector on the stack which gets destroyed once the
`send()` method returns.
Added a unit test for TCP server.
Diffstat (limited to 'gr-blocks/lib/tcp_connection.cc')
-rw-r--r-- | gr-blocks/lib/tcp_connection.cc | 23 |
1 files changed, 16 insertions, 7 deletions
diff --git a/gr-blocks/lib/tcp_connection.cc b/gr-blocks/lib/tcp_connection.cc index 3b0afa13fc..6980ddadb0 100644 --- a/gr-blocks/lib/tcp_connection.cc +++ b/gr-blocks/lib/tcp_connection.cc @@ -54,16 +54,25 @@ namespace gr { tcp_connection::send(pmt::pmt_t vector) { size_t len = pmt::blob_length(vector); + + // Asio async_write() requires the buffer to remain valid until the handler is called. It will be + // deleted in tcp_connection::handle_write. + char* txbuf = new char[len]; + + size_t temp = 0; + memcpy(txbuf, pmt::uniform_vector_elements(vector, temp), len); + size_t offset = 0; - std::vector<char> txbuf(std::min(len, d_buf.size())); while (offset < len) { - size_t send_len = std::min((len - offset), txbuf.size()); - memcpy(&txbuf[0], pmt::uniform_vector_elements(vector, offset), send_len); + // Limit the size of each write() to the MTU. + // FIXME: Note that this has the effect of breaking a large PDU into several smaller PDUs, each + // containing <= MTU bytes. Is this the desired behavior? + size_t send_len = std::min((len - offset), d_buf.size()); + boost::asio::async_write(d_socket, boost::asio::buffer(txbuf + offset, send_len), + boost::bind(&tcp_connection::handle_write, this, txbuf, + boost::asio::placeholders::error, + boost::asio::placeholders::bytes_transferred)); offset += send_len; - boost::asio::async_write(d_socket, boost::asio::buffer(txbuf, send_len), - boost::bind(&tcp_connection::handle_write, this, - boost::asio::placeholders::error, - boost::asio::placeholders::bytes_transferred)); } } |