KerberosTime.java 12.2 KB
Newer Older
D
duke 已提交
1 2 3 4 5
/*
 * 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
6
 * published by the Free Software Foundation.  Oracle designates this
D
duke 已提交
7
 * particular file as subject to the "Classpath" exception as provided
8
 * by Oracle in the LICENSE file that accompanied this code.
D
duke 已提交
9 10 11 12 13 14 15 16 17 18 19
 *
 * 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.
 *
20 21 22
 * 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 已提交
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
 */

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

package sun.security.krb5.internal;

import java.util.TimeZone;
import sun.security.util.*;
import sun.security.krb5.Config;
import sun.security.krb5.KrbException;
import sun.security.krb5.Asn1Exception;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.Calendar;
import java.io.IOException;

/**
 * Implements the ASN.1 KerberosTime type.
 *
 * <xmp>
 * KerberosTime    ::= GeneralizedTime -- with no fractional seconds
 * </xmp>
 *
 * The timestamps used in Kerberos are encoded as GeneralizedTimes. A
 * KerberosTime value shall not include any fractional portions of the
 * seconds.  As required by the DER, it further shall not include any
 * separators, and it shall specify the UTC time zone (Z).
 *
 * <p>
 * This definition reflects the Network Working Group RFC 4120
 * specification available at
 * <a href="http://www.ietf.org/rfc/rfc4120.txt">
 * http://www.ietf.org/rfc/rfc4120.txt</a>.
W
weijun 已提交
60 61 62
 *
 * The implementation also includes the microseconds info so that the
 * same class can be used as a precise timestamp in Authenticator etc.
D
duke 已提交
63 64 65 66 67
 */

public class KerberosTime implements Cloneable {

    private long kerberosTime; // milliseconds since epoch, a Date.getTime() value
W
weijun 已提交
68 69 70 71 72 73
    private int  microSeconds; // the last three digits of the microsecond value

    // The time when this class is loaded. Used in setNow()
    private static final long initMilli = System.currentTimeMillis();
    private static final long initMicro = System.nanoTime() / 1000;

D
duke 已提交
74 75 76 77 78 79 80 81 82 83
    private static long syncTime;
    private static boolean DEBUG = Krb5.DEBUG;

    public static final boolean NOW = true;
    public static final boolean UNADJUSTED_NOW = false;

    public KerberosTime(long time) {
        kerberosTime = time;
    }

W
weijun 已提交
84 85 86 87
    private KerberosTime(long time, int micro) {
        kerberosTime = time;
        microSeconds = micro;
    }
D
duke 已提交
88 89

    public Object clone() {
W
weijun 已提交
90
        return new KerberosTime(kerberosTime, microSeconds);
D
duke 已提交
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
    }

    // This constructor is used in the native code
    // src/windows/native/sun/security/krb5/NativeCreds.c
    public KerberosTime(String time) throws Asn1Exception {
        kerberosTime = toKerberosTime(time);
    }

    /**
     * Constructs a KerberosTime object.
     * @param encoding a DER-encoded data.
     * @exception Asn1Exception if an error occurs while decoding an ASN1 encoded data.
     * @exception IOException if an I/O error occurs while reading encoded data.
     */
    public KerberosTime(DerValue encoding) throws Asn1Exception, IOException {
        GregorianCalendar calendar = new GregorianCalendar();
        Date temp = encoding.getGeneralizedTime();
        kerberosTime = temp.getTime();
    }

    private static long toKerberosTime(String time) throws Asn1Exception {
        // this method only used by KerberosTime class.

        // ASN.1 GeneralizedTime format:

        // "19700101000000Z"
        //  |   | | | | | |
        //  0   4 6 8 | | |
        //           10 | |
W
weijun 已提交
120 121
        //             12 |
        //               14
D
duke 已提交
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

        if (time.length() != 15)
            throw new Asn1Exception(Krb5.ASN1_BAD_TIMEFORMAT);
        if (time.charAt(14) != 'Z')
            throw new Asn1Exception(Krb5.ASN1_BAD_TIMEFORMAT);
        int year = Integer.parseInt(time.substring(0, 4));
        Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
        calendar.clear(); // so that millisecond is zero
        calendar.set(year,
                     Integer.parseInt(time.substring(4, 6)) - 1,
                     Integer.parseInt(time.substring(6, 8)),
                     Integer.parseInt(time.substring(8, 10)),
                     Integer.parseInt(time.substring(10, 12)),
                     Integer.parseInt(time.substring(12, 14)));

        //The Date constructor assumes the setting are local relative
        //and converts the time to UTC before storing it.  Since we
        //want the internal representation to correspond to local
        //and not UTC time we subtract the UTC time offset.
        return (calendar.getTime().getTime());

    }

