DnsContext.java 36.5 KB
Newer Older
D
duke 已提交
1
/*
2
 * Copyright 2000-2009 Sun Microsystems, Inc.  All Rights Reserved.
D
duke 已提交
3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 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 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 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 277 278 279 280 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 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * This code is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License version 2 only, as
 * published by the Free Software Foundation.  Sun designates this
 * particular file as subject to the "Classpath" exception as provided
 * by Sun in the LICENSE file that accompanied this code.
 *
 * This code is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
 * version 2 for more details (a copy is included in the LICENSE file that
 * accompanied this code).
 *
 * You should have received a copy of the GNU General Public License version
 * 2 along with this work; if not, write to the Free Software Foundation,
 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
 *
 * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
 * CA 95054 USA or visit www.sun.com if you need additional information or
 * have any questions.
 */

package com.sun.jndi.dns;


import java.util.Enumeration;
import java.util.Hashtable;

import javax.naming.*;
import javax.naming.directory.*;
import javax.naming.spi.DirectoryManager;

import com.sun.jndi.toolkit.ctx.*;


/**
 * A DnsContext is a directory context representing a DNS node.
 *
 * @author Scott Seligman
 */


public class DnsContext extends ComponentDirContext {

    DnsName domain;             // fully-qualified domain name of this context,
                                // with a root (empty) label at position 0
    Hashtable environment;
    private boolean envShared;  // true if environment is possibly shared
                                // and so must be copied on write
    private boolean parentIsDns;        // was this DnsContext created by
                                        // another?  see composeName()
    private String[] servers;
    private Resolver resolver;

    private boolean authoritative;      // must all responses be authoritative?
    private boolean recursion;          // request recursion on queries?
    private int timeout;                // initial timeout on UDP queries in ms
    private int retries;                // number of UDP retries

    static final NameParser nameParser = new DnsNameParser();

    // Timeouts for UDP queries use exponential backoff:  each retry
    // is for twice as long as the last.  The following constants set
    // the defaults for the initial timeout (in ms) and the number of
    // retries, and name the environment properties used to override
    // these defaults.
    private static final int DEFAULT_INIT_TIMEOUT = 1000;
    private static final int DEFAULT_RETRIES = 4;
    private static final String INIT_TIMEOUT =
                                          "com.sun.jndi.dns.timeout.initial";
    private static final String RETRIES = "com.sun.jndi.dns.timeout.retries";

    // The resource record type and class to use for lookups, and the
    // property used to modify them
    private CT lookupCT;
    private static final String LOOKUP_ATTR = "com.sun.jndi.dns.lookup.attr";

    // Property used to disallow recursion on queries
    private static final String RECURSION = "com.sun.jndi.dns.recursion";

    // ANY == ResourceRecord.QCLASS_STAR == ResourceRecord.QTYPE_STAR
    private static final int ANY = ResourceRecord.QTYPE_STAR;

    // The zone tree used for list operations
    private static final ZoneNode zoneTree = new ZoneNode(null);


    /**
     * Returns a DNS context for a given domain and servers.
     * Each server is of the form "server[:port]".
     * IPv6 literal host names include delimiting brackets.
     * There must be at least one server.
     * The environment must not be null; it is cloned before being stored.
     */
    public DnsContext(String domain, String[] servers, Hashtable environment)
            throws NamingException {

        this.domain = new DnsName(domain.endsWith(".")
                                  ? domain
                                  : domain + ".");
        this.servers = servers;
        this.environment = (Hashtable) environment.clone();
        envShared = false;
        parentIsDns = false;
        resolver = null;

        initFromEnvironment();
    }

    /*
     * Returns a clone of a DNS context, just like DnsContext(DnsContext)
     * but with a different domain name and with parentIsDns set to true.
     */
    DnsContext(DnsContext ctx, DnsName domain) {
        this(ctx);
        this.domain = domain;
        parentIsDns = true;
    }

