Config.java 49.6 KB
Newer Older
D
duke 已提交
1
/*
2
 * Copyright (c) 2000, 2019, Oracle and/or its affiliates. All rights reserved.
D
duke 已提交
3 4 5 6
 * 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
7
 * published by the Free Software Foundation.  Oracle designates this
D
duke 已提交
8
 * particular file as subject to the "Classpath" exception as provided
9
 * by Oracle in the LICENSE file that accompanied this code.
D
duke 已提交
10 11 12 13 14 15 16 17 18 19 20
 *
 * 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.
 *
21 22 23
 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
 * or visit www.oracle.com if you need additional information or have any
 * questions.
D
duke 已提交
24 25 26 27 28 29 30 31 32
 */

/*
 *
 *  (C) Copyright IBM Corp. 1999 All Rights Reserved.
 *  Copyright 1997 The Open Group Research Institute.  All rights reserved.
 */
package sun.security.krb5;

33
import java.io.*;
D
duke 已提交
34 35
import java.net.InetAddress;
import java.net.UnknownHostException;
W
weijun 已提交
36 37
import java.security.AccessController;
import java.security.PrivilegedExceptionAction;
38
import java.util.ArrayList;
W
weijun 已提交
39
import java.util.Arrays;
40
import java.util.Hashtable;
41
import java.util.List;
W
weijun 已提交
42
import java.util.Locale;
43 44 45 46
import java.util.StringTokenizer;
import java.util.Vector;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
47
import sun.net.dns.ResolverConfiguration;
D
duke 已提交
48 49
import sun.security.krb5.internal.crypto.EType;
import sun.security.krb5.internal.Krb5;
50
import sun.security.util.SecurityProperties;
D
duke 已提交
51 52 53 54 55 56 57 58

/**
 * This class maintains key-value pairs of Kerberos configurable constants
 * from configuration file or from user specified system properties.
 */

public class Config {

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
    /**
     * {@systemProperty sun.security.krb5.disableReferrals} property
     * indicating whether or not cross-realm referrals (RFC 6806) are
     * enabled.
     */
    public static final boolean DISABLE_REFERRALS;

    /**
     * {@systemProperty sun.security.krb5.maxReferrals} property
     * indicating the maximum number of cross-realm referral
     * hops allowed.
     */
    public static final int MAX_REFERRALS;

    static {
        String disableReferralsProp =
                SecurityProperties.privilegedGetOverridable(
                        "sun.security.krb5.disableReferrals");
        if (disableReferralsProp != null) {
            DISABLE_REFERRALS = "true".equalsIgnoreCase(disableReferralsProp);
        } else {
            DISABLE_REFERRALS = false;
        }

        int maxReferralsValue = 5;
        String maxReferralsProp =
                SecurityProperties.privilegedGetOverridable(
                        "sun.security.krb5.maxReferrals");
        try {
            maxReferralsValue = Integer.parseInt(maxReferralsProp);
        } catch (NumberFormatException e) {
        }
        MAX_REFERRALS = maxReferralsValue;
    }

D
duke 已提交
94 95 96 97 98 99
    /*
     * Only allow a single instance of Config.
     */
    private static Config singleton = null;

    /*
100
     * Hashtable used to store configuration information.
D
duke 已提交
101
     */
W
weijun 已提交
102
    private Hashtable<String,Object> stanzaTable = new Hashtable<>();
D
duke 已提交
103 104 105 106 107 108 109 110

    private static boolean DEBUG = sun.security.krb5.internal.Krb5.DEBUG;

    // these are used for hexdecimal calculation.
    private static final int BASE16_0 = 1;
    private static final int BASE16_1 = 16;
    private static final int BASE16_2 = 16 * 16;
    private static final int BASE16_3 = 16 * 16 * 16;
111 112 113 114 115 116

    /**
     * Specified by system properties. Must be both null or non-null.
     */
    private final String defaultRealm;
    private final String defaultKDC;
D
duke 已提交
117 118

    // used for native interface
119
    private static native String getWindowsDirectory(boolean isSystem);
D
duke 已提交
120 121 122 123 124 125 126


    /**
     * Gets an instance of Config class. One and only one instance (the
     * singleton) is returned.
     *
     * @exception KrbException if error occurs when constructing a Config
127 128
     * instance. Possible causes would be either of java.security.krb5.realm or
     * java.security.krb5.kdc not specified, error reading configuration file.
D
duke 已提交
129 130 131 132 133 134 135 136 137 138 139
     */
    public static synchronized Config getInstance() throws KrbException {
        if (singleton == null) {
            singleton = new Config();
        }
        return singleton;
    }

    /**
     * Refresh and reload the Configuration. This could involve,
     * for example reading the Configuration file again or getting
W
weijun 已提交
140 141 142
     * the java.security.krb5.* system properties again. This method
     * also tries its best to update static fields in other classes
     * that depend on the configuration.
D
duke 已提交
143 144
     *
     * @exception KrbException if error occurs when constructing a Config
145 146
     * instance. Possible causes would be either of java.security.krb5.realm or
     * java.security.krb5.kdc not specified, error reading configuration file.
D
duke 已提交
147 148 149 150
     */

