summaryrefslogtreecommitdiffstats
path: root/luni/src/main/java/org/apache/harmony/security/x501/AttributeValue.java
blob: b3eb200fe6f68ed8ad423d6135ec75dc03c91bf1 (plain)
1
2
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
/*
 *  Licensed to the Apache Software Foundation (ASF) under one or more
 *  contributor license agreements.  See the NOTICE file distributed with
 *  this work for additional information regarding copyright ownership.
 *  The ASF licenses this file to You under the Apache License, Version 2.0
 *  (the "License"); you may not use this file except in compliance with
 *  the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */

/**
* @author Alexander V. Esin
* @version $Revision$
*/

package org.apache.harmony.security.x501;

import java.io.IOException;
import java.util.Collection;
import org.apache.harmony.security.asn1.ASN1SetOf;
import org.apache.harmony.security.asn1.ASN1StringType;
import org.apache.harmony.security.asn1.ASN1Type;
import org.apache.harmony.security.asn1.DerInputStream;
import org.apache.harmony.security.utils.ObjectIdentifier;

/**
 * X.501 Attribute Value
 */
public final class AttributeValue {

    public boolean wasEncoded;

    private boolean hasConsecutiveSpaces;

    public final String escapedString;

    private String rfc2253String;

    private String hexString;

    private final int tag;

    public byte[] encoded;

    public byte[] bytes; //FIXME remove??? bytes to be encoded

    public boolean hasQE; // raw string contains '"' or '\'

    public final String rawString;

    public AttributeValue(String parsedString, boolean hasQorE, ObjectIdentifier oid) {
        wasEncoded = false;

        this.hasQE = hasQorE;
        this.rawString = parsedString;
        this.escapedString = makeEscaped(rawString); // overwrites hasQE

        int tag;
        if (oid == AttributeTypeAndValue.EMAILADDRESS || oid == AttributeTypeAndValue.DC) {
            // http://www.rfc-editor.org/rfc/rfc5280.txt
            // says that EmailAddress and DomainComponent should be a IA5String
            tag = ASN1StringType.IA5STRING.id;
        } else if (isPrintableString(rawString)) {
            tag = ASN1StringType.PRINTABLESTRING.id;
        } else {
            tag = ASN1StringType.UTF8STRING.id;
        }
        this.tag = tag;
    }

    public AttributeValue(String hexString, byte[] encoded) {
        wasEncoded = true;

        this.hexString = hexString;
        this.encoded = encoded;

        try {
            DerInputStream in = new DerInputStream(encoded);

            tag = in.tag;

            if (DirectoryString.ASN1.checkTag(tag)) {
                // has string representation
                this.rawString = (String) DirectoryString.ASN1.decode(in);
                this.escapedString = makeEscaped(rawString);
            } else {
                this.rawString = hexString;
                this.escapedString = hexString;
            }
        } catch (IOException e) {
            IllegalArgumentException iae = new IllegalArgumentException(); //FIXME message
            iae.initCause(e);
            throw iae;
        }
    }

    public AttributeValue(String rawString, byte[] encoded, int tag) {
        wasEncoded = true;

        this.encoded = encoded;
        this.tag = tag;

        if (rawString == null) {
            this.rawString = getHexString();
            this.escapedString = hexString;
        } else {
            this.rawString = rawString;
            this.escapedString = makeEscaped(rawString);
        }
    }

    /**
     * Checks if the string is PrintableString (see X.680)
     */
    private static boolean isPrintableString(String str) {
        for (int i = 0; i< str.length(); ++i) {
            char ch = str.charAt(i);
            if (!(ch == 0x20
            || ch >= 0x27 && ch<= 0x29 // '()
            || ch >= 0x2B && ch<= 0x3A // +,-./0-9:
            || ch == '='
            || ch == '?'
            || ch >= 'A' && ch<= 'Z'
            || ch >= 'a' && ch<= 'z')) {
                return false;
            }
        }
        return true;
    }

    public int getTag() {
        return tag;
    }

    public String getHexString() {
        if (hexString == null) {
            if (!wasEncoded) {
                //FIXME optimize me: what about reusable OutputStream???
                if (tag == ASN1StringType.IA5STRING.id) {
                    encoded = ASN1StringType.IA5STRING.encode(rawString);
                } else if (tag == ASN1StringType.PRINTABLESTRING.id) {
                    encoded = ASN1StringType.PRINTABLESTRING.encode(rawString);
                } else {
                    encoded = ASN1StringType.UTF8STRING.encode(rawString);
                }
                wasEncoded = true;
            }

            StringBuilder buf = new StringBuilder(encoded.length * 2 + 1);
            buf.append('#');

            for (int i = 0, c; i < encoded.length; i++) {
                c = (encoded[i] >> 4) & 0x0F;
                if (c < 10) {
                    buf.append((char) (c + 48));
                } else {
                    buf.append((char) (c + 87));
                }

                c = encoded[i] & 0x0F;
                if (c < 10) {
                    buf.append((char) (c + 48));
                } else {
                    buf.append((char) (c + 87));
                }
            }
            hexString = buf.toString();
        }
        return hexString;
    }

