dhcp6_client.cc 15.3 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
// Copyright (C) 2014 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 <dhcp/dhcp6.h>
#include <dhcp/option_custom.h>
#include <dhcp/option6_ia.h>
#include <dhcp/option6_iaaddr.h>
#include <dhcp/pkt6.h>
#include <dhcpsrv/lease.h>
#include <dhcp6/tests/dhcp6_client.h>
#include <util/buffer.h>
#include <boost/pointer_cast.hpp>
24
#include <cstdlib>
25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41
#include <time.h>

using namespace isc::test;

namespace isc {
namespace dhcp {
namespace test {

Dhcp6Client::Dhcp6Client() :
    relay_link_addr_("3000:1::1"),
    curr_transid_(0),
    dest_addr_(ALL_DHCP_RELAY_AGENTS_AND_SERVERS),
    duid_(generateDUID(DUID::DUID_LLT)),
    link_local_("fe80::3a60:77ff:fed5:cdef"),
    srv_(boost::shared_ptr<NakedDhcpv6Srv>(new NakedDhcpv6Srv(0))),
    use_na_(false),
    use_pd_(false),
42 43
    use_relay_(false),
    prefix_hint_() {
44 45
}

46 47 48 49 50 51 52 53 54 55 56 57
Dhcp6Client::Dhcp6Client(boost::shared_ptr<NakedDhcpv6Srv>& srv) :
    relay_link_addr_("3000:1::1"),
    curr_transid_(0),
    dest_addr_(ALL_DHCP_RELAY_AGENTS_AND_SERVERS),
    duid_(generateDUID(DUID::DUID_LLT)),
    link_local_("fe80::3a60:77ff:fed5:cdef"),
    srv_(srv),
    use_na_(false),
    use_pd_(false),
    use_relay_(false) {
}

58
void
59
Dhcp6Client::applyRcvdConfiguration(const Pkt6Ptr& reply) {
60
    typedef OptionCollection Opts;
61 62
    // Get all options in the reply message and pick IA_NA, IA_PD and
    // Status code.
63
    Opts opts = reply->options_;
64 65
    // Set the global status code to default: success and not received.
    config_.resetGlobalStatusCode();
66 67 68 69 70
    for (Opts::const_iterator opt = opts.begin(); opt != opts.end(); ++opt) {
        Option6IAPtr ia = boost::dynamic_pointer_cast<Option6IA>(opt->second);
        if (!ia) {
            continue;
        }
71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137

        const Opts& ia_opts = ia->getOptions();
        for (Opts::const_iterator iter_ia_opt = ia_opts.begin();
             iter_ia_opt != ia_opts.end(); ++iter_ia_opt) {
            OptionPtr ia_opt = iter_ia_opt->second;
            LeaseInfo lease_info;
            switch (ia_opt->getType()) {
            case D6O_IAADDR:
                {
                    Option6IAAddrPtr iaaddr = boost::dynamic_pointer_cast<
                        Option6IAAddr>(ia->getOption(D6O_IAADDR));
                    if (!iaaddr) {
                        // There is no address. This IA option may simply
                        // contain a status code, so let's just reset the
                        // lease and keep IAID around.
                        lease_info.lease_ = Lease6();
                        lease_info.lease_.type_ = Lease::TYPE_NA;
                        lease_info.lease_.iaid_ = ia->getIAID();
                        break;
                    }
                    lease_info.lease_ = Lease6(Lease::TYPE_NA,
                                               iaaddr->getAddress(),
                                               duid_, ia->getIAID(),
                                               iaaddr->getPreferred(),
                                               iaaddr->getValid(),
                                               ia->getT1(), ia->getT2(), 0);
                    lease_info.lease_.cltt_ = time(NULL);
                }
                break;

            case D6O_IAPREFIX:
                {
                    Option6IAPrefixPtr iaprefix = boost::dynamic_pointer_cast<
                        Option6IAPrefix>(ia->getOption(D6O_IAPREFIX));
                    if (!iaprefix) {
                        // There is no prefix. This IA option may simply
                        // contain a status code, so let's just reset the
                        // lease and keep IAID around.
                        lease_info.lease_ = Lease6();
                        lease_info.lease_.type_ = Lease::TYPE_PD;
                        lease_info.lease_.iaid_ = ia->getIAID();
                        break;
                    }
                    lease_info.lease_ = Lease6(Lease::TYPE_PD,
                                               iaprefix->getAddress(), duid_,
                                               ia->getIAID(),
                                               iaprefix->getPreferred(),
                                               iaprefix->getValid(),
                                               ia->getT1(), ia->getT2(), 0,
                                               iaprefix->getLength());
                    lease_info.lease_.cltt_ = time(NULL);
                }
                break;

            case D6O_STATUS_CODE:
                {
                    // Check if the server has sent status code. If no status
                    // code, assume the status code to be 0.
                    OptionCustomPtr status_code = boost::dynamic_pointer_cast<
                        OptionCustom>(ia->getOption(D6O_STATUS_CODE));
                    lease_info.status_code_ =
                        status_code ? status_code->readInteger<uint16_t>(0) : 0;
                }
                break;

            default:
                ; // no-op
138 139
            }

140
            applyLease(lease_info);
141 142
        }
    }
143 144 145 146 147 148 149 150 151 152

    // Get the global status code.
    OptionCustomPtr status_code = boost::dynamic_pointer_cast<
        OptionCustom>(reply->getOption(D6O_STATUS_CODE));
    // If status code has been sent, we override the default status code:
    // Success and record that we have received the status code.
    if (status_code) {
        config_.received_status_code_ = true;
        config_.status_code_ = status_code->readInteger<uint16_t>(0);
    }
153 154 155 156 157 158 159 160 161 162 163 164
}

void
Dhcp6Client::applyLease(const LeaseInfo& lease_info) {
    // Go over existing leases and try to match the one that we have.
    for (int i = 0; i < config_.leases_.size(); ++i) {
        Lease6 existing_lease = config_.leases_[i].lease_;
        // If IAID is matching and there is an actual address assigned
        // replace the current lease. The default address is :: if the
        // server hasn't sent the IA option. In this case, there is no
        // lease assignment so we keep what we have.
        if ((existing_lease.iaid_ == lease_info.lease_.iaid_)
165
            && (existing_lease.type_ == lease_info.lease_.type_)
166 167
            && (lease_info.lease_.addr_ != asiolink::IOAddress("::"))
            && (existing_lease.addr_ == lease_info.lease_.addr_)) {
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
            config_.leases_[i] = lease_info;
            return;

        } else if (lease_info.lease_.addr_ == asiolink::IOAddress("::")) {
            config_.leases_[i].status_code_ = lease_info.status_code_;
            return;

        }
    }
    // It is a new lease. Add it.
    config_.leases_.push_back(lease_info);
}

void
Dhcp6Client::copyIAs(const Pkt6Ptr& source, const Pkt6Ptr& dest) {
    typedef OptionCollection Opts;
    // Copy IA_NAs.
    Opts opts = source->getOptions(D6O_IA_NA);
    for (Opts::const_iterator opt = opts.begin(); opt != opts.end(); ++opt) {
        dest->addOption(opt->second);
    }
    // Copy IA_PDs.
    opts = source->getOptions(D6O_IA_PD);
    for (Opts::const_iterator opt = opts.begin(); opt != opts.end(); ++opt) {
        dest->addOption(opt->second);
    }
}

void
Dhcp6Client::copyIAsFromLeases(const Pkt6Ptr& dest) const {
    // Go over leases and create IA_NA and IA_PD options from them.
    // Create one IA per lease.
200 201 202 203 204 205 206 207 208 209
    std::set<uint32_t> iaids = getIAIDs();
    for (std::set<uint32_t>::const_iterator iaid = iaids.begin();
         iaid != iaids.end(); ++iaid) {
        std::vector<Lease6> leases = getLeasesByIAID(*iaid);
        Option6IAPtr opt(new Option6IA(leases[0].type_ == Lease::TYPE_NA ?
                                       D6O_IA_NA : D6O_IA_PD, *iaid));
        opt->setT1(leases[0].t1_);
        opt->setT2(leases[0].t2_);
        for (std::vector<Lease6>::const_iterator lease = leases.begin();
             lease != leases.end(); ++lease) {
210 211 212 213
            if ((lease->preferred_lft_ != 0) && (lease->valid_lft_ != 0)) {
                if (lease->type_ == Lease::TYPE_NA) {
                    opt->addOption(Option6IAAddrPtr(new Option6IAAddr(
                                                          D6O_IAADDR,
214 215 216
                                                          lease->addr_,
                                                          lease->preferred_lft_,
                                                          lease->valid_lft_)));
217 218 219
                } else if (lease->type_ == Lease::TYPE_PD) {
                    opt->addOption(Option6IAAddrPtr(new Option6IAPrefix(
                                                          D6O_IAPREFIX,
220 221 222 223
                                                          lease->addr_,
                                                          lease->prefixlen_,
                                                          lease->preferred_lft_,
                                                          lease->valid_lft_)));
224
                }
225
            }
226
        }
227
        dest->addOption(opt);
228 229 230
    }
}

231 232 233 234 235 236 237
void
Dhcp6Client::createLease(const Lease6& lease) {
    LeaseInfo info;
    info.lease_ = lease;
    applyLease(info);
}

238 239 240 241 242 243 244 245 246
Pkt6Ptr
Dhcp6Client::createMsg(const uint8_t msg_type) {
    Pkt6Ptr msg(new Pkt6(msg_type, curr_transid_++));
    msg->addOption(getClientId());
    return (msg);
}

void
Dhcp6Client::doSARR() {
247
    doSolicit();
248 249
    // Don't send the Request if there was no Advertise.
    if (context_.response_) {
250
        doRequest();
251 252 253 254
    }
}

void
255
Dhcp6Client::doSolicit() {
256 257 258 259 260 261
    context_.query_ = createMsg(DHCPV6_SOLICIT);
    if (use_na_) {
        context_.query_->addOption(Option6IAPtr(new Option6IA(D6O_IA_NA,
                                                              1234)));
    }
    if (use_pd_) {
262 263 264 265 266
        Option6IAPtr ia(new Option6IA(D6O_IA_PD, 5678));
        if (prefix_hint_) {
            ia->addOption(prefix_hint_);
        }
        context_.query_->addOption(ia);
267 268 269 270 271 272 273 274
    }
    sendMsg(context_.query_);
    context_.response_ = receiveOneMsg();

    /// @todo Sanity check here
}

void
275
Dhcp6Client::doRequest() {
276 277 278 279 280 281 282 283 284 285 286
    Pkt6Ptr query = createMsg(DHCPV6_REQUEST);
    query->addOption(context_.response_->getOption(D6O_SERVERID));
    copyIAs(context_.response_, query);
    context_.query_ = query;
    sendMsg(context_.query_);
    context_.response_ = receiveOneMsg();

    /// @todo sanity check here.

    // Apply new configuration only if the server has responded.
    if (context_.response_) {
287
        applyRcvdConfiguration(context_.response_);
288 289 290 291 292 293 294 295 296 297 298 299
    }
}

void
Dhcp6Client::doRebind() {
    Pkt6Ptr query = createMsg(DHCPV6_REBIND);
    copyIAsFromLeases(query);
    context_.query_ = query;
    sendMsg(context_.query_);
    context_.response_ = receiveOneMsg();
    // Apply configuration only if the server has responded.
    if (context_.response_) {
300
        applyRcvdConfiguration(context_.response_);
301 302 303
    }
}

304 305 306 307 308 309 310 311 312 313 314 315 316
void
Dhcp6Client::doConfirm() {
    context_.query_ = createMsg(DHCPV6_CONFIRM);
    copyIAsFromLeases(context_.query_);
    sendMsg(context_.query_);
    context_.response_ = receiveOneMsg();
    // Set the global status code to default: success and not received.
    config_.resetGlobalStatusCode();
    if (context_.response_) {
        applyRcvdConfiguration(context_.response_);
    }
}

317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334
void
Dhcp6Client::fastFwdTime(const uint32_t secs) {
    // Iterate over all leases and move their cltt backwards.
    for (int i = 0; i < config_.leases_.size(); ++i) {
        config_.leases_[i].lease_.cltt_ -= secs;
    }
}

DuidPtr
Dhcp6Client::generateDUID(DUID::DUIDType duid_type) const {
    std::vector<uint8_t> duid;

    /// @todo remove this check once other DUID types are implemented.
    if (duid_type != DUID::DUID_LLT) {
        isc_throw(NotImplemented, "currently the Dhcp6Client only supports"
                  " generation of DUID LLT");
    }
    duid.push_back(static_cast<uint8_t>(duid_type));
335 336 337
    for (int i = 0; i < 4; ++i) {
        duid.push_back(static_cast<uint8_t>(rand() % 255));
    }
338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353
    for (int i = 0; i < 6; ++i) {
        duid.push_back(static_cast<uint8_t>(i));
    }

    return (DuidPtr(new DUID(duid)));
}

OptionPtr
Dhcp6Client::getClientId() const {
    OptionPtr opt_client_id(new Option(Option::V6,
                                       D6O_CLIENTID,
                                       duid_->getDuid().begin(),
                                       duid_->getDuid().end()));
    return (opt_client_id);
}

354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377
std::set<uint32_t>
Dhcp6Client::getIAIDs() const {
    std::set<uint32_t> iaids;
    for (std::vector<LeaseInfo>::const_iterator lease_info =
             config_.leases_.begin(); lease_info != config_.leases_.end();
         ++lease_info) {
        iaids.insert(lease_info->lease_.iaid_);
    }
    return (iaids);
}

std::vector<Lease6>
Dhcp6Client::getLeasesByIAID(const uint32_t iaid) const {
    std::vector<Lease6> leases;
    for (std::vector<LeaseInfo>::const_iterator lease_info =
             config_.leases_.begin(); lease_info != config_.leases_.end();
         ++lease_info) {
        if (lease_info->lease_.iaid_ == iaid) {
            leases.push_back(lease_info->lease_);
        }
    }
    return (leases);
}

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 419 420 421 422 423 424 425
void
Dhcp6Client::modifyDUID() {
    if (!duid_) {
        duid_ = generateDUID(DUID::DUID_LLT);
        return;
    }
    std::vector<uint8_t> new_duid = duid_->getDuid();
    // Modify the DUID by adding 1 to its last byte.
    ++new_duid[new_duid.size() - 1];
    duid_.reset(new DUID(new_duid));
}

Pkt6Ptr
Dhcp6Client::receiveOneMsg() {
    // Return empty pointer if server hasn't responded.
    if (srv_->fake_sent_.empty()) {
        return (Pkt6Ptr());
    }
    Pkt6Ptr msg = srv_->fake_sent_.front();
    srv_->fake_sent_.pop_front();
    return (msg);
}

void
Dhcp6Client::sendMsg(const Pkt6Ptr& msg) {
    srv_->shutdown_ = false;
    // The client is configured to send through the relay. We achieve that
    // adding the relay structure.
    if (use_relay_) {
        Pkt6::RelayInfo relay;
        relay.linkaddr_ = relay_link_addr_;
        relay.peeraddr_ = asiolink::IOAddress("fe80::1");
        relay.msg_type_ = DHCPV6_RELAY_FORW;
        relay.hop_count_ = 1;
        msg->relay_info_.push_back(relay);
    }
    // Repack the message to simulate wire-data parsing.
    msg->pack();
    Pkt6Ptr msg_copy(new Pkt6(static_cast<const uint8_t*>
                              (msg->getBuffer().getData()),
                              msg->getBuffer().getLength()));
    msg_copy->setRemoteAddr(link_local_);
    msg_copy->setLocalAddr(dest_addr_);
    msg_copy->setIface("eth0");
    srv_->fakeReceive(msg_copy);
    srv_->run();
}

426 427 428 429 430 431 432 433
void
Dhcp6Client::useHint(const uint32_t pref_lft, const uint32_t valid_lft,
                     const uint8_t len, const std::string& prefix) {
    prefix_hint_.reset(new Option6IAPrefix(D6O_IAPREFIX,
                                           asiolink::IOAddress(prefix),
                                           len, pref_lft, valid_lft));
}

434

435 436 437
} // end of namespace isc::dhcp::test
} // end of namespace isc::dhcp
} // end of namespace isc