aboutsummaryrefslogtreecommitdiffstats
path: root/src/org/theb/ssh/SecureShell.java
blob: e1c5d8073d580f7175eb8c4f772a20c32082fa23 (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
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
package org.theb.ssh;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.concurrent.Semaphore;

import org.theb.provider.HostDb;

import com.trilead.ssh2.Connection;
import com.trilead.ssh2.ConnectionMonitor;
import com.trilead.ssh2.Session;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.net.ContentURI;
import android.os.Bundle;
import android.os.Handler;
import android.text.method.KeyCharacterMap;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class SecureShell extends Activity {
	private Context mContext;
	private TextView mOutput;
	private ConnectionThread mConn;
	private String mBuffer;
	private KeyCharacterMap mKMap;
	
	static final int PASSWORD_REQUEST = 0;
	
	private static final int HOSTNAME_INDEX = 1;
	private static final int USERNAME_INDEX = 2;
	private static final int PORT_INDEX = 3;
	
	private static final String[] PROJECTION = new String[] {
		HostDb.Hosts._ID, // 0
		HostDb.Hosts.HOSTNAME, // 1
		HostDb.Hosts.USERNAME, // 2
		HostDb.Hosts.PORT, // 3
	};
	
	private Cursor mCursor;
	
	// This is for the password dialog.
	Semaphore sPass;
	String mPassword = null;
	
	Connection conn;
	Session sess;
	InputStream in;
	OutputStream out;
	int x;
	int y;
		
	final Handler mHandler = new Handler();
	
	final Runnable mUpdateView = new Runnable() {
		public void run() {
			updateViewInUI();
		}
	};
	
	class ConnectionThread extends Thread {
		String hostname;
		String username;
		int port;
		
		char[][] lines;
		int posy = 0;
		int posx = 0;
		
		public ConnectionThread(String hostname, String username, int port) {
			this.hostname = hostname;
			this.username = username;
			this.port = port;
		}
		
		public void run() {
			conn = new Connection(hostname, port);

			conn.addConnectionMonitor(mConnectionMonitor);
			
			Log.d("SSH", "Starting connection attempt...");
			mBuffer =  "Attemping to connect...";
			mHandler.post(mUpdateView);

	        try {
				conn.connect(new InteractiveHostKeyVerifier());

				Log.d("SSH", "Starting authentication...");
				mBuffer =  "Attemping to authenticate...";
				mHandler.post(mUpdateView);
				
				boolean enableKeyboardInteractive = true;
				boolean enableDSA = true;
				boolean enableRSA = true;
				
				while (true) {
					/*
					if ((enableDSA || enableRSA ) &&
							mConn.isAuthMethodAvailable(username, "publickey");
							*/
					
					if (conn.isAuthMethodAvailable(username, "password")) {
						Log.d("SSH", "Trying password authentication...");
						
						// Set a semaphore that is unset by the returning dialog.
						sPass = new Semaphore(0);
						askPassword();
						
						// Wait for the user to answer.
						sPass.acquire();
						sPass = null;
						if (mPassword == null)
							continue;
						
						boolean res = conn.authenticateWithPassword(username, mPassword);
						if (res == true)
							break;
						
						continue;
					}
					
					throw new IOException("No supported authentication methods available.");
				}
				
				Log.d("SSH", "Opening session...");
				mBuffer =  "Opening session...";
				mHandler.post(mUpdateView);
				
				sess = conn.openSession();
				
		        y = (int)(mOutput.getHeight() / mOutput.getLineHeight());
		        // TODO: figure out how to get the width of monospace font characters.
		        x = y * 3;
		        Log.d("SSH", "Requesting PTY of size " + x + "x" + y);
		        
				sess.requestPTY("dumb", x, y, 0, 0, null);
				
				Log.d("SSH", "Requesting shell...");
				sess.startShell();

				out = sess.getStdin();
				in = sess.getStdout();

				mBuffer = "Welcome...";
				mHandler.post(mUpdateView);
				
			} catch (IOException e) {
				Log.e("SSH", e.getMessage());
				mConnectionMonitor.connectionLost(e);
				return;
			} catch (InterruptedException e) {
				// This thread is coming to an end. Let us exit.
				Log.e("SSH", "Connection thread interrupted.");
				return;
			}
			
			byte[] buff = new byte[8192];
			lines = new char[y][];
			
			try {
				while (true) {
					int len = in.read(buff);
					if (len == -1)
						return;
					addText(buff, len);
				}
			} catch (Exception e) {
				Log.e("SSH", "Got exception reading: " + e.getMessage());
			}
		}
		
		public void addText(byte[] data, int len) {
			for (int i = 0; i < len; i++) {
				char c = (char) (data[i] & 0xff);
			
				if (c == 8) { // Backspace, VERASE
					if (posx < 0)
						continue;
					posx--;
					continue;
				}
				if (c == '\r') {
					posx = 0;
					continue;
				}

				if (c == '\n') {
					posy++;
					if (posy >= y) {
						for (int k = 1; k < y; k++)
							lines[k - 1] = lines[k];
						
						posy--;
						lines[y - 1] = new char[x];
						
						for (int k = 0; k < x; k++)
							lines[y - 1][k] = ' ';
					}
					continue;
				}

				if (c < 32) {
					continue;
				}

				if (posx >= x) {
					posx = 0;
					posy++;
					if (posy >= y) {
						posy--;
						
						for (int k = 1; k < y; k++)
							lines[k - 1] = lines[k];
						lines[y - 1] = new char[x];
						for (int k = 0; k < x; k++)
							lines[y - 1][k] = ' ';
					}
				}

				if (lines[posy] == null) {
					lines[posy] = new char[x];
					for (int k = 0; k < x; k++)
						lines[posy][k] = ' ';
				}

				lines[posy][posx] = c;
				posx++;
			}
			
			StringBuffer sb = new StringBuffer(x * y);
			
			for (int i = 0; i < lines.length; i++) {
				if (i != 0)
					sb.append('\n');
				
				if (lines[i] != null)
					sb.append(lines[i]);
			}
			
			mBuffer = sb.toString();
			mHandler.post(mUpdateView);
		}
	}
	
    @Override
    public void onCreate(Bundle savedValues) {
        super.onCreate(savedValues);
        
        mContext = this;
        
        setContentView(R.layout.secure_shell);
        
        Log.d("SSH", "using URI " + getIntent().getData().toString());
        
        mCursor = managedQuery(getIntent().getData(), PROJECTION, null, null);
        mCursor.first();
        
        mOutput  = (TextView) findViewById(R.id.output);
        
        mKMap = KeyCharacterMap.load(KeyCharacterMap.BUILT_IN_KEYBOARD);
                
        mConn = new ConnectionThread(
        		mCursor.getString(HOSTNAME_INDEX),
        		mCursor.getString(USERNAME_INDEX),
        		mCursor.getInt(PORT_INDEX));
        
        Log.d("SSH", "Starting new ConnectionThread");
        mConn.start();
    }
    
    public String askPassword() {
    	Intent intent = new Intent(this, PasswordDialog.class);
    	this.startSubActivity(intent, PASSWORD_REQUEST);
    	return null;
	}

    @Override
    protected void onActivityResult(int requestCode, int resultCode,
            String data, Bundle extras)
	{
	    if (requestCode == PASSWORD_REQUEST) {
	
	        // If the request was cancelled, then we didn't get anything.
	        if (resultCode == RESULT_CANCELED) {
	            return;
	
	        // Otherwise, there now should be a password ready for us.
	        } else {
	            mPassword = data;
	            sPass.release();
	        }
	    }
	}
    
	@Override
    public void onDestroy() {
    	super.onDestroy();
    	
    	if (sess != null) {
    		sess.close();
    		sess = null;
    	}
    	
    	if (conn != null) {
    		conn.close();
    		conn = null;
    	}
    	
    	finish();
    }
    
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent msg) {
    	if (out != null) {
	    	int c = mKMap.get(keyCode, msg.getMetaState());
	    	try {
				out.write(c);
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
    	}
    	
    	return super.onKeyDown(keyCode, msg);
    }
    
    public void updateViewInUI() {
    	mOutput.setText(mBuffer);
    }

    final ConnectionMonitor mConnectionMonitor = new ConnectionMonitor() {
    	public void connectionLost(Throwable reason) {
    		Log.d("SSH", "Connection ended.");
    		Dialog d = new Dialog(mContext);
    		d.setTitle("Connection Lost");
    		d.setContentView(R.layout.message_dialog);
    		
    		TextView msg = (TextView) d.findViewById(R.id.message);
    		msg.setText(reason.getMessage());
    		
    		Button b = (Button) d.findViewById(R.id.dismiss);
    		b.setOnClickListener(new OnClickListener() {
				public void onClick(View v) {
					// TODO Auto-generated method stub
					finish();
				}
    		});
    		d.show();
    		finish();
    	}
    };
}