    /*
     * Returns a clone of a DNS context.  The context's modifiable
     * private state is independent of the original's (so closing one
     * context, for example, won't close the other).  The two contexts
     * share <tt>environment</tt>, but it's copy-on-write so there's
     * no conflict.
     */
    private DnsContext(DnsContext ctx) {
        environment = ctx.environment;
        envShared = ctx.envShared = true;
        parentIsDns = ctx.parentIsDns;
        domain = ctx.domain;
        servers = ctx.servers;
        resolver = ctx.resolver;
        authoritative = ctx.authoritative;
        recursion = ctx.recursion;
        timeout = ctx.timeout;
        retries = ctx.retries;
        lookupCT = ctx.lookupCT;
    }

    public void close() {
        if (resolver != null) {
            resolver.close();
            resolver = null;
        }
    }


    //---------- Environment operations

    /*
     * Override default with a noncloning version.
     */
    protected Hashtable p_getEnvironment() {
        return environment;
    }

    public Hashtable getEnvironment() throws NamingException {
        return (Hashtable) environment.clone();
    }

    public Object addToEnvironment(String propName, Object propVal)
            throws NamingException {

        if (propName.equals(LOOKUP_ATTR)) {
            lookupCT = getLookupCT((String) propVal);
        } else if (propName.equals(Context.AUTHORITATIVE)) {
            authoritative = "true".equalsIgnoreCase((String) propVal);
        } else if (propName.equals(RECURSION)) {
            recursion = "true".equalsIgnoreCase((String) propVal);
        } else if (propName.equals(INIT_TIMEOUT)) {
            int val = Integer.parseInt((String) propVal);
            if (timeout != val) {
                timeout = val;
                resolver = null;
            }
        } else if (propName.equals(RETRIES)) {
            int val = Integer.parseInt((String) propVal);
            if (retries != val) {
                retries = val;
                resolver = null;
            }
        }

        if (!envShared) {
            return environment.put(propName, propVal);
        } else if (environment.get(propName) != propVal) {
            // copy on write
            environment = (Hashtable) environment.clone();
            envShared = false;
            return environment.put(propName, propVal);
        } else {
            return propVal;
        }
    }

    public Object removeFromEnvironment(String propName)
            throws NamingException {

        if (propName.equals(LOOKUP_ATTR)) {
            lookupCT = getLookupCT(null);
        } else if (propName.equals(Context.AUTHORITATIVE)) {
            authoritative = false;
        } else if (propName.equals(RECURSION)) {
            recursion = true;
        } else if (propName.equals(INIT_TIMEOUT)) {
            if (timeout != DEFAULT_INIT_TIMEOUT) {
                timeout = DEFAULT_INIT_TIMEOUT;
                resolver = null;
            }
        } else if (propName.equals(RETRIES)) {
            if (retries != DEFAULT_RETRIES) {
                retries = DEFAULT_RETRIES;
                resolver = null;
            }
        }

        if (!envShared) {
            return environment.remove(propName);
        } else if (environment.get(propName) != null) {
            // copy-on-write
            environment = (Hashtable) environment.clone();
            envShared = false;
            return environment.remove(propName);
        } else {
            return null;
        }
    }

    /*
     * Update PROVIDER_URL property.  Call this only when environment
     * is not being shared.
     */
    void setProviderUrl(String url) {
        // assert !envShared;
        environment.put(Context.PROVIDER_URL, url);
    }

    /*
     * Read environment properties and set parameters.
     */
    private void initFromEnvironment()
            throws InvalidAttributeIdentifierException {

        lookupCT = getLookupCT((String) environment.get(LOOKUP_ATTR));
        authoritative = "true".equalsIgnoreCase((String)
                                       environment.get(Context.AUTHORITATIVE));
        String val = (String) environment.get(RECURSION);
        recursion = ((val == null) ||
                     "true".equalsIgnoreCase(val));
        val = (String) environment.get(INIT_TIMEOUT);
        timeout = (val == null)
            ? DEFAULT_INIT_TIMEOUT
            : Integer.parseInt(val);
        val = (String) environment.get(RETRIES);
        retries = (val == null)
            ? DEFAULT_RETRIES
            : Integer.parseInt(val);
    }