    // should be moved to sun.security.krb5.util class
    public static String zeroPad(String s, int length) {
        StringBuffer temp = new StringBuffer(s);
        while (temp.length() < length)
            temp.insert(0, '0');
        return temp.toString();
    }

    public KerberosTime(Date time) {
        kerberosTime = time.getTime(); // (time.getTimezoneOffset() * 60000L);
    }

    public KerberosTime(boolean initToNow) {
        if (initToNow) {
W
weijun 已提交
159
            setNow();
D
duke 已提交
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
        }
    }

    /**
     * Returns a string representation of KerberosTime object.
     * @return a string representation of this object.
     */
    public String toGeneralizedTimeString() {
        Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
        calendar.clear();

        calendar.setTimeInMillis(kerberosTime);
        return zeroPad(Integer.toString(calendar.get(Calendar.YEAR)), 4) +
            zeroPad(Integer.toString(calendar.get(Calendar.MONTH) + 1), 2) +
            zeroPad(Integer.toString(calendar.get(Calendar.DAY_OF_MONTH)), 2) +
            zeroPad(Integer.toString(calendar.get(Calendar.HOUR_OF_DAY)), 2) +
            zeroPad(Integer.toString(calendar.get(Calendar.MINUTE)), 2) +
            zeroPad(Integer.toString(calendar.get(Calendar.SECOND)), 2) + 'Z';

    }

    /**
     * Encodes this object to a byte array.
     * @return a byte array of encoded data.
     * @exception Asn1Exception if an error occurs while decoding an ASN1 encoded data.
     * @exception IOException if an I/O error occurs while reading encoded data.
     */
    public byte[] asn1Encode() throws Asn1Exception, IOException {
        DerOutputStream out = new DerOutputStream();
        out.putGeneralizedTime(this.toDate());
        return out.toByteArray();
    }

    public long getTime() {
        return kerberosTime;
    }


    public void setTime(Date time) {
        kerberosTime = time.getTime(); // (time.getTimezoneOffset() * 60000L);
W
weijun 已提交
200
        microSeconds = 0;
D
duke 已提交
201 202 203 204
    }

    public void setTime(long time) {
        kerberosTime = time;
W
weijun 已提交
205
        microSeconds = 0;
D
duke 已提交
206 207 208 209 210 211 212 213 214
    }

    public Date toDate() {
        Date temp = new Date(kerberosTime);
        temp.setTime(temp.getTime());
        return temp;
    }

    public void setNow() {
W
weijun 已提交
215 216 217
        long microElapsed = System.nanoTime() / 1000 - initMicro;
        setTime(initMilli + microElapsed/1000);
        microSeconds = (int)(microElapsed % 1000);
D
duke 已提交
218 219 220 221
    }

    public int getMicroSeconds() {
        Long temp_long = new Long((kerberosTime % 1000L) * 1000L);
W
weijun 已提交
222
        return temp_long.intValue() + microSeconds;
D
duke 已提交
223 224 225
    }

    public void setMicroSeconds(int usec) {
W
weijun 已提交
226
        microSeconds = usec % 1000;
D
duke 已提交
227 228 229 230 231 232 233
        Integer temp_int = new Integer(usec);
        long temp_long = temp_int.longValue() / 1000L;
        kerberosTime = kerberosTime - (kerberosTime % 1000L) + temp_long;
    }

    public void setMicroSeconds(Integer usec) {
        if (usec != null) {
W
weijun 已提交
234
            microSeconds = usec.intValue() % 1000;
D
duke 已提交
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
            long temp_long = usec.longValue() / 1000L;
            kerberosTime = kerberosTime - (kerberosTime % 1000L) + temp_long;
        }
    }

