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