From fb9d993c7922012c359253e0dfeac05621c1c269 Mon Sep 17 00:00:00 2001 From: lloyd Date: Sat, 7 Jan 2012 02:02:06 +0000 Subject: Avoid overlapping writes. Pretend to be an HTTP server --- doc/examples/asio_tls_server.cpp | 98 ++++++++++++++++++++++++++++++++-------- 1 file changed, 79 insertions(+), 19 deletions(-) (limited to 'doc/examples') diff --git a/doc/examples/asio_tls_server.cpp b/doc/examples/asio_tls_server.cpp index 9a1c3cefd..457460d41 100644 --- a/doc/examples/asio_tls_server.cpp +++ b/doc/examples/asio_tls_server.cpp @@ -1,8 +1,11 @@ #include #include +#include + #include #include #include + #include #include @@ -49,6 +52,11 @@ class tls_server_session : public boost::enable_shared_from_this 0) + m_outbox.insert(m_outbox.end(), buf, buf + buf_len); + // no write pending and have output pending + if(m_write_buf.empty() && !m_outbox.empty()) + { + std::swap(m_outbox, m_write_buf); + + asio::async_write(m_socket, + asio::buffer(&m_write_buf[0], m_write_buf.size()), + boost::bind(&tls_server_session::handle_write, + shared_from_this(), + asio::placeholders::error, + asio::placeholders::bytes_transferred)); + } } void tls_data_recv(const byte buf[], size_t buf_len, Botan::u16bit alert_info) { if(buf_len == 0 && alert_info != Botan::NULL_ALERT) - printf("Alert: %d\n", alert_info); + { + //printf("Alert: %d\n", alert_info); + if(alert_info == 0) + { + m_tls.close(); + return; + } + } + - printf("Got %d bytes: ", (int)buf_len); - for(size_t i = 0; i != buf_len; ++i) + + //printf("Got %d bytes: ", (int)buf_len); + + if(buf_len > 4) { - if(isprint(buf[i])) - printf("%c", buf[i]); + std::string out; + out += "\r\n"; + out += "HTTP/1.0 200 OK\r\n"; + out += "Server: Botan ASIO test server\r\n"; + out += "Host: 192.168.10.5\r\n"; + out += "Content-Type: text/html\r\n"; + out += "\r\n"; + out += "Greets. You said: "; + out += std::string((const char*)buf, buf_len); + out += "\r\n\r\n"; + + m_tls.queue_for_sending(reinterpret_cast(&out[0]), + out.size()); + m_tls.close(); } - printf("\n"); } bool tls_handshake_complete(const Botan::TLS_Session& session) { - printf("handshake complete\n"); + //printf("handshake complete\n"); return true; } tcp::socket m_socket; - Botan::TLS_Server m_tls; unsigned char m_read_buf[Botan::MAX_TLS_RECORD_SIZE]; - unsigned char m_write_buf[Botan::MAX_TLS_RECORD_SIZE]; + + // used to hold the data currently being written by the system + std::vector m_write_buf; + + // used to hold data queued for writing + std::vector m_outbox; }; class Credentials_Manager_Simple : public Botan::Credentials_Manager -- cgit v1.2.3