1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18 package org.apache.commons.net.telnet;
19
20 import java.io.IOException;
21 import java.io.OutputStream;
22
23
24
25
26
27
28
29
30
31
32
33 final class TelnetOutputStream extends OutputStream {
34 private static final boolean CONVERT_TO_CRLF = true;
35 private final TelnetClient client;
36
37 private boolean lastWasCR;
38
39 TelnetOutputStream(final TelnetClient client) {
40 this.client = client;
41 }
42
43
44 @Override
45 public void close() throws IOException {
46 client.closeOutputStream();
47 }
48
49
50 @Override
51 public void flush() throws IOException {
52 client.flushOutputStream();
53 }
54
55
56
57
58
59
60
61 @Override
62 public void write(final byte buffer[]) throws IOException {
63 write(buffer, 0, buffer.length);
64 }
65
66
67
68
69
70
71
72
73
74 @Override
75 public void write(final byte buffer[], int offset, int length) throws IOException {
76 synchronized (client) {
77 while (length-- > 0) {
78 write(buffer[offset++]);
79 }
80 }
81 }
82
83
84
85
86
87
88
89 @Override
90 public void write(int ch) throws IOException {
91
92 synchronized (client) {
93 ch &= 0xff;
94
95
96 if (client.requestedWont(TelnetOption.BINARY)) {
97 if (lastWasCR) {
98 if (CONVERT_TO_CRLF) {
99 client.sendByte('\n');
100 if (ch == '\n') {
101
102 lastWasCR = false;
103 return;
104 }
105 } else if (ch != '\n') {
106
107 client.sendByte(Telnet.NUL);
108 }
109 }
110
111 switch (ch) {
112 case '\r':
113 client.sendByte('\r');
114 lastWasCR = true;
115 break;
116 case '\n':
117 if (!lastWasCR) {
118 client.sendByte('\r');
119 }
120 client.sendByte(ch);
121 lastWasCR = false;
122 break;
123 case TelnetCommand.IAC:
124 client.sendByte(TelnetCommand.IAC);
125 client.sendByte(TelnetCommand.IAC);
126 lastWasCR = false;
127 break;
128 default:
129 client.sendByte(ch);
130 lastWasCR = false;
131 break;
132 }
133
134 } else if (ch == TelnetCommand.IAC) {
135 client.sendByte(ch);
136 client.sendByte(TelnetCommand.IAC);
137 } else {
138 client.sendByte(ch);
139 }
140 }
141 }
142 }