    private CT getLookupCT(String attrId)
            throws InvalidAttributeIdentifierException {
        return (attrId == null)
            ? new CT(ResourceRecord.CLASS_INTERNET, ResourceRecord.TYPE_TXT)
            : fromAttrId(attrId);
    }


    //---------- Naming operations

    public Object c_lookup(Name name, Continuation cont)
            throws NamingException {

        cont.setSuccess();
        if (name.isEmpty()) {
            DnsContext ctx = new DnsContext(this);
            ctx.resolver = new Resolver(servers, timeout, retries);
                                                // clone for parallelism
            return ctx;
        }
        try {
            DnsName fqdn = fullyQualify(name);
            ResourceRecords rrs =
                getResolver().query(fqdn, lookupCT.rrclass, lookupCT.rrtype,
                                    recursion, authoritative);
            Attributes attrs = rrsToAttrs(rrs, null);
            DnsContext ctx = new DnsContext(this, fqdn);
            return DirectoryManager.getObjectInstance(ctx, name, this,
                                                      environment, attrs);
        } catch (NamingException e) {
            cont.setError(this, name);
            throw cont.fillInException(e);
        } catch (Exception e) {
            cont.setError(this, name);
            NamingException ne = new NamingException(
                    "Problem generating object using object factory");
            ne.setRootCause(e);
            throw cont.fillInException(ne);
        }
    }

    public Object c_lookupLink(Name name, Continuation cont)
            throws NamingException {
        return c_lookup(name, cont);
    }

    public NamingEnumeration c_list(Name name, Continuation cont)
            throws NamingException {
        cont.setSuccess();
        try {
            DnsName fqdn = fullyQualify(name);
            NameNode nnode = getNameNode(fqdn);
            DnsContext ctx = new DnsContext(this, fqdn);
            return new NameClassPairEnumeration(ctx, nnode.getChildren());

        } catch (NamingException e) {
            cont.setError(this, name);
            throw cont.fillInException(e);
        }
    }

    public NamingEnumeration c_listBindings(Name name, Continuation cont)
            throws NamingException {
        cont.setSuccess();
        try {
            DnsName fqdn = fullyQualify(name);
            NameNode nnode = getNameNode(fqdn);
            DnsContext ctx = new DnsContext(this, fqdn);
            return new BindingEnumeration(ctx, nnode.getChildren());

        } catch (NamingException e) {
            cont.setError(this, name);
            throw cont.fillInException(e);
        }
    }

    public void c_bind(Name name, Object obj, Continuation cont)
            throws NamingException {
        cont.setError(this, name);
        throw cont.fillInException(
                new OperationNotSupportedException());
    }

    public void c_rebind(Name name, Object obj, Continuation cont)
            throws NamingException {
        cont.setError(this, name);
        throw cont.fillInException(
                new OperationNotSupportedException());
    }

    public void c_unbind(Name name, Continuation cont)
            throws NamingException {
        cont.setError(this, name);
        throw cont.fillInException(
                new OperationNotSupportedException());
    }

    public void c_rename(Name oldname, Name newname, Continuation cont)
            throws NamingException {
        cont.setError(this, oldname);
        throw cont.fillInException(
                new OperationNotSupportedException());
    }

    public Context c_createSubcontext(Name name, Continuation cont)
            throws NamingException {
        cont.setError(this, name);
        throw cont.fillInException(
                new OperationNotSupportedException());
    }

    public void c_destroySubcontext(Name name, Continuation cont)
            throws NamingException {
        cont.setError(this, name);
        throw cont.fillInException(
                new OperationNotSupportedException());
    }

    public NameParser c_getNameParser(Name name, Continuation cont)
            throws NamingException {
        cont.setSuccess();
        return nameParser;
    }


    //---------- Directory operations

    public void c_bind(Name name,
                       Object obj,
                       Attributes attrs,
                       Continuation cont)
            throws NamingException {
        cont.setError(this, name);
        throw cont.fillInException(
                new OperationNotSupportedException());
    }