    public Collection<?> getValues(ASN1Type type) throws IOException {
        return (Collection<?>) new ASN1SetOf(type).decode(encoded);
    }

    public void appendQEString(StringBuilder sb) {
        sb.append('"');
        if (hasQE) {
            char c;
            for (int i = 0; i < rawString.length(); i++) {
                c = rawString.charAt(i);
                if (c == '"' || c == '\\') {
                    sb.append('\\');
                }
                sb.append(c);
            }
        } else {
            sb.append(rawString);
        }
        sb.append('"');
    }

    /**
     * Escapes:
     * 1) chars ",", "+", """, "\", "<", ">", ";" (RFC 2253)
     * 2) chars "#", "=" (required by RFC 1779)
     * 3) leading or trailing spaces
     * 4) consecutive spaces (RFC 1779)
     * 5) according to the requirement to be RFC 1779 compatible:
     *    '#' char is escaped in any position
     */
    private String makeEscaped(String name) {
        int length = name.length();
        if (length == 0) {
            return name;
        }
        StringBuilder buf = new StringBuilder(length * 2);

        // Keeps track of whether we are escaping spaces.
        boolean escapeSpaces = false;

        for (int index = 0; index < length; index++) {
            char ch = name.charAt(index);
            switch (ch) {
            case ' ':
                /*
                 * We should escape spaces in the following cases:
                 *   1) at the beginning
                 *   2) at the end
                 *   3) consecutive spaces
                 * Since multiple spaces at the beginning or end will be covered by
                 * 3, we don't need a special case to check for that. Note that RFC 2253
                 * doesn't escape consecutive spaces, so they are removed in
                 * getRFC2253String instead of making two different strings here.
                 */
                if (index < (length - 1)) {
                    boolean nextIsSpace = name.charAt(index + 1) == ' ';
                    escapeSpaces = escapeSpaces || nextIsSpace || index == 0;
                    hasConsecutiveSpaces |= nextIsSpace;
                } else {
                    escapeSpaces = true;
                }

                if (escapeSpaces) {
                    buf.append('\\');
                }

                buf.append(' ');
                break;

            case '"':
            case '\\':
                hasQE = true;
                buf.append('\\');
                buf.append(ch);
                break;

            case ',':
            case '+':
            case '<':
            case '>':
            case ';':
            case '#': // required by RFC 1779
            case '=': // required by RFC 1779
                buf.append('\\');
                buf.append(ch);
                break;

            default:
                buf.append(ch);
                break;
            }

            if (escapeSpaces && ch != ' ') {
                escapeSpaces = false;
            }
        }

        return buf.toString();
    }

    public String makeCanonical() {
        int length = rawString.length();
        if (length == 0) {
            return rawString;
        }
        StringBuilder buf = new StringBuilder(length * 2);

        int index = 0;
        if (rawString.charAt(0) == '#') {
            buf.append('\\');
            buf.append('#');
            index++;
        }

        int bufLength;
        for (; index < length; index++) {
            char ch = rawString.charAt(index);

            switch (ch) {
            case ' ':
                bufLength = buf.length();
                if (bufLength == 0 || buf.charAt(bufLength - 1) == ' ') {
                    break;
                }
                buf.append(' ');
                break;

            case '"':
            case '\\':
            case ',':
            case '+':
            case '<':
            case '>':
            case ';':
                buf.append('\\');

            default:
                buf.append(ch);
            }
        }

        //remove trailing spaces
        for (bufLength = buf.length() - 1; bufLength > -1
                && buf.charAt(bufLength) == ' '; bufLength--) {
        }
        buf.setLength(bufLength + 1);

        return buf.toString();
    }

    /**
     * Removes escape sequences used in RFC1779 escaping but not in RFC2253 and
     * returns the RFC2253 string to the caller..
     */
    public String getRFC2253String() {
        if (!hasConsecutiveSpaces) {
            return escapedString;
        }

        if (rfc2253String == null) {
            // Scan backwards first since runs of spaces at the end are escaped.
            int lastIndex = escapedString.length() - 2;
            for (int i = lastIndex; i > 0; i -= 2) {
                if (escapedString.charAt(i) == '\\' && escapedString.charAt(i + 1) == ' ') {
                    lastIndex = i - 1;
                }
            }

            boolean beginning = true;
            StringBuilder sb = new StringBuilder(escapedString.length());
            for (int i = 0; i < escapedString.length(); i++) {
                char ch = escapedString.charAt(i);
                if (ch != '\\') {
                    sb.append(ch);
                    beginning = false;
                } else {
                    char nextCh = escapedString.charAt(i + 1);
                    if (nextCh == ' ') {
                        if (beginning || i > lastIndex) {
                            sb.append(ch);
                        }
                        sb.append(nextCh);
                    } else {
                        sb.append(ch);
                        sb.append(nextCh);
                        beginning = false;
                    }

                    i++;
                }
            }
            rfc2253String = sb.toString();
        }
        return rfc2253String;
    }
}