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.apache.harmony.xnet.provider.jsse; 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 31 public OpenSSLBIOInputStream(InputStream is) { 32 super(is); 33 34 ctx = NativeCrypto.create_BIO_InputStream(this); 35 } 36 37 public long getBioContext() { 38 return ctx; 39 } 40 41 /** 42 * Similar to a {@code readLine} method, but matches what OpenSSL expects 43 * from a {@code BIO_gets} method. 44 */ 45 public int gets(byte[] buffer) throws IOException { 46 if (buffer == null || buffer.length == 0) { 47 return 0; 48 } 49 50 int offset = 0; 51 int inputByte = 0; 52 while (offset < buffer.length) { 53 inputByte = read(); 54 if (inputByte == -1) { 55 // EOF 56 break; 57 } 58 if (inputByte == '\n') { 59 if (offset == 0) { 60 // If we haven't read anything yet, ignore CRLF. 61 continue; 62 } else { 63 break; 64 } 65 } 66 67 buffer[offset++] = (byte) inputByte; 68 } 69 70 return offset; 71 } 72 } 73