    public void c_rebind(Name name,
                         Object obj,
                         Attributes attrs,
                         Continuation cont)
            throws NamingException {
        cont.setError(this, name);
        throw cont.fillInException(
                new OperationNotSupportedException());
    }

    public DirContext c_createSubcontext(Name name,
                                         Attributes attrs,
                                         Continuation cont)
            throws NamingException {
        cont.setError(this, name);
        throw cont.fillInException(
                new OperationNotSupportedException());
    }

    public Attributes c_getAttributes(Name name,
                                      String[] attrIds,
                                      Continuation cont)
            throws NamingException {

        cont.setSuccess();
        try {
            DnsName fqdn = fullyQualify(name);
            CT[] cts = attrIdsToClassesAndTypes(attrIds);
            CT ct = getClassAndTypeToQuery(cts);
            ResourceRecords rrs =
                getResolver().query(fqdn, ct.rrclass, ct.rrtype,
                                    recursion, authoritative);
            return rrsToAttrs(rrs, cts);

        } catch (NamingException e) {
            cont.setError(this, name);
            throw cont.fillInException(e);
        }
    }

    public void c_modifyAttributes(Name name,
                                   int mod_op,
                                   Attributes attrs,
                                   Continuation cont)
            throws NamingException {
        cont.setError(this, name);
        throw cont.fillInException(
                new OperationNotSupportedException());
    }

    public void c_modifyAttributes(Name name,
                                   ModificationItem[] mods,
                                   Continuation cont)
            throws NamingException {
        cont.setError(this, name);
        throw cont.fillInException(
                new OperationNotSupportedException());
    }

    public NamingEnumeration c_search(Name name,
                                      Attributes matchingAttributes,
                                      String[] attributesToReturn,
                                      Continuation cont)
            throws NamingException {
        throw new OperationNotSupportedException();
    }

    public NamingEnumeration c_search(Name name,
                                      String filter,
                                      SearchControls cons,
                                      Continuation cont)
            throws NamingException {
        throw new OperationNotSupportedException();
    }

    public NamingEnumeration c_search(Name name,
                                      String filterExpr,
                                      Object[] filterArgs,
                                      SearchControls cons,
                                      Continuation cont)
            throws NamingException {
        throw new OperationNotSupportedException();
    }

    public DirContext c_getSchema(Name name, Continuation cont)
            throws NamingException {
        cont.setError(this, name);
        throw cont.fillInException(
                new OperationNotSupportedException());
    }

    public DirContext c_getSchemaClassDefinition(Name name, Continuation cont)
            throws NamingException {
        cont.setError(this, name);
        throw cont.fillInException(
                new OperationNotSupportedException());
    }


    //---------- Name-related operations

    public String getNameInNamespace() {
        return domain.toString();
    }

    public Name composeName(Name name, Name prefix) throws NamingException {
        Name result;

        // Any name that's not a CompositeName is assumed to be a DNS
        // compound name.  Convert each to a DnsName for syntax checking.
        if (!(prefix instanceof DnsName || prefix instanceof CompositeName)) {
            prefix = (new DnsName()).addAll(prefix);
        }
        if (!(name instanceof DnsName || name instanceof CompositeName)) {
            name = (new DnsName()).addAll(name);
        }

        // Each of prefix and name is now either a DnsName or a CompositeName.

        // If we have two DnsNames, simply join them together.
        if ((prefix instanceof DnsName) && (name instanceof DnsName)) {
            result = (DnsName) (prefix.clone());
            result.addAll(name);
            return new CompositeName().add(result.toString());
        }

        // Wrap compound names in composite names.
        Name prefixC = (prefix instanceof CompositeName)
            ? prefix
            : new CompositeName().add(prefix.toString());
        Name nameC = (name instanceof CompositeName)
            ? name
            : new CompositeName().add(name.toString());
        int prefixLast = prefixC.size() - 1;

        // Let toolkit do the work at namespace boundaries.
        if (nameC.isEmpty() || nameC.get(0).equals("") ||
                prefixC.isEmpty() || prefixC.get(prefixLast).equals("")) {
            return super.composeName(nameC, prefixC);
        }

        result = (prefix == prefixC)
            ? (CompositeName) prefixC.clone()
            : prefixC;                  // prefixC is already a clone
        result.addAll(nameC);

        if (parentIsDns) {
            DnsName dnsComp = (prefix instanceof DnsName)
                           ? (DnsName) prefix.clone()
                           : new DnsName(prefixC.get(prefixLast));
            dnsComp.addAll((name instanceof DnsName)
                           ? name
                           : new DnsName(nameC.get(0)));
            result.remove(prefixLast + 1);
            result.remove(prefixLast);
            result.add(prefixLast, dnsComp.toString());
        }
        return result;
    }


