asio_link.cc 13.4 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
// Copyright (C) 2010  Internet Systems Consortium, Inc. ("ISC")
//
// 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.

// $Id$

#include <config.h>

19
#include <unistd.h>             // for some IPC/network system calls
20
21
22
23
24
25
26
#include <asio.hpp>
#include <boost/bind.hpp>

#include <dns/buffer.h>
#include <dns/message.h>
#include <dns/messagerenderer.h>

27
28
29
30
31
#if defined(HAVE_BOOST_PYTHON)
#define USE_XFROUT
#include <xfr/xfrout_client.h>
#endif

32
33
#include <asio_link.h>

34
#include "spec_config.h"        // for XFROUT.  should not be here.
35
36
37
38
39
40
#include "auth_srv.h"

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

41
using namespace std;
42
using namespace isc::dns;
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
#ifdef USE_XFROUT
using namespace isc::xfr;
#endif

namespace {
// As a short term workaround, we have XFROUT specific code.  We should soon
// refactor the code with some abstraction so that we can separate this level
// details from the (AS)IO module.
#ifdef USE_XFROUT
//TODO. The sample way for checking axfr query, the code should be merged to auth server class
bool
check_axfr_query(char* const msg_data, const uint16_t msg_len) {
    if (msg_len < 15) {
        return false;
    }

    const uint16_t query_type = *(uint16_t *)(msg_data + (msg_len - 4));
    if ( query_type == 0xFC00) {
        return true;
    }
    
    return false;
}

//TODO. Send the xfr query to xfrout module, the code should be merged to auth server class
void
dispatch_axfr_query(const int tcp_sock, char const axfr_query[],
                    const uint16_t query_len)
{
72
73
74
75
76
77
78
    string path;
    if (getenv("B10_FROM_BUILD")) {
        path = string(getenv("B10_FROM_BUILD")) + "/auth_xfrout_conn";
    } else {
        path = UNIX_SOCKET_FILE;
    }
    
79
80
81
82
83
84
85
86
87
88
89
90
91
92
    XfroutClient xfr_client(path);
    try {
        xfr_client.connect();
        xfr_client.sendXfroutRequestInfo(tcp_sock, (uint8_t *)axfr_query,
                                         query_len);
        xfr_client.disconnect();
    }
    catch (const exception & err) {
        //if (verbose_mode)
        cerr << "error handle xfr query:" << err.what() << endl;
    }
}
#endif
}
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109

namespace asio_link {
//
// Helper classes for asynchronous I/O using asio
//
class TCPClient {
public:
    TCPClient(AuthSrv* auth_server, io_service& io_service) :
        auth_server_(auth_server),
        socket_(io_service),
        response_buffer_(0),
        responselen_buffer_(TCP_MESSAGE_LENGTHSIZE),
        response_renderer_(response_buffer_),
        dns_message_(Message::PARSE)
    {}

    void start() {
110
111
112
113
        // Check for queued configuration commands
        if (auth_server_->configSession()->hasQueuedMsgs()) {
            auth_server_->configSession()->checkCommand();
        }
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
        async_read(socket_, asio::buffer(data_, TCP_MESSAGE_LENGTHSIZE),
                   boost::bind(&TCPClient::headerRead, this,
                               placeholders::error,
                               placeholders::bytes_transferred));
    }

    tcp::socket& getSocket() { return (socket_); }

    void headerRead(const asio::error_code& error,
                    size_t bytes_transferred)
    {
        if (!error) {
            InputBuffer dnsbuffer(data_, bytes_transferred);

            uint16_t msglen = dnsbuffer.readUint16();
            async_read(socket_, asio::buffer(data_, msglen),

                       boost::bind(&TCPClient::requestRead, this,
                                   placeholders::error,
                                   placeholders::bytes_transferred));
        } else {
            delete this;
        }
    }

