tcp_server.cc 7.85 KB
Newer Older
1
// Copyright (C) 2011  Internet Systems Consortium, Inc. ("ISC")
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
//
// Permission to use, copy, modify, and/or distribute this software for any
// purpose with or without fee is hereby granted, provided that the above
// copyright notice and this permission notice appear in all copies.
//
// THE SOFTWARE IS PROVIDED "AS IS" AND ISC DISCLAIMS ALL WARRANTIES WITH
// REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
// AND FITNESS.  IN NO EVENT SHALL ISC BE LIABLE FOR ANY SPECIAL, DIRECT,
// INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
// LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE
// OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
// PERFORMANCE OF THIS SOFTWARE.

#include <config.h>

17
#include <netinet/in.h>
18 19
#include <sys/socket.h>
#include <unistd.h>             // for some IPC/network system calls
20

21
#include <boost/shared_array.hpp>
22

23
#include <log/dummylog.h>
24

25
#include <asio.hpp>
26
#include <asiolink/dummy_io_cb.h>
27 28 29
#include <asiolink/tcp_endpoint.h>
#include <asiolink/tcp_socket.h>
#include <asiolink/tcp_server.h>
30 31 32 33 34 35 36 37 38 39


using namespace asio;
using asio::ip::udp;
using asio::ip::tcp;

using namespace std;
using namespace isc::dns;