    //---------- Helper methods

    /*
     * Resolver is not created until needed, to allow time for updates
     * to the environment.
     */
    private synchronized Resolver getResolver() throws NamingException {
        if (resolver == null) {
            resolver = new Resolver(servers, timeout, retries);
        }
        return resolver;
    }

    /*
     * Returns the fully-qualified domain name of a name given
     * relative to this context.  Result includes a root label (an
     * empty component at position 0).
     */
    DnsName fullyQualify(Name name) throws NamingException {
        if (name.isEmpty()) {
            return domain;
        }
        DnsName dnsName = (name instanceof CompositeName)
            ? new DnsName(name.get(0))                  // parse name
            : (DnsName) (new DnsName()).addAll(name);   // clone & check syntax

        if (dnsName.hasRootLabel()) {
            // Be overly generous and allow root label if we're in root domain.
            if (domain.size() == 1) {
                return dnsName;
            } else {
                throw new InvalidNameException(
                       "DNS name " + dnsName + " not relative to " + domain);
            }
        }
        return (DnsName) dnsName.addAll(0, domain);
    }

    /*
     * Converts resource records to an attribute set.  Only resource
     * records in the answer section are used, and only those that
     * match the classes and types in cts (see classAndTypeMatch()
     * for matching rules).
     */
    private static Attributes rrsToAttrs(ResourceRecords rrs, CT[] cts) {

        BasicAttributes attrs = new BasicAttributes(true);

        for (int i = 0; i < rrs.answer.size(); i++) {
            ResourceRecord rr = (ResourceRecord) rrs.answer.elementAt(i);
            int rrtype  = rr.getType();
            int rrclass = rr.getRrclass();

            if (!classAndTypeMatch(rrclass, rrtype, cts)) {
                continue;
            }

            String attrId = toAttrId(rrclass, rrtype);
            Attribute attr = attrs.get(attrId);
            if (attr == null) {
                attr = new BasicAttribute(attrId);
                attrs.put(attr);
            }
            attr.add(rr.getRdata());
        }
        return attrs;
    }

    /*
     * Returns true if rrclass and rrtype match some element of cts.
     * A match occurs if corresponding classes and types are equal,
     * or if the array value is ANY.  If cts is null, then any class
     * and type match.
     */
    private static boolean classAndTypeMatch(int rrclass, int rrtype,
                                             CT[] cts) {
        if (cts == null) {
            return true;
        }
        for (int i = 0; i < cts.length; i++) {
            CT ct = cts[i];
            boolean classMatch = (ct.rrclass == ANY) ||
                                 (ct.rrclass == rrclass);
            boolean typeMatch  = (ct.rrtype == ANY) ||
                                 (ct.rrtype == rrtype);
            if (classMatch && typeMatch) {
                return true;
            }
        }
        return false;
    }

    /*
     * Returns the attribute ID for a resource record given its class
     * and type.  If the record is in the internet class, the
     * corresponding attribute ID is the record's type name (or the
     * integer type value if the name is not known).  If the record is
     * not in the internet class, the class name (or integer class
     * value) is prepended to the attribute ID, separated by a space.
     *
     * A class or type value of ANY represents an indeterminate class
     * or type, and is represented within the attribute ID by "*".
     * For example, the attribute ID "IN *" represents
     * any type in the internet class, and "* NS" represents an NS
     * record of any class.
     */
    private static String toAttrId(int rrclass, int rrtype) {
        String attrId = ResourceRecord.getTypeName(rrtype);
        if (rrclass != ResourceRecord.CLASS_INTERNET) {
            attrId = ResourceRecord.getRrclassName(rrclass) + " " + attrId;
        }
        return attrId;
    }

