dns_client.cc 10.3 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
// Copyright (C) 2013 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.

#include <d2/dns_client.h>
16
#include <d2/d2_log.h>
17
#include <dns/messagerenderer.h>
18
#include <limits>
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34

namespace isc {
namespace d2 {

namespace {

// OutputBuffer objects are pre-allocated before data is written to them.
// This is a default number of bytes for the buffers we create within
// DNSClient class.
const size_t DEFAULT_BUFFER_SIZE = 128;

}

using namespace isc::util;
using namespace isc::asiolink;
using namespace isc::asiodns;
35
using namespace isc::dns;
36

37
// This class provides the implementation for the DNSClient. This allows for
38
39
40
41
42
43
44
45
46
// the separation of the DNSClient interface from the implementation details.
// Currently, implementation uses IOFetch object to handle asynchronous
// communication with the DNS. This design may be revisited in the future. If
// implementation is changed, the DNSClient API will remain unchanged thanks
// to this separation.
class DNSClientImpl : public asiodns::IOFetch::Callback {
public:
    // A buffer holding response from a DNS.
    util::OutputBufferPtr in_buf_;
47
48
49
50
51
52
    // A caller-supplied object which will hold the parsed response from DNS.
    // The response object is (or descends from) isc::dns::Message and is
    // populated using Message::fromWire().  This method may only be called
    // once in the lifetime of a Message instance.  Therefore, response_ is a
    // pointer reference thus allowing this class to replace the object
    // pointed to with a new Message instance each time a message is
53
54
55
56
    // received. This allows a single DNSClientImpl instance to be used for
    // multiple, sequential IOFetch calls. (@todo Trac# 3286 has been opened
    // against dns::Message::fromWire.  Should the behavior of fromWire change
    // the behavior here with could be rexamined).
57
    D2UpdateMessagePtr& response_;
58
59
60
    // A caller-supplied external callback which is invoked when DNS message
    // exchange is complete or interrupted.
    DNSClient::Callback* callback_;
61
62
    // A Transport Layer protocol used to communicate with a DNS.
    DNSClient::Protocol proto_;
63

64
    // Constructor and Destructor
65
    DNSClientImpl(D2UpdateMessagePtr& response_placeholder,
66
67
                  DNSClient::Callback* callback,
                  const DNSClient::Protocol proto);
68
69
70
71
72
73
74
75
    virtual ~DNSClientImpl();

    // This internal callback is called when the DNS update message exchange is
    // complete. It further invokes the external callback provided by a caller.
    // Before external callback is invoked, an object of the D2UpdateMessage
    // type, representing a response from the server is set.
    virtual void operator()(asiodns::IOFetch::Result result);

76
    // Starts asynchronous DNS Update.
77
    void doUpdate(asiolink::IOService& io_service,
78
79
80
                  const asiolink::IOAddress& ns_addr,
                  const uint16_t ns_port,
                  D2UpdateMessage& update,
81
                  const unsigned int wait);
82
83
84
85
86
87

