1 package kawa; import java.io.*; 3 4 9 10 public class TelnetInputStream extends FilterInputStream 11 { 12 Telnet connection; 13 14 public TelnetInputStream (InputStream in, Telnet conn) 15 throws IOException 16 { 17 super(in); 18 buf = new byte[512]; 19 this.connection = conn; 20 } 21 22 protected byte[] buf; 23 24 int pos; 25 int count; 26 27 28 int state = 0; 29 30 int subCommandLength = 0; 31 32 static final int SB_IAC = 400; 33 34 public int read () throws IOException 35 { 36 for (;;) 37 { 38 if (pos >= count) 39 { 40 int avail = in.available(); 41 if (avail <= 0) 42 avail = 1; 43 else if (avail > buf.length - subCommandLength) 44 { 45 avail = buf.length - subCommandLength; } 47 avail = in.read(buf, subCommandLength, avail); 48 pos = subCommandLength; 49 count = avail; 50 if (avail <= 0) 51 return -1; 52 } 53 int ch = buf[pos++] & 0xff; 54 if (state == 0) 55 { 56 if (ch != Telnet.IAC) 57 return ch; 58 state = Telnet.IAC; 59 continue; 60 } 61 else if (state == Telnet.IAC) 62 { 63 if (ch == Telnet.IAC) 64 { 65 state = 0; 66 return Telnet.IAC; 67 } 68 else if (ch == Telnet.WILL 69 || ch == Telnet.WONT 70 || ch == Telnet.DO 71 || ch == Telnet.DONT 72 || ch == Telnet.SB) 73 { 74 state = ch; 75 } 76 else if (ch == Telnet.IP) 77 { 78 System.err.println("Interrupt Process"); 79 state = 0; 80 } 81 else if (ch == Telnet.EOF) 82 { 83 return -1; 84 } 85 else 86 { 87 state = 0; } 89 } 90 else if (state == Telnet.WILL || state == Telnet.WONT 91 || state == Telnet.DO || state == Telnet.DONT) 92 { 93 connection.handle (state, ch); 94 state = 0; 95 } 96 else if (state == Telnet.SB) 97 { 98 if (ch == Telnet.IAC) 99 state = SB_IAC; 100 else 101 buf[subCommandLength++] = (byte) ch; 102 } 103 else if (state == SB_IAC) 104 { 105 if (ch == Telnet.IAC) 106 { 107 buf[subCommandLength++] = (byte) ch; 108 state = Telnet.SB; 109 } 110 else if (ch == Telnet.SE) 111 { 112 connection.subCommand(buf, 0, subCommandLength); 113 state = 0; 114 subCommandLength = 0; 115 } 116 else { 118 state = 0; 119 subCommandLength = 0; 120 } 121 } 122 else 123 System.err.println("Bad state "+state); 124 } 125 } 126 127 public int read (byte[] b, int offset, int length) throws IOException 128 { 129 if (length <= 0) 130 return 0; 131 int done = 0; 132 if (state != 0 || pos >= count) 133 { 134 int ch = read(); 135 if (ch < 0) 136 return ch; 137 b[offset++] = (byte) ch; 138 done++; 139 } 140 if (state == 0) 141 { 142 while (pos < count && done < length) 143 { 144 byte ch = buf[pos]; 145 if (ch == (byte) Telnet.IAC) 146 break; 147 b[offset++] = ch; 148 done++; 149 pos++; 150 } 151 } 152 return done; 153 } 154 } 155 | Popular Tags |