    /*
     * Returns the class and type values corresponding to an attribute
     * ID.  An indeterminate class or type is represented by ANY.  See
     * toAttrId() for the format of attribute IDs.
     *
     * @throws InvalidAttributeIdentifierException
     *          if class or type is unknown
     */
    private static CT fromAttrId(String attrId)
            throws InvalidAttributeIdentifierException {

        if (attrId.equals("")) {
            throw new InvalidAttributeIdentifierException(
                    "Attribute ID cannot be empty");
        }
        int rrclass;
        int rrtype;
        int space = attrId.indexOf(' ');

        // class
        if (space < 0) {
            rrclass = ResourceRecord.CLASS_INTERNET;
        } else {
            String className = attrId.substring(0, space);
            rrclass = ResourceRecord.getRrclass(className);
            if (rrclass < 0) {
                throw new InvalidAttributeIdentifierException(
                        "Unknown resource record class '" + className + '\'');
            }
        }

        // type
        String typeName = attrId.substring(space + 1);
        rrtype = ResourceRecord.getType(typeName);
        if (rrtype < 0) {
            throw new InvalidAttributeIdentifierException(
                    "Unknown resource record type '" + typeName + '\'');
        }

        return new CT(rrclass, rrtype);
    }

    /*
     * Returns an array of the classes and types corresponding to a
     * set of attribute IDs.  See toAttrId() for the format of
     * attribute IDs, and classAndTypeMatch() for the format of the
     * array returned.
     */
    private static CT[] attrIdsToClassesAndTypes(String[] attrIds)
            throws InvalidAttributeIdentifierException {
        if (attrIds == null) {
            return null;
        }
        CT[] cts = new CT[attrIds.length];

        for (int i = 0; i < attrIds.length; i++) {
            cts[i] = fromAttrId(attrIds[i]);
        }
        return cts;
    }

    /*
     * Returns the most restrictive resource record class and type
     * that may be used to query for records matching cts.
     * See classAndTypeMatch() for matching rules.
     */
    private static CT getClassAndTypeToQuery(CT[] cts) {
        int rrclass;
        int rrtype;

        if (cts == null) {
            // Query all records.
            rrclass = ANY;
            rrtype  = ANY;
        } else if (cts.length == 0) {
            // No records are requested, but we need to ask for something.
            rrclass = ResourceRecord.CLASS_INTERNET;
            rrtype  = ANY;
        } else {
            rrclass = cts[0].rrclass;
            rrtype  = cts[0].rrtype;
            for (int i = 1; i < cts.length; i++) {
                if (rrclass != cts[i].rrclass) {
                    rrclass = ANY;
                }
                if (rrtype != cts[i].rrtype) {
                    rrtype = ANY;
                }
            }
        }
        return new CT(rrclass, rrtype);
    }


    //---------- Support for list operations

    /*
     * Synchronization notes:
     *
     * Any access to zoneTree that walks the tree, whether it modifies
     * the tree or not, is synchronized on zoneTree.
     * [%%% Note:  a read/write lock would allow increased concurrency.]
     * The depth of a ZoneNode can thereafter be accessed without
     * further synchronization.  Access to other fields and methods
     * should be synchronized on the node itself.
     *
     * A zone's contents is a NameNode tree that, once created, is never
     * modified.  The only synchronization needed is to ensure that it
     * gets flushed into shared memory after being created, which is
     * accomplished by ZoneNode.populate().  The contents are accessed
     * via a soft reference, so a ZoneNode may be seen to be populated
     * one moment and unpopulated the next.
     */

