aboutsummaryrefslogtreecommitdiffstats
path: root/app/src/main/java/org/connectbot/transport/Telnet.java
blob: 3ace82780d9093af1ac8bb62127c1ee51822b61e (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
/*
 * ConnectBot: simple, powerful, open-source SSH client for Android
 * Copyright 2007 Kenny Root, Jeffrey Sharkey
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.connectbot.transport;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.SocketException;
import java.net.SocketTimeoutException;
import java.net.UnknownHostException;
import java.nio.charset.Charset;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.connectbot.R;
import org.connectbot.bean.HostBean;
import org.connectbot.service.TerminalBridge;
import org.connectbot.service.TerminalManager;
import org.connectbot.util.HostDatabase;

import android.content.Context;
import android.net.Uri;
import android.util.Log;
import de.mud.telnet.TelnetProtocolHandler;

/**
 * Telnet transport implementation.<br/>
 * Original idea from the JTA telnet package (de.mud.telnet)
 *
 * @author Kenny Root
 *
 */
public class Telnet extends AbsTransport {
	private static final String TAG = "CB.Telnet";
	private static final String PROTOCOL = "telnet";

	private static final int DEFAULT_PORT = 23;

	private TelnetProtocolHandler handler;
	private Socket socket;

	private InputStream is;
	private OutputStream os;
	private int width;
	private int height;

	private boolean connected = false;

	static final Pattern hostmask;
	static {
		hostmask = Pattern.compile("^([0-9a-z.-]+)(:(\\d+))?$", Pattern.CASE_INSENSITIVE);
	}

	public Telnet() {
		handler = new TelnetProtocolHandler() {
			/** get the current terminal type */
			@Override
			public String getTerminalType() {
				return getEmulation();
			}

			/** get the current window size */
			@Override
			public int[] getWindowSize() {
				return new int[] { width, height };
			}

			/** notify about local echo */
			@Override
			public void setLocalEcho(boolean echo) {
				/* EMPTY */
			}

			/** write data to our back end */
			@Override
			public void write(byte[] b) throws IOException {
				if (os != null)
					os.write(b);
			}

			/** sent on IAC EOR (prompt terminator for remote access systems). */
			@Override
			public void notifyEndOfRecord() {
			}

			@Override
			protected String getCharsetName() {
				Charset charset = bridge.getCharset();
				if (charset != null)
					return charset.name();
				else
					return "";
			}
		};
	}

	/**
	 * @param host
	 * @param bridge
	 * @param manager
	 */
	public Telnet(HostBean host, TerminalBridge bridge, TerminalManager manager) {
		super(host, bridge, manager);
	}

	public static String getProtocolName() {
		return PROTOCOL;
	}

	private static void tryAllAddresses(Socket sock, String host, int port) throws IOException {
		InetAddress[] addresses = InetAddress.getAllByName(host);
		for (InetAddress addr : addresses) {
			try {
				sock.connect(new InetSocketAddress(addr, port));
				return;
			} catch (SocketTimeoutException e) {
			}
		}
		throw new SocketTimeoutException("Could not connect; socket timed out");
	}

	@Override
	public void connect() {
		try {
			socket = new Socket();

			tryAllAddresses(socket, host.getHostname(), host.getPort());

			connected = true;

			is = socket.getInputStream();
			os = socket.getOutputStream();

			bridge.onConnected();
		} catch (UnknownHostException e) {
			Log.d(TAG, "IO Exception connecting to host", e);
		} catch (IOException e) {
			Log.d(TAG, "IO Exception connecting to host", e);
		}
	}

	@Override
	public void close() {
		connected = false;
		if (socket != null)
			try {
				socket.close();
				socket = null;
			} catch (IOException e) {
				Log.d(TAG, "Error closing telnet socket.", e);
			}
	}

	@Override
	public void flush() throws IOException {
		os.flush();
	}

	@Override
	public int getDefaultPort() {
		return DEFAULT_PORT;
	}

	@Override
	public boolean isConnected() {
		return connected;
	}

	@Override
	public boolean isSessionOpen() {
		return connected;
	}

	@Override
	public int read(byte[] buffer, int start, int len) throws IOException {
		/* process all already read bytes */
		int n = 0;

		do {
			n = handler.negotiate(buffer, start);
			if (n > 0)
				return n;
		} while (n == 0);

		while (n <= 0) {
			do {
				n = handler.negotiate(buffer, start);
				if (n > 0)
					return n;
			} while (n == 0);
			n = is.read(buffer, start, len);
			if (n < 0) {
				bridge.dispatchDisconnect(false);
				throw new IOException("Remote end closed connection.");
			}

			handler.inputfeed(buffer, start, n);
			n = handler.negotiate(buffer, start);
		}
		return n;
	}

	@Override
	public void write(byte[] buffer) throws IOException {
		try {
			if (os != null)
				os.write(buffer);
		} catch (SocketException e) {
			bridge.dispatchDisconnect(false);
		}
	}

	@Override
	public void write(int c) throws IOException {
		try {
			if (os != null)
				os.write(c);
		} catch (SocketException e) {
			bridge.dispatchDisconnect(false);
		}
	}

	@Override
	public void setDimensions(int columns, int rows, int width, int height) {
		try {
			handler.setWindowSize(columns, rows);
		} catch (IOException e) {
			Log.e(TAG, "Couldn't resize remote terminal", e);
		}
	}

	@Override
	public String getDefaultNickname(String username, String hostname, int port) {
		if (port == DEFAULT_PORT) {
			return String.format("%s", hostname);
		} else {
			return String.format("%s:%d", hostname, port);
		}
	}

	public static Uri getUri(String input) {
		Matcher matcher = hostmask.matcher(input);

		if (!matcher.matches())
			return null;

		StringBuilder sb = new StringBuilder();

		sb.append(PROTOCOL)
			.append("://")
			.append(matcher.group(1));

		String portString = matcher.group(3);
		int port = DEFAULT_PORT;
		if (portString != null) {
			try {
				port = Integer.parseInt(portString);
				if (port < 1 || port > 65535) {
					port = DEFAULT_PORT;
				}
			} catch (NumberFormatException nfe) {
				// Keep the default port
			}
		}

		if (port != DEFAULT_PORT) {
			sb.append(':');
			sb.append(port);
		}

		sb.append("/#")
			.append(Uri.encode(input));

		Uri uri = Uri.parse(sb.toString());

		return uri;
	}

	@Override
	public HostBean createHost(Uri uri) {
		HostBean host = new HostBean();

		host.setProtocol(PROTOCOL);

		host.setHostname(uri.getHost());

		int port = uri.getPort();
		if (port < 0 || port > 65535)
			port = DEFAULT_PORT;
		host.setPort(port);

		String nickname = uri.getFragment();
		if (nickname == null || nickname.length() == 0) {
			host.setNickname(getDefaultNickname(host.getUsername(),
					host.getHostname(), host.getPort()));
		} else {
			host.setNickname(uri.getFragment());
		}

		return host;
	}

	@Override
	public void getSelectionArgs(Uri uri, Map<String, String> selection) {
		selection.put(HostDatabase.FIELD_HOST_PROTOCOL, PROTOCOL);
		selection.put(HostDatabase.FIELD_HOST_NICKNAME, uri.getFragment());
		selection.put(HostDatabase.FIELD_HOST_HOSTNAME, uri.getHost());

		int port = uri.getPort();
		if (port < 0 || port > 65535)
			port = DEFAULT_PORT;
		selection.put(HostDatabase.FIELD_HOST_PORT, Integer.toString(port));
	}

	public static String getFormatHint(Context context) {
		return String.format("%s:%s",
				context.getString(R.string.format_hostname),
				context.getString(R.string.format_port));
	}

	/* (non-Javadoc)
	 * @see org.connectbot.transport.AbsTransport#usesNetwork()
	 */
	@Override
	public boolean usesNetwork() {
		return true;
	}
}