1/*
2 * Copyright (C) 2011 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package android.webkit;
18
19import android.content.Context;
20import android.os.Handler;
21import android.util.Log;
22
23/**
24 * KeyStoreHandler: class responsible for certificate installation to
25 * the system key store. It reads the certificates file from network
26 * then pass the bytes to class CertTool.
27 * This class is only needed if the Chromium HTTP stack is used.
28 */
29class KeyStoreHandler extends Handler {
30    private static final String LOGTAG = "KeyStoreHandler";
31
32    private final ByteArrayBuilder mDataBuilder = new ByteArrayBuilder();
33
34    private String mMimeType;
35
36    public KeyStoreHandler(String mimeType) {
37      mMimeType = mimeType;
38    }
39
40    /**
41     * Add data to the internal collection of data.
42     * @param data A byte array containing the content.
43     * @param length The length of data.
44     */
45    public void didReceiveData(byte[] data, int length) {
46        synchronized (mDataBuilder) {
47            mDataBuilder.append(data, 0, length);
48        }
49    }
50
51    public void installCert(Context context) {
52        String type = CertTool.getCertType(mMimeType);
53        if (type == null) return;
54
55        // This must be synchronized so that no more data can be added
56        // after getByteSize returns.
57        synchronized (mDataBuilder) {
58            // In the case of downloading certificate, we will save it
59            // to the KeyStore and stop the current loading so that it
60            // will not generate a new history page
61            byte[] cert = new byte[mDataBuilder.getByteSize()];
62            int offset = 0;
63            while (true) {
64                ByteArrayBuilder.Chunk c = mDataBuilder.getFirstChunk();
65                if (c == null) break;
66
67                if (c.mLength != 0) {
68                    System.arraycopy(c.mArray, 0, cert, offset, c.mLength);
69                    offset += c.mLength;
70                }
71                c.release();
72            }
73            CertTool.addCertificate(context, type, cert);
74            return;
75        }
76    }
77}
78