    // This function maps the IO error to the DNSClient error.
    DNSClient::Status getStatus(const asiodns::IOFetch::Result);
};

DNSClientImpl::DNSClientImpl(D2UpdateMessagePtr& response_placeholder,
88
89
                             DNSClient::Callback* callback,
                             const DNSClient::Protocol proto)
90
    : in_buf_(new OutputBuffer(DEFAULT_BUFFER_SIZE)),
91
92
      response_(response_placeholder), callback_(callback), proto_(proto) {

93
94
95
96
97
98
    // Response should be an empty pointer. It gets populated by the
    // operator() method.
    if (response_) {
        isc_throw(isc::BadValue, "Response buffer pointer should be null");
    }

99
100
    // @todo Currently we only support UDP. The support for TCP is planned for
    // the future release.
101
102
103
104
105
106
107
108
    if (proto_ == DNSClient::TCP) {
        isc_throw(isc::NotImplemented, "TCP is currently not supported as a"
                  << " Transport protocol for DNS Updates; please use UDP");
    }

    // Given that we already eliminated the possibility that TCP is used, it
    // would be sufficient  to check that (proto != DNSClient::UDP). But, once
    // support TCP is added the check above will disappear and the extra check
109
110
111
112
113
114
115
116
117
118
119
120
    // will be needed here anyway.
    // Note that cascaded check is used here instead of:
    //   if (proto_ != DNSClient::TCP && proto_ != DNSClient::UDP)..
    // because some versions of GCC compiler complain that check above would
    // be always 'false' due to limited range of enumeration. In fact, it is
    // possible to pass out of range integral value through enum and it should
    // be caught here.
    if (proto_ != DNSClient::TCP) {
        if (proto_ != DNSClient::UDP) {
            isc_throw(isc::NotImplemented, "invalid transport protocol type '"
                      << proto_ << "' specified for DNS Updates");
        }
121
    }
122
123
}

124
125
126
DNSClientImpl::~DNSClientImpl() {
}

127
void
128
DNSClientImpl::operator()(asiodns::IOFetch::Result result) {
129
130
    // Get the status from IO. If no success, we just call user's callback
    // and pass the status code.
131
132
    DNSClient::Status status = getStatus(result);
    if (status == DNSClient::SUCCESS) {
133
        InputBuffer response_buf(in_buf_->getData(), in_buf_->getLength());
134
135
136
137
138
        // Allocate a new response message. (Note that Message::fromWire
        // may only be run once per message, so we need to start fresh
        // each time.)
        response_.reset(new D2UpdateMessage(D2UpdateMessage::INBOUND));

139
140
141
        // Server's response may be corrupted. In such case, fromWire will
        // throw an exception. We want to catch this exception to return
        // appropriate status code to the caller and log this event.
142
143
        try {
            response_->fromWire(response_buf);
144

145
146
        } catch (const Exception& ex) {
            status = DNSClient::INVALID_RESPONSE;
147
148
149
            LOG_DEBUG(dctl_logger, DBGLVL_TRACE_DETAIL,
                      DHCP_DDNS_INVALID_RESPONSE).arg(ex.what());

150
        }
151
    }
152
153
154
155

    // Once we are done with internal business, let's call a callback supplied
    // by a caller.
    if (callback_ != NULL) {
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
        (*callback_)(status);
    }
}

DNSClient::Status
DNSClientImpl::getStatus(const asiodns::IOFetch::Result result) {
    switch (result) {
    case IOFetch::SUCCESS:
        return (DNSClient::SUCCESS);

    case IOFetch::TIME_OUT:
        return (DNSClient::TIMEOUT);

    case IOFetch::STOPPED:
        return (DNSClient::IO_STOPPED);

    default:
        ;
174
    }
175
    return (DNSClient::OTHER);
176
177
178
}

void
179
DNSClientImpl::doUpdate(asiolink::IOService& io_service,
180
181
182
                        const IOAddress& ns_addr,
                        const uint16_t ns_port,
                        D2UpdateMessage& update,
183
                        const unsigned int wait) {
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
    // A renderer is used by the toWire function which creates the on-wire data
    // from the DNS Update message. A renderer has its internal buffer where it
    // renders data by default. However, this buffer can't be directly accessed.
    // Fortunately, the renderer's API accepts user-supplied buffers. So, let's
    // create our own buffer and pass it to the renderer so as the message is
    // rendered to this buffer. Finally, we pass this buffer to IOFetch.
    dns::MessageRenderer renderer;
    OutputBufferPtr msg_buf(new OutputBuffer(DEFAULT_BUFFER_SIZE));
    renderer.setBuffer(msg_buf.get());

    // Render DNS Update message. This may throw a bunch of exceptions if
    // invalid message object is given.
    update.toWire(renderer);

    // IOFetch has all the mechanisms that we need to perform asynchronous
    // communication with the DNS server. The last but one argument points to
    // this object as a completion callback for the message exchange. As a
201
    // result operator()(Status) will be called.
202
203
204
205

    // Timeout value is explicitly cast to the int type to avoid warnings about
    // overflows when doing implicit cast. It should have been checked by the
    // caller that the unsigned timeout value will fit into int.
206
    IOFetch io_fetch(IOFetch::UDP, io_service, msg_buf, ns_addr, ns_port,
207
                     in_buf_, this, static_cast<int>(wait));
208

209
210
    // Post the task to the task queue in the IO service. Caller will actually
    // run these tasks by executing IOService::run.
211
    io_service.post(io_fetch);
212
213
214
}


215
DNSClient::DNSClient(D2UpdateMessagePtr& response_placeholder,
216
217
                     Callback* callback, const DNSClient::Protocol proto)
    : impl_(new DNSClientImpl(response_placeholder, callback, proto)) {
218
219
220
221
222
223
}

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

224
225
226
227
228
229
230
unsigned int
DNSClient::getMaxTimeout() {
    static const unsigned int max_timeout = std::numeric_limits<int>::max();
    return (max_timeout);
}

void
231
DNSClient::doUpdate(asiolink::IOService&,
232
233
234
235
236
237
238
239
240
                    const IOAddress&,
                    const uint16_t,
                    D2UpdateMessage&,
                    const unsigned int,
                    const dns::TSIGKey&) {
    isc_throw(isc::NotImplemented, "TSIG is currently not supported for"
              "DNS Update message");
}

241
void
242
DNSClient::doUpdate(asiolink::IOService& io_service,
243
244
245
                    const IOAddress& ns_addr,
                    const uint16_t ns_port,
                    D2UpdateMessage& update,
246
247
248
249
250
251
252
253
254
                    const unsigned int wait) {
    // The underlying implementation which we use to send DNS Updates uses
    // signed integers for timeout. If we want to avoid overflows we need to
    // respect this limitation here.
    if (wait > getMaxTimeout()) {
        isc_throw(isc::BadValue, "A timeout value for DNS Update request must"
                  " not exceed " << getMaxTimeout()
                  << ". Provided timeout value is '" << wait << "'");
    }
255
256
257
258
    impl_->doUpdate(io_service, ns_addr, ns_port, update, wait);
}


259

260
261
262
} // namespace d2
} // namespace isc