    void requestRead(const asio::error_code& error,
                     size_t bytes_transferred)
    {
        if (!error) {
            InputBuffer dnsbuffer(data_, bytes_transferred);
#ifdef USE_XFROUT
            if (check_axfr_query(data_, bytes_transferred)) {
                dispatch_axfr_query(socket_.native(), data_, bytes_transferred); 
                // start to get new query ?
                start();
            } else {
#endif          
                if (auth_server_->processMessage(dnsbuffer, dns_message_,
                                                response_renderer_, false)) {
                    responselen_buffer_.writeUint16(
                        response_buffer_.getLength());
                    async_write(socket_,
                                asio::buffer(
                                    responselen_buffer_.getData(),
                                    responselen_buffer_.getLength()),
                                boost::bind(&TCPClient::responseWrite, this,
                                            placeholders::error));
                } else {
                    delete this;
                }
#ifdef USE_XFROUT
            }
#endif
        } else {
            delete this;
        }
    }

    void responseWrite(const asio::error_code& error) {
        if (!error) {
                async_write(socket_,
                            asio::buffer(response_buffer_.getData(),
                                                response_buffer_.getLength()),
                        boost::bind(&TCPClient::handleWrite, this,
                                    placeholders::error));
        } else {
            delete this;
        }
    }

    void handleWrite(const asio::error_code& error) {
        if (!error) {
            start();            // handle next request, if any.
      } else {
            delete this;
      }
    }

private:
    AuthSrv* auth_server_;
    tcp::socket socket_;
    OutputBuffer response_buffer_;
    OutputBuffer responselen_buffer_;
    MessageRenderer response_renderer_;
    Message dns_message_;
    enum { MAX_LENGTH = 65535 };
    static const size_t TCP_MESSAGE_LENGTHSIZE = 2;
    char data_[MAX_LENGTH];
};

class TCPServer {
public:
    TCPServer(AuthSrv* auth_server, io_service& io_service,
              int af, short port) :
        auth_server_(auth_server), io_service_(io_service),
        acceptor_(io_service_), listening_(new TCPClient(auth_server_,
                                                         io_service_))
    {
        tcp::endpoint endpoint(af == AF_INET6 ? tcp::v6() : tcp::v4(), port);
        acceptor_.open(endpoint.protocol());
        // Set v6-only (we use a different instantiation for v4,
        // otherwise asio will bind to both v4 and v6
        if (af == AF_INET6) {
            acceptor_.set_option(ip::v6_only(true));
        }
        acceptor_.set_option(tcp::acceptor::reuse_address(true));
        acceptor_.bind(endpoint);
        acceptor_.listen();
        acceptor_.async_accept(listening_->getSocket(),
                               boost::bind(&TCPServer::handleAccept, this,
                                           listening_, placeholders::error));
    }

    ~TCPServer() { delete listening_; }

    void handleAccept(TCPClient* new_client,
                      const asio::error_code& error)
    {
        if (!error) {
            assert(new_client == listening_);
            new_client->start();
            listening_ = new TCPClient(auth_server_, io_service_);
            acceptor_.async_accept(listening_->getSocket(),
                                   boost::bind(&TCPServer::handleAccept,
                                               this, listening_,
                                               placeholders::error));
        } else {
            delete new_client;
        }
    }

private:
    AuthSrv* auth_server_;
    io_service& io_service_;
    tcp::acceptor acceptor_;
    TCPClient* listening_;
};

class UDPServer {
public:
    UDPServer(AuthSrv* auth_server, io_service& io_service,
              int af, short port) :
        auth_server_(auth_server),
        io_service_(io_service),
        socket_(io_service, af == AF_INET6 ? udp::v6() : udp::v4()),
        response_buffer_(0),
        response_renderer_(response_buffer_),
        dns_message_(Message::PARSE)
    {
        // Set v6-only (we use a different instantiation for v4,
        // otherwise asio will bind to both v4 and v6
        if (af == AF_INET6) {
            socket_.set_option(asio::ip::v6_only(true));
            socket_.bind(udp::endpoint(udp::v6(), port));
        } else {
            socket_.bind(udp::endpoint(udp::v4(), port));
        }
        startReceive();
    }

    void handleRequest(const asio::error_code& error,
                       size_t bytes_recvd)
    {
277
278
279
280
        // Check for queued configuration commands
        if (auth_server_->configSession()->hasQueuedMsgs()) {
            auth_server_->configSession()->checkCommand();
        }
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
        if (!error && bytes_recvd > 0) {
            InputBuffer request_buffer(data_, bytes_recvd);

            dns_message_.clear(Message::PARSE);
            response_renderer_.clear();
            if (auth_server_->processMessage(request_buffer, dns_message_,
                                            response_renderer_, true)) {
                socket_.async_send_to(
                    asio::buffer(response_buffer_.getData(),
                                        response_buffer_.getLength()),
                    sender_endpoint_,
                    boost::bind(&UDPServer::sendCompleted,
                                this,
                                placeholders::error,
                                placeholders::bytes_transferred));
            } else {
                startReceive();
            }
        } else {
            startReceive();
        }
    }

