001/*
002 * Copyright (c) 1997, 2010, Oracle and/or its affiliates. All rights reserved.
003 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
004 *
005 * This code is free software; you can redistribute it and/or modify it
006 * under the terms of the GNU General Public License version 2 only, as
007 * published by the Free Software Foundation.  Oracle designates this
008 * particular file as subject to the "Classpath" exception as provided
009 * by Oracle in the LICENSE file that accompanied this code.
010 *
011 * This code is distributed in the hope that it will be useful, but WITHOUT
012 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
013 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
014 * version 2 for more details (a copy is included in the LICENSE file that
015 * accompanied this code).
016 *
017 * You should have received a copy of the GNU General Public License version
018 * 2 along with this work; if not, write to the Free Software Foundation,
019 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
020 *
021 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
022 * or visit www.oracle.com if you need additional information or have any
023 * questions.
024 */
025package org.openstreetmap.josm.io.remotecontrol;
026
027import java.io.IOException;
028import java.util.Locale;
029
030import sun.security.util.DerOutputStream;
031import sun.security.x509.GeneralNameInterface;
032
033/**
034 * This class implements the DNSName as required by the GeneralNames
035 * ASN.1 object.
036 * <p>
037 * [RFC2459] When the subjectAltName extension contains a domain name service
038 * label, the domain name MUST be stored in the dNSName (an IA5String).
039 * The name MUST be in the "preferred name syntax," as specified by RFC
040 * 1034 [RFC 1034]. Note that while upper and lower case letters are
041 * allowed in domain names, no signifigance is attached to the case.  In
042 * addition, while the string " " is a legal domain name, subjectAltName
043 * extensions with a dNSName " " are not permitted.  Finally, the use of
044 * the DNS representation for Internet mail addresses (wpolk.nist.gov
045 * instead of wpolk@nist.gov) is not permitted; such identities are to
046 * be encoded as rfc822Name.
047 *
048 * This class has been copied from OpenJDK7u repository and modified
049 * in order to fix Java bug 8016345:
050 * https://bugs.openjdk.java.net/browse/JDK-8016345
051 *
052 * It can be deleted after a migration to a Java release fixing this bug.
053 * <p>
054 * @author Amit Kapoor
055 * @author Hemma Prafullchandra
056 * @author JOSM developers
057 * @since 7347
058 */
059public class DNSName implements GeneralNameInterface {
060    private final String name;
061
062    private static final String alpha = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
063    private static final String digitsAndHyphen = "0123456789-";
064    private static final String alphaDigitsAndHyphen = alpha + digitsAndHyphen;
065
066    /**
067     * Create the DNSName object with the specified name.
068     *
069     * @param name the DNSName.
070     * @throws IOException if the name is not a valid DNSName subjectAltName
071     */
072    public DNSName(String name) throws IOException {
073        if (name == null || name.length() == 0)
074            throw new IOException("DNS name must not be null");
075        if (name.indexOf(' ') != -1)
076            throw new IOException("DNS names or NameConstraints with blank components are not permitted");
077        if (name.charAt(0) == '.' || name.charAt(name.length() -1) == '.')
078            throw new IOException("DNS names or NameConstraints may not begin or end with a .");
079        //Name will consist of label components separated by "."
080        //startIndex is the index of the first character of a component
081        //endIndex is the index of the last character of a component plus 1
082        for (int endIndex,startIndex=0; startIndex < name.length(); startIndex = endIndex+1) {
083            endIndex = name.indexOf('.', startIndex);
084            if (endIndex < 0) {
085                endIndex = name.length();
086            }
087            if ((endIndex-startIndex) < 1)
088                throw new IOException("DNSName SubjectAltNames with empty components are not permitted");
089
090            //nonStartIndex: index for characters in the component beyond the first one
091            for (int nonStartIndex=startIndex+1; nonStartIndex < endIndex; nonStartIndex++) {
092                char x = name.charAt(nonStartIndex);
093                if ((alphaDigitsAndHyphen).indexOf(x) < 0)
094                    throw new IOException("DNSName components must consist of letters, digits, and hyphens");
095            }
096        }
097        this.name = name;
098    }
099
100    /**
101     * Return the type of the GeneralName.
102     */
103    public int getType() {
104        return GeneralNameInterface.NAME_DNS;
105    }
106
107    /**
108     * Return the actual name value of the GeneralName.
109     * @return the actual name value of the GeneralName
110     */
111    public String getName() {
112        return name;
113    }
114
115    /**
116     * Encode the DNS name into the DerOutputStream.
117     *
118     * @param out the DER stream to encode the DNSName to.
119     * @exception IOException on encoding errors.
120     */
121    public void encode(DerOutputStream out) throws IOException {
122        out.putIA5String(name);
123    }
124
125    /**
126     * Convert the name into user readable string.
127     */
128    @Override
129    public String toString() {
130        return "DNSName: " + name;
131    }
132
133    /**
134     * Compares this name with another, for equality.
135     *
136     * @return true iff the names are equivalent
137     * according to RFC2459.
138     */
139    @Override
140    public boolean equals(Object obj) {
141        if (this == obj)
142            return true;
143
144        if (!(obj instanceof DNSName))
145            return false;
146
147        DNSName other = (DNSName)obj;
148
149        // RFC2459 mandates that these names are
150        // not case-sensitive
151        return name.equalsIgnoreCase(other.name);
152    }
153
154    /**
155     * Returns the hash code value for this object.
156     *
157     * @return a hash code value for this object.
158     */
159    @Override
160    public int hashCode() {
161        return name.toUpperCase().hashCode();
162    }
163
164    /**
165     * Return type of constraint inputName places on this name:<ul>
166     *   <li>NAME_DIFF_TYPE = -1: input name is different type from name (i.e. does not constrain).
167     *   <li>NAME_MATCH = 0: input name matches name.
168     *   <li>NAME_NARROWS = 1: input name narrows name (is lower in the naming subtree)
169     *   <li>NAME_WIDENS = 2: input name widens name (is higher in the naming subtree)
170     *   <li>NAME_SAME_TYPE = 3: input name does not match or narrow name, but is same type.
171     * </ul>.  These results are used in checking NameConstraints during
172     * certification path verification.
173     * <p>
174     * RFC2459: DNS name restrictions are expressed as foo.bar.com. Any subdomain
175     * satisfies the name constraint. For example, www.foo.bar.com would
176     * satisfy the constraint but bigfoo.bar.com would not.
177     * <p>
178     * draft-ietf-pkix-new-part1-00.txt:  DNS name restrictions are expressed as foo.bar.com.
179     * Any DNS name that
180     * can be constructed by simply adding to the left hand side of the name
181     * satisfies the name constraint. For example, www.foo.bar.com would
182     * satisfy the constraint but foo1.bar.com would not.
183     * <p>
184     * RFC1034: By convention, domain names can be stored with arbitrary case, but
185     * domain name comparisons for all present domain functions are done in a
186     * case-insensitive manner, assuming an ASCII character set, and a high
187     * order zero bit.
188     * <p>
189     * @param inputName to be checked for being constrained
190     * @return constraint type above
191     * @throws UnsupportedOperationException if name is not exact match, but narrowing and widening are
192     *          not supported for this name type.
193     */
194    @Override
195    public int constrains(GeneralNameInterface inputName) {
196        int constraintType;
197        if (inputName == null)
198            constraintType = NAME_DIFF_TYPE;
199        else if (inputName.getType() != NAME_DNS)
200            constraintType = NAME_DIFF_TYPE;
201        else {
202            String inName =
203                (((DNSName)inputName).getName()).toLowerCase(Locale.ENGLISH);
204            String thisName = name.toLowerCase(Locale.ENGLISH);
205            if (inName.equals(thisName))
206                constraintType = NAME_MATCH;
207            else if (thisName.endsWith(inName)) {
208                int inNdx = thisName.lastIndexOf(inName);
209                if (thisName.charAt(inNdx-1) == '.' )
210                    constraintType = NAME_WIDENS;
211                else
212                    constraintType = NAME_SAME_TYPE;
213            } else if (inName.endsWith(thisName)) {
214                int ndx = inName.lastIndexOf(thisName);
215                if (inName.charAt(ndx-1) == '.' )
216                    constraintType = NAME_NARROWS;
217                else
218                    constraintType = NAME_SAME_TYPE;
219            } else {
220                constraintType = NAME_SAME_TYPE;
221            }
222        }
223        return constraintType;
224    }
225
226    /**
227     * Return subtree depth of this name for purposes of determining
228     * NameConstraints minimum and maximum bounds and for calculating
229     * path lengths in name subtrees.
230     *
231     * @return distance of name from root
232     * @throws UnsupportedOperationException if not supported for this name type
233     */
234    @Override
235    public int subtreeDepth() {
236        String subtree=name;
237        int i=1;
238
239        /* count dots */
240        for (; subtree.lastIndexOf('.') >= 0; i++) {
241            subtree=subtree.substring(0,subtree.lastIndexOf('.'));
242        }
243
244        return i;
245    }
246}