1/*
2 * ConnectBot: simple, powerful, open-source SSH client for Android
3 * Copyright 2007 Kenny Root, Jeffrey Sharkey
4 *
5 * Licensed under the Apache License, Version 2.0 (the "License");
6 * you may not use this file except in compliance with the License.
7 * You may obtain a copy of the License at
8 *
9 *     http://www.apache.org/licenses/LICENSE-2.0
10 *
11 * Unless required by applicable law or agreed to in writing, software
12 * distributed under the License is distributed on an "AS IS" BASIS,
13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 * See the License for the specific language governing permissions and
15 * limitations under the License.
16 */
17
18package org.connectbot.transport;
19
20import com.googlecode.android_scripting.Exec;
21import com.googlecode.android_scripting.Log;
22import com.googlecode.android_scripting.Process;
23
24import java.io.FileDescriptor;
25import java.io.IOException;
26import java.io.InputStream;
27import java.io.OutputStream;
28
29public class ProcessTransport extends AbsTransport {
30
31  private FileDescriptor shellFd;
32  private final Process mProcess;
33  private InputStream is;
34  private OutputStream os;
35  private boolean mConnected = false;
36
37  public ProcessTransport(Process process) {
38    mProcess = process;
39    shellFd = process.getFd();
40    is = process.getIn();
41    os = process.getOut();
42  }
43
44  @Override
45  public void close() {
46    mProcess.kill();
47  }
48
49  @Override
50  public void connect() {
51    mConnected = true;
52  }
53
54  @Override
55  public void flush() throws IOException {
56    os.flush();
57  }
58
59  @Override
60  public boolean isConnected() {
61    return mConnected && mProcess.isAlive();
62  }
63
64  @Override
65  public boolean isSessionOpen() {
66    return mProcess.isAlive();
67  }
68
69  @Override
70  public int read(byte[] buffer, int start, int len) throws IOException {
71    if (is == null) {
72      mConnected = false;
73      bridge.dispatchDisconnect(false);
74      throw new IOException("session closed");
75    }
76    try {
77      return is.read(buffer, start, len);
78    } catch (IOException e) {
79      mConnected = false;
80      bridge.dispatchDisconnect(false);
81      throw new IOException("session closed");
82    }
83  }
84
85  @Override
86  public void setDimensions(int columns, int rows, int width, int height) {
87    try {
88      Exec.setPtyWindowSize(shellFd, rows, columns, width, height);
89    } catch (Exception e) {
90      Log.e("Couldn't resize pty", e);
91    }
92  }
93
94  @Override
95  public void write(byte[] buffer) throws IOException {
96    if (os != null) {
97      os.write(buffer);
98    }
99  }
100
101  @Override
102  public void write(int c) throws IOException {
103    if (os != null) {
104      os.write(c);
105    }
106  }
107
108}
109