1/* 2 * Copyright (C) 2012 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 org.conscrypt; 18 19import java.io.FilterInputStream; 20import java.io.IOException; 21import java.io.InputStream; 22 23/** 24 * Provides an interface to OpenSSL's BIO system directly from a Java 25 * InputStream. It allows an OpenSSL API to read directly from something more 26 * flexible interface than a byte array. 27 * 28 * @hide 29 */ 30@Internal 31public class OpenSSLBIOInputStream extends FilterInputStream { 32 private long ctx; 33 34 public OpenSSLBIOInputStream(InputStream is, boolean isFinite) { 35 super(is); 36 37 ctx = NativeCrypto.create_BIO_InputStream(this, isFinite); 38 } 39 40 public long getBioContext() { 41 return ctx; 42 } 43 44 public void release() { 45 NativeCrypto.BIO_free_all(ctx); 46 } 47 48 /** 49 * Similar to a {@code readLine} method, but matches what OpenSSL expects 50 * from a {@code BIO_gets} method. 51 */ 52 public int gets(byte[] buffer) throws IOException { 53 if (buffer == null || buffer.length == 0) { 54 return 0; 55 } 56 57 int offset = 0; 58 int inputByte = 0; 59 while (offset < buffer.length) { 60 inputByte = read(); 61 if (inputByte == -1) { 62 // EOF 63 break; 64 } 65 if (inputByte == '\n') { 66 if (offset == 0) { 67 // If we haven't read anything yet, ignore CRLF. 68 continue; 69 } else { 70 break; 71 } 72 } 73 74 buffer[offset++] = (byte) inputByte; 75 } 76 77 return offset; 78 } 79} 80