    /*
     * Returns the node in the zone tree corresponding to a
     * fully-qualified domain name.  If the desired portion of the
     * tree has not yet been populated or has been outdated, a zone
     * transfer is done to populate the tree.
     */
    private NameNode getNameNode(DnsName fqdn) throws NamingException {
        dprint("getNameNode(" + fqdn + ")");

        // Find deepest related zone in zone tree.
        ZoneNode znode;
        DnsName zone;
        synchronized (zoneTree) {
            znode = zoneTree.getDeepestPopulated(fqdn);
        }
        dprint("Deepest related zone in zone tree: " +
               ((znode != null) ? znode.getLabel() : "[none]"));

        NameNode topOfZone;
        NameNode nnode;

        if (znode != null) {
            synchronized (znode) {
                topOfZone = znode.getContents();
            }
            // If fqdn is in znode's zone, is not at a zone cut, and
            // is current, we're done.
            if (topOfZone != null) {
                nnode = topOfZone.get(fqdn, znode.depth() + 1); // +1 for root

                if ((nnode != null) && !nnode.isZoneCut()) {
                    dprint("Found node " + fqdn + " in zone tree");
                    zone = (DnsName)
                        fqdn.getPrefix(znode.depth() + 1);      // +1 for root
                    boolean current = isZoneCurrent(znode, zone);
                    boolean restart = false;

                    synchronized (znode) {
                        if (topOfZone != znode.getContents()) {
                            // Zone was modified while we were examining it.
                            // All bets are off.
                            restart = true;
                        } else if (!current) {
                            znode.depopulate();
                        } else {
                            return nnode;                       // cache hit!
                        }
                    }
                    dprint("Zone not current; discarding node");
                    if (restart) {
                        return getNameNode(fqdn);
                    }
                }
            }
        }

        // Cache miss...  do it the expensive way.
        dprint("Adding node " + fqdn + " to zone tree");

        // Find fqdn's zone and add it to the tree.
        zone = getResolver().findZoneName(fqdn, ResourceRecord.CLASS_INTERNET,
                                          recursion);
        dprint("Node's zone is " + zone);
        synchronized (zoneTree) {
            znode = (ZoneNode) zoneTree.add(zone, 1);   // "1" to skip root
        }

        // If znode is now populated we know -- because the first half of
        // getNodeName() didn't find it -- that it was populated by another
        // thread during this method call.  Assume then that it's current.

        synchronized (znode) {
            topOfZone = znode.isPopulated()
                ? znode.getContents()
                : populateZone(znode, zone);
        }
        // Desired node should now be in znode's populated zone.  Find it.
        nnode = topOfZone.get(fqdn, zone.size());
        if (nnode == null) {
            throw new ConfigurationException(
                    "DNS error: node not found in its own zone");
        }
        dprint("Found node in newly-populated zone");
        return nnode;
    }

    /*
     * Does a zone transfer to [re]populate a zone in the zone tree.
     * Returns the zone's new contents.
     */
    private NameNode populateZone(ZoneNode znode, DnsName zone)
            throws NamingException {
        dprint("Populating zone " + zone);
        // assert Thread.holdsLock(znode);
        ResourceRecords rrs =
            getResolver().queryZone(zone,
                                    ResourceRecord.CLASS_INTERNET, recursion);
        dprint("zone xfer complete: " + rrs.answer.size() + " records");
        return znode.populate(zone, rrs);
    }

    /*
     * Determine if a ZoneNode's data is current.
     * We base this on a comparison between the cached serial
     * number and the latest SOA record.
     *
     * If there is no SOA record, znode is not (or is no longer) a zone:
     * depopulate znode and return false.
     *
     * Since this method may perform a network operation, it is best
     * to call it with znode unlocked.  Caller must then note that the
     * result may be outdated by the time this method returns.
     */
    private boolean isZoneCurrent(ZoneNode znode, DnsName zone)
            throws NamingException {
        // former version:  return !znode.isExpired();

        if (!znode.isPopulated()) {
            return false;
        }
        ResourceRecord soa =
            getResolver().findSoa(zone, ResourceRecord.CLASS_INTERNET,
                                  recursion);
        synchronized (znode) {
            if (soa == null) {
                znode.depopulate();
            }
            return (znode.isPopulated() &&
                    znode.compareSerialNumberTo(soa) >= 0);
        }
    }