    void sendCompleted(const asio::error_code& error UNUSED_PARAM,
                       size_t bytes_sent UNUSED_PARAM)
    {
        // Even if error occurred there's nothing to do.  Simply handle
        // the next request.
        startReceive();
    }
private:
    void startReceive() {
        socket_.async_receive_from(
            asio::buffer(data_, MAX_LENGTH), sender_endpoint_,
            boost::bind(&UDPServer::handleRequest, this,
                        placeholders::error,
                        placeholders::bytes_transferred));
    }

private:
    AuthSrv* auth_server_;
    io_service& io_service_;
    udp::socket socket_;
    OutputBuffer response_buffer_;
    MessageRenderer response_renderer_;
    Message dns_message_;
    udp::endpoint sender_endpoint_;
    enum { MAX_LENGTH = 4096 };
    char data_[MAX_LENGTH];
};

// This is a helper structure just to make the construction of IOServiceImpl
// exception safe.  If the constructor of {UDP/TCP}Server throws an exception,
// the destructor of this class will automatically perform the necessary
// cleanup.
struct ServerSet {
    ServerSet() : udp4_server(NULL), udp6_server(NULL),
                  tcp4_server(NULL), tcp6_server(NULL)
    {}
    ~ServerSet() {
        delete udp4_server;
        delete udp6_server;
        delete tcp4_server;
        delete tcp6_server;
    }
    UDPServer* udp4_server;
    UDPServer* udp6_server;
    TCPServer* tcp4_server;
    TCPServer* tcp6_server;
};

class IOServiceImpl {
public:
    IOServiceImpl(AuthSrv* auth_server, const char* port,
                  const bool use_ipv4, const bool use_ipv6);
    ~IOServiceImpl();
    asio::io_service io_service_;
    AuthSrv* auth_server_;
    UDPServer* udp4_server_;
    UDPServer* udp6_server_;
    TCPServer* tcp4_server_;
    TCPServer* tcp6_server_;
};

IOServiceImpl::IOServiceImpl(AuthSrv* auth_server, const char* const port,
                             const bool use_ipv4, const bool use_ipv6) :
    auth_server_(auth_server), udp4_server_(NULL), udp6_server_(NULL),
    tcp4_server_(NULL), tcp6_server_(NULL)
{
    ServerSet servers;
    short portnum = atoi(port);

    if (use_ipv4) {
        servers.udp4_server = new UDPServer(auth_server, io_service_,
                                            AF_INET, portnum);
        servers.tcp4_server = new TCPServer(auth_server, io_service_,
                                            AF_INET, portnum);
    }
    if (use_ipv6) {
        servers.udp6_server = new UDPServer(auth_server, io_service_,
                                            AF_INET6, portnum);
        servers.tcp6_server = new TCPServer(auth_server, io_service_,
                                            AF_INET6, portnum);
    }

    // Now we don't have to worry about exception, and need to make sure that
    // the server objects won't be accidentally cleaned up.
    servers.udp4_server = NULL;
    servers.udp6_server = NULL;
    servers.tcp4_server = NULL;
    servers.tcp6_server = NULL;
}

IOServiceImpl::~IOServiceImpl() {
    delete udp4_server_;
    delete udp6_server_;
    delete tcp4_server_;
    delete tcp6_server_;
}

IOService::IOService(AuthSrv* auth_server, const char* const port,
                     const bool use_ipv4, const bool use_ipv6) {
    impl_ = new IOServiceImpl(auth_server, port, use_ipv4, use_ipv6);
}

IOService::~IOService() {
    delete impl_;
}

void
IOService::run() {
    impl_->io_service_.run();
}

void
IOService::stop() {
    impl_->io_service_.stop();
}
419
420
421
422
423

asio::io_service&
IOService::get_io_service() {
    return impl_->io_service_;
}
424
}