    public static synchronized void refresh() throws KrbException {
        singleton = new Config();
151
        KdcComm.initStatic();
W
weijun 已提交
152 153
        EType.initStatic();
        Checksum.initStatic();
D
duke 已提交
154 155 156
    }


157 158
    private static boolean isMacosLionOrBetter() {
        // split the "10.x.y" version number
159 160 161 162 163 164
        String osname = getProperty("os.name");
        if (!osname.contains("OS X")) {
            return false;
        }

        String osVersion = getProperty("os.version");
165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181
        String[] fragments = osVersion.split("\\.");

        // sanity check the "10." part of the version
        if (!fragments[0].equals("10")) return false;
        if (fragments.length < 2) return false;

        // check if Mac OS X 10.7(.y)
        try {
            int minorVers = Integer.parseInt(fragments[1]);
            if (minorVers >= 7) return true;
        } catch (NumberFormatException e) {
            // was not an integer
        }

        return false;
    }

D
duke 已提交
182 183 184 185 186
    /**
     * Private constructor - can not be instantiated externally.
     */
    private Config() throws KrbException {
        /*
187
         * If either one system property is specified, we throw exception.
D
duke 已提交
188
         */
189
        String tmp = getProperty("java.security.krb5.kdc");
190 191 192 193 194 195
        if (tmp != null) {
            // The user can specify a list of kdc hosts separated by ":"
            defaultKDC = tmp.replace(':', ' ');
        } else {
            defaultKDC = null;
        }
196
        defaultRealm = getProperty("java.security.krb5.realm");
197 198
        if ((defaultKDC == null && defaultRealm != null) ||
            (defaultRealm == null && defaultKDC != null)) {
D
duke 已提交
199 200 201 202 203
            throw new KrbException
                ("System property java.security.krb5.kdc and " +
                 "java.security.krb5.realm both must be set or " +
                 "neither must be set.");
        }
204

205
        // Always read the Kerberos configuration file
206
        try {
W
weijun 已提交
207
            List<String> configFile;
208 209 210
            String fileName = getJavaFileName();
            if (fileName != null) {
                configFile = loadConfigFile(fileName);
211
                stanzaTable = parseStanzaTable(configFile);
212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235
                if (DEBUG) {
                    System.out.println("Loaded from Java config");
                }
            } else {
                boolean found = false;
                if (isMacosLionOrBetter()) {
                    try {
                        stanzaTable = SCDynamicStoreConfig.getConfig();
                        if (DEBUG) {
                            System.out.println("Loaded from SCDynamicStoreConfig");
                        }
                        found = true;
                    } catch (IOException ioe) {
                        // OK. Will go on with file
                    }
                }
                if (!found) {
                    fileName = getNativeFileName();
                    configFile = loadConfigFile(fileName);
                    stanzaTable = parseStanzaTable(configFile);
                    if (DEBUG) {
                        System.out.println("Loaded from native config");
                    }
                }
236
            }
237
        } catch (IOException ioe) {
W
weijun 已提交
238 239
            // I/O error, mostly like krb5.conf missing.
            // No problem. We'll use DNS or system property etc.
D
duke 已提交
240 241 242 243
        }
    }

    /**
W
weijun 已提交
244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260
     * Gets the last-defined string value for the specified keys.
     * @param keys the keys, as an array from section name, sub-section names
     * (if any), to value name.
     * @return the value. When there are multiple values for the same key,
     * returns the last one. {@code null} is returned if not all the keys are
     * defined. For example, {@code get("libdefaults", "forwardable")} will
     * return null if "forwardable" is not defined in [libdefaults], and
     * {@code get("realms", "R", "kdc")} will return null if "R" is not
     * defined in [realms] or "kdc" is not defined for "R".
     * @throws IllegalArgumentException if any of the keys is illegal, either
     * because a key not the last one is not a (sub)section name or the last
     * key is still a section name. For example, {@code get("libdefaults")}
     * throws this exception because [libdefaults] is a section name instead of
     * a value name, and {@code get("libdefaults", "forwardable", "tail")}
     * also throws this exception because "forwardable" is already a value name
     * and has no sub-key at all (given "forwardable" is defined, otherwise,
     * this method has no knowledge if it's a value name or a section name),
D
duke 已提交
261
     */
W
weijun 已提交
262
    public String get(String... keys) {
263
        Vector<String> v = getString0(keys);
W
weijun 已提交
264 265 266 267
        if (v == null) return null;
        return v.lastElement();
    }

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
    /**
     * Gets the boolean value for the specified keys. Returns TRUE if the
     * string value is "yes", or "true", FALSE if "no", or "false", or null
     * if otherwise or not defined. The comparision is case-insensitive.
     *
     * @param keys the keys, see {@link #get(String...)}
     * @return the boolean value, or null if there is no value defined or the
     * value does not look like a boolean value.
     * @throws IllegalArgumentException see {@link #get(String...)}
     */
    private Boolean getBooleanObject(String... keys) {
        String s = get(keys);
        if (s == null) {
            return null;
        }
        switch (s.toLowerCase(Locale.US)) {
            case "yes": case "true":
                return Boolean.TRUE;
            case "no": case "false":
                return Boolean.FALSE;
            default:
                return null;
        }
    }

W
weijun 已提交
293
    /**
A
andrew 已提交
294 295 296 297 298
     * Gets all values (at least one) for the specified keys separated by
     * a whitespace, or null if there is no such keys.
     * The values can either be provided on a single line, or on multiple lines
     * using the same key. When provided on a single line, the value can be
     * comma or space separated.
299 300
     * @throws IllegalArgumentException if any of the keys is illegal
     *         (See {@link #get})
W
weijun 已提交
301 302
     */
    public String getAll(String... keys) {
303
        Vector<String> v = getString0(keys);
W
weijun 已提交
304 305 306 307
        if (v == null) return null;
        StringBuilder sb = new StringBuilder();
        boolean first = true;
        for (String s: v) {
A
andrew 已提交
308
            s = s.replaceAll("[\\s,]+", " ");
W
weijun 已提交
309 310 311 312 313
            if (first) {
                sb.append(s);
                first = false;
            } else {
                sb.append(' ').append(s);
D
duke 已提交
314 315
            }
        }
W
weijun 已提交
316 317 318
        return sb.toString();
    }

319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339
    /**
     * Returns true if keys exists, can be either final string(s) or sub-stanza
     * @throws IllegalArgumentException if any of the keys is illegal
     *         (See {@link #get})
     */
    public boolean exists(String... keys) {
        return get0(keys) != null;
    }

    // Returns final string value(s) for given keys.
    @SuppressWarnings("unchecked")
    private Vector<String> getString0(String... keys) {
        try {
            return (Vector<String>)get0(keys);
        } catch (ClassCastException cce) {
            throw new IllegalArgumentException(cce);
        }
    }