    //---------- Debugging

925
    private static final boolean debug = false;
D
duke 已提交
926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974

    private static final void dprint(String msg) {
        if (debug) {
            System.err.println("** " + msg);
        }
    }
}


//----------

/*
 * A pairing of a resource record class and a resource record type.
 * A value of ANY in either field represents an indeterminate value.
 */
class CT {
    int rrclass;
    int rrtype;

    CT(int rrclass, int rrtype) {
        this.rrclass = rrclass;
        this.rrtype = rrtype;
    }
}


//----------

/*
 * An enumeration of name/classname pairs.
 *
 * Nodes that have children or that are zone cuts are returned with
 * classname DirContext.  Other nodes are returned with classname
 * Object even though they are DirContexts as well, since this might
 * make the namespace easier to browse.
 */
class NameClassPairEnumeration implements NamingEnumeration {

    protected Enumeration nodes;    // nodes to be enumerated, or null if none
    protected DnsContext ctx;       // context being enumerated

    NameClassPairEnumeration(DnsContext ctx, Hashtable nodes) {
        this.ctx = ctx;
        this.nodes = (nodes != null)
            ? nodes.elements()
            : null;
    }

    /*
975
     * ctx will be set to null when no longer needed by the enumeration.
D
duke 已提交
976
     */
977
    public void close() {
D
duke 已提交
978
        nodes = null;
979
        ctx = null;
D
duke 已提交
980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068
    }

    public boolean hasMore() {
        boolean more = ((nodes != null) && nodes.hasMoreElements());
        if (!more) {
            close();
        }
        return more;
    }

    public Object next() throws NamingException {
        if (!hasMore()) {
            throw new java.util.NoSuchElementException();
        }
        NameNode nnode = (NameNode) nodes.nextElement();
        String className = (nnode.isZoneCut() ||
                            (nnode.getChildren() != null))
            ? "javax.naming.directory.DirContext"
            : "java.lang.Object";

        String label = nnode.getLabel();
        Name compName = (new DnsName()).add(label);
        Name cname = (new CompositeName()).add(compName.toString());

        NameClassPair ncp = new NameClassPair(cname.toString(), className);
        ncp.setNameInNamespace(ctx.fullyQualify(cname).toString());
        return ncp;
    }

    public boolean hasMoreElements() {
        return hasMore();
    }

    public Object nextElement() {
        try {
            return next();
        } catch (NamingException e) {
            throw (new java.util.NoSuchElementException(
                    "javax.naming.NamingException was thrown: " +
                    e.getMessage()));
        }
    }
}

/*
 * An enumeration of Bindings.
 */
class BindingEnumeration extends NameClassPairEnumeration {

    BindingEnumeration(DnsContext ctx, Hashtable nodes) {
        super(ctx, nodes);
    }

    // Finalizer not needed since it's safe to leave ctx unclosed.
//  protected void finalize() {
//      close();
//  }

    public Object next() throws NamingException {
        if (!hasMore()) {
            throw (new java.util.NoSuchElementException());
        }
        NameNode nnode = (NameNode) nodes.nextElement();

        String label = nnode.getLabel();
        Name compName = (new DnsName()).add(label);
        String compNameStr = compName.toString();
        Name cname = (new CompositeName()).add(compNameStr);
        String cnameStr = cname.toString();

        DnsName fqdn = ctx.fullyQualify(compName);

        // Clone ctx to create the child context.
        DnsContext child = new DnsContext(ctx, fqdn);

        try {
            Object obj = DirectoryManager.getObjectInstance(
                    child, cname, ctx, child.environment, null);
            Binding binding = new Binding(cnameStr, obj);
            binding.setNameInNamespace(ctx.fullyQualify(cname).toString());
            return binding;
        } catch (Exception e) {
            NamingException ne = new NamingException(
                    "Problem generating object using object factory");
            ne.setRootCause(e);
            throw ne;
        }
    }
}