Debian Codegraph @

gss/src/main/java/org/globus/gsi/gssapi/net/GssInputStream.java

raw
1 /*
2 * Copyright 1999-2010 University of Chicago
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in
5 * compliance with the License. You may obtain a copy of the License at
6 *
7 * http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software distributed under the License is
10 * distributed on an "AS IS" BASIS,WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
11 * express or implied.
12 *
13 * See the License for the specific language governing permissions and limitations under the License.
14 */
15 package org.globus.gsi.gssapi.net;
16
17 import java.io.EOFException;
18 import java.io.InputStream;
19 import java.io.IOException;
20
21 import org.globus.common.ChainedIOException;
22
23 import org.globus.gsi.gssapi.ClosedGSSException;
24 import org.ietf.jgss.GSSContext;
25 import org.ietf.jgss.GSSException;
26
27 public abstract class GssInputStream extends InputStream {
28
29 protected InputStream in;
30 protected GSSContext context;
31
32 protected byte [] buff;
33 protected int index;
34
35 public GssInputStream(InputStream in, GSSContext context) {
36 this.in = in;
37 this.context = context;
38 this.buff = new byte[0];
39 this.index = 0;
40 }
41
42 protected byte[] unwrap(byte [] msg)
43 throws IOException {
44 try {
45 return this.context.unwrap(msg, 0, msg.length, null);
46 } catch (ClosedGSSException e) {
47 throw new EOFException("Remote host terminated connection");
48 } catch (GSSException e) {
49 throw new ChainedIOException("unwrap failed", e);
50 }
51 }
52
53 protected abstract void readMsg()
54 throws IOException;
55
56 public int read(byte [] data)
57 throws IOException {
58 return read(data, 0, data.length);
59 }
60
61 public int read(byte [] data, int off, int len)
62 throws IOException {
63 if (!hasData()) {
64 return -1;
65 }
66
67 int max = (index + len > buff.length) ? buff.length - index : len;
68
69 System.arraycopy(buff, index, data, off, max);
70 index += max;
71 return max;
72 }
73
74 public int read()
75 throws IOException {
76 if (!hasData()) {
77 return -1;
78 }
79
80 return buff[index++] & 0xff;
81 }
82
83 protected boolean hasData()
84 throws IOException {
85 if (this.buff == null) {
86 return false;
87 }
88 if (this.buff.length == this.index) {
89 try {
90 readMsg();
91 } catch (EOFException e) {
92 return false;
93 }
94 }
95 if (this.buff == null) {
96 return false;
97 }
98 return (this.buff.length != this.index);
99 }
100
101 /* does not dispose of the context */
102 public void close()
103 throws IOException {
104 this.buff = null;
105 in.close();
106 }
107
108 public int available()
109 throws IOException {
110 if (this.buff == null) {
111 return -1;
112 }
113 int avail = this.buff.length - this.index;
114 return (avail == 0) ? in.available() : avail;
115 }
116
117 }