    public boolean inClockSkew(int clockSkew) {
        KerberosTime now = new KerberosTime(KerberosTime.NOW);

        if (java.lang.Math.abs(kerberosTime - now.kerberosTime) >
            clockSkew * 1000L)
            return false;
        return true;
    }

    public boolean inClockSkew() {
        return inClockSkew(getDefaultSkew());
    }

    public boolean inClockSkew(int clockSkew, KerberosTime now) {
        if (java.lang.Math.abs(kerberosTime - now.kerberosTime) >
            clockSkew * 1000L)
            return false;
        return true;
    }

    public boolean inClockSkew(KerberosTime time) {
        return inClockSkew(getDefaultSkew(), time);
    }

    public boolean greaterThanWRTClockSkew(KerberosTime time, int clockSkew) {
        if ((kerberosTime - time.kerberosTime) > clockSkew * 1000L)
            return true;
        return false;
    }

    public boolean greaterThanWRTClockSkew(KerberosTime time) {
        return greaterThanWRTClockSkew(time, getDefaultSkew());
    }

    public boolean greaterThan(KerberosTime time) {
W
weijun 已提交
275 276 277
        return kerberosTime > time.kerberosTime ||
            kerberosTime == time.kerberosTime &&
                    microSeconds > time.microSeconds;
D
duke 已提交
278 279 280 281 282 283 284 285 286 287 288
    }

    public boolean equals(Object obj) {
        if (this == obj) {
            return true;
        }

        if (!(obj instanceof KerberosTime)) {
            return false;
        }

W
weijun 已提交
289 290
        return kerberosTime == ((KerberosTime)obj).kerberosTime &&
                microSeconds == ((KerberosTime)obj).microSeconds;
D
duke 已提交
291 292 293
    }

    public int hashCode() {
W
weijun 已提交
294 295
        int result = 37 * 17 + (int)(kerberosTime ^ (kerberosTime >>> 32));
        return result * 17 + microSeconds;
D
duke 已提交
296 297 298
    }

    public boolean isZero() {
W
weijun 已提交
299
        return kerberosTime == 0 && microSeconds == 0;
D
duke 已提交
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
    }

    public int getSeconds() {
        Long temp_long = new Long(kerberosTime / 1000L);
        return temp_long.intValue();
    }

    public void setSeconds(int sec) {
        Integer temp_int = new Integer(sec);
        kerberosTime = temp_int.longValue() * 1000L;
    }

    /**
     * Parse (unmarshal) a kerberostime from a DER input stream.  This form
     * parsing might be used when expanding a value which is part of
     * a constructed sequence and uses explicitly tagged type.
     *
     * @exception Asn1Exception on error.
     * @param data the Der input stream value, which contains one or more marshaled value.
     * @param explicitTag tag number.
     * @param optional indicates if this data field is optional
     * @return an instance of KerberosTime.
     *
     */
    public static KerberosTime parse(DerInputStream data, byte explicitTag, boolean optional) throws Asn1Exception, IOException {
        if ((optional) && (((byte)data.peekByte() & (byte)0x1F)!= explicitTag))
            return null;
        DerValue der = data.getDerValue();
        if (explicitTag != (der.getTag() & (byte)0x1F))  {
            throw new Asn1Exception(Krb5.ASN1_BAD_ID);
        }
        else {
            DerValue subDer = der.getData().getDerValue();
            return new KerberosTime(subDer);
        }
    }

    public static int getDefaultSkew() {
        int tdiff = Krb5.DEFAULT_ALLOWABLE_CLOCKSKEW;
        try {
            Config c = Config.getInstance();
            if ((tdiff = c.getDefaultIntValue("clockskew",
                                              "libdefaults")) == Integer.MIN_VALUE) {   //value is not defined
                tdiff = Krb5.DEFAULT_ALLOWABLE_CLOCKSKEW;
            }
        } catch (KrbException e) {
            if (DEBUG) {
                System.out.println("Exception in getting clockskew from " +
                                   "Configuration " +
                                   "using default value " +
                                   e.getMessage());
            }
        }
        return tdiff;
    }

    public String toString() {
        return toGeneralizedTimeString();
    }
}