    // Internal method. Returns the value for keys, which can be a sub-stanza
    // or final string value(s).
W
weijun 已提交
340 341
    // The only method (except for toString) that reads stanzaTable directly.
    @SuppressWarnings("unchecked")
342
    private Object get0(String... keys) {
W
weijun 已提交
343 344 345 346 347 348
        Object current = stanzaTable;
        try {
            for (String key: keys) {
                current = ((Hashtable<String,Object>)current).get(key);
                if (current == null) return null;
            }
349
            return current;
W
weijun 已提交
350 351 352
        } catch (ClassCastException cce) {
            throw new IllegalArgumentException(cce);
        }
D
duke 已提交
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
    /**
     * Translates a duration value into seconds.
     *
     * The format can be one of "h:m[:s]", "NdNhNmNs", and "N". See
     * http://web.mit.edu/kerberos/krb5-devel/doc/basic/date_format.html#duration
     * for definitions.
     *
     * @param s the string duration
     * @return time in seconds
     * @throw KrbException if format is illegal
     */
    public static int duration(String s) throws KrbException {

        if (s.isEmpty()) {
            throw new KrbException("Duration cannot be empty");
        }

        // N
        if (s.matches("\\d+")) {
            return Integer.parseInt(s);
        }

        // h:m[:s]
        Matcher m = Pattern.compile("(\\d+):(\\d+)(:(\\d+))?").matcher(s);
        if (m.matches()) {
            int hr = Integer.parseInt(m.group(1));
            int min = Integer.parseInt(m.group(2));
            if (min >= 60) {
                throw new KrbException("Illegal duration format " + s);
            }
            int result = hr * 3600 + min * 60;
            if (m.group(4) != null) {
                int sec = Integer.parseInt(m.group(4));
                if (sec >= 60) {
                    throw new KrbException("Illegal duration format " + s);
                }
                result += sec;
            }
            return result;
        }

        // NdNhNmNs
        // 120m allowed. Maybe 1h120m is not good, but still allowed
        m = Pattern.compile(
                    "((\\d+)d)?\\s*((\\d+)h)?\\s*((\\d+)m)?\\s*((\\d+)s)?",
                Pattern.CASE_INSENSITIVE).matcher(s);
        if (m.matches()) {
            int result = 0;
            if (m.group(2) != null) {
                result += 86400 * Integer.parseInt(m.group(2));
            }
            if (m.group(4) != null) {
                result += 3600 * Integer.parseInt(m.group(4));
            }
            if (m.group(6) != null) {
                result += 60 * Integer.parseInt(m.group(6));
            }
            if (m.group(8) != null) {
                result += Integer.parseInt(m.group(8));
            }
            return result;
        }

        throw new KrbException("Illegal duration format " + s);
    }

D
duke 已提交
421
    /**
W
weijun 已提交
422 423 424 425 426 427
     * Gets the int value for the specified keys.
     * @param keys the keys
     * @return the int value, Integer.MIN_VALUE is returned if it cannot be
     * found or the value is not a legal integer.
     * @throw IllegalArgumentException if any of the keys is illegal
     * @see #get(java.lang.String[])
D
duke 已提交
428
     */
W
weijun 已提交
429 430
    public int getIntValue(String... keys) {
        String result = get(keys);
D
duke 已提交
431 432 433 434 435 436 437
        int value = Integer.MIN_VALUE;
        if (result != null) {
            try {
                value = parseIntValue(result);
            } catch (NumberFormatException e) {
                if (DEBUG) {
                    System.out.println("Exception in getting value of " +
W
weijun 已提交
438 439 440
                                       Arrays.toString(keys) + " " +
                                       e.getMessage());
                    System.out.println("Setting " + Arrays.toString(keys) +
D
duke 已提交
441 442 443 444 445 446 447 448 449
                                       " to minimum value");
                }
                value = Integer.MIN_VALUE;
            }
        }
        return value;
    }

    /**
W
weijun 已提交
450 451 452 453 454 455
     * Gets the boolean value for the specified keys.
     * @param keys the keys
     * @return the boolean value, false is returned if it cannot be
     * found or the value is not "true" (case insensitive).
     * @throw IllegalArgumentException if any of the keys is illegal
     * @see #get(java.lang.String[])
D
duke 已提交
456
     */
W
weijun 已提交
457 458
    public boolean getBooleanValue(String... keys) {
        String val = get(keys);
D
duke 已提交
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
        if (val != null && val.equalsIgnoreCase("true")) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * Parses a string to an integer. The convertible strings include the
     * string representations of positive integers, negative integers, and
     * hex decimal integers.  Valid inputs are, e.g., -1234, +1234,
     * 0x40000.
     *
     * @param input the String to be converted to an Integer.
     * @return an numeric value represented by the string
     * @exception NumberFormationException if the String does not contain a
     * parsable integer.
     */
    private int parseIntValue(String input) throws NumberFormatException {
        int value = 0;
        if (input.startsWith("+")) {
            String temp = input.substring(1);
            return Integer.parseInt(temp);
        } else if (input.startsWith("0x")) {
            String temp = input.substring(2);
            char[] chars = temp.toCharArray();
            if (chars.length > 8) {
                throw new NumberFormatException();
            } else {
                for (int i = 0; i < chars.length; i++) {
                    int index = chars.length - i - 1;
                    switch (chars[i]) {
                    case '0':
                        value += 0;
                        break;
                    case '1':
                        value += 1 * getBase(index);
                        break;
                    case '2':
                        value += 2 * getBase(index);
                        break;
                    case '3':
                        value += 3 * getBase(index);
                        break;
                    case '4':
                        value += 4 * getBase(index);
                        break;
                    case '5':
                        value += 5 * getBase(index);
                        break;
                    case '6':
                        value += 6 * getBase(index);
                        break;
                    case '7':
                        value += 7 * getBase(index);
                        break;
                    case '8':
                        value += 8 * getBase(index);
                        break;
                    case '9':
                        value += 9 * getBase(index);
                        break;
                    case 'a':
                    case 'A':
                        value += 10 * getBase(index);
                        break;
                    case 'b':
                    case 'B':
                        value += 11 * getBase(index);
                        break;
                    case 'c':
                    case 'C':
                        value += 12 * getBase(index);
                        break;
                    case 'd':
                    case 'D':
                        value += 13 * getBase(index);
                        break;
                    case 'e':
                    case 'E':
                        value += 14 * getBase(index);
                        break;
                    case 'f':
                    case 'F':
                        value += 15 * getBase(index);
                        break;
                    default:
                        throw new NumberFormatException("Invalid numerical format");
                    }
                }
            }
            if (value < 0) {
                throw new NumberFormatException("Data overflow.");
            }
        } else {
            value = Integer.parseInt(input);
        }
        return value;
    }

    private int getBase(int i) {
        int result = 16;
        switch (i) {
        case 0:
            result = BASE16_0;
            break;
        case 1:
            result = BASE16_1;
            break;
        case 2:
            result = BASE16_2;
            break;
        case 3:
            result = BASE16_3;
            break;
        default:
            for (int j = 1; j < i; j++) {
                result *= 16;
            }
        }
        return result;
    }

    /**
W
weijun 已提交
583
     * Reads lines to the memory from the configuration file.
D
duke 已提交
584 585 586 587 588 589
     *
     * Configuration file contains information about the default realm,
     * ticket parameters, location of the KDC and the admin server for
     * known realms, etc. The file is divided into sections. Each section
     * contains one or more name/value pairs with one pair per line. A
     * typical file would be:
W
weijun 已提交
590
     * <pre>
D
duke 已提交
591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607
     * [libdefaults]
     *          default_realm = EXAMPLE.COM
     *          default_tgs_enctypes = des-cbc-md5
     *          default_tkt_enctypes = des-cbc-md5
     * [realms]
     *          EXAMPLE.COM = {
     *                  kdc = kerberos.example.com
     *                  kdc = kerberos-1.example.com
     *                  admin_server = kerberos.example.com
     *                  }
     *          SAMPLE_COM = {
     *                  kdc = orange.sample.com
     *                  admin_server = orange.sample.com
     *                  }
     * [domain_realm]
     *          blue.sample.com = TEST.SAMPLE.COM
     *          .backup.com     = EXAMPLE.COM
W
weijun 已提交
608 609 610 611 612 613 614 615 616
     * </pre>
     * @return an ordered list of strings representing the config file after
     * some initial processing, including:<ol>
     * <li> Comment lines and empty lines are removed
     * <li> "{" not at the end of a line is appended to the previous line
     * <li> The content of a section is also placed between "{" and "}".
     * <li> Lines are trimmed</ol>
     * @throws IOException if there is an I/O error
     * @throws KrbException if there is a file format error
D
duke 已提交
617
     */
W
weijun 已提交
618 619
    private List<String> loadConfigFile(final String fileName)
            throws IOException, KrbException {
D
duke 已提交
620
        try {
W
weijun 已提交
621 622 623 624 625 626 627 628 629
            List<String> v = new ArrayList<>();
            try (BufferedReader br = new BufferedReader(new InputStreamReader(
                AccessController.doPrivileged(
                    new PrivilegedExceptionAction<FileInputStream> () {
                        public FileInputStream run() throws IOException {
                            return new FileInputStream(fileName);
                        }
                    })))) {
                String line;
D
duke 已提交
630
                String previous = null;
W
weijun 已提交
631 632
                while ((line = br.readLine()) != null) {
                    line = line.trim();
633
                    if (line.isEmpty() || line.startsWith("#") || line.startsWith(";")) {
W
weijun 已提交
634
                        // ignore comments and blank line
635
                        // Comments start with '#' or ';'
W
weijun 已提交
636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657
                        continue;
                    }
                    // In practice, a subsection might look like:
                    //      [realms]
                    //      EXAMPLE.COM =
                    //      {
                    //          kdc = kerberos.example.com
                    //          ...
                    //      }
                    // Before parsed into stanza table, it needs to be
                    // converted into a canonicalized style (no indent):
                    //      realms = {
                    //          EXAMPLE.COM = {
                    //              kdc = kerberos.example.com
                    //              ...
                    //          }
                    //      }
                    //
                    if (line.startsWith("[")) {
                        if (!line.endsWith("]")) {
                            throw new KrbException("Illegal config content:"
                                    + line);
D
duke 已提交
658
                        }
W
weijun 已提交
659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681
                        if (previous != null) {
                            v.add(previous);
                            v.add("}");
                        }
                        String title = line.substring(
                                1, line.length()-1).trim();
                        if (title.isEmpty()) {
                            throw new KrbException("Illegal config content:"
                                    + line);
                        }
                        previous = title + " = {";
                    } else if (line.startsWith("{")) {
                        if (previous == null) {
                            throw new KrbException(
                                "Config file should not start with \"{\"");
                        }
                        previous += " {";
                        if (line.length() > 1) {
                            // { and content on the same line
                            v.add(previous);
                            previous = line.substring(1).trim();
                        }
                    } else {
682 683 684 685
                        // Lines before the first section are ignored
                        if (previous != null) {
                            v.add(previous);
                            previous = line;
W
weijun 已提交
686
                        }
D
duke 已提交
687 688 689
                    }
                }
                if (previous != null) {
W
weijun 已提交
690 691
                    v.add(previous);
                    v.add("}");
D
duke 已提交
692 693
                }
            }
W
weijun 已提交
694
            return v;
D
duke 已提交
695 696 697 698 699 700 701 702 703 704
        } catch (java.security.PrivilegedActionException pe) {
            throw (IOException)pe.getException();
        }
    }

    /**
     * Parses stanza names and values from configuration file to
     * stanzaTable (Hashtable). Hashtable key would be stanza names,
     * (libdefaults, realms, domain_realms, etc), and the hashtable value
     * would be another hashtable which contains the key-value pairs under
W
weijun 已提交
705 706 707 708 709 710 711 712 713 714 715 716 717 718 719
     * a stanza name. The value of this sub-hashtable can be another hashtable
     * containing another sub-sub-section or a vector of strings for
     * final values (even if there is only one value defined).
     * <p>
     * For duplicates section names, the latter overwrites the former. For
     * duplicate value names, the values are in a vector in its appearing order.
     * </ol>
     * Please note that this behavior is Java traditional. and it is
     * not the same as the MIT krb5 behavior, where:<ol>
     * <li>Duplicated root sections will be merged
     * <li>For duplicated sub-sections, the former overwrites the latter
     * <li>Duplicate keys for values are always saved in a vector
     * </ol>
     * @param v the strings in the file, never null, might be empty
     * @throws KrbException if there is a file format error
D
duke 已提交
720
     */
W
weijun 已提交
721 722 723 724 725 726 727 728 729 730 731 732 733 734
    @SuppressWarnings("unchecked")
    private Hashtable<String,Object> parseStanzaTable(List<String> v)
            throws KrbException {
        Hashtable<String,Object> current = stanzaTable;
        for (String line: v) {
            // There are 3 kinds of lines
            // 1. a = b
            // 2. a = {
            // 3. }
            if (line.equals("}")) {
                // Go back to parent, see below
                current = (Hashtable<String,Object>)current.remove(" PARENT ");
                if (current == null) {
                    throw new KrbException("Unmatched close brace");
D
duke 已提交
735
                }
W
weijun 已提交
736 737 738 739
            } else {
                int pos = line.indexOf('=');
                if (pos < 0) {
                    throw new KrbException("Illegal config content:" + line);
D
duke 已提交
740
                }
W
weijun 已提交
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
                String key = line.substring(0, pos).trim();
                String value = trimmed(line.substring(pos+1));
                if (value.equals("{")) {
                    Hashtable<String,Object> subTable;
                    if (current == stanzaTable) {
                        key = key.toLowerCase(Locale.US);
                    }
                    subTable = new Hashtable<>();
                    current.put(key, subTable);
                    // A special entry for its parent. Put whitespaces around,
                    // so will never be confused with a normal key
                    subTable.put(" PARENT ", current);
                    current = subTable;
                } else {
                    Vector<String> values;
                    if (current.containsKey(key)) {
                        Object obj = current.get(key);
                        // If a key first shows as a section and then a value,
                        // this is illegal. However, we haven't really forbid
                        // first value then section, which the final result
                        // is a section.
                        if (!(obj instanceof Vector)) {
                            throw new KrbException("Key " + key
                                    + "used for both value and section");
                        }
                        values = (Vector<String>)current.get(key);
                    } else {
                        values = new Vector<String>();
                        current.put(key, values);
D
duke 已提交
770
                    }
W
weijun 已提交
771
                    values.add(value);
D
duke 已提交
772 773 774
                }
            }
        }
W
weijun 已提交
775 776 777 778
        if (current != stanzaTable) {
            throw new KrbException("Not closed");
        }
        return current;
D
duke 已提交
779 780 781
    }

    /**
782
     * Gets the default Java configuration file name.
783 784
     *
     * If the system property "java.security.krb5.conf" is defined, we'll
785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808
     * use its value, no matter if the file exists or not. Otherwise, we
     * will look at $JAVA_HOME/lib/security directory with "krb5.conf" name,
     * and return it if the file exists.
     *
     * The method returns null if it cannot find a Java config file.
     */
    private String getJavaFileName() {
        String name = getProperty("java.security.krb5.conf");
        if (name == null) {
            name = getProperty("java.home") + File.separator +
                                "lib" + File.separator + "security" +
                                File.separator + "krb5.conf";
            if (!fileExists(name)) {
                name = null;
            }
        }
        if (DEBUG) {
            System.out.println("Java config name: " + name);
        }
        return name;
    }

    /**
     * Gets the default native configuration file name.
809
     *
810 811 812 813
     * Depending on the OS type, the method returns the default native
     * kerberos config file name, which is at windows directory with
     * the name of "krb5.ini" for Windows, /etc/krb5/krb5.conf for Solaris,
     * /etc/krb5.conf otherwise. Mac OSX X has a different file name.
814 815 816 817 818 819
     *
     * Note: When the Terminal Service is started in Windows (from 2003),
     * there are two kinds of Windows directories: A system one (say,
     * C:\Windows), and a user-private one (say, C:\Users\Me\Windows).
     * We will first look for krb5.ini in the user-private one. If not
     * found, try the system one instead.
820 821 822
     *
     * This method will always return a non-null non-empty file name,
     * even if that file does not exist.
D
duke 已提交
823
     */
824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839
    private String getNativeFileName() {
        String name = null;
        String osname = getProperty("os.name");
        if (osname.startsWith("Windows")) {
            try {
                Credentials.ensureLoaded();
            } catch (Exception e) {
                // ignore exceptions
            }
            if (Credentials.alreadyLoaded) {
                String path = getWindowsDirectory(false);
                if (path != null) {
                    if (path.endsWith("\\")) {
                        path = path + "krb5.ini";
                    } else {
                        path = path + "\\krb5.ini";
D
duke 已提交
840
                    }
841 842
                    if (fileExists(path)) {
                        name = path;
843
                    }
844 845 846 847 848 849 850 851 852 853
                }
                if (name == null) {
                    path = getWindowsDirectory(true);
                    if (path != null) {
                        if (path.endsWith("\\")) {
                            path = path + "krb5.ini";
                        } else {
                            path = path + "\\krb5.ini";
                        }
                        name = path;
D
duke 已提交
854 855 856
                    }
                }
            }
857 858 859 860 861 862 863 864 865
            if (name == null) {
                name = "c:\\winnt\\krb5.ini";
            }
        } else if (osname.startsWith("SunOS")) {
            name =  "/etc/krb5/krb5.conf";
        } else if (osname.contains("OS X")) {
            name = findMacosConfigFile();
        } else {
            name =  "/etc/krb5.conf";
D
duke 已提交
866 867
        }
        if (DEBUG) {
868
            System.out.println("Native config name: " + name);
D
duke 已提交
869 870 871 872
        }
        return name;
    }

873 874 875
    private static String getProperty(String property) {
        return java.security.AccessController.doPrivileged(
                new sun.security.action.GetPropertyAction(property));
876 877 878 879 880
    }

    private String findMacosConfigFile() {
        String userHome = getProperty("user.home");
        final String PREF_FILE = "/Library/Preferences/edu.mit.Kerberos";
881
        String userPrefs = userHome + PREF_FILE;
882 883 884 885 886 887 888 889 890

        if (fileExists(userPrefs)) {
            return userPrefs;
        }

        if (fileExists(PREF_FILE)) {
            return PREF_FILE;
        }

891
        return "/etc/krb5.conf";
892 893
    }

894 895
    private static String trimmed(String s) {
        s = s.trim();
896 897 898
        if (s.length() >= 2 &&
                ((s.charAt(0) == '"' && s.charAt(s.length()-1) == '"') ||
                 (s.charAt(0) == '\'' && s.charAt(s.length()-1) == '\''))) {
899 900 901 902
            s = s.substring(1, s.length()-1).trim();
        }
        return s;
    }
D
duke 已提交
903 904 905 906 907 908

    /**
     * For testing purpose. This method lists all information being parsed from
     * the configuration file to the hashtable.
     */
    public void listTable() {
W
weijun 已提交
909
        System.out.println(this);
D
duke 已提交
910 911 912
    }

    /**
913 914 915
     * Returns all etypes specified in krb5.conf for the given configName,
     * or all the builtin defaults. This result is always non-empty.
     * If no etypes are found, an exception is thrown.
D
duke 已提交
916
     */
917
    public int[] defaultEtype(String configName) throws KrbException {
D
duke 已提交
918
        String default_enctypes;
919
        default_enctypes = get("libdefaults", configName);
D
duke 已提交
920 921 922 923
        int[] etype;
        if (default_enctypes == null) {
            if (DEBUG) {
                System.out.println("Using builtin default etypes for " +
924
                    configName);
D
duke 已提交
925 926 927
            }
            etype = EType.getBuiltInDefaults();
        } else {
928 929
            String delim = " ";
            StringTokenizer st;
D
duke 已提交
930 931 932 933 934 935 936 937 938 939
            for (int j = 0; j < default_enctypes.length(); j++) {
                if (default_enctypes.substring(j, j + 1).equals(",")) {
                    // only two delimiters are allowed to use
                    // according to Kerberos DCE doc.
                    delim = ",";
                    break;
                }
            }
            st = new StringTokenizer(default_enctypes, delim);
            int len = st.countTokens();
940
            ArrayList<Integer> ls = new ArrayList<>(len);
D
duke 已提交
941 942
            int type;
            for (int i = 0; i < len; i++) {
W
weijun 已提交
943
                type = Config.getType(st.nextToken());
944
                if (type != -1 && EType.isSupported(type)) {
D
duke 已提交
945 946 947
                    ls.add(type);
                }
            }
948
            if (ls.isEmpty()) {
949 950
                throw new KrbException("no supported default etypes for "
                        + configName);
D
duke 已提交
951 952 953 954 955 956 957 958 959
            } else {
                etype = new int[ls.size()];
                for (int i = 0; i < etype.length; i++) {
                    etype[i] = ls.get(i);
                }
            }
        }

        if (DEBUG) {
960
            System.out.print("default etypes for " + configName + ":");
D
duke 已提交
961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979
            for (int i = 0; i < etype.length; i++) {
                System.out.print(" " + etype[i]);
            }
            System.out.println(".");
        }
        return etype;
    }


    /**
     * Get the etype and checksum value for the specified encryption and
     * checksum type.
     *
     */
    /*
     * This method converts the string representation of encryption type and
     * checksum type to int value that can be later used by EType and
     * Checksum classes.
     */
W
weijun 已提交
980
    public static int getType(String input) {
D
duke 已提交
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
        int result = -1;
        if (input == null) {
            return result;
        }
        if (input.startsWith("d") || (input.startsWith("D"))) {
            if (input.equalsIgnoreCase("des-cbc-crc")) {
                result = EncryptedData.ETYPE_DES_CBC_CRC;
            } else if (input.equalsIgnoreCase("des-cbc-md5")) {
                result = EncryptedData.ETYPE_DES_CBC_MD5;
            } else if (input.equalsIgnoreCase("des-mac")) {
                result = Checksum.CKSUMTYPE_DES_MAC;
            } else if (input.equalsIgnoreCase("des-mac-k")) {
                result = Checksum.CKSUMTYPE_DES_MAC_K;
            } else if (input.equalsIgnoreCase("des-cbc-md4")) {
                result = EncryptedData.ETYPE_DES_CBC_MD4;
            } else if (input.equalsIgnoreCase("des3-cbc-sha1") ||
                input.equalsIgnoreCase("des3-hmac-sha1") ||
                input.equalsIgnoreCase("des3-cbc-sha1-kd") ||
                input.equalsIgnoreCase("des3-cbc-hmac-sha1-kd")) {
                result = EncryptedData.ETYPE_DES3_CBC_HMAC_SHA1_KD;
            }
        } else if (input.startsWith("a") || (input.startsWith("A"))) {
            // AES
            if (input.equalsIgnoreCase("aes128-cts") ||
                input.equalsIgnoreCase("aes128-cts-hmac-sha1-96")) {
                result = EncryptedData.ETYPE_AES128_CTS_HMAC_SHA1_96;
            } else if (input.equalsIgnoreCase("aes256-cts") ||
                input.equalsIgnoreCase("aes256-cts-hmac-sha1-96")) {
                result = EncryptedData.ETYPE_AES256_CTS_HMAC_SHA1_96;
            // ARCFOUR-HMAC
            } else if (input.equalsIgnoreCase("arcfour-hmac") ||
                   input.equalsIgnoreCase("arcfour-hmac-md5")) {
                result = EncryptedData.ETYPE_ARCFOUR_HMAC;
            }
        // RC4-HMAC
        } else if (input.equalsIgnoreCase("rc4-hmac")) {
            result = EncryptedData.ETYPE_ARCFOUR_HMAC;
        } else if (input.equalsIgnoreCase("CRC32")) {
            result = Checksum.CKSUMTYPE_CRC32;
        } else if (input.startsWith("r") || (input.startsWith("R"))) {
            if (input.equalsIgnoreCase("rsa-md5")) {
                result = Checksum.CKSUMTYPE_RSA_MD5;
            } else if (input.equalsIgnoreCase("rsa-md5-des")) {
                result = Checksum.CKSUMTYPE_RSA_MD5_DES;
            }
        } else if (input.equalsIgnoreCase("hmac-sha1-des3-kd")) {
            result = Checksum.CKSUMTYPE_HMAC_SHA1_DES3_KD;
        } else if (input.equalsIgnoreCase("hmac-sha1-96-aes128")) {
            result = Checksum.CKSUMTYPE_HMAC_SHA1_96_AES128;
        } else if (input.equalsIgnoreCase("hmac-sha1-96-aes256")) {
            result = Checksum.CKSUMTYPE_HMAC_SHA1_96_AES256;
        } else if (input.equalsIgnoreCase("hmac-md5-rc4") ||
                input.equalsIgnoreCase("hmac-md5-arcfour") ||
                input.equalsIgnoreCase("hmac-md5-enc")) {
            result = Checksum.CKSUMTYPE_HMAC_MD5_ARCFOUR;
        } else if (input.equalsIgnoreCase("NULL")) {
            result = EncryptedData.ETYPE_NULL;
        }

        return result;
    }

    /**
     * Resets the default kdc realm.
     * We do not need to synchronize these methods since assignments are atomic
1046 1047
     *
     * This method was useless. Kept here in case some class still calls it.
D
duke 已提交
1048 1049 1050
     */
    public void resetDefaultRealm(String realm) {
        if (DEBUG) {
1051
            System.out.println(">>> Config try resetting default kdc " + realm);
D
duke 已提交
1052 1053 1054 1055 1056 1057 1058 1059 1060 1061
        }
    }

    /**
     * Check to use addresses in tickets
     * use addresses if "no_addresses" or "noaddresses" is set to false
     */
    public boolean useAddresses() {
        boolean useAddr = false;
        // use addresses if "no_addresses" is set to false
W
weijun 已提交
1062
        String value = get("libdefaults", "no_addresses");
D
duke 已提交
1063 1064 1065
        useAddr = (value != null && value.equalsIgnoreCase("false"));
        if (useAddr == false) {
            // use addresses if "noaddresses" is set to false
W
weijun 已提交
1066
            value = get("libdefaults", "noaddresses");
D
duke 已提交
1067 1068 1069 1070 1071 1072 1073 1074
            useAddr = (value != null && value.equalsIgnoreCase("false"));
        }
        return useAddr;
    }

    /**
     * Check if need to use DNS to locate Kerberos services
     */
1075 1076 1077 1078 1079 1080 1081 1082
    private boolean useDNS(String name, boolean defaultValue) {
        Boolean value = getBooleanObject("libdefaults", name);
        if (value != null) {
            return value.booleanValue();
        }
        value = getBooleanObject("libdefaults", "dns_fallback");
        if (value != null) {
            return value.booleanValue();
D
duke 已提交
1083
        }
1084
        return defaultValue;
D
duke 已提交
1085 1086 1087 1088 1089
    }

    /**
     * Check if need to use DNS to locate the KDC
     */
W
weijun 已提交
1090
    private boolean useDNS_KDC() {
1091
        return useDNS("dns_lookup_kdc", true);
D
duke 已提交
1092 1093 1094 1095 1096
    }

    /*
     * Check if need to use DNS to locate the Realm
     */
W
weijun 已提交
1097
    private boolean useDNS_Realm() {
1098
        return useDNS("dns_lookup_realm", false);
D
duke 已提交
1099 1100 1101 1102
    }

    /**
     * Gets default realm.
1103 1104
     * @throws KrbException where no realm can be located
     * @return the default realm, always non null
D
duke 已提交
1105 1106
     */
    public String getDefaultRealm() throws KrbException {
1107 1108 1109
        if (defaultRealm != null) {
            return defaultRealm;
        }
1110
        Exception cause = null;
W
weijun 已提交
1111
        String realm = get("libdefaults", "default_realm");
D
duke 已提交
1112 1113
        if ((realm == null) && useDNS_Realm()) {
            // use DNS to locate Kerberos realm
1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138
            try {
                realm = getRealmFromDNS();
            } catch (KrbException ke) {
                cause = ke;
            }
        }
        if (realm == null) {
            realm = java.security.AccessController.doPrivileged(
                    new java.security.PrivilegedAction<String>() {
                @Override
                public String run() {
                    String osname = System.getProperty("os.name");
                    if (osname.startsWith("Windows")) {
                        return System.getenv("USERDNSDOMAIN");
                    }
                    return null;
                }
            });
        }
        if (realm == null) {
            KrbException ke = new KrbException("Cannot locate default realm");
            if (cause != null) {
                ke.initCause(cause);
            }
            throw ke;
D
duke 已提交
1139 1140 1141 1142 1143 1144 1145
        }
        return realm;
    }

    /**
     * Returns a list of KDC's with each KDC separated by a space
     *
1146 1147 1148
     * @param realm the realm for which the KDC list is desired
     * @throws KrbException if there's no way to find KDC for the realm
     * @return the list of KDCs separated by a space, always non null
D
duke 已提交
1149 1150 1151 1152 1153
     */
    public String getKDCList(String realm) throws KrbException {
        if (realm == null) {
            realm = getDefaultRealm();
        }
1154 1155 1156
        if (realm.equalsIgnoreCase(defaultRealm)) {
            return defaultKDC;
        }
1157
        Exception cause = null;
W
weijun 已提交
1158
        String kdcs = getAll("realms", realm, "kdc");
D
duke 已提交
1159 1160
        if ((kdcs == null) && useDNS_KDC()) {
            // use DNS to locate KDC
1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185
            try {
                kdcs = getKDCFromDNS(realm);
            } catch (KrbException ke) {
                cause = ke;
            }
        }
        if (kdcs == null) {
            kdcs = java.security.AccessController.doPrivileged(
                    new java.security.PrivilegedAction<String>() {
                @Override
                public String run() {
                    String osname = System.getProperty("os.name");
                    if (osname.startsWith("Windows")) {
                        String logonServer = System.getenv("LOGONSERVER");
                        if (logonServer != null
                                && logonServer.startsWith("\\\\")) {
                            logonServer = logonServer.substring(2);
                        }
                        return logonServer;
                    }
                    return null;
                }
            });
        }
        if (kdcs == null) {
1186 1187 1188
            if (defaultKDC != null) {
                return defaultKDC;
            }
1189 1190 1191 1192 1193
            KrbException ke = new KrbException("Cannot locate KDC");
            if (cause != null) {
                ke.initCause(cause);
            }
            throw ke;
D
duke 已提交
1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207
        }
        return kdcs;
    }

    /**
     * Locate Kerberos realm using DNS
     *
     * @return the Kerberos realm
     */
    private String getRealmFromDNS() throws KrbException {
        // use DNS to locate Kerberos realm
        String realm = null;
        String hostName = null;
        try {
1208
            hostName = InetAddress.getLocalHost().getCanonicalHostName();
D
duke 已提交
1209 1210 1211 1212 1213 1214 1215 1216
        } catch (UnknownHostException e) {
            KrbException ke = new KrbException(Krb5.KRB_ERR_GENERIC,
                "Unable to locate Kerberos realm: " + e.getMessage());
            ke.initCause(e);
            throw (ke);
        }
        // get the domain realm mapping from the configuration
        String mapRealm = PrincipalName.mapHostToRealm(hostName);
1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243
        if (mapRealm == null) {
            // No match. Try search and/or domain in /etc/resolv.conf
            List<String> srchlist = ResolverConfiguration.open().searchlist();
            for (String domain: srchlist) {
                realm = checkRealm(domain);
                if (realm != null) {
                    break;
                }
            }
        } else {
            realm = checkRealm(mapRealm);
        }
        if (realm == null) {
            throw new KrbException(Krb5.KRB_ERR_GENERIC,
                                "Unable to locate Kerberos realm");
        }
        return realm;
    }

    /**
     * Check if the provided realm is the correct realm
     * @return the realm if correct, or null otherwise
     */
    private static String checkRealm(String mapRealm) {
        if (DEBUG) {
            System.out.println("getRealmFromDNS: trying " + mapRealm);
        }
D
duke 已提交
1244 1245 1246 1247 1248 1249 1250 1251
        String[] records = null;
        String newRealm = mapRealm;
        while ((records == null) && (newRealm != null)) {
            // locate DNS TXT record
            records = KrbServiceLocator.getKerberosService(newRealm);
            newRealm = Realm.parseRealmComponent(newRealm);
            // if no DNS TXT records found, try again using sub-realm
        }
1252 1253 1254 1255 1256
        if (records != null) {
            for (int i = 0; i < records.length; i++) {
                if (records[i].equalsIgnoreCase(mapRealm)) {
                    return records[i];
                }
D
duke 已提交
1257 1258
            }
        }
1259
        return null;
D
duke 已提交
1260 1261 1262 1263 1264 1265 1266 1267 1268 1269
    }

    /**
     * Locate KDC using DNS
     *
     * @param realm the realm for which the master KDC is desired
     * @return the KDC
     */
    private String getKDCFromDNS(String realm) throws KrbException {
        // use DNS to locate KDC
1270
        String kdcs = "";
D
duke 已提交
1271 1272
        String[] srvs = null;
        // locate DNS SRV record using UDP
1273 1274 1275 1276
        if (DEBUG) {
            System.out.println("getKDCFromDNS using UDP");
        }
        srvs = KrbServiceLocator.getKerberosService(realm, "_udp");
D
duke 已提交
1277 1278
        if (srvs == null) {
            // locate DNS SRV record using TCP
1279
            if (DEBUG) {
1280
                System.out.println("getKDCFromDNS using TCP");
1281 1282
            }
            srvs = KrbServiceLocator.getKerberosService(realm, "_tcp");
D
duke 已提交
1283 1284 1285 1286 1287 1288
        }
        if (srvs == null) {
            // no DNS SRV records
            throw new KrbException(Krb5.KRB_ERR_GENERIC,
                "Unable to locate KDC for realm " + realm);
        }
1289 1290 1291
        if (srvs.length == 0) {
            return null;
        }
D
duke 已提交
1292
        for (int i = 0; i < srvs.length; i++) {
1293 1294 1295 1296 1297
            kdcs += srvs[i].trim() + " ";
        }
        kdcs = kdcs.trim();
        if (kdcs.equals("")) {
            return null;
D
duke 已提交
1298 1299 1300 1301
        }
        return kdcs;
    }

1302 1303 1304 1305 1306
    private boolean fileExists(String name) {
        return java.security.AccessController.doPrivileged(
                                new FileExistsAction(name));
    }

D
duke 已提交
1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320
    static class FileExistsAction
        implements java.security.PrivilegedAction<Boolean> {

        private String fileName;

        public FileExistsAction(String fileName) {
            this.fileName = fileName;
        }

        public Boolean run() {
            return new File(fileName).exists();
        }
    }

1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333
    // Shows the content of the Config object for debug purpose.
    //
    // {
    //      libdefaults = {
    //          default_realm = R
    //      }
    //      realms = {
    //          R = {
    //              kdc = [k1,k2]
    //          }
    //      }
    // }

1334 1335 1336
    @Override
    public String toString() {
        StringBuffer sb = new StringBuffer();
1337
        toStringInternal("", stanzaTable, sb);
1338 1339
        return sb.toString();
    }
1340
    private static void toStringInternal(String prefix, Object obj,
1341 1342
            StringBuffer sb) {
        if (obj instanceof String) {
1343 1344
            // A string value, just print it
            sb.append(obj).append('\n');
1345
        } else if (obj instanceof Hashtable) {
1346
            // A table, start a new sub-section...
1347
            Hashtable<?, ?> tab = (Hashtable<?, ?>)obj;
1348
            sb.append("{\n");
1349
            for (Object o: tab.keySet()) {
1350 1351 1352 1353
                // ...indent, print "key = ", and
                sb.append(prefix).append("    ").append(o).append(" = ");
                // ...go recursively into value
                toStringInternal(prefix + "    ", tab.get(o), sb);
1354
            }
1355
            sb.append(prefix).append("}\n");
1356
        } else if (obj instanceof Vector) {
1357
            // A vector of strings, print them inside [ and ]
1358
            Vector<?> v = (Vector<?>)obj;
1359 1360
            sb.append("[");
            boolean first = true;
1361
            for (Object o: v.toArray()) {
1362 1363 1364
                if (!first) sb.append(",");
                sb.append(o);
                first = false;
1365
            }
1366
            sb.append("]\n");
1367 1368
        }
    }
D
duke 已提交
1369
}