namespace asiolink {
40 41

/// The following functions implement the \c TCPServer class.
42 43
///
/// The constructor
44 45
TCPServer::TCPServer(io_service& io_service,
                     const ip::address& addr, const uint16_t port, 
46
                     const SimpleCallback* checkin,
47 48
                     const DNSLookup* lookup,
                     const DNSAnswer* answer) :
49
    io_(io_service), done_(false), stopped_by_hand_(false),
50 51
    checkin_callback_(checkin), lookup_callback_(lookup),
    answer_callback_(answer)
52 53 54 55
{
    tcp::endpoint endpoint(addr, port);
    acceptor_.reset(new tcp::acceptor(io_service));
    acceptor_->open(endpoint.protocol());
56
    // Set v6-only (we use a separate instantiation for v4,
57 58 59 60 61 62 63 64 65 66 67
    // otherwise asio will bind to both v4 and v6
    if (addr.is_v6()) {
        acceptor_->set_option(ip::v6_only(true));
    }
    acceptor_->set_option(tcp::acceptor::reuse_address(true));
    acceptor_->bind(endpoint);
    acceptor_->listen();
}

void
TCPServer::operator()(error_code ec, size_t length) {
68 69 70
    /// Because the coroutine reeentry block is implemented as
    /// a switch statement, inline variable declarations are not
    /// permitted.  Certain variables used below can be declared here.
71

72
    /// If user has stopped the server, we won't enter the
73
    /// coroutine body, just return
74 75 76 77
    if (stopped_by_hand_) {
        return;
    }

78
    boost::array<const_buffer,2> bufs;
Jelte Jansen's avatar
Jelte Jansen committed
79
    OutputBuffer lenbuf(TCP_MESSAGE_LENGTHSIZE);
80

81 82
    CORO_REENTER (this) {
        do {
83
            /// Create a socket to listen for connections
84
            socket_.reset(new tcp::socket(acceptor_->get_io_service()));
85

86 87 88 89 90
            /// Wait for new connections. In the event of error,
            /// try again
            do {
                CORO_YIELD acceptor_->async_accept(*socket_, *this);
            } while (!ec);
91 92 93 94 95

            /// Fork the coroutine by creating a copy of this one and
            /// scheduling it on the ASIO service queue.  The parent
            /// will continue listening for DNS connections while the
            /// handles the one that has just arrived.
96 97
            CORO_FORK io_.post(TCPServer(*this));
        } while (is_parent());
98

99 100
        /// Instantiate the data buffer that will be used by the
        /// asynchronous read call.
101
        data_.reset(new char[MAX_LENGTH]);
102

103
        /// Read the message, in two parts.  First, the message length:
104
        CORO_YIELD async_read(*socket_, asio::buffer(data_.get(),
105
                              TCP_MESSAGE_LENGTHSIZE), *this);
106 107 108
        if (ec) {
            CORO_YIELD return;
        }
109

110 111
        /// Now read the message itself. (This is done in a different scope
        /// to allow inline variable declarations.)
112 113 114 115 116 117
        CORO_YIELD {
            InputBuffer dnsbuffer((const void *) data_.get(), length);
            uint16_t msglen = dnsbuffer.readUint16();
            async_read(*socket_, asio::buffer(data_.get(), msglen), *this);
        }

118 119 120 121
        if (ec) {
            CORO_YIELD return;
        }

122
        // Create an \c IOMessage object to store the query.
123 124 125 126
        //
        // (XXX: It would be good to write a factory function
        // that would quickly generate an IOMessage object without
        // all these calls to "new".)
127
        peer_.reset(new TCPEndpoint(socket_->remote_endpoint()));
Stephen Morris's avatar
Stephen Morris committed
128 129 130 131 132

        // The TCP socket class has been extended with asynchronous functions
        // and takes as a template parameter a completion callback class.  As
        // TCPServer does not use these extended functions (only those defined
        // in the IOSocket base class) - but needs a TCPSocket to get hold of
133 134 135
        // the underlying Boost TCP socket - DummyIOCallback is used.  This
        // provides the appropriate operator() but is otherwise functionless.
        iosock_.reset(new TCPSocket<DummyIOCallback>(*socket_));
136
        io_message_.reset(new IOMessage(data_.get(), length, *iosock_, *peer_));
137
        bytes_ = length;
138

139 140 141 142 143 144 145 146
        // Perform any necessary operations prior to processing the incoming
        // packet (e.g., checking for queued configuration messages).
        //
        // (XXX: it may be a performance issue to have this called for
        // every single incoming packet; we may wish to throttle it somehow
        // in the future.)
        if (checkin_callback_ != NULL) {
            (*checkin_callback_)(*io_message_);
147 148
        }

149 150
        // If we don't have a DNS Lookup provider, there's no point in
        // continuing; we exit the coroutine permanently.
151
        if (lookup_callback_ == NULL) {
152 153 154
            CORO_YIELD return;
        }

155 156
        // Reset or instantiate objects that will be needed by the
        // DNS lookup and the write call.
157
        respbuf_.reset(new OutputBuffer(0));
158
        query_message_.reset(new Message(Message::PARSE));
159
        answer_message_.reset(new Message(Message::RENDER));
160

161 162 163 164
        // Schedule a DNS lookup, and yield.  When the lookup is
        // finished, the coroutine will resume immediately after
        // this point.
        CORO_YIELD io_.post(AsyncLookup<TCPServer>(*this));
165

166 167
        // The 'done_' flag indicates whether we have an answer
        // to send back.  If not, exit the coroutine permanently.
168 169
        if (!done_) {
            CORO_YIELD return;
170
        }
171

172 173
        // Call the DNS answer provider to render the answer into
        // wire format
174 175
        (*answer_callback_)(*io_message_, query_message_,
                            answer_message_, respbuf_);
176

177
        // Set up the response, beginning with two length bytes.
Jelte Jansen's avatar
Jelte Jansen committed
178 179
        lenbuf.writeUint16(respbuf_->getLength());
        bufs[0] = buffer(lenbuf.getData(), lenbuf.getLength());
180
        bufs[1] = buffer(respbuf_->getData(), respbuf_->getLength());
181 182 183 184 185

        // Begin an asynchronous send, and then yield.  When the
        // send completes, we will resume immediately after this point
        // (though we have nothing further to do, so the coroutine
        // will simply exit at that time).
186
        CORO_YIELD async_write(*socket_, bufs, *this);
187 188 189
    }
}

190 191
/// Call the DNS lookup provider.  (Expected to be called by the
/// AsyncLookup<TCPServer> handler.)
192
void
193
TCPServer::asyncLookup() {
194 195
    (*lookup_callback_)(*io_message_, query_message_,
                        answer_message_, respbuf_, this);
196 197
}

198
void TCPServer::stop() {
199 200 201 202
    //server should not be stopped twice
    if (stopped_by_hand_)
        return;

203 204 205 206
    stopped_by_hand_ = true;
    acceptor_->close();
    socket_->close();
}
207 208 209
/// Post this coroutine on the ASIO service queue so that it will
/// resume processing where it left off.  The 'done' parameter indicates
/// whether there is an answer to return to the client.
210
void
211 212
TCPServer::resume(const bool done) {
    done_ = done;
213 214 215
    io_.post(*this);
}

216 217
} // namespace asiolink