code
stringlengths 3
1.18M
| language
stringclasses 1
value |
|---|---|
/*
* 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.util;
/**
* @author Kenny Root
*
*/
public class Colors {
public final static Integer[] defaults = new Integer[] {
0xff000000, // black
0xffcc0000, // red
0xff00cc00, // green
0xffcccc00, // brown
0xff0000cc, // blue
0xffcc00cc, // purple
0xff00cccc, // cyan
0xffcccccc, // light grey
0xff444444, // dark grey
0xffff4444, // light red
0xff44ff44, // light green
0xffffff44, // yellow
0xff4444ff, // light blue
0xffff44ff, // light purple
0xff44ffff, // light cyan
0xffffffff, // white
0xff000000, 0xff00005f, 0xff000087, 0xff0000af, 0xff0000d7,
0xff0000ff, 0xff005f00, 0xff005f5f, 0xff005f87, 0xff005faf,
0xff005fd7, 0xff005fff, 0xff008700, 0xff00875f, 0xff008787,
0xff0087af, 0xff0087d7, 0xff0087ff, 0xff00af00, 0xff00af5f,
0xff00af87, 0xff00afaf, 0xff00afd7, 0xff00afff, 0xff00d700,
0xff00d75f, 0xff00d787, 0xff00d7af, 0xff00d7d7, 0xff00d7ff,
0xff00ff00, 0xff00ff5f, 0xff00ff87, 0xff00ffaf, 0xff00ffd7,
0xff00ffff, 0xff5f0000, 0xff5f005f, 0xff5f0087, 0xff5f00af,
0xff5f00d7, 0xff5f00ff, 0xff5f5f00, 0xff5f5f5f, 0xff5f5f87,
0xff5f5faf, 0xff5f5fd7, 0xff5f5fff, 0xff5f8700, 0xff5f875f,
0xff5f8787, 0xff5f87af, 0xff5f87d7, 0xff5f87ff, 0xff5faf00,
0xff5faf5f, 0xff5faf87, 0xff5fafaf, 0xff5fafd7, 0xff5fafff,
0xff5fd700, 0xff5fd75f, 0xff5fd787, 0xff5fd7af, 0xff5fd7d7,
0xff5fd7ff, 0xff5fff00, 0xff5fff5f, 0xff5fff87, 0xff5fffaf,
0xff5fffd7, 0xff5fffff, 0xff870000, 0xff87005f, 0xff870087,
0xff8700af, 0xff8700d7, 0xff8700ff, 0xff875f00, 0xff875f5f,
0xff875f87, 0xff875faf, 0xff875fd7, 0xff875fff, 0xff878700,
0xff87875f, 0xff878787, 0xff8787af, 0xff8787d7, 0xff8787ff,
0xff87af00, 0xff87af5f, 0xff87af87, 0xff87afaf, 0xff87afd7,
0xff87afff, 0xff87d700, 0xff87d75f, 0xff87d787, 0xff87d7af,
0xff87d7d7, 0xff87d7ff, 0xff87ff00, 0xff87ff5f, 0xff87ff87,
0xff87ffaf, 0xff87ffd7, 0xff87ffff, 0xffaf0000, 0xffaf005f,
0xffaf0087, 0xffaf00af, 0xffaf00d7, 0xffaf00ff, 0xffaf5f00,
0xffaf5f5f, 0xffaf5f87, 0xffaf5faf, 0xffaf5fd7, 0xffaf5fff,
0xffaf8700, 0xffaf875f, 0xffaf8787, 0xffaf87af, 0xffaf87d7,
0xffaf87ff, 0xffafaf00, 0xffafaf5f, 0xffafaf87, 0xffafafaf,
0xffafafd7, 0xffafafff, 0xffafd700, 0xffafd75f, 0xffafd787,
0xffafd7af, 0xffafd7d7, 0xffafd7ff, 0xffafff00, 0xffafff5f,
0xffafff87, 0xffafffaf, 0xffafffd7, 0xffafffff, 0xffd70000,
0xffd7005f, 0xffd70087, 0xffd700af, 0xffd700d7, 0xffd700ff,
0xffd75f00, 0xffd75f5f, 0xffd75f87, 0xffd75faf, 0xffd75fd7,
0xffd75fff, 0xffd78700, 0xffd7875f, 0xffd78787, 0xffd787af,
0xffd787d7, 0xffd787ff, 0xffd7af00, 0xffd7af5f, 0xffd7af87,
0xffd7afaf, 0xffd7afd7, 0xffd7afff, 0xffd7d700, 0xffd7d75f,
0xffd7d787, 0xffd7d7af, 0xffd7d7d7, 0xffd7d7ff, 0xffd7ff00,
0xffd7ff5f, 0xffd7ff87, 0xffd7ffaf, 0xffd7ffd7, 0xffd7ffff,
0xffff0000, 0xffff005f, 0xffff0087, 0xffff00af, 0xffff00d7,
0xffff00ff, 0xffff5f00, 0xffff5f5f, 0xffff5f87, 0xffff5faf,
0xffff5fd7, 0xffff5fff, 0xffff8700, 0xffff875f, 0xffff8787,
0xffff87af, 0xffff87d7, 0xffff87ff, 0xffffaf00, 0xffffaf5f,
0xffffaf87, 0xffffafaf, 0xffffafd7, 0xffffafff, 0xffffd700,
0xffffd75f, 0xffffd787, 0xffffd7af, 0xffffd7d7, 0xffffd7ff,
0xffffff00, 0xffffff5f, 0xffffff87, 0xffffffaf, 0xffffffd7,
0xffffffff, 0xff080808, 0xff121212, 0xff1c1c1c, 0xff262626,
0xff303030, 0xff3a3a3a, 0xff444444, 0xff4e4e4e, 0xff585858,
0xff626262, 0xff6c6c6c, 0xff767676, 0xff808080, 0xff8a8a8a,
0xff949494, 0xff9e9e9e, 0xffa8a8a8, 0xffb2b2b2, 0xffbcbcbc,
0xffc6c6c6, 0xffd0d0d0, 0xffdadada, 0xffe4e4e4, 0xffeeeeee,
};
}
|
Java
|
/*
* 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.util;
import java.io.IOException;
import java.math.BigInteger;
import java.security.AlgorithmParameters;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.Key;
import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.SecureRandom;
import java.security.interfaces.DSAParams;
import java.security.interfaces.DSAPrivateKey;
import java.security.interfaces.DSAPublicKey;
import java.security.interfaces.RSAPrivateCrtKey;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.DSAPublicKeySpec;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.InvalidParameterSpecException;
import java.security.spec.KeySpec;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.RSAPublicKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.Arrays;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.EncryptedPrivateKeyInfo;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.PBEKeySpec;
import javax.crypto.spec.PBEParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import android.util.Log;
import com.trilead.ssh2.crypto.Base64;
import com.trilead.ssh2.signature.DSASHA1Verify;
import com.trilead.ssh2.signature.RSASHA1Verify;
public class PubkeyUtils {
public static final String PKCS8_START = "-----BEGIN PRIVATE KEY-----";
public static final String PKCS8_END = "-----END PRIVATE KEY-----";
// Size in bytes of salt to use.
private static final int SALT_SIZE = 8;
// Number of iterations for password hashing. PKCS#5 recommends 1000
private static final int ITERATIONS = 1000;
public static String formatKey(Key key){
String algo = key.getAlgorithm();
String fmt = key.getFormat();
byte[] encoded = key.getEncoded();
return "Key[algorithm=" + algo + ", format=" + fmt +
", bytes=" + encoded.length + "]";
}
public static byte[] sha256(byte[] data) throws NoSuchAlgorithmException {
return MessageDigest.getInstance("SHA-256").digest(data);
}
public static byte[] cipher(int mode, byte[] data, byte[] secret) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException {
SecretKeySpec secretKeySpec = new SecretKeySpec(sha256(secret), "AES");
Cipher c = Cipher.getInstance("AES");
c.init(mode, secretKeySpec);
return c.doFinal(data);
}
public static byte[] encrypt(byte[] cleartext, String secret) throws Exception {
byte[] salt = new byte[SALT_SIZE];
byte[] ciphertext = Encryptor.encrypt(salt, ITERATIONS, secret, cleartext);
byte[] complete = new byte[salt.length + ciphertext.length];
System.arraycopy(salt, 0, complete, 0, salt.length);
System.arraycopy(ciphertext, 0, complete, salt.length, ciphertext.length);
Arrays.fill(salt, (byte) 0x00);
Arrays.fill(ciphertext, (byte) 0x00);
return complete;
}
public static byte[] decrypt(byte[] complete, String secret) throws Exception {
try {
byte[] salt = new byte[SALT_SIZE];
byte[] ciphertext = new byte[complete.length - salt.length];
System.arraycopy(complete, 0, salt, 0, salt.length);
System.arraycopy(complete, salt.length, ciphertext, 0, ciphertext.length);
return Encryptor.decrypt(salt, ITERATIONS, secret, ciphertext);
} catch (Exception e) {
Log.d("decrypt", "Could not decrypt with new method", e);
// We might be using the old encryption method.
return cipher(Cipher.DECRYPT_MODE, complete, secret.getBytes());
}
}
public static byte[] getEncodedPublic(PublicKey pk) {
return new X509EncodedKeySpec(pk.getEncoded()).getEncoded();
}
public static byte[] getEncodedPrivate(PrivateKey pk) {
return new PKCS8EncodedKeySpec(pk.getEncoded()).getEncoded();
}
public static byte[] getEncodedPrivate(PrivateKey pk, String secret) throws Exception {
if (secret.length() > 0)
return encrypt(getEncodedPrivate(pk), secret);
else
return getEncodedPrivate(pk);
}
public static PrivateKey decodePrivate(byte[] encoded, String keyType) throws NoSuchAlgorithmException, InvalidKeySpecException {
PKCS8EncodedKeySpec privKeySpec = new PKCS8EncodedKeySpec(encoded);
KeyFactory kf = KeyFactory.getInstance(keyType);
return kf.generatePrivate(privKeySpec);
}
public static PrivateKey decodePrivate(byte[] encoded, String keyType, String secret) throws Exception {
if (secret != null && secret.length() > 0)
return decodePrivate(decrypt(encoded, secret), keyType);
else
return decodePrivate(encoded, keyType);
}
public static PublicKey decodePublic(byte[] encoded, String keyType) throws NoSuchAlgorithmException, InvalidKeySpecException {
X509EncodedKeySpec pubKeySpec = new X509EncodedKeySpec(encoded);
KeyFactory kf = KeyFactory.getInstance(keyType);
return kf.generatePublic(pubKeySpec);
}
public static KeyPair recoverKeyPair(byte[] encoded) throws NoSuchAlgorithmException, InvalidKeySpecException {
KeySpec privKeySpec = new PKCS8EncodedKeySpec(encoded);
KeySpec pubKeySpec;
PrivateKey priv;
PublicKey pub;
KeyFactory kf;
try {
kf = KeyFactory.getInstance(PubkeyDatabase.KEY_TYPE_RSA);
priv = kf.generatePrivate(privKeySpec);
pubKeySpec = new RSAPublicKeySpec(((RSAPrivateCrtKey) priv)
.getModulus(), ((RSAPrivateCrtKey) priv)
.getPublicExponent());
pub = kf.generatePublic(pubKeySpec);
} catch (ClassCastException e) {
kf = KeyFactory.getInstance(PubkeyDatabase.KEY_TYPE_DSA);
priv = kf.generatePrivate(privKeySpec);
DSAParams params = ((DSAPrivateKey) priv).getParams();
// Calculate public key Y
BigInteger y = params.getG().modPow(((DSAPrivateKey) priv).getX(),
params.getP());
pubKeySpec = new DSAPublicKeySpec(y, params.getP(), params.getQ(),
params.getG());
pub = kf.generatePublic(pubKeySpec);
}
return new KeyPair(pub, priv);
}
/*
* Trilead compatibility methods
*/
public static Object convertToTrilead(PublicKey pk) {
if (pk instanceof RSAPublicKey) {
return new com.trilead.ssh2.signature.RSAPublicKey(
((RSAPublicKey) pk).getPublicExponent(),
((RSAPublicKey) pk).getModulus());
} else if (pk instanceof DSAPublicKey) {
DSAParams dp = ((DSAPublicKey) pk).getParams();
return new com.trilead.ssh2.signature.DSAPublicKey(
dp.getP(), dp.getQ(), dp.getG(), ((DSAPublicKey) pk).getY());
}
throw new IllegalArgumentException("PublicKey is not RSA or DSA format");
}
public static Object convertToTrilead(PrivateKey priv, PublicKey pub) {
if (priv instanceof RSAPrivateKey) {
return new com.trilead.ssh2.signature.RSAPrivateKey(
((RSAPrivateKey) priv).getPrivateExponent(),
((RSAPublicKey) pub).getPublicExponent(),
((RSAPrivateKey) priv).getModulus());
} else if (priv instanceof DSAPrivateKey) {
DSAParams dp = ((DSAPrivateKey) priv).getParams();
return new com.trilead.ssh2.signature.DSAPrivateKey(
dp.getP(), dp.getQ(), dp.getG(), ((DSAPublicKey) pub).getY(),
((DSAPrivateKey) priv).getX());
}
throw new IllegalArgumentException("Key is not RSA or DSA format");
}
/*
* OpenSSH compatibility methods
*/
public static String convertToOpenSSHFormat(PublicKey pk, String origNickname) throws IOException, InvalidKeyException {
String nickname = origNickname;
if (nickname == null)
nickname = "connectbot@android";
if (pk instanceof RSAPublicKey) {
String data = "ssh-rsa ";
data += String.valueOf(Base64.encode(RSASHA1Verify.encodeSSHRSAPublicKey(
(com.trilead.ssh2.signature.RSAPublicKey)convertToTrilead(pk))));
return data + " " + nickname;
} else if (pk instanceof DSAPublicKey) {
String data = "ssh-dss ";
data += String.valueOf(Base64.encode(DSASHA1Verify.encodeSSHDSAPublicKey(
(com.trilead.ssh2.signature.DSAPublicKey)convertToTrilead(pk))));
return data + " " + nickname;
}
throw new InvalidKeyException("Unknown key type");
}
/*
* OpenSSH compatibility methods
*/
/**
* @param trileadKey
* @return OpenSSH-encoded pubkey
*/
public static byte[] extractOpenSSHPublic(Object trileadKey) {
try {
if (trileadKey instanceof com.trilead.ssh2.signature.RSAPrivateKey)
return RSASHA1Verify.encodeSSHRSAPublicKey(
((com.trilead.ssh2.signature.RSAPrivateKey) trileadKey).getPublicKey());
else if (trileadKey instanceof com.trilead.ssh2.signature.DSAPrivateKey)
return DSASHA1Verify.encodeSSHDSAPublicKey(
((com.trilead.ssh2.signature.DSAPrivateKey) trileadKey).getPublicKey());
else
return null;
} catch (IOException e) {
return null;
}
}
public static String exportPEM(PrivateKey key, String secret) throws NoSuchAlgorithmException, InvalidParameterSpecException, NoSuchPaddingException, InvalidKeyException, InvalidAlgorithmParameterException, InvalidKeySpecException, IllegalBlockSizeException, IOException {
StringBuilder sb = new StringBuilder();
byte[] data = key.getEncoded();
sb.append(PKCS8_START);
sb.append('\n');
if (secret != null) {
byte[] salt = new byte[8];
SecureRandom random = new SecureRandom();
random.nextBytes(salt);
PBEParameterSpec defParams = new PBEParameterSpec(salt, 1);
AlgorithmParameters params = AlgorithmParameters.getInstance(key.getAlgorithm());
params.init(defParams);
PBEKeySpec pbeSpec = new PBEKeySpec(secret.toCharArray());
SecretKeyFactory keyFact = SecretKeyFactory.getInstance(key.getAlgorithm());
Cipher cipher = Cipher.getInstance(key.getAlgorithm());
cipher.init(Cipher.WRAP_MODE, keyFact.generateSecret(pbeSpec), params);
byte[] wrappedKey = cipher.wrap(key);
EncryptedPrivateKeyInfo pinfo = new EncryptedPrivateKeyInfo(params, wrappedKey);
data = pinfo.getEncoded();
sb.append("Proc-Type: 4,ENCRYPTED\n");
sb.append("DEK-Info: DES-EDE3-CBC,");
sb.append(encodeHex(salt));
sb.append("\n\n");
}
int i = sb.length();
sb.append(Base64.encode(data));
for (i += 63; i < sb.length(); i += 64) {
sb.insert(i, "\n");
}
sb.append('\n');
sb.append(PKCS8_END);
sb.append('\n');
return sb.toString();
}
private static final char[] HEX_DIGITS = { '0', '1', '2', '3', '4', '5', '6',
'7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
protected static String encodeHex(byte[] bytes) {
final char[] hex = new char[bytes.length * 2];
int i = 0;
for (byte b : bytes) {
hex[i++] = HEX_DIGITS[(b >> 4) & 0x0f];
hex[i++] = HEX_DIGITS[b & 0x0f];
}
return String.valueOf(hex);
}
}
|
Java
|
/*
* 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.util;
import org.connectbot.R;
import android.app.Dialog;
import android.content.Context;
import android.view.View;
public class EntropyDialog extends Dialog implements OnEntropyGatheredListener {
public EntropyDialog(Context context) {
super(context);
this.setContentView(R.layout.dia_gatherentropy);
this.setTitle(R.string.pubkey_gather_entropy);
((EntropyView) findViewById(R.id.entropy)).addOnEntropyGatheredListener(this);
}
public EntropyDialog(Context context, View view) {
super(context);
this.setContentView(view);
this.setTitle(R.string.pubkey_gather_entropy);
((EntropyView) findViewById(R.id.entropy)).addOnEntropyGatheredListener(this);
}
public void onEntropyGathered(byte[] entropy) {
this.dismiss();
}
}
|
Java
|
/*
* 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.util;
import java.util.LinkedList;
import java.util.List;
import org.connectbot.bean.PubkeyBean;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
/**
* Public Key Encryption database. Contains private and public key pairs
* for public key authentication.
*
* @author Kenny Root
*/
public class PubkeyDatabase extends RobustSQLiteOpenHelper {
public final static String TAG = "ConnectBot.PubkeyDatabase";
public final static String DB_NAME = "pubkeys";
public final static int DB_VERSION = 2;
public final static String TABLE_PUBKEYS = "pubkeys";
public final static String FIELD_PUBKEY_NICKNAME = "nickname";
public final static String FIELD_PUBKEY_TYPE = "type";
public final static String FIELD_PUBKEY_PRIVATE = "private";
public final static String FIELD_PUBKEY_PUBLIC = "public";
public final static String FIELD_PUBKEY_ENCRYPTED = "encrypted";
public final static String FIELD_PUBKEY_STARTUP = "startup";
public final static String FIELD_PUBKEY_CONFIRMUSE = "confirmuse";
public final static String FIELD_PUBKEY_LIFETIME = "lifetime";
public final static String KEY_TYPE_RSA = "RSA",
KEY_TYPE_DSA = "DSA",
KEY_TYPE_IMPORTED = "IMPORTED";
private Context context;
static {
addTableName(TABLE_PUBKEYS);
}
public PubkeyDatabase(Context context) {
super(context, DB_NAME, null, DB_VERSION);
this.context = context;
}
@Override
public void onCreate(SQLiteDatabase db) {
super.onCreate(db);
db.execSQL("CREATE TABLE " + TABLE_PUBKEYS
+ " (_id INTEGER PRIMARY KEY, "
+ FIELD_PUBKEY_NICKNAME + " TEXT, "
+ FIELD_PUBKEY_TYPE + " TEXT, "
+ FIELD_PUBKEY_PRIVATE + " BLOB, "
+ FIELD_PUBKEY_PUBLIC + " BLOB, "
+ FIELD_PUBKEY_ENCRYPTED + " INTEGER, "
+ FIELD_PUBKEY_STARTUP + " INTEGER, "
+ FIELD_PUBKEY_CONFIRMUSE + " INTEGER DEFAULT 0, "
+ FIELD_PUBKEY_LIFETIME + " INTEGER DEFAULT 0)");
}
@Override
public void onRobustUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) throws SQLiteException {
switch (oldVersion) {
case 1:
db.execSQL("ALTER TABLE " + TABLE_PUBKEYS
+ " ADD COLUMN " + FIELD_PUBKEY_CONFIRMUSE + " INTEGER DEFAULT 0");
db.execSQL("ALTER TABLE " + TABLE_PUBKEYS
+ " ADD COLUMN " + FIELD_PUBKEY_LIFETIME + " INTEGER DEFAULT 0");
}
}
/**
* Delete a specific host by its <code>_id</code> value.
*/
public void deletePubkey(PubkeyBean pubkey) {
HostDatabase hostdb = new HostDatabase(context);
hostdb.stopUsingPubkey(pubkey.getId());
hostdb.close();
SQLiteDatabase db = getWritableDatabase();
db.delete(TABLE_PUBKEYS, "_id = ?", new String[] { Long.toString(pubkey.getId()) });
db.close();
}
/**
* Return a cursor that contains information about all known hosts.
*/
/*
public Cursor allPubkeys() {
SQLiteDatabase db = this.getReadableDatabase();
return db.query(TABLE_PUBKEYS, new String[] { "_id",
FIELD_PUBKEY_NICKNAME, FIELD_PUBKEY_TYPE, FIELD_PUBKEY_PRIVATE,
FIELD_PUBKEY_PUBLIC, FIELD_PUBKEY_ENCRYPTED, FIELD_PUBKEY_STARTUP },
null, null, null, null, null);
}*/
public List<PubkeyBean> allPubkeys() {
return getPubkeys(null, null);
}
public List<PubkeyBean> getAllStartPubkeys() {
return getPubkeys(FIELD_PUBKEY_STARTUP + " = 1 AND " + FIELD_PUBKEY_ENCRYPTED + " = 0", null);
}
private List<PubkeyBean> getPubkeys(String selection, String[] selectionArgs) {
SQLiteDatabase db = getReadableDatabase();
List<PubkeyBean> pubkeys = new LinkedList<PubkeyBean>();
Cursor c = db.query(TABLE_PUBKEYS, null, selection, selectionArgs, null, null, null);
if (c != null) {
final int COL_ID = c.getColumnIndexOrThrow("_id"),
COL_NICKNAME = c.getColumnIndexOrThrow(FIELD_PUBKEY_NICKNAME),
COL_TYPE = c.getColumnIndexOrThrow(FIELD_PUBKEY_TYPE),
COL_PRIVATE = c.getColumnIndexOrThrow(FIELD_PUBKEY_PRIVATE),
COL_PUBLIC = c.getColumnIndexOrThrow(FIELD_PUBKEY_PUBLIC),
COL_ENCRYPTED = c.getColumnIndexOrThrow(FIELD_PUBKEY_ENCRYPTED),
COL_STARTUP = c.getColumnIndexOrThrow(FIELD_PUBKEY_STARTUP),
COL_CONFIRMUSE = c.getColumnIndexOrThrow(FIELD_PUBKEY_CONFIRMUSE),
COL_LIFETIME = c.getColumnIndexOrThrow(FIELD_PUBKEY_LIFETIME);
while (c.moveToNext()) {
PubkeyBean pubkey = new PubkeyBean();
pubkey.setId(c.getLong(COL_ID));
pubkey.setNickname(c.getString(COL_NICKNAME));
pubkey.setType(c.getString(COL_TYPE));
pubkey.setPrivateKey(c.getBlob(COL_PRIVATE));
pubkey.setPublicKey(c.getBlob(COL_PUBLIC));
pubkey.setEncrypted(c.getInt(COL_ENCRYPTED) > 0);
pubkey.setStartup(c.getInt(COL_STARTUP) > 0);
pubkey.setConfirmUse(c.getInt(COL_CONFIRMUSE) > 0);
pubkey.setLifetime(c.getInt(COL_LIFETIME));
pubkeys.add(pubkey);
}
c.close();
}
db.close();
return pubkeys;
}
/**
* @param hostId
* @return
*/
public PubkeyBean findPubkeyById(long pubkeyId) {
SQLiteDatabase db = getReadableDatabase();
Cursor c = db.query(TABLE_PUBKEYS, null,
"_id = ?", new String[] { String.valueOf(pubkeyId) },
null, null, null);
PubkeyBean pubkey = null;
if (c != null) {
if (c.moveToFirst())
pubkey = createPubkeyBean(c);
c.close();
}
db.close();
return pubkey;
}
private PubkeyBean createPubkeyBean(Cursor c) {
PubkeyBean pubkey = new PubkeyBean();
pubkey.setId(c.getLong(c.getColumnIndexOrThrow("_id")));
pubkey.setNickname(c.getString(c.getColumnIndexOrThrow(FIELD_PUBKEY_NICKNAME)));
pubkey.setType(c.getString(c.getColumnIndexOrThrow(FIELD_PUBKEY_TYPE)));
pubkey.setPrivateKey(c.getBlob(c.getColumnIndexOrThrow(FIELD_PUBKEY_PRIVATE)));
pubkey.setPublicKey(c.getBlob(c.getColumnIndexOrThrow(FIELD_PUBKEY_PUBLIC)));
pubkey.setEncrypted(c.getInt(c.getColumnIndexOrThrow(FIELD_PUBKEY_ENCRYPTED)) > 0);
pubkey.setStartup(c.getInt(c.getColumnIndexOrThrow(FIELD_PUBKEY_STARTUP)) > 0);
pubkey.setConfirmUse(c.getInt(c.getColumnIndexOrThrow(FIELD_PUBKEY_CONFIRMUSE)) > 0);
pubkey.setLifetime(c.getInt(c.getColumnIndexOrThrow(FIELD_PUBKEY_LIFETIME)));
return pubkey;
}
/**
* Pull all values for a given column as a list of Strings, probably for use
* in a ListPreference. Sorted by <code>_id</code> ascending.
*/
public List<CharSequence> allValues(String column) {
List<CharSequence> list = new LinkedList<CharSequence>();
SQLiteDatabase db = this.getReadableDatabase();
Cursor c = db.query(TABLE_PUBKEYS, new String[] { "_id", column },
null, null, null, null, "_id ASC");
if (c != null) {
int COL = c.getColumnIndexOrThrow(column);
while (c.moveToNext())
list.add(c.getString(COL));
c.close();
}
db.close();
return list;
}
public String getNickname(long id) {
String nickname = null;
SQLiteDatabase db = this.getReadableDatabase();
Cursor c = db.query(TABLE_PUBKEYS, new String[] { "_id",
FIELD_PUBKEY_NICKNAME }, "_id = ?",
new String[] { Long.toString(id) }, null, null, null);
if (c != null) {
if (c.moveToFirst())
nickname = c.getString(c.getColumnIndexOrThrow(FIELD_PUBKEY_NICKNAME));
c.close();
}
db.close();
return nickname;
}
/*
public void setOnStart(long id, boolean onStart) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(FIELD_PUBKEY_STARTUP, onStart ? 1 : 0);
db.update(TABLE_PUBKEYS, values, "_id = ?", new String[] { Long.toString(id) });
}
public boolean changePassword(long id, String oldPassword, String newPassword) throws NoSuchAlgorithmException, NoSuchPaddingException, IllegalBlockSizeException, InvalidKeyException, BadPaddingException {
SQLiteDatabase db = this.getWritableDatabase();
Cursor c = db.query(TABLE_PUBKEYS, new String[] { FIELD_PUBKEY_TYPE,
FIELD_PUBKEY_PRIVATE, FIELD_PUBKEY_ENCRYPTED },
"_id = ?", new String[] { String.valueOf(id) },
null, null, null);
if (!c.moveToFirst())
return false;
String keyType = c.getString(0);
byte[] encPriv = c.getBlob(1);
c.close();
PrivateKey priv;
try {
priv = PubkeyUtils.decodePrivate(encPriv, keyType, oldPassword);
} catch (InvalidKeyException e) {
return false;
} catch (BadPaddingException e) {
return false;
} catch (InvalidKeySpecException e) {
return false;
}
ContentValues values = new ContentValues();
values.put(FIELD_PUBKEY_PRIVATE, PubkeyUtils.getEncodedPrivate(priv, newPassword));
values.put(FIELD_PUBKEY_ENCRYPTED, newPassword.length() > 0 ? 1 : 0);
db.update(TABLE_PUBKEYS, values, "_id = ?", new String[] { String.valueOf(id) });
return true;
}
*/
/**
* @param pubkey
*/
public PubkeyBean savePubkey(PubkeyBean pubkey) {
SQLiteDatabase db = this.getWritableDatabase();
boolean success = false;
ContentValues values = pubkey.getValues();
if (pubkey.getId() > 0) {
values.remove("_id");
if (db.update(TABLE_PUBKEYS, values, "_id = ?", new String[] { String.valueOf(pubkey.getId()) }) > 0)
success = true;
}
if (!success) {
long id = db.insert(TABLE_PUBKEYS, null, pubkey.getValues());
pubkey.setId(id);
}
db.close();
return pubkey;
}
}
|
Java
|
/*
* 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.util;
import android.graphics.Paint;
import android.text.AndroidCharacter;
/**
* @author Kenny Root
*
*/
public abstract class EastAsianWidth {
public static EastAsianWidth getInstance() {
if (PreferenceConstants.PRE_FROYO)
return PreFroyo.Holder.sInstance;
else
return FroyoAndBeyond.Holder.sInstance;
}
/**
* @param charArray
* @param i
* @param position
* @param wideAttribute
*/
public abstract void measure(char[] charArray, int start, int end,
byte[] wideAttribute, Paint paint, int charWidth);
private static class PreFroyo extends EastAsianWidth {
private static final int BUFFER_SIZE = 4096;
private float[] mWidths = new float[BUFFER_SIZE];
private static class Holder {
private static final PreFroyo sInstance = new PreFroyo();
}
@Override
public void measure(char[] charArray, int start, int end,
byte[] wideAttribute, Paint paint, int charWidth) {
paint.getTextWidths(charArray, start, end, mWidths);
final int N = end - start;
for (int i = 0; i < N; i++)
wideAttribute[i] = (byte) (((int)mWidths[i] != charWidth) ?
AndroidCharacter.EAST_ASIAN_WIDTH_WIDE :
AndroidCharacter.EAST_ASIAN_WIDTH_NARROW);
}
}
private static class FroyoAndBeyond extends EastAsianWidth {
private static class Holder {
private static final FroyoAndBeyond sInstance = new FroyoAndBeyond();
}
@Override
public void measure(char[] charArray, int start, int end,
byte[] wideAttribute, Paint paint, int charWidth) {
AndroidCharacter.getEastAsianWidths(charArray, start, end - start, wideAttribute);
}
}
}
|
Java
|
/*
* 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.util;
import org.connectbot.HelpActivity;
import android.content.Context;
import android.util.AttributeSet;
import android.webkit.WebSettings;
import android.webkit.WebView;
/**
* @author Kenny Root
*
*/
public class HelpTopicView extends WebView {
public HelpTopicView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
initialize();
}
public HelpTopicView(Context context, AttributeSet attrs) {
super(context, attrs);
initialize();
}
public HelpTopicView(Context context) {
super(context);
initialize();
}
private void initialize() {
WebSettings wSet = getSettings();
wSet.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NARROW_COLUMNS);
wSet.setUseWideViewPort(false);
}
public HelpTopicView setTopic(String topic) {
String path = String.format("file:///android_asset/%s/%s%s",
HelpActivity.HELPDIR, topic, HelpActivity.SUFFIX);
loadUrl(path);
computeScroll();
return this;
}
}
|
Java
|
/*
* ConnectBot: simple, powerful, open-source SSH client for Android
* Copyright 2010 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.util;
/**
* @author kroot
*
*/
public interface OnDbWrittenListener {
public void onDbWritten();
}
|
Java
|
/*
* 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.util;
import java.util.Vector;
import org.connectbot.R;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Typeface;
import android.graphics.Paint.FontMetrics;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
public class EntropyView extends View {
private static final int SHA1_MAX_BYTES = 20;
private static final int MILLIS_BETWEEN_INPUTS = 50;
private Paint mPaint;
private FontMetrics mFontMetrics;
private boolean mFlipFlop;
private long mLastTime;
private Vector<OnEntropyGatheredListener> listeners;
private byte[] mEntropy;
private int mEntropyByteIndex;
private int mEntropyBitIndex;
private int splitText = 0;
private float lastX = 0.0f, lastY = 0.0f;
public EntropyView(Context context) {
super(context);
setUpEntropy();
}
public EntropyView(Context context, AttributeSet attrs) {
super(context, attrs);
setUpEntropy();
}
private void setUpEntropy() {
mPaint = new Paint();
mPaint.setAntiAlias(true);
mPaint.setTypeface(Typeface.DEFAULT);
mPaint.setTextAlign(Paint.Align.CENTER);
mPaint.setTextSize(16);
mPaint.setColor(Color.WHITE);
mFontMetrics = mPaint.getFontMetrics();
mEntropy = new byte[SHA1_MAX_BYTES];
mEntropyByteIndex = 0;
mEntropyBitIndex = 0;
listeners = new Vector<OnEntropyGatheredListener>();
}
public void addOnEntropyGatheredListener(OnEntropyGatheredListener listener) {
listeners.add(listener);
}
public void removeOnEntropyGatheredListener(OnEntropyGatheredListener listener) {
listeners.remove(listener);
}
@Override
public void onDraw(Canvas c) {
String prompt = String.format(getResources().getString(R.string.pubkey_touch_prompt),
(int)(100.0 * (mEntropyByteIndex / 20.0)) + (int)(5.0 * (mEntropyBitIndex / 8.0)));
if (splitText > 0 ||
mPaint.measureText(prompt) > (getWidth() * 0.8)) {
if (splitText == 0)
splitText = prompt.indexOf(" ", prompt.length() / 2);
c.drawText(prompt.substring(0, splitText),
getWidth() / 2.0f,
getHeight() / 2.0f + (mPaint.ascent() + mPaint.descent()),
mPaint);
c.drawText(prompt.substring(splitText),
getWidth() / 2.0f,
getHeight() / 2.0f - (mPaint.ascent() + mPaint.descent()),
mPaint);
} else {
c.drawText(prompt,
getWidth() / 2.0f,
getHeight() / 2.0f - (mFontMetrics.ascent + mFontMetrics.descent) / 2,
mPaint);
}
}
@Override
public boolean onTouchEvent(MotionEvent event) {
if (mEntropyByteIndex >= SHA1_MAX_BYTES
|| lastX == event.getX()
|| lastY == event.getY())
return true;
// Only get entropy every 200 milliseconds to ensure the user has moved around.
long now = System.currentTimeMillis();
if ((now - mLastTime) < MILLIS_BETWEEN_INPUTS)
return true;
else
mLastTime = now;
byte input;
lastX = event.getX();
lastY = event.getY();
// Get the lowest 4 bits of each X, Y input and concat to the entropy-gathering
// string.
if (mFlipFlop)
input = (byte)((((int)lastX & 0x0F) << 4) | ((int)lastY & 0x0F));
else
input = (byte)((((int)lastY & 0x0F) << 4) | ((int)lastX & 0x0F));
mFlipFlop = !mFlipFlop;
for (int i = 0; i < 4 && mEntropyByteIndex < SHA1_MAX_BYTES; i++) {
if ((input & 0x3) == 0x1) {
mEntropy[mEntropyByteIndex] <<= 1;
mEntropy[mEntropyByteIndex] |= 1;
mEntropyBitIndex++;
input >>= 2;
} else if ((input & 0x3) == 0x2) {
mEntropy[mEntropyByteIndex] <<= 1;
mEntropyBitIndex++;
input >>= 2;
}
if (mEntropyBitIndex >= 8) {
mEntropyBitIndex = 0;
mEntropyByteIndex++;
}
}
// SHA1PRNG only keeps 160 bits of entropy.
if (mEntropyByteIndex >= SHA1_MAX_BYTES) {
for (OnEntropyGatheredListener listener: listeners) {
listener.onEntropyGathered(mEntropy);
}
}
invalidate();
return true;
}
}
|
Java
|
/*
* 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.util;
/**
* This class is from:
*
* Encryptor.java
* Copyright 2008 Zach Scrivena
* zachscrivena@gmail.com
* http://zs.freeshell.org/
*/
import java.security.MessageDigest;
import java.security.SecureRandom;
import java.util.Arrays;
import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
/**
* Perform AES-128 encryption.
*/
public final class Encryptor
{
/** name of the character set to use for converting between characters and bytes */
private static final String CHARSET_NAME = "UTF-8";
/** random number generator algorithm */
private static final String RNG_ALGORITHM = "SHA1PRNG";
/** message digest algorithm (must be sufficiently long to provide the key and initialization vector) */
private static final String DIGEST_ALGORITHM = "SHA-256";
/** key algorithm (must be compatible with CIPHER_ALGORITHM) */
private static final String KEY_ALGORITHM = "AES";
/** cipher algorithm (must be compatible with KEY_ALGORITHM) */
private static final String CIPHER_ALGORITHM = "AES/CBC/PKCS5Padding";
/**
* Private constructor that should never be called.
*/
private Encryptor()
{}
/**
* Encrypt the specified cleartext using the given password.
* With the correct salt, number of iterations, and password, the decrypt() method reverses
* the effect of this method.
* This method generates and uses a random salt, and the user-specified number of iterations
* and password to create a 16-byte secret key and 16-byte initialization vector.
* The secret key and initialization vector are then used in the AES-128 cipher to encrypt
* the given cleartext.
*
* @param salt
* salt that was used in the encryption (to be populated)
* @param iterations
* number of iterations to use in salting
* @param password
* password to be used for encryption
* @param cleartext
* cleartext to be encrypted
* @return
* ciphertext
* @throws Exception
* on any error encountered in encryption
*/
public static byte[] encrypt(
final byte[] salt,
final int iterations,
final String password,
final byte[] cleartext)
throws Exception
{
/* generate salt randomly */
SecureRandom.getInstance(RNG_ALGORITHM).nextBytes(salt);
/* compute key and initialization vector */
final MessageDigest shaDigest = MessageDigest.getInstance(DIGEST_ALGORITHM);
byte[] pw = password.getBytes(CHARSET_NAME);
for (int i = 0; i < iterations; i++)
{
/* add salt */
final byte[] salted = new byte[pw.length + salt.length];
System.arraycopy(pw, 0, salted, 0, pw.length);
System.arraycopy(salt, 0, salted, pw.length, salt.length);
Arrays.fill(pw, (byte) 0x00);
/* compute SHA-256 digest */
shaDigest.reset();
pw = shaDigest.digest(salted);
Arrays.fill(salted, (byte) 0x00);
}
/* extract the 16-byte key and initialization vector from the SHA-256 digest */
final byte[] key = new byte[16];
final byte[] iv = new byte[16];
System.arraycopy(pw, 0, key, 0, 16);
System.arraycopy(pw, 16, iv, 0, 16);
Arrays.fill(pw, (byte) 0x00);
/* perform AES-128 encryption */
final Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
cipher.init(
Cipher.ENCRYPT_MODE,
new SecretKeySpec(key, KEY_ALGORITHM),
new IvParameterSpec(iv));
Arrays.fill(key, (byte) 0x00);
Arrays.fill(iv, (byte) 0x00);
return cipher.doFinal(cleartext);
}
/**
* Decrypt the specified ciphertext using the given password.
* With the correct salt, number of iterations, and password, this method reverses the effect
* of the encrypt() method.
* This method uses the user-specified salt, number of iterations, and password
* to recreate the 16-byte secret key and 16-byte initialization vector.
* The secret key and initialization vector are then used in the AES-128 cipher to decrypt
* the given ciphertext.
*
* @param salt
* salt to be used in decryption
* @param iterations
* number of iterations to use in salting
* @param password
* password to be used for decryption
* @param ciphertext
* ciphertext to be decrypted
* @return
* cleartext
* @throws Exception
* on any error encountered in decryption
*/
public static byte[] decrypt(
final byte[] salt,
final int iterations,
final String password,
final byte[] ciphertext)
throws Exception
{
/* compute key and initialization vector */
final MessageDigest shaDigest = MessageDigest.getInstance(DIGEST_ALGORITHM);
byte[] pw = password.getBytes(CHARSET_NAME);
for (int i = 0; i < iterations; i++)
{
/* add salt */
final byte[] salted = new byte[pw.length + salt.length];
System.arraycopy(pw, 0, salted, 0, pw.length);
System.arraycopy(salt, 0, salted, pw.length, salt.length);
Arrays.fill(pw, (byte) 0x00);
/* compute SHA-256 digest */
shaDigest.reset();
pw = shaDigest.digest(salted);
Arrays.fill(salted, (byte) 0x00);
}
/* extract the 16-byte key and initialization vector from the SHA-256 digest */
final byte[] key = new byte[16];
final byte[] iv = new byte[16];
System.arraycopy(pw, 0, key, 0, 16);
System.arraycopy(pw, 16, iv, 0, 16);
Arrays.fill(pw, (byte) 0x00);
/* perform AES-128 decryption */
final Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
cipher.init(
Cipher.DECRYPT_MODE,
new SecretKeySpec(key, KEY_ALGORITHM),
new IvParameterSpec(iv));
Arrays.fill(key, (byte) 0x00);
Arrays.fill(iv, (byte) 0x00);
return cipher.doFinal(ciphertext);
}
}
|
Java
|
/*
* 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.util;
import java.nio.charset.Charset;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import org.connectbot.bean.HostBean;
import org.connectbot.bean.PortForwardBean;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.util.Log;
import com.trilead.ssh2.KnownHosts;
/**
* Contains information about various SSH hosts, include public hostkey if known
* from previous sessions.
*
* @author jsharkey
*/
public class HostDatabase extends RobustSQLiteOpenHelper {
public final static String TAG = "ConnectBot.HostDatabase";
public final static String DB_NAME = "hosts";
public final static int DB_VERSION = 22;
public final static String TABLE_HOSTS = "hosts";
public final static String FIELD_HOST_NICKNAME = "nickname";
public final static String FIELD_HOST_PROTOCOL = "protocol";
public final static String FIELD_HOST_USERNAME = "username";
public final static String FIELD_HOST_HOSTNAME = "hostname";
public final static String FIELD_HOST_PORT = "port";
public final static String FIELD_HOST_HOSTKEYALGO = "hostkeyalgo";
public final static String FIELD_HOST_HOSTKEY = "hostkey";
public final static String FIELD_HOST_LASTCONNECT = "lastconnect";
public final static String FIELD_HOST_COLOR = "color";
public final static String FIELD_HOST_USEKEYS = "usekeys";
public final static String FIELD_HOST_USEAUTHAGENT = "useauthagent";
public final static String FIELD_HOST_POSTLOGIN = "postlogin";
public final static String FIELD_HOST_PUBKEYID = "pubkeyid";
public final static String FIELD_HOST_WANTSESSION = "wantsession";
public final static String FIELD_HOST_DELKEY = "delkey";
public final static String FIELD_HOST_FONTSIZE = "fontsize";
public final static String FIELD_HOST_COMPRESSION = "compression";
public final static String FIELD_HOST_ENCODING = "encoding";
public final static String FIELD_HOST_STAYCONNECTED = "stayconnected";
public final static String TABLE_PORTFORWARDS = "portforwards";
public final static String FIELD_PORTFORWARD_HOSTID = "hostid";
public final static String FIELD_PORTFORWARD_NICKNAME = "nickname";
public final static String FIELD_PORTFORWARD_TYPE = "type";
public final static String FIELD_PORTFORWARD_SOURCEPORT = "sourceport";
public final static String FIELD_PORTFORWARD_DESTADDR = "destaddr";
public final static String FIELD_PORTFORWARD_DESTPORT = "destport";
public final static String TABLE_COLORS = "colors";
public final static String FIELD_COLOR_SCHEME = "scheme";
public final static String FIELD_COLOR_NUMBER = "number";
public final static String FIELD_COLOR_VALUE = "value";
public final static String TABLE_COLOR_DEFAULTS = "colorDefaults";
public final static String FIELD_COLOR_FG = "fg";
public final static String FIELD_COLOR_BG = "bg";
public final static int DEFAULT_FG_COLOR = 7;
public final static int DEFAULT_BG_COLOR = 0;
public final static String COLOR_RED = "red";
public final static String COLOR_GREEN = "green";
public final static String COLOR_BLUE = "blue";
public final static String COLOR_GRAY = "gray";
public final static String PORTFORWARD_LOCAL = "local";
public final static String PORTFORWARD_REMOTE = "remote";
public final static String PORTFORWARD_DYNAMIC4 = "dynamic4";
public final static String PORTFORWARD_DYNAMIC5 = "dynamic5";
public final static String DELKEY_DEL = "del";
public final static String DELKEY_BACKSPACE = "backspace";
public final static String AUTHAGENT_NO = "no";
public final static String AUTHAGENT_CONFIRM = "confirm";
public final static String AUTHAGENT_YES = "yes";
public final static String ENCODING_DEFAULT = Charset.defaultCharset().name();
public final static long PUBKEYID_NEVER = -2;
public final static long PUBKEYID_ANY = -1;
public static final int DEFAULT_COLOR_SCHEME = 0;
// Table creation strings
public static final String CREATE_TABLE_COLOR_DEFAULTS =
"CREATE TABLE " + TABLE_COLOR_DEFAULTS
+ " (" + FIELD_COLOR_SCHEME + " INTEGER NOT NULL, "
+ FIELD_COLOR_FG + " INTEGER NOT NULL DEFAULT " + DEFAULT_FG_COLOR + ", "
+ FIELD_COLOR_BG + " INTEGER NOT NULL DEFAULT " + DEFAULT_BG_COLOR + ")";
public static final String CREATE_TABLE_COLOR_DEFAULTS_INDEX =
"CREATE INDEX " + TABLE_COLOR_DEFAULTS + FIELD_COLOR_SCHEME + "index ON "
+ TABLE_COLOR_DEFAULTS + " (" + FIELD_COLOR_SCHEME + ");";
private static final String WHERE_SCHEME_AND_COLOR = FIELD_COLOR_SCHEME + " = ? AND "
+ FIELD_COLOR_NUMBER + " = ?";
static {
addTableName(TABLE_HOSTS);
addTableName(TABLE_PORTFORWARDS);
addIndexName(TABLE_PORTFORWARDS + FIELD_PORTFORWARD_HOSTID + "index");
addTableName(TABLE_COLORS);
addIndexName(TABLE_COLORS + FIELD_COLOR_SCHEME + "index");
addTableName(TABLE_COLOR_DEFAULTS);
addIndexName(TABLE_COLOR_DEFAULTS + FIELD_COLOR_SCHEME + "index");
}
public static final Object[] dbLock = new Object[0];
public HostDatabase(Context context) {
super(context, DB_NAME, null, DB_VERSION);
getWritableDatabase().close();
}
@Override
public void onCreate(SQLiteDatabase db) {
super.onCreate(db);
db.execSQL("CREATE TABLE " + TABLE_HOSTS
+ " (_id INTEGER PRIMARY KEY, "
+ FIELD_HOST_NICKNAME + " TEXT, "
+ FIELD_HOST_PROTOCOL + " TEXT DEFAULT 'ssh', "
+ FIELD_HOST_USERNAME + " TEXT, "
+ FIELD_HOST_HOSTNAME + " TEXT, "
+ FIELD_HOST_PORT + " INTEGER, "
+ FIELD_HOST_HOSTKEYALGO + " TEXT, "
+ FIELD_HOST_HOSTKEY + " BLOB, "
+ FIELD_HOST_LASTCONNECT + " INTEGER, "
+ FIELD_HOST_COLOR + " TEXT, "
+ FIELD_HOST_USEKEYS + " TEXT, "
+ FIELD_HOST_USEAUTHAGENT + " TEXT, "
+ FIELD_HOST_POSTLOGIN + " TEXT, "
+ FIELD_HOST_PUBKEYID + " INTEGER DEFAULT " + PUBKEYID_ANY + ", "
+ FIELD_HOST_DELKEY + " TEXT DEFAULT '" + DELKEY_DEL + "', "
+ FIELD_HOST_FONTSIZE + " INTEGER, "
+ FIELD_HOST_WANTSESSION + " TEXT DEFAULT '" + Boolean.toString(true) + "', "
+ FIELD_HOST_COMPRESSION + " TEXT DEFAULT '" + Boolean.toString(false) + "', "
+ FIELD_HOST_ENCODING + " TEXT DEFAULT '" + ENCODING_DEFAULT + "', "
+ FIELD_HOST_STAYCONNECTED + " TEXT)");
db.execSQL("CREATE TABLE " + TABLE_PORTFORWARDS
+ " (_id INTEGER PRIMARY KEY, "
+ FIELD_PORTFORWARD_HOSTID + " INTEGER, "
+ FIELD_PORTFORWARD_NICKNAME + " TEXT, "
+ FIELD_PORTFORWARD_TYPE + " TEXT NOT NULL DEFAULT " + PORTFORWARD_LOCAL + ", "
+ FIELD_PORTFORWARD_SOURCEPORT + " INTEGER NOT NULL DEFAULT 8080, "
+ FIELD_PORTFORWARD_DESTADDR + " TEXT, "
+ FIELD_PORTFORWARD_DESTPORT + " TEXT)");
db.execSQL("CREATE INDEX " + TABLE_PORTFORWARDS + FIELD_PORTFORWARD_HOSTID + "index ON "
+ TABLE_PORTFORWARDS + " (" + FIELD_PORTFORWARD_HOSTID + ");");
db.execSQL("CREATE TABLE " + TABLE_COLORS
+ " (_id INTEGER PRIMARY KEY, "
+ FIELD_COLOR_NUMBER + " INTEGER, "
+ FIELD_COLOR_VALUE + " INTEGER, "
+ FIELD_COLOR_SCHEME + " INTEGER)");
db.execSQL("CREATE INDEX " + TABLE_COLORS + FIELD_COLOR_SCHEME + "index ON "
+ TABLE_COLORS + " (" + FIELD_COLOR_SCHEME + ");");
db.execSQL(CREATE_TABLE_COLOR_DEFAULTS);
db.execSQL(CREATE_TABLE_COLOR_DEFAULTS_INDEX);
}
@Override
public void onRobustUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) throws SQLiteException {
// Versions of the database before the Android Market release will be
// shot without warning.
if (oldVersion <= 9) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_HOSTS);
onCreate(db);
return;
}
switch (oldVersion) {
case 10:
db.execSQL("ALTER TABLE " + TABLE_HOSTS
+ " ADD COLUMN " + FIELD_HOST_PUBKEYID + " INTEGER DEFAULT " + PUBKEYID_ANY);
case 11:
db.execSQL("CREATE TABLE " + TABLE_PORTFORWARDS
+ " (_id INTEGER PRIMARY KEY, "
+ FIELD_PORTFORWARD_HOSTID + " INTEGER, "
+ FIELD_PORTFORWARD_NICKNAME + " TEXT, "
+ FIELD_PORTFORWARD_TYPE + " TEXT NOT NULL DEFAULT " + PORTFORWARD_LOCAL + ", "
+ FIELD_PORTFORWARD_SOURCEPORT + " INTEGER NOT NULL DEFAULT 8080, "
+ FIELD_PORTFORWARD_DESTADDR + " TEXT, "
+ FIELD_PORTFORWARD_DESTPORT + " INTEGER)");
case 12:
db.execSQL("ALTER TABLE " + TABLE_HOSTS
+ " ADD COLUMN " + FIELD_HOST_WANTSESSION + " TEXT DEFAULT '" + Boolean.toString(true) + "'");
case 13:
db.execSQL("ALTER TABLE " + TABLE_HOSTS
+ " ADD COLUMN " + FIELD_HOST_COMPRESSION + " TEXT DEFAULT '" + Boolean.toString(false) + "'");
case 14:
db.execSQL("ALTER TABLE " + TABLE_HOSTS
+ " ADD COLUMN " + FIELD_HOST_ENCODING + " TEXT DEFAULT '" + ENCODING_DEFAULT + "'");
case 15:
db.execSQL("ALTER TABLE " + TABLE_HOSTS
+ " ADD COLUMN " + FIELD_HOST_PROTOCOL + " TEXT DEFAULT 'ssh'");
case 16:
db.execSQL("ALTER TABLE " + TABLE_HOSTS
+ " ADD COLUMN " + FIELD_HOST_DELKEY + " TEXT DEFAULT '" + DELKEY_DEL + "'");
case 17:
db.execSQL("CREATE INDEX " + TABLE_PORTFORWARDS + FIELD_PORTFORWARD_HOSTID + "index ON "
+ TABLE_PORTFORWARDS + " (" + FIELD_PORTFORWARD_HOSTID + ");");
// Add colors
db.execSQL("CREATE TABLE " + TABLE_COLORS
+ " (_id INTEGER PRIMARY KEY, "
+ FIELD_COLOR_NUMBER + " INTEGER, "
+ FIELD_COLOR_VALUE + " INTEGER, "
+ FIELD_COLOR_SCHEME + " INTEGER)");
db.execSQL("CREATE INDEX " + TABLE_COLORS + FIELD_COLOR_SCHEME + "index ON "
+ TABLE_COLORS + " (" + FIELD_COLOR_SCHEME + ");");
case 18:
db.execSQL("ALTER TABLE " + TABLE_HOSTS
+ " ADD COLUMN " + FIELD_HOST_USEAUTHAGENT + " TEXT DEFAULT '" + AUTHAGENT_NO + "'");
case 19:
db.execSQL("ALTER TABLE " + TABLE_HOSTS
+ " ADD COLUMN " + FIELD_HOST_STAYCONNECTED + " TEXT");
case 20:
db.execSQL("ALTER TABLE " + TABLE_HOSTS
+ " ADD COLUMN " + FIELD_HOST_FONTSIZE + " INTEGER");
case 21:
db.execSQL("DROP TABLE " + TABLE_COLOR_DEFAULTS);
db.execSQL(CREATE_TABLE_COLOR_DEFAULTS);
db.execSQL(CREATE_TABLE_COLOR_DEFAULTS_INDEX);
}
}
/**
* Touch a specific host to update its "last connected" field.
* @param nickname Nickname field of host to update
*/
public void touchHost(HostBean host) {
long now = System.currentTimeMillis() / 1000;
ContentValues values = new ContentValues();
values.put(FIELD_HOST_LASTCONNECT, now);
synchronized (dbLock) {
SQLiteDatabase db = this.getWritableDatabase();
db.update(TABLE_HOSTS, values, "_id = ?", new String[] { String.valueOf(host.getId()) });
}
}
/**
* Create a new host using the given parameters.
*/
public HostBean saveHost(HostBean host) {
long id;
synchronized (dbLock) {
SQLiteDatabase db = this.getWritableDatabase();
id = db.insert(TABLE_HOSTS, null, host.getValues());
}
host.setId(id);
return host;
}
/**
* Update a field in a host record.
*/
public boolean updateFontSize(HostBean host) {
long id = host.getId();
if (id < 0)
return false;
ContentValues updates = new ContentValues();
updates.put(FIELD_HOST_FONTSIZE, host.getFontSize());
synchronized (dbLock) {
SQLiteDatabase db = getWritableDatabase();
db.update(TABLE_HOSTS, updates, "_id = ?",
new String[] { String.valueOf(id) });
}
return true;
}
/**
* Delete a specific host by its <code>_id</code> value.
*/
public void deleteHost(HostBean host) {
if (host.getId() < 0)
return;
synchronized (dbLock) {
SQLiteDatabase db = this.getWritableDatabase();
db.delete(TABLE_HOSTS, "_id = ?", new String[] { String.valueOf(host.getId()) });
}
}
/**
* Return a cursor that contains information about all known hosts.
* @param sortColors If true, sort by color, otherwise sort by nickname.
*/
public List<HostBean> getHosts(boolean sortColors) {
String sortField = sortColors ? FIELD_HOST_COLOR : FIELD_HOST_NICKNAME;
List<HostBean> hosts;
synchronized (dbLock) {
SQLiteDatabase db = this.getReadableDatabase();
Cursor c = db.query(TABLE_HOSTS, null, null, null, null, null, sortField + " ASC");
hosts = createHostBeans(c);
c.close();
}
return hosts;
}
/**
* @param hosts
* @param c
*/
private List<HostBean> createHostBeans(Cursor c) {
List<HostBean> hosts = new LinkedList<HostBean>();
final int COL_ID = c.getColumnIndexOrThrow("_id"),
COL_NICKNAME = c.getColumnIndexOrThrow(FIELD_HOST_NICKNAME),
COL_PROTOCOL = c.getColumnIndexOrThrow(FIELD_HOST_PROTOCOL),
COL_USERNAME = c.getColumnIndexOrThrow(FIELD_HOST_USERNAME),
COL_HOSTNAME = c.getColumnIndexOrThrow(FIELD_HOST_HOSTNAME),
COL_PORT = c.getColumnIndexOrThrow(FIELD_HOST_PORT),
COL_LASTCONNECT = c.getColumnIndexOrThrow(FIELD_HOST_LASTCONNECT),
COL_COLOR = c.getColumnIndexOrThrow(FIELD_HOST_COLOR),
COL_USEKEYS = c.getColumnIndexOrThrow(FIELD_HOST_USEKEYS),
COL_USEAUTHAGENT = c.getColumnIndexOrThrow(FIELD_HOST_USEAUTHAGENT),
COL_POSTLOGIN = c.getColumnIndexOrThrow(FIELD_HOST_POSTLOGIN),
COL_PUBKEYID = c.getColumnIndexOrThrow(FIELD_HOST_PUBKEYID),
COL_WANTSESSION = c.getColumnIndexOrThrow(FIELD_HOST_WANTSESSION),
COL_DELKEY = c.getColumnIndexOrThrow(FIELD_HOST_DELKEY),
COL_FONTSIZE = c.getColumnIndexOrThrow(FIELD_HOST_FONTSIZE),
COL_COMPRESSION = c.getColumnIndexOrThrow(FIELD_HOST_COMPRESSION),
COL_ENCODING = c.getColumnIndexOrThrow(FIELD_HOST_ENCODING),
COL_STAYCONNECTED = c.getColumnIndexOrThrow(FIELD_HOST_STAYCONNECTED);
while (c.moveToNext()) {
HostBean host = new HostBean();
host.setId(c.getLong(COL_ID));
host.setNickname(c.getString(COL_NICKNAME));
host.setProtocol(c.getString(COL_PROTOCOL));
host.setUsername(c.getString(COL_USERNAME));
host.setHostname(c.getString(COL_HOSTNAME));
host.setPort(c.getInt(COL_PORT));
host.setLastConnect(c.getLong(COL_LASTCONNECT));
host.setColor(c.getString(COL_COLOR));
host.setUseKeys(Boolean.valueOf(c.getString(COL_USEKEYS)));
host.setUseAuthAgent(c.getString(COL_USEAUTHAGENT));
host.setPostLogin(c.getString(COL_POSTLOGIN));
host.setPubkeyId(c.getLong(COL_PUBKEYID));
host.setWantSession(Boolean.valueOf(c.getString(COL_WANTSESSION)));
host.setDelKey(c.getString(COL_DELKEY));
host.setFontSize(c.getInt(COL_FONTSIZE));
host.setCompression(Boolean.valueOf(c.getString(COL_COMPRESSION)));
host.setEncoding(c.getString(COL_ENCODING));
host.setStayConnected(Boolean.valueOf(c.getString(COL_STAYCONNECTED)));
hosts.add(host);
}
return hosts;
}
/**
* @param c
* @return
*/
private HostBean getFirstHostBean(Cursor c) {
HostBean host = null;
List<HostBean> hosts = createHostBeans(c);
if (hosts.size() > 0)
host = hosts.get(0);
c.close();
return host;
}
/**
* @param nickname
* @param protocol
* @param username
* @param hostname
* @param hostname2
* @param port
* @return
*/
public HostBean findHost(Map<String, String> selection) {
StringBuilder selectionBuilder = new StringBuilder();
Iterator<Entry<String, String>> i = selection.entrySet().iterator();
List<String> selectionValuesList = new LinkedList<String>();
int n = 0;
while (i.hasNext()) {
Entry<String, String> entry = i.next();
if (entry.getValue() == null)
continue;
if (n++ > 0)
selectionBuilder.append(" AND ");
selectionBuilder.append(entry.getKey())
.append(" = ?");
selectionValuesList.add(entry.getValue());
}
String selectionValues[] = new String[selectionValuesList.size()];
selectionValuesList.toArray(selectionValues);
selectionValuesList = null;
HostBean host;
synchronized (dbLock) {
SQLiteDatabase db = getReadableDatabase();
Cursor c = db.query(TABLE_HOSTS, null,
selectionBuilder.toString(),
selectionValues,
null, null, null);
host = getFirstHostBean(c);
}
return host;
}
/**
* @param hostId
* @return
*/
public HostBean findHostById(long hostId) {
HostBean host;
synchronized (dbLock) {
SQLiteDatabase db = getReadableDatabase();
Cursor c = db.query(TABLE_HOSTS, null,
"_id = ?", new String[] { String.valueOf(hostId) },
null, null, null);
host = getFirstHostBean(c);
}
return host;
}
/**
* Record the given hostkey into database under this nickname.
* @param hostname
* @param port
* @param hostkeyalgo
* @param hostkey
*/
public void saveKnownHost(String hostname, int port, String hostkeyalgo, byte[] hostkey) {
ContentValues values = new ContentValues();
values.put(FIELD_HOST_HOSTKEYALGO, hostkeyalgo);
values.put(FIELD_HOST_HOSTKEY, hostkey);
synchronized (dbLock) {
SQLiteDatabase db = getReadableDatabase();
db.update(TABLE_HOSTS, values,
FIELD_HOST_HOSTNAME + " = ? AND " + FIELD_HOST_PORT + " = ?",
new String[] { hostname, String.valueOf(port) });
Log.d(TAG, String.format("Finished saving hostkey information for '%s'", hostname));
}
}
/**
* Build list of known hosts for Trilead library.
* @return
*/
public KnownHosts getKnownHosts() {
KnownHosts known = new KnownHosts();
synchronized (dbLock) {
SQLiteDatabase db = this.getReadableDatabase();
Cursor c = db.query(TABLE_HOSTS, new String[] { FIELD_HOST_HOSTNAME,
FIELD_HOST_PORT, FIELD_HOST_HOSTKEYALGO, FIELD_HOST_HOSTKEY },
null, null, null, null, null);
if (c != null) {
int COL_HOSTNAME = c.getColumnIndexOrThrow(FIELD_HOST_HOSTNAME),
COL_PORT = c.getColumnIndexOrThrow(FIELD_HOST_PORT),
COL_HOSTKEYALGO = c.getColumnIndexOrThrow(FIELD_HOST_HOSTKEYALGO),
COL_HOSTKEY = c.getColumnIndexOrThrow(FIELD_HOST_HOSTKEY);
while (c.moveToNext()) {
String hostname = c.getString(COL_HOSTNAME),
hostkeyalgo = c.getString(COL_HOSTKEYALGO);
int port = c.getInt(COL_PORT);
byte[] hostkey = c.getBlob(COL_HOSTKEY);
if (hostkeyalgo == null || hostkeyalgo.length() == 0) continue;
if (hostkey == null || hostkey.length == 0) continue;
try {
known.addHostkey(new String[] { String.format("%s:%d", hostname, port) }, hostkeyalgo, hostkey);
} catch(Exception e) {
Log.e(TAG, "Problem while adding a known host from database", e);
}
}
c.close();
}
}
return known;
}
/**
* Unset any hosts using a pubkey ID that has been deleted.
* @param pubkeyId
*/
public void stopUsingPubkey(long pubkeyId) {
if (pubkeyId < 0) return;
ContentValues values = new ContentValues();
values.put(FIELD_HOST_PUBKEYID, PUBKEYID_ANY);
synchronized (dbLock) {
SQLiteDatabase db = this.getWritableDatabase();
db.update(TABLE_HOSTS, values, FIELD_HOST_PUBKEYID + " = ?", new String[] { String.valueOf(pubkeyId) });
}
Log.d(TAG, String.format("Set all hosts using pubkey id %d to -1", pubkeyId));
}
/*
* Methods for dealing with port forwards attached to hosts
*/
/**
* Returns a list of all the port forwards associated with a particular host ID.
* @param host the host for which we want the port forward list
* @return port forwards associated with host ID
*/
public List<PortForwardBean> getPortForwardsForHost(HostBean host) {
List<PortForwardBean> portForwards = new LinkedList<PortForwardBean>();
synchronized (dbLock) {
SQLiteDatabase db = this.getReadableDatabase();
Cursor c = db.query(TABLE_PORTFORWARDS, new String[] {
"_id", FIELD_PORTFORWARD_NICKNAME, FIELD_PORTFORWARD_TYPE, FIELD_PORTFORWARD_SOURCEPORT,
FIELD_PORTFORWARD_DESTADDR, FIELD_PORTFORWARD_DESTPORT },
FIELD_PORTFORWARD_HOSTID + " = ?", new String[] { String.valueOf(host.getId()) },
null, null, null);
while (c.moveToNext()) {
PortForwardBean pfb = new PortForwardBean(
c.getInt(0),
host.getId(),
c.getString(1),
c.getString(2),
c.getInt(3),
c.getString(4),
c.getInt(5));
portForwards.add(pfb);
}
c.close();
}
return portForwards;
}
/**
* Update the parameters of a port forward in the database.
* @param pfb {@link PortForwardBean} to save
* @return true on success
*/
public boolean savePortForward(PortForwardBean pfb) {
boolean success = false;
synchronized (dbLock) {
SQLiteDatabase db = getWritableDatabase();
if (pfb.getId() < 0) {
long id = db.insert(TABLE_PORTFORWARDS, null, pfb.getValues());
pfb.setId(id);
success = true;
} else {
if (db.update(TABLE_PORTFORWARDS, pfb.getValues(), "_id = ?", new String[] { String.valueOf(pfb.getId()) }) > 0)
success = true;
}
}
return success;
}
/**
* Deletes a port forward from the database.
* @param pfb {@link PortForwardBean} to delete
*/
public void deletePortForward(PortForwardBean pfb) {
if (pfb.getId() < 0)
return;
synchronized (dbLock) {
SQLiteDatabase db = this.getWritableDatabase();
db.delete(TABLE_PORTFORWARDS, "_id = ?", new String[] { String.valueOf(pfb.getId()) });
}
}
public Integer[] getColorsForScheme(int scheme) {
Integer[] colors = Colors.defaults.clone();
synchronized (dbLock) {
SQLiteDatabase db = getReadableDatabase();
Cursor c = db.query(TABLE_COLORS, new String[] {
FIELD_COLOR_NUMBER, FIELD_COLOR_VALUE },
FIELD_COLOR_SCHEME + " = ?",
new String[] { String.valueOf(scheme) },
null, null, null);
while (c.moveToNext()) {
colors[c.getInt(0)] = new Integer(c.getInt(1));
}
c.close();
}
return colors;
}
public void setColorForScheme(int scheme, int number, int value) {
final SQLiteDatabase db;
final String[] whereArgs = new String[] { String.valueOf(scheme), String.valueOf(number) };
if (value == Colors.defaults[number]) {
synchronized (dbLock) {
db = getWritableDatabase();
db.delete(TABLE_COLORS,
WHERE_SCHEME_AND_COLOR, whereArgs);
}
} else {
final ContentValues values = new ContentValues();
values.put(FIELD_COLOR_VALUE, value);
synchronized (dbLock) {
db = getWritableDatabase();
final int rowsAffected = db.update(TABLE_COLORS, values,
WHERE_SCHEME_AND_COLOR, whereArgs);
if (rowsAffected == 0) {
values.put(FIELD_COLOR_SCHEME, scheme);
values.put(FIELD_COLOR_NUMBER, number);
db.insert(TABLE_COLORS, null, values);
}
}
}
}
public void setGlobalColor(int number, int value) {
setColorForScheme(DEFAULT_COLOR_SCHEME, number, value);
}
public int[] getDefaultColorsForScheme(int scheme) {
int[] colors = new int[] { DEFAULT_FG_COLOR, DEFAULT_BG_COLOR };
synchronized (dbLock) {
SQLiteDatabase db = getReadableDatabase();
Cursor c = db.query(TABLE_COLOR_DEFAULTS,
new String[] { FIELD_COLOR_FG, FIELD_COLOR_BG },
FIELD_COLOR_SCHEME + " = ?",
new String[] { String.valueOf(scheme) },
null, null, null);
if (c.moveToFirst()) {
colors[0] = c.getInt(0);
colors[1] = c.getInt(1);
}
c.close();
}
return colors;
}
public int[] getGlobalDefaultColors() {
return getDefaultColorsForScheme(DEFAULT_COLOR_SCHEME);
}
public void setDefaultColorsForScheme(int scheme, int fg, int bg) {
SQLiteDatabase db;
String schemeWhere = null;
String[] whereArgs;
schemeWhere = FIELD_COLOR_SCHEME + " = ?";
whereArgs = new String[] { String.valueOf(scheme) };
ContentValues values = new ContentValues();
values.put(FIELD_COLOR_FG, fg);
values.put(FIELD_COLOR_BG, bg);
synchronized (dbLock) {
db = getWritableDatabase();
int rowsAffected = db.update(TABLE_COLOR_DEFAULTS, values,
schemeWhere, whereArgs);
if (rowsAffected == 0) {
values.put(FIELD_COLOR_SCHEME, scheme);
db.insert(TABLE_COLOR_DEFAULTS, null, values);
}
}
}
}
|
Java
|
/*
* 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.util;
import android.os.Build;
/**
* @author Kenny Root
*
*/
public class PreferenceConstants {
public static final boolean PRE_ECLAIR = (Integer.parseInt(Build.VERSION.SDK) <= 4);
public static final boolean PRE_FROYO = PRE_ECLAIR ? true :
(Integer.parseInt(Build.VERSION.SDK) <= 7);
public static final String MEMKEYS = "memkeys";
public static final String UPDATE = "update";
public static final String UPDATE_DAILY = "Daily";
public static final String UPDATE_WEEKLY = "Weekly";
public static final String UPDATE_NEVER = "Never";
public static final String LAST_CHECKED = "lastchecked";
public static final String SCROLLBACK = "scrollback";
public static final String EMULATION = "emulation";
public static final String ROTATION = "rotation";
public static final String ROTATION_DEFAULT = "Default";
public static final String ROTATION_LANDSCAPE = "Force landscape";
public static final String ROTATION_PORTRAIT = "Force portrait";
public static final String ROTATION_AUTOMATIC = "Automatic";
public static final String FULLSCREEN = "fullscreen";
public static final String KEYMODE = "keymode";
public static final String KEYMODE_RIGHT = "Use right-side keys";
public static final String KEYMODE_LEFT = "Use left-side keys";
public static final String CAMERA = "camera";
public static final String CAMERA_CTRLA_SPACE = "Ctrl+A then Space";
public static final String CAMERA_CTRLA = "Ctrl+A";
public static final String CAMERA_ESC = "Esc";
public static final String CAMERA_ESC_A = "Esc+A";
public static final String KEEP_ALIVE = "keepalive";
public static final String WIFI_LOCK = "wifilock";
public static final String BUMPY_ARROWS = "bumpyarrows";
public static final String EULA = "eula";
public static final String SORT_BY_COLOR = "sortByColor";
public static final String BELL = "bell";
public static final String BELL_VOLUME = "bellVolume";
public static final String BELL_VIBRATE = "bellVibrate";
public static final String BELL_NOTIFICATION = "bellNotification";
public static final float DEFAULT_BELL_VOLUME = 0.25f;
public static final String CONNECTION_PERSIST = "connPersist";
/* Backup identifiers */
public static final String BACKUP_PREF_KEY = "prefs";
}
|
Java
|
/*
* Copyright (C) 2007 The Android Open Source Project
*
* 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.
*/
/*
* 090408
* Keith Wiley
* kwiley@keithwiley.com
* http://keithwiley.com
*
* UberColorPickerDialog v1.1
*
* This color picker was implemented as a (significant) extension of the
* ColorPickerDialog class provided in the Android API Demos. You are free
* to drop it unchanged into your own projects or to modify it as you see
* fit. I would appreciate it if this comment block were let intact,
* merely for credit's sake.
*
* Enjoy!
*/
package org.connectbot.util;
import android.app.Dialog;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.ColorMatrix;
import android.graphics.ComposeShader;
import android.graphics.Paint;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffXfermode;
import android.graphics.RadialGradient;
import android.graphics.Rect;
import android.graphics.RectF;
import android.graphics.Shader;
import android.graphics.SweepGradient;
import android.graphics.drawable.GradientDrawable;
import android.graphics.drawable.GradientDrawable.Orientation;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.view.MotionEvent;
import android.view.View;
/**
* UberColorPickerDialog is a seriously enhanced version of the UberColorPickerDialog
* class provided in the Android API Demos.<p>
*
* NOTE (from Kenny Root): This is a VERY slimmed down version custom for ConnectBot.
* Visit Keith's site for the full version at the URL listed in the author line.<p>
*
* @author Keith Wiley, kwiley@keithwiley.com, http://keithwiley.com
*/
public class UberColorPickerDialog extends Dialog {
private final OnColorChangedListener mListener;
private final int mInitialColor;
/**
* Callback to the creator of the dialog, informing the creator of a new color and notifying that the dialog is about to dismiss.
*/
public interface OnColorChangedListener {
void colorChanged(int color);
}
/**
* Ctor
* @param context
* @param listener
* @param initialColor
* @param showTitle If true, a title is shown across the top of the dialog. If false a toast is shown instead.
*/
public UberColorPickerDialog(Context context,
OnColorChangedListener listener,
int initialColor) {
super(context);
mListener = listener;
mInitialColor = initialColor;
}
/**
* Activity entry point
*/
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
OnColorChangedListener l = new OnColorChangedListener() {
public void colorChanged(int color) {
mListener.colorChanged(color);
dismiss();
}
};
DisplayMetrics dm = new DisplayMetrics();
getWindow().getWindowManager().getDefaultDisplay().getMetrics(dm);
int screenWidth = dm.widthPixels;
int screenHeight = dm.heightPixels;
setTitle("Pick a color (try the trackball)");
try {
setContentView(new ColorPickerView(getContext(), l, screenWidth, screenHeight, mInitialColor));
}
catch (Exception e) {
//There is currently only one kind of ctor exception, that where no methods are enabled.
dismiss(); //This doesn't work! The dialog is still shown (its title at least, the layout is empty from the exception being thrown). <sigh>
}
}
/**
* ColorPickerView is the meat of this color picker (as opposed to the enclosing class).
* All the heavy lifting is done directly by this View subclass.
* <P>
* You can enable/disable whichever color chooser methods you want by modifying the ENABLED_METHODS switches. They *should*
* do all the work required to properly enable/disable methods without losing track of what goes with what and what maps to what.
* <P>
* If you add a new color chooser method, do a text search for "NEW_METHOD_WORK_NEEDED_HERE". That tag indicates all
* the locations in the code that will have to be amended in order to properly add a new color chooser method.
* I highly recommend adding new methods to the end of the list. If you want to try to reorder the list, you're on your own.
*/
private static class ColorPickerView extends View {
private static int SWATCH_WIDTH = 95;
private static final int SWATCH_HEIGHT = 60;
private static int PALETTE_POS_X = 0;
private static int PALETTE_POS_Y = SWATCH_HEIGHT;
private static final int PALETTE_DIM = SWATCH_WIDTH * 2;
private static final int PALETTE_RADIUS = PALETTE_DIM / 2;
private static final int PALETTE_CENTER_X = PALETTE_RADIUS;
private static final int PALETTE_CENTER_Y = PALETTE_RADIUS;
private static final int SLIDER_THICKNESS = 40;
private static int VIEW_DIM_X = PALETTE_DIM;
private static int VIEW_DIM_Y = SWATCH_HEIGHT;
//NEW_METHOD_WORK_NEEDED_HERE
private static final int METHOD_HS_V_PALETTE = 0;
//NEW_METHOD_WORK_NEEDED_HERE
//Add a new entry to the list for each controller in the new method
private static final int TRACKED_NONE = -1; //No object on screen is currently being tracked
private static final int TRACK_SWATCH_OLD = 10;
private static final int TRACK_SWATCH_NEW = 11;
private static final int TRACK_HS_PALETTE = 30;
private static final int TRACK_VER_VALUE_SLIDER = 31;
private static final int TEXT_SIZE = 12;
private static int[] TEXT_HSV_POS = new int[2];
private static int[] TEXT_RGB_POS = new int[2];
private static int[] TEXT_YUV_POS = new int[2];
private static int[] TEXT_HEX_POS = new int[2];
private static final float PI = 3.141592653589793f;
private int mMethod = METHOD_HS_V_PALETTE;
private int mTracking = TRACKED_NONE; //What object on screen is currently being tracked for movement
//Zillions of persistant Paint objecs for drawing the View
private Paint mSwatchOld, mSwatchNew;
//NEW_METHOD_WORK_NEEDED_HERE
//Add Paints to represent the palettes of the new method's UI controllers
private Paint mOvalHueSat;
private Bitmap mVerSliderBM;
private Canvas mVerSliderCv;
private Bitmap[] mHorSlidersBM = new Bitmap[3];
private Canvas[] mHorSlidersCv = new Canvas[3];
private Paint mValDimmer;
//NEW_METHOD_WORK_NEEDED_HERE
//Add Paints to represent the icon for the new method
private Paint mOvalHueSatSmall;
private Paint mPosMarker;
private Paint mText;
private Rect mOldSwatchRect = new Rect();
private Rect mNewSwatchRect = new Rect();
private Rect mPaletteRect = new Rect();
private Rect mVerSliderRect = new Rect();
private int[] mSpectrumColorsRev;
private int mOriginalColor = 0; //The color passed in at the beginning, which can be reverted to at any time by tapping the old swatch.
private float[] mHSV = new float[3];
private int[] mRGB = new int[3];
private float[] mYUV = new float[3];
private String mHexStr = "";
private boolean mHSVenabled = true; //Only true if an HSV method is enabled
private boolean mRGBenabled = true; //Only true if an RGB method is enabled
private boolean mYUVenabled = true; //Only true if a YUV method is enabled
private boolean mHexenabled = true; //Only true if an RGB method is enabled
private int[] mCoord = new int[3]; //For drawing slider/palette markers
private int mFocusedControl = -1; //Which control receives trackball events.
private OnColorChangedListener mListener;
/**
* Ctor.
* @param c
* @param l
* @param width Used to determine orientation and adjust layout accordingly
* @param height Used to determine orientation and adjust layout accordingly
* @param color The initial color
* @throws Exception
*/
ColorPickerView(Context c, OnColorChangedListener l, int width, int height, int color)
throws Exception {
super(c);
//We need to make the dialog focusable to retrieve trackball events.
setFocusable(true);
mListener = l;
mOriginalColor = color;
Color.colorToHSV(color, mHSV);
updateAllFromHSV();
//Setup the layout based on whether this is a portrait or landscape orientation.
if (width <= height) { //Portrait layout
SWATCH_WIDTH = (PALETTE_DIM + SLIDER_THICKNESS) / 2;
PALETTE_POS_X = 0;
PALETTE_POS_Y = TEXT_SIZE * 4 + SWATCH_HEIGHT;
//Set more rects, lots of rects
mOldSwatchRect.set(0, TEXT_SIZE * 4, SWATCH_WIDTH, TEXT_SIZE * 4 + SWATCH_HEIGHT);
mNewSwatchRect.set(SWATCH_WIDTH, TEXT_SIZE * 4, SWATCH_WIDTH * 2, TEXT_SIZE * 4 + SWATCH_HEIGHT);
mPaletteRect.set(0, PALETTE_POS_Y, PALETTE_DIM, PALETTE_POS_Y + PALETTE_DIM);
mVerSliderRect.set(PALETTE_DIM, PALETTE_POS_Y, PALETTE_DIM + SLIDER_THICKNESS, PALETTE_POS_Y + PALETTE_DIM);
TEXT_HSV_POS[0] = 3;
TEXT_HSV_POS[1] = 0;
TEXT_RGB_POS[0] = TEXT_HSV_POS[0] + 50;
TEXT_RGB_POS[1] = TEXT_HSV_POS[1];
TEXT_YUV_POS[0] = TEXT_HSV_POS[0] + 100;
TEXT_YUV_POS[1] = TEXT_HSV_POS[1];
TEXT_HEX_POS[0] = TEXT_HSV_POS[0] + 150;
TEXT_HEX_POS[1] = TEXT_HSV_POS[1];
VIEW_DIM_X = PALETTE_DIM + SLIDER_THICKNESS;
VIEW_DIM_Y = SWATCH_HEIGHT + PALETTE_DIM + TEXT_SIZE * 4;
}
else { //Landscape layout
SWATCH_WIDTH = 110;
PALETTE_POS_X = SWATCH_WIDTH;
PALETTE_POS_Y = 0;
//Set more rects, lots of rects
mOldSwatchRect.set(0, TEXT_SIZE * 7, SWATCH_WIDTH, TEXT_SIZE * 7 + SWATCH_HEIGHT);
mNewSwatchRect.set(0, TEXT_SIZE * 7 + SWATCH_HEIGHT, SWATCH_WIDTH, TEXT_SIZE * 7 + SWATCH_HEIGHT * 2);
mPaletteRect.set(SWATCH_WIDTH, PALETTE_POS_Y, SWATCH_WIDTH + PALETTE_DIM, PALETTE_POS_Y + PALETTE_DIM);
mVerSliderRect.set(SWATCH_WIDTH + PALETTE_DIM, PALETTE_POS_Y, SWATCH_WIDTH + PALETTE_DIM + SLIDER_THICKNESS, PALETTE_POS_Y + PALETTE_DIM);
TEXT_HSV_POS[0] = 3;
TEXT_HSV_POS[1] = 0;
TEXT_RGB_POS[0] = TEXT_HSV_POS[0];
TEXT_RGB_POS[1] = (int)(TEXT_HSV_POS[1] + TEXT_SIZE * 3.5);
TEXT_YUV_POS[0] = TEXT_HSV_POS[0] + 50;
TEXT_YUV_POS[1] = (int)(TEXT_HSV_POS[1] + TEXT_SIZE * 3.5);
TEXT_HEX_POS[0] = TEXT_HSV_POS[0] + 50;
TEXT_HEX_POS[1] = TEXT_HSV_POS[1];
VIEW_DIM_X = PALETTE_POS_X + PALETTE_DIM + SLIDER_THICKNESS;
VIEW_DIM_Y = Math.max(mNewSwatchRect.bottom, PALETTE_DIM);
}
//Rainbows make everybody happy!
mSpectrumColorsRev = new int[] {
0xFFFF0000, 0xFFFF00FF, 0xFF0000FF, 0xFF00FFFF,
0xFF00FF00, 0xFFFFFF00, 0xFFFF0000,
};
//Setup all the Paint and Shader objects. There are lots of them!
//NEW_METHOD_WORK_NEEDED_HERE
//Add Paints to represent the palettes of the new method's UI controllers
mSwatchOld = new Paint(Paint.ANTI_ALIAS_FLAG);
mSwatchOld.setStyle(Paint.Style.FILL);
mSwatchOld.setColor(Color.HSVToColor(mHSV));
mSwatchNew = new Paint(Paint.ANTI_ALIAS_FLAG);
mSwatchNew.setStyle(Paint.Style.FILL);
mSwatchNew.setColor(Color.HSVToColor(mHSV));
Shader shaderA = new SweepGradient(0, 0, mSpectrumColorsRev, null);
Shader shaderB = new RadialGradient(0, 0, PALETTE_CENTER_X, 0xFFFFFFFF, 0xFF000000, Shader.TileMode.CLAMP);
Shader shader = new ComposeShader(shaderA, shaderB, PorterDuff.Mode.SCREEN);
mOvalHueSat = new Paint(Paint.ANTI_ALIAS_FLAG);
mOvalHueSat.setShader(shader);
mOvalHueSat.setStyle(Paint.Style.FILL);
mOvalHueSat.setDither(true);
mVerSliderBM = Bitmap.createBitmap(SLIDER_THICKNESS, PALETTE_DIM, Bitmap.Config.RGB_565);
mVerSliderCv = new Canvas(mVerSliderBM);
for (int i = 0; i < 3; i++) {
mHorSlidersBM[i] = Bitmap.createBitmap(PALETTE_DIM, SLIDER_THICKNESS, Bitmap.Config.RGB_565);
mHorSlidersCv[i] = new Canvas(mHorSlidersBM[i]);
}
mValDimmer = new Paint(Paint.ANTI_ALIAS_FLAG);
mValDimmer.setStyle(Paint.Style.FILL);
mValDimmer.setDither(true);
mValDimmer.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.MULTIPLY));
//Whew, we're done making the big Paints and Shaders for the swatches, palettes, and sliders.
//Now we need to make the Paints and Shaders that will draw the little method icons in the method selector list.
//NEW_METHOD_WORK_NEEDED_HERE
//Add Paints to represent the icon for the new method
shaderA = new SweepGradient(0, 0, mSpectrumColorsRev, null);
shaderB = new RadialGradient(0, 0, PALETTE_DIM / 2, 0xFFFFFFFF, 0xFF000000, Shader.TileMode.CLAMP);
shader = new ComposeShader(shaderA, shaderB, PorterDuff.Mode.SCREEN);
mOvalHueSatSmall = new Paint(Paint.ANTI_ALIAS_FLAG);
mOvalHueSatSmall.setShader(shader);
mOvalHueSatSmall.setStyle(Paint.Style.FILL);
//Make a simple stroking Paint for drawing markers and borders and stuff like that.
mPosMarker = new Paint(Paint.ANTI_ALIAS_FLAG);
mPosMarker.setStyle(Paint.Style.STROKE);
mPosMarker.setStrokeWidth(2);
//Make a basic text Paint.
mText = new Paint(Paint.ANTI_ALIAS_FLAG);
mText.setTextSize(TEXT_SIZE);
mText.setColor(Color.WHITE);
//Kickstart
initUI();
}
/**
* Draw the entire view (the entire dialog).
*/
@Override
protected void onDraw(Canvas canvas) {
//Draw the old and new swatches
drawSwatches(canvas);
//Write the text
writeColorParams(canvas);
//Draw the palette and sliders (the UI)
if (mMethod == METHOD_HS_V_PALETTE)
drawHSV1Palette(canvas);
}
/**
* Draw the old and new swatches.
* @param canvas
*/
private void drawSwatches(Canvas canvas) {
float[] hsv = new float[3];
mText.setTextSize(16);
//Draw the original swatch
canvas.drawRect(mOldSwatchRect, mSwatchOld);
Color.colorToHSV(mOriginalColor, hsv);
//if (UberColorPickerDialog.isGray(mColor)) //Don't need this right here, but imp't to note
// hsv[1] = 0;
if (hsv[2] > .5)
mText.setColor(Color.BLACK);
canvas.drawText("Revert", mOldSwatchRect.left + SWATCH_WIDTH / 2 - mText.measureText("Revert") / 2, mOldSwatchRect.top + 16, mText);
mText.setColor(Color.WHITE);
//Draw the new swatch
canvas.drawRect(mNewSwatchRect, mSwatchNew);
if (mHSV[2] > .5)
mText.setColor(Color.BLACK);
canvas.drawText("Accept", mNewSwatchRect.left + SWATCH_WIDTH / 2 - mText.measureText("Accept") / 2, mNewSwatchRect.top + 16, mText);
mText.setColor(Color.WHITE);
mText.setTextSize(TEXT_SIZE);
}
/**
* Write the color parametes (HSV, RGB, YUV, Hex, etc.).
* @param canvas
*/
private void writeColorParams(Canvas canvas) {
if (mHSVenabled) {
canvas.drawText("H: " + Integer.toString((int)(mHSV[0] / 360.0f * 255)), TEXT_HSV_POS[0], TEXT_HSV_POS[1] + TEXT_SIZE, mText);
canvas.drawText("S: " + Integer.toString((int)(mHSV[1] * 255)), TEXT_HSV_POS[0], TEXT_HSV_POS[1] + TEXT_SIZE * 2, mText);
canvas.drawText("V: " + Integer.toString((int)(mHSV[2] * 255)), TEXT_HSV_POS[0], TEXT_HSV_POS[1] + TEXT_SIZE * 3, mText);
}
if (mRGBenabled) {
canvas.drawText("R: " + mRGB[0], TEXT_RGB_POS[0], TEXT_RGB_POS[1] + TEXT_SIZE, mText);
canvas.drawText("G: " + mRGB[1], TEXT_RGB_POS[0], TEXT_RGB_POS[1] + TEXT_SIZE * 2, mText);
canvas.drawText("B: " + mRGB[2], TEXT_RGB_POS[0], TEXT_RGB_POS[1] + TEXT_SIZE * 3, mText);
}
if (mYUVenabled) {
canvas.drawText("Y: " + Integer.toString((int)(mYUV[0] * 255)), TEXT_YUV_POS[0], TEXT_YUV_POS[1] + TEXT_SIZE, mText);
canvas.drawText("U: " + Integer.toString((int)((mYUV[1] + .5f) * 255)), TEXT_YUV_POS[0], TEXT_YUV_POS[1] + TEXT_SIZE * 2, mText);
canvas.drawText("V: " + Integer.toString((int)((mYUV[2] + .5f) * 255)), TEXT_YUV_POS[0], TEXT_YUV_POS[1] + TEXT_SIZE * 3, mText);
}
if (mHexenabled)
canvas.drawText("#" + mHexStr, TEXT_HEX_POS[0], TEXT_HEX_POS[1] + TEXT_SIZE, mText);
}
/**
* Place a small circle on the 2D palette to indicate the current values.
* @param canvas
* @param markerPosX
* @param markerPosY
*/
private void mark2DPalette(Canvas canvas, int markerPosX, int markerPosY) {
mPosMarker.setColor(Color.BLACK);
canvas.drawOval(new RectF(markerPosX - 5, markerPosY - 5, markerPosX + 5, markerPosY + 5), mPosMarker);
mPosMarker.setColor(Color.WHITE);
canvas.drawOval(new RectF(markerPosX - 3, markerPosY - 3, markerPosX + 3, markerPosY + 3), mPosMarker);
}
/**
* Draw a line across the slider to indicate its current value.
* @param canvas
* @param markerPos
*/
private void markVerSlider(Canvas canvas, int markerPos) {
mPosMarker.setColor(Color.BLACK);
canvas.drawRect(new Rect(0, markerPos - 2, SLIDER_THICKNESS, markerPos + 3), mPosMarker);
mPosMarker.setColor(Color.WHITE);
canvas.drawRect(new Rect(0, markerPos, SLIDER_THICKNESS, markerPos + 1), mPosMarker);
}
/**
* Frame the slider to indicate that it has trackball focus.
* @param canvas
*/
private void hilightFocusedVerSlider(Canvas canvas) {
mPosMarker.setColor(Color.WHITE);
canvas.drawRect(new Rect(0, 0, SLIDER_THICKNESS, PALETTE_DIM), mPosMarker);
mPosMarker.setColor(Color.BLACK);
canvas.drawRect(new Rect(2, 2, SLIDER_THICKNESS - 2, PALETTE_DIM - 2), mPosMarker);
}
/**
* Frame the 2D palette to indicate that it has trackball focus.
* @param canvas
*/
private void hilightFocusedOvalPalette(Canvas canvas) {
mPosMarker.setColor(Color.WHITE);
canvas.drawOval(new RectF(-PALETTE_RADIUS, -PALETTE_RADIUS, PALETTE_RADIUS, PALETTE_RADIUS), mPosMarker);
mPosMarker.setColor(Color.BLACK);
canvas.drawOval(new RectF(-PALETTE_RADIUS + 2, -PALETTE_RADIUS + 2, PALETTE_RADIUS - 2, PALETTE_RADIUS - 2), mPosMarker);
}
//NEW_METHOD_WORK_NEEDED_HERE
//To add a new method, replicate the basic draw functions here. Use the 2D palette or 1D sliders as templates for the new method.
/**
* Draw the UI for HSV with angular H and radial S combined in 2D and a 1D V slider.
* @param canvas
*/
private void drawHSV1Palette(Canvas canvas) {
canvas.save();
canvas.translate(PALETTE_POS_X, PALETTE_POS_Y);
//Draw the 2D palette
canvas.translate(PALETTE_CENTER_X, PALETTE_CENTER_Y);
canvas.drawOval(new RectF(-PALETTE_RADIUS, -PALETTE_RADIUS, PALETTE_RADIUS, PALETTE_RADIUS), mOvalHueSat);
canvas.drawOval(new RectF(-PALETTE_RADIUS, -PALETTE_RADIUS, PALETTE_RADIUS, PALETTE_RADIUS), mValDimmer);
if (mFocusedControl == 0)
hilightFocusedOvalPalette(canvas);
mark2DPalette(canvas, mCoord[0], mCoord[1]);
canvas.translate(-PALETTE_CENTER_X, -PALETTE_CENTER_Y);
//Draw the 1D slider
canvas.translate(PALETTE_DIM, 0);
canvas.drawBitmap(mVerSliderBM, 0, 0, null);
if (mFocusedControl == 1)
hilightFocusedVerSlider(canvas);
markVerSlider(canvas, mCoord[2]);
canvas.restore();
}
/**
* Initialize the current color chooser's UI (set its color parameters and set its palette and slider values accordingly).
*/
private void initUI() {
initHSV1Palette();
//Focus on the first controller (arbitrary).
mFocusedControl = 0;
}
//NEW_METHOD_WORK_NEEDED_HERE
//To add a new method, replicate and extend the last init function shown below
/**
* Initialize a color chooser.
*/
private void initHSV1Palette() {
setOvalValDimmer();
setVerValSlider();
float angle = 2*PI - mHSV[0] / (180 / 3.1415927f);
float radius = mHSV[1] * PALETTE_RADIUS;
mCoord[0] = (int)(Math.cos(angle) * radius);
mCoord[1] = (int)(Math.sin(angle) * radius);
mCoord[2] = PALETTE_DIM - (int)(mHSV[2] * PALETTE_DIM);
}
//NEW_METHOD_WORK_NEEDED_HERE
//To add a new method, replicate and extend the set functions below, one per UI controller in the new method
/**
* Adjust a Paint which, when painted, dims its underlying object to show the effects of varying value (brightness).
*/
private void setOvalValDimmer() {
float[] hsv = new float[3];
hsv[0] = mHSV[0];
hsv[1] = 0;
hsv[2] = mHSV[2];
int gray = Color.HSVToColor(hsv);
mValDimmer.setColor(gray);
}
/**
* Create a linear gradient shader to show variations in value.
*/
private void setVerValSlider() {
float[] hsv = new float[3];
hsv[0] = mHSV[0];
hsv[1] = mHSV[1];
hsv[2] = 1;
int col = Color.HSVToColor(hsv);
int colors[] = new int[2];
colors[0] = col;
colors[1] = 0xFF000000;
GradientDrawable gradDraw = new GradientDrawable(Orientation.TOP_BOTTOM, colors);
gradDraw.setDither(true);
gradDraw.setLevel(10000);
gradDraw.setBounds(0, 0, SLIDER_THICKNESS, PALETTE_DIM);
gradDraw.draw(mVerSliderCv);
}
/**
* Report the correct tightly bounded dimensions of the view.
*/
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
setMeasuredDimension(VIEW_DIM_X, VIEW_DIM_Y);
}
/**
* Wrap Math.round(). I'm not a Java expert. Is this the only way to avoid writing "(int)Math.round" everywhere?
* @param x
* @return
*/
private int round(double x) {
return (int)Math.round(x);
}
/**
* Limit a value to the range [0,1].
* @param n
* @return
*/
private float pinToUnit(float n) {
if (n < 0) {
n = 0;
} else if (n > 1) {
n = 1;
}
return n;
}
/**
* Limit a value to the range [0,max].
* @param n
* @param max
* @return
*/
private float pin(float n, float max) {
if (n < 0) {
n = 0;
} else if (n > max) {
n = max;
}
return n;
}
/**
* Limit a value to the range [min,max].
* @param n
* @param min
* @param max
* @return
*/
private float pin(float n, float min, float max) {
if (n < min) {
n = min;
} else if (n > max) {
n = max;
}
return n;
}
/**
* No clue what this does (some sort of average/mean I presume). It came with the original UberColorPickerDialog
* in the API Demos and wasn't documented. I don't feel like spending any time figuring it out, I haven't looked at it at all.
* @param s
* @param d
* @param p
* @return
*/
private int ave(int s, int d, float p) {
return s + round(p * (d - s));
}
/**
* Came with the original UberColorPickerDialog in the API Demos, wasn't documented. I believe it takes an array of
* colors and a value in the range [0,1] and interpolates a resulting color in a seemingly predictable manner.
* I haven't looked at it at all.
* @param colors
* @param unit
* @return
*/
private int interpColor(int colors[], float unit) {
if (unit <= 0) {
return colors[0];
}
if (unit >= 1) {
return colors[colors.length - 1];
}
float p = unit * (colors.length - 1);
int i = (int)p;
p -= i;
// now p is just the fractional part [0...1) and i is the index
int c0 = colors[i];
int c1 = colors[i+1];
int a = ave(Color.alpha(c0), Color.alpha(c1), p);
int r = ave(Color.red(c0), Color.red(c1), p);
int g = ave(Color.green(c0), Color.green(c1), p);
int b = ave(Color.blue(c0), Color.blue(c1), p);
return Color.argb(a, r, g, b);
}
/**
* A standard point-in-rect routine.
* @param x
* @param y
* @param r
* @return true if point x,y is in rect r
*/
public boolean ptInRect(int x, int y, Rect r) {
return x > r.left && x < r.right && y > r.top && y < r.bottom;
}
/**
* Process trackball events. Used mainly for fine-tuned color adjustment, or alternatively to switch between slider controls.
*/
@Override
public boolean dispatchTrackballEvent(MotionEvent event) {
float x = event.getX();
float y = event.getY();
//A longer event history implies faster trackball movement.
//Use it to infer a larger jump and therefore faster palette/slider adjustment.
int jump = event.getHistorySize() + 1;
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN: {
}
break;
case MotionEvent.ACTION_MOVE: {
//NEW_METHOD_WORK_NEEDED_HERE
//To add a new method, replicate and extend the appropriate entry in this list,
//depending on whether you use 1D or 2D controllers
switch (mMethod) {
case METHOD_HS_V_PALETTE:
if (mFocusedControl == 0) {
changeHSPalette(x, y, jump);
}
else if (mFocusedControl == 1) {
if (y < 0)
changeSlider(mFocusedControl, true, jump);
else if (y > 0)
changeSlider(mFocusedControl, false, jump);
}
break;
}
}
break;
case MotionEvent.ACTION_UP: {
}
break;
}
return true;
}
//NEW_METHOD_WORK_NEEDED_HERE
//To add a new method, replicate and extend the appropriate functions below,
//one per UI controller in the new method
/**
* Effect a trackball change to a 2D palette.
* @param x -1: negative x change, 0: no x change, +1: positive x change.
* @param y -1: negative y change, 0, no y change, +1: positive y change.
* @param jump the amount by which to change.
*/
private void changeHSPalette(float x, float y, int jump) {
int x2 = 0, y2 = 0;
if (x < 0)
x2 = -jump;
else if (x > 0)
x2 = jump;
if (y < 0)
y2 = -jump;
else if (y > 0)
y2 = jump;
mCoord[0] += x2;
mCoord[1] += y2;
if (mCoord[0] < -PALETTE_RADIUS)
mCoord[0] = -PALETTE_RADIUS;
else if (mCoord[0] > PALETTE_RADIUS)
mCoord[0] = PALETTE_RADIUS;
if (mCoord[1] < -PALETTE_RADIUS)
mCoord[1] = -PALETTE_RADIUS;
else if (mCoord[1] > PALETTE_RADIUS)
mCoord[1] = PALETTE_RADIUS;
float radius = (float)java.lang.Math.sqrt(mCoord[0] * mCoord[0] + mCoord[1] * mCoord[1]);
if (radius > PALETTE_RADIUS)
radius = PALETTE_RADIUS;
float angle = (float)java.lang.Math.atan2(mCoord[1], mCoord[0]);
// need to turn angle [-PI ... PI] into unit [0....1]
float unit = angle/(2*PI);
if (unit < 0) {
unit += 1;
}
mCoord[0] = round(Math.cos(angle) * radius);
mCoord[1] = round(Math.sin(angle) * radius);
int c = interpColor(mSpectrumColorsRev, unit);
float[] hsv = new float[3];
Color.colorToHSV(c, hsv);
mHSV[0] = hsv[0];
mHSV[1] = radius / PALETTE_RADIUS;
updateAllFromHSV();
mSwatchNew.setColor(Color.HSVToColor(mHSV));
setVerValSlider();
invalidate();
}
/**
* Effect a trackball change to a 1D slider.
* @param slider id of the slider to be effected
* @param increase true if the change is an increase, false if a decrease
* @param jump the amount by which to change in units of the range [0,255]
*/
private void changeSlider(int slider, boolean increase, int jump) {
//NEW_METHOD_WORK_NEEDED_HERE
//It is only necessary to add an entry here for a new method if the new method uses a 1D slider.
//Note, some sliders are horizontal and others are vertical.
//They differ a bit, especially in a sign flip on the vertical axis.
if (mMethod == METHOD_HS_V_PALETTE) {
//slider *must* equal 1
mHSV[2] += (increase ? jump : -jump) / 256.0f;
mHSV[2] = pinToUnit(mHSV[2]);
updateAllFromHSV();
mCoord[2] = PALETTE_DIM - (int)(mHSV[2] * PALETTE_DIM);
mSwatchNew.setColor(Color.HSVToColor(mHSV));
setOvalValDimmer();
invalidate();
}
}
/**
* Keep all colorspace representations in sync.
*/
private void updateRGBfromHSV() {
int color = Color.HSVToColor(mHSV);
mRGB[0] = Color.red(color);
mRGB[1] = Color.green(color);
mRGB[2] = Color.blue(color);
}
/**
* Keep all colorspace representations in sync.
*/
private void updateYUVfromRGB() {
float r = mRGB[0] / 255.0f;
float g = mRGB[1] / 255.0f;
float b = mRGB[2] / 255.0f;
ColorMatrix cm = new ColorMatrix();
cm.setRGB2YUV();
final float[] a = cm.getArray();
mYUV[0] = a[0] * r + a[1] * g + a[2] * b;
mYUV[0] = pinToUnit(mYUV[0]);
mYUV[1] = a[5] * r + a[6] * g + a[7] * b;
mYUV[1] = pin(mYUV[1], -.5f, .5f);
mYUV[2] = a[10] * r + a[11] * g + a[12] * b;
mYUV[2] = pin(mYUV[2], -.5f, .5f);
}
/**
* Keep all colorspace representations in sync.
*/
private void updateHexFromHSV() {
//For now, assume 100% opacity
mHexStr = Integer.toHexString(Color.HSVToColor(mHSV)).toUpperCase();
mHexStr = mHexStr.substring(2, mHexStr.length());
}
/**
* Keep all colorspace representations in sync.
*/
private void updateAllFromHSV() {
//Update mRGB
if (mRGBenabled || mYUVenabled)
updateRGBfromHSV();
//Update mYUV
if (mYUVenabled)
updateYUVfromRGB();
//Update mHexStr
if (mRGBenabled)
updateHexFromHSV();
}
/**
* Process touch events: down, move, and up
*/
@Override
public boolean onTouchEvent(MotionEvent event) {
float x = event.getX();
float y = event.getY();
//Generate coordinates which are palette=local with the origin at the upper left of the main 2D palette
int y2 = (int)(pin(round(y - PALETTE_POS_Y), PALETTE_DIM));
//Generate coordinates which are palette-local with the origin at the center of the main 2D palette
float circlePinnedX = x - PALETTE_POS_X - PALETTE_CENTER_X;
float circlePinnedY = y - PALETTE_POS_Y - PALETTE_CENTER_Y;
//Is the event in a swatch?
boolean inSwatchOld = ptInRect(round(x), round(y), mOldSwatchRect);
boolean inSwatchNew = ptInRect(round(x), round(y), mNewSwatchRect);
//Get the event's distance from the center of the main 2D palette
float radius = (float)java.lang.Math.sqrt(circlePinnedX * circlePinnedX + circlePinnedY * circlePinnedY);
//Is the event in a circle-pinned 2D palette?
boolean inOvalPalette = radius <= PALETTE_RADIUS;
//Pin the radius
if (radius > PALETTE_RADIUS)
radius = PALETTE_RADIUS;
//Is the event in a vertical slider to the right of the main 2D palette
boolean inVerSlider = ptInRect(round(x), round(y), mVerSliderRect);
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
mTracking = TRACKED_NONE;
if (inSwatchOld)
mTracking = TRACK_SWATCH_OLD;
else if (inSwatchNew)
mTracking = TRACK_SWATCH_NEW;
//NEW_METHOD_WORK_NEEDED_HERE
//To add a new method, replicate and extend the last entry in this list
else if (mMethod == METHOD_HS_V_PALETTE) {
if (inOvalPalette) {
mTracking = TRACK_HS_PALETTE;
mFocusedControl = 0;
}
else if (inVerSlider) {
mTracking = TRACK_VER_VALUE_SLIDER;
mFocusedControl = 1;
}
}
case MotionEvent.ACTION_MOVE:
//NEW_METHOD_WORK_NEEDED_HERE
//To add a new method, replicate and extend the entries in this list,
//one per UI controller the new method requires.
if (mTracking == TRACK_HS_PALETTE) {
float angle = (float)java.lang.Math.atan2(circlePinnedY, circlePinnedX);
// need to turn angle [-PI ... PI] into unit [0....1]
float unit = angle/(2*PI);
if (unit < 0) {
unit += 1;
}
mCoord[0] = round(Math.cos(angle) * radius);
mCoord[1] = round(Math.sin(angle) * radius);
int c = interpColor(mSpectrumColorsRev, unit);
float[] hsv = new float[3];
Color.colorToHSV(c, hsv);
mHSV[0] = hsv[0];
mHSV[1] = radius / PALETTE_RADIUS;
updateAllFromHSV();
mSwatchNew.setColor(Color.HSVToColor(mHSV));
setVerValSlider();
invalidate();
}
else if (mTracking == TRACK_VER_VALUE_SLIDER) {
if (mCoord[2] != y2) {
mCoord[2] = y2;
float value = 1.0f - (float)y2 / (float)PALETTE_DIM;
mHSV[2] = value;
updateAllFromHSV();
mSwatchNew.setColor(Color.HSVToColor(mHSV));
setOvalValDimmer();
invalidate();
}
}
break;
case MotionEvent.ACTION_UP:
//NEW_METHOD_WORK_NEEDED_HERE
//To add a new method, replicate and extend the last entry in this list.
if (mTracking == TRACK_SWATCH_OLD && inSwatchOld) {
Color.colorToHSV(mOriginalColor, mHSV);
mSwatchNew.setColor(mOriginalColor);
initUI();
invalidate();
}
else if (mTracking == TRACK_SWATCH_NEW && inSwatchNew) {
mListener.colorChanged(mSwatchNew.getColor());
invalidate();
}
mTracking= TRACKED_NONE;
break;
}
return true;
}
}
}
|
Java
|
/*
* 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.util;
import com.trilead.ssh2.crypto.Base64;
/**
* @author Kenny Root
*
*/
public class XmlBuilder {
private StringBuilder sb;
public XmlBuilder() {
sb = new StringBuilder();
}
public XmlBuilder append(String data) {
sb.append(data);
return this;
}
public XmlBuilder append(String field, Object data) {
if (data == null) {
sb.append(String.format("<%s/>", field));
} else if (data instanceof String) {
String input = (String) data;
boolean binary = false;
for (byte b : input.getBytes()) {
if (b < 0x20 || b > 0x7e) {
binary = true;
break;
}
}
sb.append(String.format("<%s>%s</%s>", field,
binary ? new String(Base64.encode(input.getBytes())) : input, field));
} else if (data instanceof Integer) {
sb.append(String.format("<%s>%d</%s>", field, (Integer) data, field));
} else if (data instanceof Long) {
sb.append(String.format("<%s>%d</%s>", field, (Long) data, field));
} else if (data instanceof byte[]) {
sb.append(String.format("<%s>%s</%s>", field, new String(Base64.encode((byte[]) data)), field));
} else if (data instanceof Boolean) {
sb.append(String.format("<%s>%s</%s>", field, (Boolean) data, field));
}
return this;
}
public String toString() {
return sb.toString();
}
}
|
Java
|
/*
* 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.util;
import java.util.LinkedList;
import java.util.List;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
/**
* @author Kenny Root
*
*/
public abstract class RobustSQLiteOpenHelper extends SQLiteOpenHelper {
private static List<String> mTableNames = new LinkedList<String>();
private static List<String> mIndexNames = new LinkedList<String>();
public RobustSQLiteOpenHelper(Context context, String name,
CursorFactory factory, int version) {
super(context, name, factory, version);
}
protected static void addTableName(String tableName) {
mTableNames.add(tableName);
}
protected static void addIndexName(String indexName) {
mIndexNames.add(indexName);
}
@Override
public void onCreate(SQLiteDatabase db) {
dropAllTables(db);
}
@Override
public final void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
try {
onRobustUpgrade(db, oldVersion, newVersion);
} catch (SQLiteException e) {
// The database has entered an unknown state. Try to recover.
try {
regenerateTables(db);
} catch (SQLiteException e2) {
dropAndCreateTables(db);
}
}
}
public abstract void onRobustUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) throws SQLiteException;
private void regenerateTables(SQLiteDatabase db) {
dropAllTablesWithPrefix(db, "OLD_");
for (String tableName : mTableNames)
db.execSQL("ALTER TABLE " + tableName + " RENAME TO OLD_"
+ tableName);
onCreate(db);
for (String tableName : mTableNames)
repopulateTable(db, tableName);
dropAllTablesWithPrefix(db, "OLD_");
}
private void repopulateTable(SQLiteDatabase db, String tableName) {
String columns = getTableColumnNames(db, tableName);
StringBuilder sb = new StringBuilder();
sb.append("INSERT INTO ")
.append(tableName)
.append(" (")
.append(columns)
.append(") SELECT ")
.append(columns)
.append(" FROM OLD_")
.append(tableName);
String sql = sb.toString();
db.execSQL(sql);
}
private String getTableColumnNames(SQLiteDatabase db, String tableName) {
StringBuilder sb = new StringBuilder();
Cursor fields = db.rawQuery("PRAGMA table_info(" + tableName + ")", null);
while (fields.moveToNext()) {
if (!fields.isFirst())
sb.append(", ");
sb.append(fields.getString(1));
}
fields.close();
return sb.toString();
}
private void dropAndCreateTables(SQLiteDatabase db) {
dropAllTables(db);
onCreate(db);
}
private void dropAllTablesWithPrefix(SQLiteDatabase db, String prefix) {
for (String indexName : mIndexNames)
db.execSQL("DROP INDEX IF EXISTS " + prefix + indexName);
for (String tableName : mTableNames)
db.execSQL("DROP TABLE IF EXISTS " + prefix + tableName);
}
private void dropAllTables(SQLiteDatabase db) {
dropAllTablesWithPrefix(db, "");
}
}
|
Java
|
/*
* 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.util;
import android.content.Context;
import android.preference.DialogPreference;
import android.util.AttributeSet;
import android.view.View;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
/**
* @author kenny
*
*/
public class VolumePreference extends DialogPreference implements OnSeekBarChangeListener {
/**
* @param context
* @param attrs
*/
public VolumePreference(Context context, AttributeSet attrs) {
super(context, attrs);
setupLayout(context, attrs);
}
public VolumePreference(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
setupLayout(context, attrs);
}
private void setupLayout(Context context, AttributeSet attrs) {
setPersistent(true);
}
@Override
protected View onCreateDialogView() {
SeekBar sb = new SeekBar(getContext());
sb.setMax(100);
sb.setProgress((int)(getPersistedFloat(
PreferenceConstants.DEFAULT_BELL_VOLUME) * 100));
sb.setPadding(10, 10, 10, 10);
sb.setOnSeekBarChangeListener(this);
return sb;
}
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
persistFloat(progress / 100f);
}
public void onStartTrackingTouch(SeekBar seekBar) { }
public void onStopTrackingTouch(SeekBar seekBar) { }
}
|
Java
|
/*
* 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.util;
public interface OnEntropyGatheredListener {
void onEntropyGathered(byte[] entropy);
}
|
Java
|
/*
* 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;
import org.connectbot.util.HelpTopicView;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ViewFlipper;
/**
* Show a series of wizard-like steps to the user, which might include an EULA,
* program credits, and helpful hints.
*
* @author jsharkey
*/
public class WizardActivity extends Activity {
protected ViewFlipper flipper = null;
private Button next, prev;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.act_wizard);
this.flipper = (ViewFlipper) findViewById(R.id.wizard_flipper);
// inflate the layout for EULA step
LayoutInflater inflater = LayoutInflater.from(this);
this.flipper.addView(inflater.inflate(R.layout.wiz_eula, this.flipper, false));
// Add a view for each help topic we want the user to see.
String[] topics = getResources().getStringArray(R.array.list_wizard_topics);
for (String topic : topics) {
flipper.addView(new HelpTopicView(this).setTopic(topic));
}
next = (Button)this.findViewById(R.id.action_next);
next.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
if(isLastDisplayed()) {
// user walked past end of wizard, so return okay
WizardActivity.this.setResult(Activity.RESULT_OK);
WizardActivity.this.finish();
} else {
// show next step and update buttons
flipper.showNext();
updateButtons();
}
}
});
prev = (Button)this.findViewById(R.id.action_prev);
prev.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
if(isFirstDisplayed()) {
// user walked past beginning of wizard, so return that they cancelled
WizardActivity.this.setResult(Activity.RESULT_CANCELED);
WizardActivity.this.finish();
} else {
// show previous step and update buttons
flipper.showPrevious();
updateButtons();
}
}
});
this.updateButtons();
}
protected boolean isFirstDisplayed() {
return (flipper.getDisplayedChild() == 0);
}
protected boolean isLastDisplayed() {
return (flipper.getDisplayedChild() == flipper.getChildCount() - 1);
}
protected void updateButtons() {
boolean eula = (flipper.getDisplayedChild() == 0);
next.setText(eula ? getString(R.string.wizard_agree) : getString(R.string.wizard_next));
prev.setText(eula ? getString(R.string.delete_neg) : getString(R.string.wizard_back));
}
}
|
Java
|
package net.sourceforge.jsocks;
import net.sourceforge.jsocks.server.*;
import java.net.*;
import java.io.*;
/**
UDP Relay server, used by ProxyServer to perform udp forwarding.
*/
class UDPRelayServer implements Runnable{
DatagramSocket client_sock;
DatagramSocket remote_sock;
Socket controlConnection;
int relayPort;
InetAddress relayIP;
Thread pipe_thread1,pipe_thread2;
Thread master_thread;
ServerAuthenticator auth;
long lastReadTime;
static PrintStream log = null;
static Proxy proxy = null;
static int datagramSize = 0xFFFF;//64K, a bit more than max udp size
static int iddleTimeout = 180000;//3 minutes
/**
Constructs UDP relay server to communicate with client
on given ip and port.
@param clientIP Address of the client from whom datagrams
will be recieved and to whom they will be forwarded.
@param clientPort Clients port.
@param master_thread Thread which will be interrupted, when
UDP relay server stoppes for some reason.
@param controlConnection Socket which will be closed, before
interrupting the master thread, it is introduced due to a bug
in windows JVM which does not throw InterruptedIOException in
threads which block in I/O operation.
*/
public UDPRelayServer(InetAddress clientIP,int clientPort,
Thread master_thread,
Socket controlConnection,
ServerAuthenticator auth)
throws IOException{
this.master_thread = master_thread;
this.controlConnection = controlConnection;
this.auth = auth;
client_sock = new Socks5DatagramSocket(true,auth.getUdpEncapsulation(),
clientIP,clientPort);
relayPort = client_sock.getLocalPort();
relayIP = client_sock.getLocalAddress();
if(relayIP.getHostAddress().equals("0.0.0.0"))
relayIP = InetAddress.getLocalHost();
if(proxy == null)
remote_sock = new DatagramSocket();
else
remote_sock = new Socks5DatagramSocket(proxy,0,null);
}
//Public methods
/////////////////
/**
Sets the timeout for UDPRelay server.<br>
Zero timeout implies infinity.<br>
Default timeout is 3 minutes.
*/
static public void setTimeout(int timeout){
iddleTimeout = timeout;
}
/**
Sets the size of the datagrams used in the UDPRelayServer.<br>
Default size is 64K, a bit more than maximum possible size of the
datagram.
*/
static public void setDatagramSize(int size){
datagramSize = size;
}
/**
Port to which client should send datagram for association.
*/
public int getRelayPort(){
return relayPort;
}
/**
IP address to which client should send datagrams for association.
*/
public InetAddress getRelayIP(){
return relayIP;
}
/**
Starts udp relay server.
Spawns two threads of execution and returns.
*/
public void start() throws IOException{
remote_sock.setSoTimeout(iddleTimeout);
client_sock.setSoTimeout(iddleTimeout);
log("Starting UDP relay server on "+relayIP+":"+relayPort);
log("Remote socket "+remote_sock.getLocalAddress()+":"+
remote_sock.getLocalPort());
pipe_thread1 = new Thread(this,"pipe1");
pipe_thread2 = new Thread(this,"pipe2");
lastReadTime = System.currentTimeMillis();
pipe_thread1.start();
pipe_thread2.start();
}
/**
Stops Relay server.
<p>
Does not close control connection, does not interrupt master_thread.
*/
public synchronized void stop(){
master_thread = null;
controlConnection = null;
abort();
}
//Runnable interface
////////////////////
public void run(){
try{
if(Thread.currentThread().getName().equals("pipe1"))
pipe(remote_sock,client_sock,false);
else
pipe(client_sock,remote_sock,true);
}catch(IOException ioe){
}finally{
abort();
log("UDP Pipe thread "+Thread.currentThread().getName()+" stopped.");
}
}
//Private methods
/////////////////
private synchronized void abort(){
if(pipe_thread1 == null) return;
log("Aborting UDP Relay Server");
remote_sock.close();
client_sock.close();
if(controlConnection != null)
try{ controlConnection.close();} catch(IOException ioe){}
if(master_thread!=null) master_thread.interrupt();
pipe_thread1.interrupt();
pipe_thread2.interrupt();
pipe_thread1 = null;
}
static private void log(String s){
if(log != null){
log.println(s);
log.flush();
}
}
private void pipe(DatagramSocket from,DatagramSocket to,boolean out)
throws IOException{
byte[] data = new byte[datagramSize];
DatagramPacket dp = new DatagramPacket(data,data.length);
while(true){
try{
from.receive(dp);
lastReadTime = System.currentTimeMillis();
if(auth.checkRequest(dp,out))
to.send(dp);
}catch(UnknownHostException uhe){
log("Dropping datagram for unknown host");
}catch(InterruptedIOException iioe){
//log("Interrupted: "+iioe);
//If we were interrupted by other thread.
if(iddleTimeout == 0) return;
//If last datagram was received, long time ago, return.
long timeSinceRead = System.currentTimeMillis() - lastReadTime;
if(timeSinceRead >= iddleTimeout -100) //-100 for adjustment
return;
}
dp.setLength(data.length);
}
}
}
|
Java
|
package net.sourceforge.jsocks;
import java.io.IOException;
import java.io.InputStream;
import java.net.InetAddress;
import java.net.UnknownHostException;
/**
Proxy which describes SOCKS4 proxy.
*/
public class Socks4Proxy extends Proxy implements Cloneable{
//Data members
String user;
//Public Constructors
//====================
/**
Creates the SOCKS4 proxy
@param p Proxy to use to connect to this proxy, allows proxy chaining.
@param proxyHost Address of the proxy server.
@param proxyPort Port of the proxy server
@param user User name to use for identification purposes.
@throws UnknownHostException If proxyHost can't be resolved.
*/
public Socks4Proxy(String proxyHost,int proxyPort,String user)
throws UnknownHostException{
super(proxyHost,proxyPort);
this.user = new String(user);
version = 4;
}
/**
Creates the SOCKS4 proxy
@param p Proxy to use to connect to this proxy, allows proxy chaining.
@param proxyIP Address of the proxy server.
@param proxyPort Port of the proxy server
@param user User name to use for identification purposes.
*/
public Socks4Proxy(Proxy p,InetAddress proxyIP,int proxyPort,String user){
super(p,proxyIP,proxyPort);
this.user = new String(user);
version = 4;
}
/**
Creates the SOCKS4 proxy
@param proxyIP Address of the proxy server.
@param proxyPort Port of the proxy server
@param user User name to use for identification purposes.
*/
public Socks4Proxy(InetAddress proxyIP,int proxyPort,String user){
this(null,proxyIP,proxyPort,user);
}
//Public instance methods
//========================
/**
* Creates a clone of this proxy. Changes made to the clone should not
* affect this object.
*/
public Object clone(){
Socks4Proxy newProxy = new Socks4Proxy(proxyIP,proxyPort,user);
newProxy.chainProxy = chainProxy;
return newProxy;
}
//Public Static(Class) Methods
//==============================
//Protected Methods
//=================
protected Proxy copy(){
Socks4Proxy copy = new Socks4Proxy(proxyIP,proxyPort,user);
copy.chainProxy = chainProxy;
return copy;
}
protected ProxyMessage formMessage(int cmd,InetAddress ip,int port){
switch(cmd){
case SOCKS_CMD_CONNECT:
cmd = Socks4Message.REQUEST_CONNECT;
break;
case SOCKS_CMD_BIND:
cmd = Socks4Message.REQUEST_BIND;
break;
default:
return null;
}
return new Socks4Message(cmd,ip,port,user);
}
protected ProxyMessage formMessage(int cmd,String host,int port)
throws UnknownHostException{
return formMessage(cmd,InetAddress.getByName(host),port);
}
protected ProxyMessage formMessage(InputStream in)
throws SocksException,
IOException{
return new Socks4Message(in,true);
}
}
|
Java
|
package net.sourceforge.jsocks;
import java.io.DataInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.UnknownHostException;
/**
SOCKS5 request/response message.
*/
public class Socks5Message extends ProxyMessage{
/** Address type of given message*/
public int addrType;
byte[] data;
/**
Server error response.
@param cmd Error code.
*/
public Socks5Message(int cmd){
super(cmd,null,0);
data = new byte[3];
data[0] = SOCKS_VERSION; //Version.
data[1] = (byte)cmd; //Reply code for some kind of failure.
data[2] = 0; //Reserved byte.
}
/**
Construct client request or server response.
@param cmd - Request/Response code.
@param ip - IP field.
@paarm port - port field.
*/
public Socks5Message(int cmd,InetAddress ip,int port){
super(cmd,ip,port);
this.host = ip==null?"0.0.0.0":ip.getHostName();
this.version = SOCKS_VERSION;
byte[] addr;
if(ip == null){
addr = new byte[4];
addr[0]=addr[1]=addr[2]=addr[3]=0;
}else
addr = ip.getAddress();
addrType = addr.length == 4 ? SOCKS_ATYP_IPV4
: SOCKS_ATYP_IPV6;
data = new byte[6+addr.length];
data[0] = (byte) SOCKS_VERSION; //Version
data[1] = (byte) command; //Command
data[2] = (byte) 0; //Reserved byte
data[3] = (byte) addrType; //Address type
//Put Address
System.arraycopy(addr,0,data,4,addr.length);
//Put port
data[data.length-2] = (byte)(port>>8);
data[data.length-1] = (byte)(port);
}
/**
Construct client request or server response.
@param cmd - Request/Response code.
@param hostName - IP field as hostName, uses ADDR_TYPE of HOSTNAME.
@paarm port - port field.
*/
public Socks5Message(int cmd,String hostName,int port){
super(cmd,null,port);
this.host = hostName;
this.version = SOCKS_VERSION;
//System.out.println("Doing ATYP_DOMAINNAME");
addrType = SOCKS_ATYP_DOMAINNAME;
byte addr[] = hostName.getBytes();
data =new byte[7+addr.length];
data[0] = (byte) SOCKS_VERSION; //Version
data[1] = (byte) command; //Command
data[2] = (byte) 0; //Reserved byte
data[3] = (byte) SOCKS_ATYP_DOMAINNAME; //Address type
data[4] = (byte) addr.length; //Length of the address
//Put Address
System.arraycopy(addr,0,data,5,addr.length);
//Put port
data[data.length-2] = (byte)(port >>8);
data[data.length-1] = (byte)(port);
}
/**
Initialises Message from the stream. Reads server response from
given stream.
@param in Input stream to read response from.
@throws SocksException If server response code is not SOCKS_SUCCESS(0), or
if any error with protocol occurs.
@throws IOException If any error happens with I/O.
*/
public Socks5Message(InputStream in) throws SocksException,
IOException{
this(in,true);
}
/**
Initialises Message from the stream. Reads server response or client
request from given stream.
@param in Input stream to read response from.
@param clinetMode If true read server response, else read client request.
@throws SocksException If server response code is not SOCKS_SUCCESS(0) and
reading in client mode, or if any error with protocol occurs.
@throws IOException If any error happens with I/O.
*/
public Socks5Message(InputStream in,boolean clientMode)throws SocksException,
IOException{
read(in,clientMode);
}
/**
Initialises Message from the stream. Reads server response from
given stream.
@param in Input stream to read response from.
@throws SocksException If server response code is not SOCKS_SUCCESS(0), or
if any error with protocol occurs.
@throws IOException If any error happens with I/O.
*/
public void read(InputStream in) throws SocksException,
IOException{
read(in,true);
}
/**
Initialises Message from the stream. Reads server response or client
request from given stream.
@param in Input stream to read response from.
@param clinetMode If true read server response, else read client request.
@throws SocksException If server response code is not SOCKS_SUCCESS(0) and
reading in client mode, or if any error with protocol occurs.
@throws IOException If any error happens with I/O.
*/
public void read(InputStream in,boolean clientMode) throws SocksException,
IOException{
data = null;
ip = null;
DataInputStream di = new DataInputStream(in);
version = di.readUnsignedByte();
command = di.readUnsignedByte();
if(clientMode && command != 0)
throw new SocksException(command);
@SuppressWarnings("unused")
int reserved = di.readUnsignedByte();
addrType = di.readUnsignedByte();
byte addr[];
switch(addrType){
case SOCKS_ATYP_IPV4:
addr = new byte[4];
di.readFully(addr);
host = bytes2IPV4(addr,0);
break;
case SOCKS_ATYP_IPV6:
addr = new byte[SOCKS_IPV6_LENGTH];//I believe it is 16 bytes,huge!
di.readFully(addr);
host = bytes2IPV6(addr,0);
break;
case SOCKS_ATYP_DOMAINNAME:
//System.out.println("Reading ATYP_DOMAINNAME");
addr = new byte[di.readUnsignedByte()];//Next byte shows the length
di.readFully(addr);
host = new String(addr);
break;
default:
throw(new SocksException(Proxy.SOCKS_JUST_ERROR));
}
port = di.readUnsignedShort();
if(addrType != SOCKS_ATYP_DOMAINNAME && doResolveIP){
try{
ip = InetAddress.getByName(host);
}catch(UnknownHostException uh_ex){
}
}
}
/**
Writes the message to the stream.
@param out Output stream to which message should be written.
*/
public void write(OutputStream out)throws SocksException,
IOException{
if(data == null){
Socks5Message msg;
if(addrType == SOCKS_ATYP_DOMAINNAME)
msg = new Socks5Message(command,host,port);
else{
if(ip == null){
try{
ip = InetAddress.getByName(host);
}catch(UnknownHostException uh_ex){
throw new SocksException(Proxy.SOCKS_JUST_ERROR);
}
}
msg = new Socks5Message(command,ip,port);
}
data = msg.data;
}
out.write(data);
}
/**
Returns IP field of the message as IP, if the message was created
with ATYP of HOSTNAME, it will attempt to resolve the hostname,
which might fail.
@throws UnknownHostException if host can't be resolved.
*/
public InetAddress getInetAddress() throws UnknownHostException{
if(ip!=null) return ip;
return (ip=InetAddress.getByName(host));
}
/**
Returns string representation of the message.
*/
public String toString(){
String s=
"Socks5Message:"+"\n"+
"VN "+version+"\n"+
"CMD "+command+"\n"+
"ATYP "+addrType+"\n"+
"ADDR "+host+"\n"+
"PORT "+port+"\n";
return s;
}
/**
*Wether to resolve hostIP returned from SOCKS server
*that is wether to create InetAddress object from the
*hostName string
*/
static public boolean resolveIP(){ return doResolveIP;}
/**
*Wether to resolve hostIP returned from SOCKS server
*that is wether to create InetAddress object from the
*hostName string
*@param doResolve Wether to resolve hostIP from SOCKS server.
*@return Previous value.
*/
static public boolean resolveIP(boolean doResolve){
boolean old = doResolveIP;
doResolveIP = doResolve;
return old;
}
/*
private static final void debug(String s){
if(DEBUG)
System.out.print(s);
}
private static final boolean DEBUG = false;
*/
//SOCKS5 constants
public static final int SOCKS_VERSION =5;
public static final int SOCKS_ATYP_IPV4 =0x1; //Where is 2??
public static final int SOCKS_ATYP_DOMAINNAME =0x3; //!!!!rfc1928
public static final int SOCKS_ATYP_IPV6 =0x4;
public static final int SOCKS_IPV6_LENGTH =16;
static boolean doResolveIP = true;
}
|
Java
|
package net.sourceforge.jsocks;
import java.io.DataInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.UnknownHostException;
/**
SOCKS4 Reply/Request message.
*/
public class Socks4Message extends ProxyMessage{
private byte[] msgBytes;
private int msgLength;
/**
* Server failed reply, cmd command for failed request
*/
public Socks4Message(int cmd){
super(cmd,null,0);
this.user = null;
msgLength = 2;
msgBytes = new byte[2];
msgBytes[0] = (byte) 0;
msgBytes[1] = (byte) command;
}
/**
* Server successfull reply
*/
public Socks4Message(int cmd,InetAddress ip,int port){
this(0,cmd,ip,port,null);
}
/**
* Client request
*/
public Socks4Message(int cmd,InetAddress ip,int port,String user){
this(SOCKS_VERSION,cmd,ip,port,user);
}
/**
* Most general constructor
*/
public Socks4Message(int version, int cmd,
InetAddress ip,int port,String user){
super(cmd,ip,port);
this.user = user;
this.version = version;
msgLength = user == null?8:9+user.length();
msgBytes = new byte[msgLength];
msgBytes[0] = (byte) version;
msgBytes[1] = (byte) command;
msgBytes[2] = (byte) (port >> 8);
msgBytes[3] = (byte) port;
byte[] addr;
if(ip != null)
addr = ip.getAddress();
else{
addr = new byte[4];
addr[0]=addr[1]=addr[2]=addr[3]=0;
}
System.arraycopy(addr,0,msgBytes,4,4);
if(user != null){
byte[] buf = user.getBytes();
System.arraycopy(buf,0,msgBytes,8,buf.length);
msgBytes[msgBytes.length -1 ] = 0;
}
}
/**
*Initialise from the stream
*If clientMode is true attempts to read a server response
*otherwise reads a client request
*see read for more detail
*/
public Socks4Message(InputStream in, boolean clientMode) throws IOException{
msgBytes = null;
read(in,clientMode);
}
@Override
public void read(InputStream in) throws IOException{
read(in,true);
}
@Override
public void read(InputStream in, boolean clientMode) throws IOException{
boolean mode4a = false;
DataInputStream d_in = new DataInputStream(in);
version= d_in.readUnsignedByte();
command = d_in.readUnsignedByte();
if(clientMode && command != REPLY_OK){
String errMsg;
if(command >REPLY_OK && command < REPLY_BAD_IDENTD)
errMsg = replyMessage[command-REPLY_OK];
else
errMsg = "Unknown Reply Code";
throw new SocksException(command,errMsg);
}
port = d_in.readUnsignedShort();
byte[] addr = new byte[4];
d_in.readFully(addr);
if (addr[0] == 0 && addr[1] == 0 && addr[2] == 0 && addr[3] != 0)
mode4a = true;
else {
ip=bytes2IP(addr);
host = ip.getHostName();
}
if(!clientMode){
StringBuilder sb = new StringBuilder();
int b;
while ((b = in.read()) != 0)
sb.append((char) b);
user = sb.toString();
if (mode4a) {
sb.setLength(0);
while ((b = in.read()) != 0)
sb.append((char) b);
host = sb.toString();
}
}
}
@Override
public void write(OutputStream out) throws IOException{
if(msgBytes == null){
Socks4Message msg = new Socks4Message(version,command,ip,port,user);
msgBytes = msg.msgBytes;
msgLength = msg.msgLength;
}
out.write(msgBytes);
}
//Class methods
static InetAddress bytes2IP(byte[] addr){
String s = bytes2IPV4(addr,0);
try{
return InetAddress.getByName(s);
}catch(UnknownHostException uh_ex){
return null;
}
}
//Constants
static final String[] replyMessage ={
"Request Granted",
"Request Rejected or Failed",
"Failed request, can't connect to Identd",
"Failed request, bad user name"};
static final int SOCKS_VERSION = 4;
public final static int REQUEST_CONNECT = 1;
public final static int REQUEST_BIND = 2;
public final static int REPLY_OK = 90;
public final static int REPLY_REJECTED = 91;
public final static int REPLY_NO_CONNECT = 92;
public final static int REPLY_BAD_IDENTD = 93;
}
|
Java
|
package net.sourceforge.jsocks;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.UnknownHostException;
/**
Abstract class which describes SOCKS4/5 response/request.
*/
public abstract class ProxyMessage{
/** Host as an IP address */
public InetAddress ip=null;
/** SOCKS version, or version of the response for SOCKS4*/
public int version;
/** Port field of the request/response*/
public int port;
/** Request/response code as an int*/
public int command;
/** Host as string.*/
public String host=null;
/** User field for SOCKS4 request messages*/
public String user=null;
ProxyMessage(int command,InetAddress ip,int port){
this.command = command;
this.ip = ip;
this.port = port;
}
ProxyMessage(){
}
/**
Initialises Message from the stream. Reads server response from
given stream.
@param in Input stream to read response from.
@throws SocksException If server response code is not SOCKS_SUCCESS(0), or
if any error with protocol occurs.
@throws IOException If any error happens with I/O.
*/
public abstract void read(InputStream in)
throws SocksException,
IOException;
/**
Initialises Message from the stream. Reads server response or client
request from given stream.
@param in Input stream to read response from.
@param clinetMode If true read server response, else read client request.
@throws SocksException If server response code is not SOCKS_SUCCESS(0) and
reading in client mode, or if any error with protocol occurs.
@throws IOException If any error happens with I/O.
*/
public abstract void read(InputStream in,boolean client_mode)
throws SocksException,
IOException;
/**
Writes the message to the stream.
@param out Output stream to which message should be written.
*/
public abstract void write(OutputStream out)throws SocksException,
IOException;
/**
Get the Address field of this message as InetAddress object.
@return Host address or null, if one can't be determined.
*/
public InetAddress getInetAddress() throws UnknownHostException{
return ip;
}
/**
Get string representaion of this message.
@return string representation of this message.
*/
public String toString(){
return
"Proxy Message:\n"+
"Version:"+ version+"\n"+
"Command:"+ command+"\n"+
"IP: "+ ip+"\n"+
"Port: "+ port+"\n"+
"User: "+ user+"\n" ;
}
//Package methods
//////////////////
static final String bytes2IPV4(byte[] addr,int offset){
String hostName = ""+(addr[offset] & 0xFF);
for(int i = offset+1;i<offset+4;++i)
hostName+="."+(addr[i] & 0xFF);
return hostName;
}
static final String bytes2IPV6(byte[] addr,int offset){
//Have no idea how they look like!
return null;
}
}
|
Java
|
package net.sourceforge.jsocks;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.Socket;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.Enumeration;
import java.util.Hashtable;
/**
SOCKS5 Proxy.
*/
public class Socks5Proxy extends Proxy implements Cloneable{
//Data members
private Hashtable<Integer, Authentication> authMethods = new Hashtable<Integer, Authentication>();
private int selectedMethod;
boolean resolveAddrLocally = true;
UDPEncapsulation udp_encapsulation=null;
//Public Constructors
//====================
/**
Creates SOCKS5 proxy.
@param proxyHost Host on which a Proxy server runs.
@param proxyPort Port on which a Proxy server listens for connections.
@throws UnknownHostException If proxyHost can't be resolved.
*/
public Socks5Proxy(String proxyHost,int proxyPort)
throws UnknownHostException{
super(proxyHost,proxyPort);
version = 5;
setAuthenticationMethod(0,new AuthenticationNone());
}
/**
Creates SOCKS5 proxy.
@param proxyIP Host on which a Proxy server runs.
@param proxyPort Port on which a Proxy server listens for connections.
*/
public Socks5Proxy(InetAddress proxyIP,int proxyPort){
super(proxyIP,proxyPort);
version = 5;
setAuthenticationMethod(0,new AuthenticationNone());
}
//Public instance methods
//========================
/**
* Wether to resolve address locally or to let proxy do so.
<p>
SOCKS5 protocol allows to send host names rather then IPs in the
requests, this option controls wether the hostnames should be send
to the proxy server as names, or should they be resolved locally.
@param doResolve Wether to perform resolution locally.
@return Previous settings.
*/
public boolean resolveAddrLocally(boolean doResolve){
boolean old = resolveAddrLocally;
resolveAddrLocally = doResolve;
return old;
}
/**
Get current setting on how the addresses should be handled.
@return Current setting for address resolution.
@see Socks5Proxy#resolveAddrLocally(boolean doResolve)
*/
public boolean resolveAddrLocally(){
return resolveAddrLocally;
}
/**
Adds another authentication method.
@param methodId Authentication method id, see rfc1928
@param method Implementation of Authentication
@see Authentication
*/
public boolean setAuthenticationMethod(int methodId,
Authentication method){
if(methodId<0 || methodId > 255)
return false;
if(method == null){
//Want to remove a particular method
return (authMethods.remove(new Integer(methodId)) != null);
}else{//Add the method, or rewrite old one
authMethods.put(new Integer(methodId),method);
}
return true;
}
/**
Get authentication method, which corresponds to given method id
@param methodId Authentication method id.
@return Implementation for given method or null, if one was not set.
*/
public Authentication getAuthenticationMethod(int methodId){
Object method = authMethods.get(new Integer(methodId));
if(method == null) return null;
return (Authentication)method;
}
/**
Creates a clone of this Proxy.
*/
@SuppressWarnings("unchecked")
public Object clone(){
Socks5Proxy newProxy = new Socks5Proxy(proxyIP,proxyPort);
newProxy.authMethods = (Hashtable<Integer, Authentication>) this.authMethods.clone();
newProxy.resolveAddrLocally = resolveAddrLocally;
newProxy.chainProxy = chainProxy;
return newProxy;
}
//Public Static(Class) Methods
//==============================
//Protected Methods
//=================
protected Proxy copy(){
Socks5Proxy copy = new Socks5Proxy(proxyIP,proxyPort);
copy.authMethods = this.authMethods; //same Hash, no copy
copy.chainProxy = this.chainProxy;
copy.resolveAddrLocally = this.resolveAddrLocally;
return copy;
}
/**
*
*
*/
protected void startSession()throws SocksException{
super.startSession();
Authentication auth;
Socket ps = proxySocket; //The name is too long
try{
byte nMethods = (byte) authMethods.size(); //Number of methods
byte[] buf = new byte[2+nMethods]; //2 is for VER,NMETHODS
buf[0] = (byte) version;
buf[1] = nMethods; //Number of methods
int i=2;
Enumeration<Integer> ids = authMethods.keys();
while(ids.hasMoreElements())
buf[i++] = (byte)((Integer)ids.nextElement()).intValue();
out.write(buf);
out.flush();
int versionNumber = in.read();
selectedMethod = in.read();
if(versionNumber < 0 || selectedMethod < 0){
//EOF condition was reached
endSession();
throw(new SocksException(SOCKS_PROXY_IO_ERROR,
"Connection to proxy lost."));
}
if(versionNumber < version){
//What should we do??
}
if(selectedMethod == 0xFF){ //No method selected
ps.close();
throw ( new SocksException(SOCKS_AUTH_NOT_SUPPORTED));
}
auth = getAuthenticationMethod(selectedMethod);
if(auth == null){
//This shouldn't happen, unless method was removed by other
//thread, or the server stuffed up
throw(new SocksException(SOCKS_JUST_ERROR,
"Speciefied Authentication not found!"));
}
Object[] in_out = auth.doSocksAuthentication(selectedMethod,ps);
if(in_out == null){
//Authentication failed by some reason
throw(new SocksException(SOCKS_AUTH_FAILURE));
}
//Most authentication methods are expected to return
//simply the input/output streams associated with
//the socket. However if the auth. method requires
//some kind of encryption/decryption being done on the
//connection it should provide classes to handle I/O.
in = (InputStream) in_out[0];
out = (OutputStream) in_out[1];
if(in_out.length > 2)
udp_encapsulation = (UDPEncapsulation) in_out[2];
}catch(SocksException s_ex){
throw s_ex;
}catch(UnknownHostException uh_ex){
throw(new SocksException(SOCKS_PROXY_NO_CONNECT));
}catch(SocketException so_ex){
throw(new SocksException(SOCKS_PROXY_NO_CONNECT));
}catch(IOException io_ex){
//System.err.println(io_ex);
throw(new SocksException(SOCKS_PROXY_IO_ERROR,""+io_ex));
}
}
protected ProxyMessage formMessage(int cmd,InetAddress ip,int port){
return new Socks5Message(cmd,ip,port);
}
protected ProxyMessage formMessage(int cmd,String host,int port)
throws UnknownHostException{
if(resolveAddrLocally)
return formMessage(cmd,InetAddress.getByName(host),port);
else
return new Socks5Message(cmd,host,port);
}
protected ProxyMessage formMessage(InputStream in)
throws SocksException,
IOException{
return new Socks5Message(in);
}
}
|
Java
|
package net.sourceforge.jsocks;
/**
The Authentication interface provides for performing method specific
authentication for SOCKS5 connections.
*/
public interface Authentication{
/**
This method is called when SOCKS5 server have selected a particular
authentication method, for whch an implementaion have been registered.
<p>
This method should return an array {inputstream,outputstream
[,UDPEncapsulation]}. The reason for that is that SOCKS5 protocol
allows to have method specific encapsulation of data on the socket for
purposes of integrity or security. And this encapsulation should be
performed by those streams returned from the method. It is also possible
to encapsulate datagrams. If authentication method supports such
encapsulation an instance of the UDPEncapsulation interface should be
returned as third element of the array, otherwise either null should be
returned as third element, or array should contain only 2 elements.
@param methodId Authentication method selected by the server.
@param proxySocket Socket used to conect to the proxy.
@return Two or three element array containing
Input/Output streams which should be used on this connection.
Third argument is optional and should contain an instance
of UDPEncapsulation. It should be provided if the authentication
method used requires any encapsulation to be done on the
datagrams.
*/
Object[] doSocksAuthentication(int methodId,java.net.Socket proxySocket)
throws java.io.IOException;
}
|
Java
|
package net.sourceforge.jsocks;
/**
SOCKS5 none authentication. Dummy class does almost nothing.
*/
public class AuthenticationNone implements Authentication{
public Object[] doSocksAuthentication(int methodId,
java.net.Socket proxySocket)
throws java.io.IOException{
if(methodId!=0) return null;
return new Object[] { proxySocket.getInputStream(),
proxySocket.getOutputStream()};
}
}
|
Java
|
package net.sourceforge.jsocks;
import java.net.*;
import java.io.*;
/**
* SocksSocket tryies to look very similar to normal Socket,
* while allowing connections through the SOCKS4 or 5 proxy.
* To use this class you will have to identify proxy you need
* to use, Proxy class allows you to set default proxy, which
* will be used by all Socks aware sockets. You can also create
* either Socks4Proxy or Socks5Proxy, and use them by passing to the
* appropriate constructors.
* <P>
* Using Socks package can be as easy as that:
*
* <pre><tt>
*
* import Socks.*;
* ....
*
* try{
* //Specify SOCKS5 proxy
* Proxy.setDefaultProxy("socks-proxy",1080);
*
* //OR you still use SOCKS4
* //Code below uses SOCKS4 proxy
* //Proxy.setDefaultProxy("socks-proxy",1080,userName);
*
* Socket s = SocksSocket("some.host.of.mine",13);
* readTimeFromSock(s);
* }catch(SocksException sock_ex){
* //Usually it will turn in more or less meaningfull message
* System.err.println("SocksException:"+sock_ex);
* }
*
* </tt></pre>
*<P>
* However if the need exist for more control, like resolving addresses
* remotely, or using some non-trivial authentication schemes, it can be done.
*/
public class SocksSocket extends Socket{
//Data members
protected Proxy proxy;
protected String localHost, remoteHost;
protected InetAddress localIP, remoteIP;
protected int localPort,remotePort;
private Socket directSock = null;
/**
* Tryies to connect to given host and port
* using default proxy. If no default proxy speciefied
* it throws SocksException with error code SOCKS_NO_PROXY.
@param host Machine to connect to.
@param port Port to which to connect.
* @see SocksSocket#SocksSocket(Proxy,String,int)
* @see Socks5Proxy#resolveAddrLocally
*/
public SocksSocket(String host,int port)
throws SocksException,UnknownHostException{
this(Proxy.defaultProxy,host,port);
}
/**
* Connects to host port using given proxy server.
@param p Proxy to use.
@param host Machine to connect to.
@param port Port to which to connect.
@throws UnknownHostException
If one of the following happens:
<ol>
<li> Proxy settings say that address should be resolved locally, but
this fails.
<li> Proxy settings say that the host should be contacted directly but
host name can't be resolved.
</ol>
@throws SocksException
If one of the following happens:
<ul>
<li> Proxy is is null.
<li> Proxy settings say that the host should be contacted directly but
this fails.
<li> Socks Server can't be contacted.
<li> Authentication fails.
<li> Connection is not allowed by the SOCKS proxy.
<li> SOCKS proxy can't establish the connection.
<li> Any IO error occured.
<li> Any protocol error occured.
</ul>
@throws IOexception if anything is wrong with I/O.
@see Socks5Proxy#resolveAddrLocally
*/
public SocksSocket(Proxy p, String host, int port) throws SocksException,
UnknownHostException {
remoteHost = host;
remotePort = port;
remoteIP = InetAddress.getByName(host);
doDirect();
}
/**
Connects to given ip and port using given Proxy server.
@param p Proxy to use.
@param ip Machine to connect to.
@param port Port to which to connect.
*/
public SocksSocket(InetAddress ip, int port) throws SocksException{
this.remoteIP = ip;
this.remotePort = port;
this.remoteHost = ip.getHostName();
doDirect();
}
/**
* These 2 constructors are used by the SocksServerSocket.
* This socket simply overrides remoteHost, remotePort
*/
protected SocksSocket(String host,int port,Proxy proxy){
this.remotePort = port;
this.proxy = proxy;
this.localIP = proxy.proxySocket.getLocalAddress();
this.localPort = proxy.proxySocket.getLocalPort();
this.remoteHost = host;
}
protected SocksSocket(InetAddress ip,int port,Proxy proxy){
remoteIP = ip;
remotePort = port;
this.proxy = proxy;
this.localIP = proxy.proxySocket.getLocalAddress();
this.localPort = proxy.proxySocket.getLocalPort();
remoteHost = remoteIP.getHostName();
}
/**
* Same as Socket
*/
public void close() throws IOException{
if(proxy!= null)proxy.endSession();
proxy = null;
}
/**
* Same as Socket
*/
public InputStream getInputStream(){
return proxy.in;
}
/**
* Same as Socket
*/
public OutputStream getOutputStream(){
return proxy.out;
}
/**
* Same as Socket
*/
public int getPort(){
return remotePort;
}
/**
* Returns remote host name, it is usefull in cases when addresses
* are resolved by proxy, and we can't create InetAddress object.
@return The name of the host this socket is connected to.
*/
public String getHost(){
return remoteHost;
}
/**
* Get remote host as InetAddress object, might return null if
* addresses are resolved by proxy, and it is not possible to resolve
* it locally
@return Ip address of the host this socket is connected to, or null
if address was returned by the proxy as DOMAINNAME and can't be
resolved locally.
*/
public InetAddress getInetAddress(){
if(remoteIP == null){
try{
remoteIP = InetAddress.getByName(remoteHost);
}catch(UnknownHostException e){
return null;
}
}
return remoteIP;
}
/**
* Get the port assigned by the proxy for the socket, not
* the port on locall machine as in Socket.
@return Port of the socket used on the proxy server.
*/
public int getLocalPort(){
return localPort;
}
/**
* Get address assigned by proxy to make a remote connection,
* it might be different from the host specified for the proxy.
* Can return null if socks server returned this address as hostname
* and it can't be resolved locally, use getLocalHost() then.
@return Address proxy is using to make a connection.
*/
public InetAddress getLocalAddress(){
if(localIP == null){
try{
localIP = InetAddress.getByName(localHost);
}catch(UnknownHostException e){
return null;
}
}
return localIP;
}
/**
Get name of the host, proxy has assigned to make a remote connection
for this socket. This method is usefull when proxy have returned
address as hostname, and we can't resolve it on this machine.
@return The name of the host proxy is using to make a connection.
*/
public String getLocalHost(){
return localHost;
}
/**
Same as socket.
*/
public void setSoLinger(boolean on,int val) throws SocketException{
proxy.proxySocket.setSoLinger(on,val);
}
/**
Same as socket.
*/
public int getSoLinger(int timeout) throws SocketException{
return proxy.proxySocket.getSoLinger();
}
/**
Same as socket.
*/
public void setSoTimeout(int timeout) throws SocketException{
proxy.proxySocket.setSoTimeout(timeout);
}
/**
Same as socket.
*/
public int getSoTimeout(int timeout) throws SocketException{
return proxy.proxySocket.getSoTimeout();
}
/**
Same as socket.
*/
public void setTcpNoDelay(boolean on) throws SocketException{
proxy.proxySocket.setTcpNoDelay(on);
}
/**
Same as socket.
*/
public boolean getTcpNoDelay() throws SocketException{
return proxy.proxySocket.getTcpNoDelay();
}
/**
Get string representation of the socket.
*/
public String toString(){
if(directSock!=null) return "Direct connection:"+directSock;
return ("Proxy:"+proxy+";"+"addr:"+remoteHost+",port:"+remotePort
+",localport:"+localPort);
}
//Private Methods
//////////////////
private void doDirect()throws SocksException{
try{
//System.out.println("IP:"+remoteIP+":"+remotePort);
directSock = new Socket(remoteIP,remotePort);
proxy.out = directSock.getOutputStream();
proxy.in = directSock.getInputStream();
proxy.proxySocket = directSock;
localIP = directSock.getLocalAddress();
localPort = directSock.getLocalPort();
}catch(IOException io_ex){
throw new SocksException(Proxy.SOCKS_DIRECT_FAILED,
"Direct connect failed:"+io_ex);
}
}
}
|
Java
|
package net.sourceforge.jsocks;
/**
This interface provides for datagram encapsulation for SOCKSv5 protocol.
<p>
SOCKSv5 allows for datagrams to be encapsulated for purposes of integrity
and/or authenticity. How it should be done is aggreed during the
authentication stage, and is authentication dependent. This interface is
provided to allow this encapsulation.
@see Authentication
*/
public interface UDPEncapsulation{
/**
This method should provide any authentication depended transformation
on datagrams being send from/to the client.
@param data Datagram data (including any SOCKS related bytes), to be
encapsulated/decapsulated.
@param out Wether the data is being send out. If true method should
encapsulate/encrypt data, otherwise it should decapsulate/
decrypt data.
@throw IOException if for some reason data can be transformed correctly.
@return Should return byte array containing data after transformation.
It is possible to return same array as input, if transformation
only involves bit mangling, and no additional data is being
added or removed.
*/
byte[] udpEncapsulate(byte[] data, boolean out) throws java.io.IOException;
}
|
Java
|
package net.sourceforge.jsocks;
import java.io.EOFException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InterruptedIOException;
import java.io.OutputStream;
import java.io.PrintStream;
import java.io.PushbackInputStream;
import java.net.ConnectException;
import java.net.InetAddress;
import java.net.NoRouteToHostException;
import java.net.ServerSocket;
import java.net.Socket;
import net.sourceforge.jsocks.server.ServerAuthenticator;
/**
SOCKS4 and SOCKS5 proxy, handles both protocols simultaniously.
Implements all SOCKS commands, including UDP relaying.
<p>
In order to use it you will need to implement ServerAuthenticator
interface. There is an implementation of this interface which does
no authentication ServerAuthenticatorNone, but it is very dangerous
to use, as it will give access to your local network to anybody
in the world. One should never use this authentication scheme unless
one have pretty good reason to do so.
There is a couple of other authentication schemes in socks.server package.
@see socks.server.ServerAuthenticator
*/
public class ProxyServer implements Runnable{
ServerAuthenticator auth;
ProxyMessage msg = null;
Socket sock=null,remote_sock=null;
ServerSocket ss=null;
UDPRelayServer relayServer = null;
InputStream in,remote_in;
OutputStream out,remote_out;
int mode;
static final int START_MODE = 0;
static final int ACCEPT_MODE = 1;
static final int PIPE_MODE = 2;
static final int ABORT_MODE = 3;
static final int BUF_SIZE = 8192;
Thread pipe_thread1,pipe_thread2;
long lastReadTime;
protected static int iddleTimeout = 180000; //3 minutes
static int acceptTimeout = 180000; //3 minutes
static PrintStream log = null;
static Proxy proxy;
//Public Constructors
/////////////////////
/**
Creates a proxy server with given Authentication scheme.
@param auth Authentication scheme to be used.
*/
public ProxyServer(ServerAuthenticator auth){
this.auth = auth;
}
//Other constructors
////////////////////
protected ProxyServer(ServerAuthenticator auth,Socket s){
this.auth = auth;
this.sock = s;
mode = START_MODE;
}
//Public methods
/////////////////
/**
Set the logging stream. Specifying null disables logging.
*/
public static void setLog(OutputStream out){
if(out == null){
log = null;
}else{
log = new PrintStream(out,true);
}
UDPRelayServer.log = log;
}
/**
Set proxy.
<p>
Allows Proxy chaining so that one Proxy server is connected to another
and so on. If proxy supports SOCKSv4, then only some SOCKSv5 requests
can be handled, UDP would not work, however CONNECT and BIND will be
translated.
@param p Proxy which should be used to handle user requests.
*/
public static void setProxy(Proxy p){
proxy =p;
UDPRelayServer.proxy = proxy;
}
/**
Get proxy.
@return Proxy wich is used to handle user requests.
*/
public static Proxy getProxy(){
return proxy;
}
/**
Sets the timeout for connections, how long shoud server wait
for data to arrive before dropping the connection.<br>
Zero timeout implies infinity.<br>
Default timeout is 3 minutes.
*/
public static void setIddleTimeout(int timeout){
iddleTimeout = timeout;
}
/**
Sets the timeout for BIND command, how long the server should
wait for the incoming connection.<br>
Zero timeout implies infinity.<br>
Default timeout is 3 minutes.
*/
public static void setAcceptTimeout(int timeout){
acceptTimeout = timeout;
}
/**
Sets the timeout for UDPRelay server.<br>
Zero timeout implies infinity.<br>
Default timeout is 3 minutes.
*/
public static void setUDPTimeout(int timeout){
UDPRelayServer.setTimeout(timeout);
}
/**
Sets the size of the datagrams used in the UDPRelayServer.<br>
Default size is 64K, a bit more than maximum possible size of the
datagram.
*/
public static void setDatagramSize(int size){
UDPRelayServer.setDatagramSize(size);
}
/**
Start the Proxy server at given port.<br>
This methods blocks.
*/
public void start(int port){
start(port,5,null);
}
/**
Create a server with the specified port, listen backlog, and local
IP address to bind to. The localIP argument can be used on a multi-homed
host for a ServerSocket that will only accept connect requests to one of
its addresses. If localIP is null, it will default accepting connections
on any/all local addresses. The port must be between 0 and 65535,
inclusive. <br>
This methods blocks.
*/
public void start(int port,int backlog,InetAddress localIP){
try{
ss = new ServerSocket(port,backlog,localIP);
log("Starting SOCKS Proxy on:"+ss.getInetAddress().getHostAddress()+":"
+ss.getLocalPort());
while(true){
Socket s = ss.accept();
log("Accepted from:"+s.getInetAddress().getHostName()+":"
+s.getPort());
ProxyServer ps = new ProxyServer(auth,s);
(new Thread(ps)).start();
}
}catch(IOException ioe){
ioe.printStackTrace();
}finally{
}
}
/**
Stop server operation.It would be wise to interrupt thread running the
server afterwards.
*/
public void stop(){
try{
if(ss != null) ss.close();
}catch(IOException ioe){
}
}
//Runnable interface
////////////////////
public void run(){
switch(mode){
case START_MODE:
try{
startSession();
}catch(IOException ioe){
handleException(ioe);
//ioe.printStackTrace();
}finally{
abort();
if(auth!=null) auth.endSession();
log("Main thread(client->remote)stopped.");
}
break;
case ACCEPT_MODE:
try{
doAccept();
mode = PIPE_MODE;
pipe_thread1.interrupt(); //Tell other thread that connection have
//been accepted.
pipe(remote_in,out);
}catch(IOException ioe){
//log("Accept exception:"+ioe);
handleException(ioe);
}finally{
abort();
log("Accept thread(remote->client) stopped");
}
break;
case PIPE_MODE:
try{
pipe(remote_in,out);
}catch(IOException ioe){
}finally{
abort();
log("Support thread(remote->client) stopped");
}
break;
case ABORT_MODE:
break;
default:
log("Unexpected MODE "+mode);
}
}
//Private methods
/////////////////
private void startSession() throws IOException{
sock.setSoTimeout(iddleTimeout);
try{
auth = auth.startSession(sock);
}catch(IOException ioe){
log("Auth throwed exception:"+ioe);
auth = null;
return;
}
if(auth == null){ //Authentication failed
log("Authentication failed");
return;
}
in = auth.getInputStream();
out = auth.getOutputStream();
msg = readMsg(in);
handleRequest(msg);
}
protected void handleRequest(ProxyMessage msg)
throws IOException{
if(!auth.checkRequest(msg)) throw new
SocksException(Proxy.SOCKS_FAILURE);
if(msg.ip == null){
if(msg instanceof Socks5Message){
msg.ip = InetAddress.getByName(msg.host);
}else
throw new SocksException(Proxy.SOCKS_FAILURE);
}
log(msg);
switch(msg.command){
case Proxy.SOCKS_CMD_CONNECT:
onConnect(msg);
break;
case Proxy.SOCKS_CMD_BIND:
onBind(msg);
break;
case Proxy.SOCKS_CMD_UDP_ASSOCIATE:
onUDP(msg);
break;
default:
throw new SocksException(Proxy.SOCKS_CMD_NOT_SUPPORTED);
}
}
private void handleException(IOException ioe){
//If we couldn't read the request, return;
if(msg == null) return;
//If have been aborted by other thread
if(mode == ABORT_MODE) return;
//If the request was successfully completed, but exception happened later
if(mode == PIPE_MODE) return;
int error_code = Proxy.SOCKS_FAILURE;
if(ioe instanceof SocksException)
error_code = ((SocksException)ioe).errCode;
else if(ioe instanceof NoRouteToHostException)
error_code = Proxy.SOCKS_HOST_UNREACHABLE;
else if(ioe instanceof ConnectException)
error_code = Proxy.SOCKS_CONNECTION_REFUSED;
else if(ioe instanceof InterruptedIOException)
error_code = Proxy.SOCKS_TTL_EXPIRE;
if(error_code > Proxy.SOCKS_ADDR_NOT_SUPPORTED || error_code < 0){
error_code = Proxy.SOCKS_FAILURE;
}
sendErrorMessage(error_code);
}
private void onConnect(ProxyMessage msg) throws IOException{
Socket s;
ProxyMessage response = null;
s = new Socket(msg.ip,msg.port);
log("Connected to "+s.getInetAddress()+":"+s.getPort());
if(msg instanceof Socks5Message){
response = new Socks5Message(Proxy.SOCKS_SUCCESS,
s.getLocalAddress(),
s.getLocalPort());
}else{
response = new Socks4Message(Socks4Message.REPLY_OK,
s.getLocalAddress(),s.getLocalPort());
}
response.write(out);
startPipe(s);
}
private void onBind(ProxyMessage msg) throws IOException{
ProxyMessage response = null;
if(proxy == null)
ss = new ServerSocket(0);
else
ss = new SocksServerSocket(proxy, msg.ip, msg.port);
ss.setSoTimeout(acceptTimeout);
log("Trying accept on "+ss.getInetAddress()+":"+ss.getLocalPort());
if(msg.version == 5)
response = new Socks5Message(Proxy.SOCKS_SUCCESS,ss.getInetAddress(),
ss.getLocalPort());
else
response = new Socks4Message(Socks4Message.REPLY_OK,
ss.getInetAddress(),
ss.getLocalPort());
response.write(out);
mode = ACCEPT_MODE;
pipe_thread1 = Thread.currentThread();
pipe_thread2 = new Thread(this);
pipe_thread2.start();
//Make timeout infinit.
sock.setSoTimeout(0);
int eof=0;
try{
while((eof=in.read())>=0){
if(mode != ACCEPT_MODE){
if(mode != PIPE_MODE) return;//Accept failed
remote_out.write(eof);
break;
}
}
}catch(EOFException eofe){
//System.out.println("EOF exception");
return;//Connection closed while we were trying to accept.
}catch(InterruptedIOException iioe){
//Accept thread interrupted us.
//System.out.println("Interrupted");
if(mode != PIPE_MODE)
return;//If accept thread was not successfull return.
}finally{
//System.out.println("Finnaly!");
}
if(eof < 0)//Connection closed while we were trying to accept;
return;
//Do not restore timeout, instead timeout is set on the
//remote socket. It does not make any difference.
pipe(in,remote_out);
}
private void onUDP(ProxyMessage msg) throws IOException{
if(msg.ip.getHostAddress().equals("0.0.0.0"))
msg.ip = sock.getInetAddress();
log("Creating UDP relay server for "+msg.ip+":"+msg.port);
relayServer = new UDPRelayServer(msg.ip,msg.port,
Thread.currentThread(),sock,auth);
ProxyMessage response;
response = new Socks5Message(Proxy.SOCKS_SUCCESS,
relayServer.relayIP,relayServer.relayPort);
response.write(out);
relayServer.start();
//Make timeout infinit.
sock.setSoTimeout(0);
try{
while(in.read()>=0) /*do nothing*/;
}catch(EOFException eofe){
}
}
//Private methods
//////////////////
private void doAccept() throws IOException{
Socket s;
long startTime = System.currentTimeMillis();
while(true){
s = ss.accept();
if(s.getInetAddress().equals(msg.ip)){
//got the connection from the right host
//Close listenning socket.
ss.close();
break;
}else if(ss instanceof SocksServerSocket){
//We can't accept more then one connection
s.close();
ss.close();
throw new SocksException(Proxy.SOCKS_FAILURE);
}else{
if(acceptTimeout!=0){ //If timeout is not infinit
int newTimeout = acceptTimeout-(int)(System.currentTimeMillis()-
startTime);
if(newTimeout <= 0) throw new InterruptedIOException(
"In doAccept()");
ss.setSoTimeout(newTimeout);
}
s.close(); //Drop all connections from other hosts
}
}
//Accepted connection
remote_sock = s;
remote_in = s.getInputStream();
remote_out = s.getOutputStream();
//Set timeout
remote_sock.setSoTimeout(iddleTimeout);
log("Accepted from "+s.getInetAddress()+":"+s.getPort());
ProxyMessage response;
if(msg.version == 5)
response = new Socks5Message(Proxy.SOCKS_SUCCESS, s.getInetAddress(),
s.getPort());
else
response = new Socks4Message(Socks4Message.REPLY_OK,
s.getInetAddress(), s.getPort());
response.write(out);
}
protected ProxyMessage readMsg(InputStream in) throws IOException{
PushbackInputStream push_in;
if(in instanceof PushbackInputStream)
push_in = (PushbackInputStream) in;
else
push_in = new PushbackInputStream(in);
int version = push_in.read();
push_in.unread(version);
ProxyMessage msg;
if(version == 5){
msg = new Socks5Message(push_in,false);
}else if(version == 4){
msg = new Socks4Message(push_in,false);
}else{
throw new SocksException(Proxy.SOCKS_FAILURE);
}
return msg;
}
private void startPipe(Socket s){
mode = PIPE_MODE;
remote_sock = s;
try{
remote_in = s.getInputStream();
remote_out = s.getOutputStream();
pipe_thread1 = Thread.currentThread();
pipe_thread2 = new Thread(this);
pipe_thread2.start();
pipe(in,remote_out);
}catch(IOException ioe){
}
}
private void sendErrorMessage(int error_code){
ProxyMessage err_msg;
if(msg instanceof Socks4Message)
err_msg = new Socks4Message(Socks4Message.REPLY_REJECTED);
else
err_msg = new Socks5Message(error_code);
try{
err_msg.write(out);
}catch(IOException ioe){}
}
private synchronized void abort(){
if(mode == ABORT_MODE) return;
mode = ABORT_MODE;
try{
log("Aborting operation");
if(remote_sock != null) remote_sock.close();
if(sock != null) sock.close();
if(relayServer!=null) relayServer.stop();
if(ss!=null) ss.close();
if(pipe_thread1 != null) pipe_thread1.interrupt();
if(pipe_thread2 != null) pipe_thread2.interrupt();
}catch(IOException ioe){}
}
static final void log(String s){
if(log != null){
log.println(s);
log.flush();
}
}
static final void log(ProxyMessage msg){
log("Request version:"+msg.version+
"\tCommand: "+command2String(msg.command));
log("IP:"+msg.ip +"\tPort:"+msg.port+
(msg.version==4?"\tUser:"+msg.user:""));
}
private void pipe(InputStream in,OutputStream out) throws IOException{
lastReadTime = System.currentTimeMillis();
byte[] buf = new byte[BUF_SIZE];
int len = 0;
while(len >= 0){
try{
if(len!=0){
out.write(buf,0,len);
out.flush();
}
len= in.read(buf);
lastReadTime = System.currentTimeMillis();
}catch(InterruptedIOException iioe){
if(iddleTimeout == 0) return;//Other thread interrupted us.
long timeSinceRead = System.currentTimeMillis() - lastReadTime;
if(timeSinceRead >= iddleTimeout - 1000) //-1s for adjustment.
return;
len = 0;
}
}
}
static final String command_names[] = {"CONNECT","BIND","UDP_ASSOCIATE"};
static final String command2String(int cmd){
if(cmd > 0 && cmd < 4) return command_names[cmd-1];
else return "Unknown Command "+cmd;
}
}
|
Java
|
package net.sourceforge.jsocks;
import java.net.*;
import java.io.*;
/**
SocksServerSocket allows to accept connections from one particular
host through the SOCKS4 or SOCKS5 proxy.
*/
public class SocksServerSocket extends ServerSocket{
//Data members
protected Proxy proxy;
protected String localHost;
protected InetAddress localIP;
protected int localPort;
boolean doing_direct = false;
InetAddress remoteAddr;
/**
*Creates ServerSocket capable of accepting one connection
*through the firewall, uses given proxy.
*@param host Host from which the connection should be recieved.
*@param port Port number of the primary connection.
*/
public SocksServerSocket(String host, int port) throws SocksException,
UnknownHostException, IOException {
super(0);
remoteAddr = InetAddress.getByName(host);
doDirect();
}
/**
* Creates ServerSocket capable of accepting one connection
* through the firewall, uses default Proxy.
*@param ip Host from which the connection should be recieved.
*@param port Port number of the primary connection.
*/
public SocksServerSocket(InetAddress ip, int port) throws SocksException,
IOException{
this(Proxy.defaultProxy,ip,port);
}
/**
*Creates ServerSocket capable of accepting one connection
*through the firewall, uses given proxy.
*@param ip Host from which the connection should be recieved.
*@param port Port number of the primary connection.
*/
public SocksServerSocket(Proxy p, InetAddress ip, int port)
throws SocksException, IOException {
super(0);
remoteAddr = ip;
doDirect();
}
/**
* Accepts the incoming connection.
*/
public Socket accept() throws IOException{
Socket s;
if(!doing_direct){
if(proxy == null) return null;
ProxyMessage msg = proxy.accept();
s = msg.ip == null? new SocksSocket(msg.host,msg.port,proxy)
: new SocksSocket(msg.ip,msg.port,proxy);
//Set timeout back to 0
proxy.proxySocket.setSoTimeout(0);
}else{ //Direct Connection
//Mimic the proxy behaviour,
//only accept connections from the speciefed host.
while(true){
s = super.accept();
if(s.getInetAddress().equals(remoteAddr)){
//got the connection from the right host
//Close listenning socket.
break;
}else
s.close(); //Drop all connections from other hosts
}
}
proxy = null;
//Return accepted socket
return s;
}
/**
* Closes the connection to proxy if socket have not been accepted, if
* the direct connection is used, closes direct ServerSocket. If the
* client socket have been allready accepted, does nothing.
*/
public void close() throws IOException{
super.close();
if(proxy != null) proxy.endSession();
proxy = null;
}
/**
Get the name of the host proxy is using to listen for incoming
connection.
<P>
Usefull when address is returned by proxy as the hostname.
@return the hostname of the address proxy is using to listen
for incoming connection.
*/
public String getHost(){
return localHost;
}
/**
* Get address assigned by proxy to listen for incomming
* connections, or the local machine address if doing direct
* connection.
*/
public InetAddress getInetAddress(){
if(localIP == null){
try{
localIP = InetAddress.getByName(localHost);
}catch(UnknownHostException e){
return null;
}
}
return localIP;
}
/**
* Get port assigned by proxy to listen for incoming connections, or
the port chosen by local system, if accepting directly.
*/
public int getLocalPort(){
return localPort;
}
/**
Set Timeout.
@param timeout Amount of time in milliseconds, accept should wait for
incoming connection before failing with exception.
Zero timeout implies infinity.
*/
public void setSoTimeout(int timeout) throws SocketException{
super.setSoTimeout(timeout);
if(!doing_direct) proxy.proxySocket.setSoTimeout(timeout);
}
//Private Methods
//////////////////
private void doDirect(){
doing_direct = true;
localPort = super.getLocalPort();
localIP = super.getInetAddress();
localHost = localIP.getHostName();
}
}
|
Java
|
package net.sourceforge.jsocks.server;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PushbackInputStream;
import java.net.Socket;
import net.sourceforge.jsocks.ProxyMessage;
import net.sourceforge.jsocks.UDPEncapsulation;
/**
An implementation of ServerAuthenticator, which does <b>not</b> do
any authentication.
<P>
<FONT size="+3" color ="FF0000"> Warning!!</font><br> Should not be
used on machines which are not behind the firewall.
<p>
It is only provided to make implementing other authentication schemes
easier.<br>
For Example: <tt><pre>
class MyAuth extends socks.server.ServerAuthenticator{
...
public ServerAuthenticator startSession(java.net.Socket s){
if(!checkHost(s.getInetAddress()) return null;
return super.startSession(s);
}
boolean checkHost(java.net.Inetaddress addr){
boolean allow;
//Do it somehow
return allow;
}
}
</pre></tt>
*/
public class ServerAuthenticatorNone implements ServerAuthenticator{
static final byte[] socks5response = {5,0};
InputStream in;
OutputStream out;
/**
Creates new instance of the ServerAuthenticatorNone.
*/
public ServerAuthenticatorNone(){
this.in = null;
this.out = null;
}
/**
Constructs new ServerAuthenticatorNone object suitable for returning
from the startSession function.
@param in Input stream to return from getInputStream method.
@param out Output stream to return from getOutputStream method.
*/
public ServerAuthenticatorNone(InputStream in, OutputStream out){
this.in = in;
this.out = out;
}
/**
Grants access to everyone.Removes authentication related bytes from
the stream, when a SOCKS5 connection is being made, selects an
authentication NONE.
*/
public ServerAuthenticator startSession(Socket s)
throws IOException{
PushbackInputStream in = new PushbackInputStream(s.getInputStream());
OutputStream out = s.getOutputStream();
int version = in.read();
if(version == 5){
if(!selectSocks5Authentication(in,out,0))
return null;
}else if(version == 4){
//Else it is the request message allready, version 4
in.unread(version);
}else
return null;
return new ServerAuthenticatorNone(in,out);
}
/**
Get input stream.
@return Input stream speciefied in the constructor.
*/
public InputStream getInputStream(){
return in;
}
/**
Get output stream.
@return Output stream speciefied in the constructor.
*/
public OutputStream getOutputStream(){
return out;
}
/**
Allways returns null.
@return null
*/
public UDPEncapsulation getUdpEncapsulation(){
return null;
}
/**
Allways returns true.
*/
public boolean checkRequest(ProxyMessage msg){
return true;
}
/**
Allways returns true.
*/
public boolean checkRequest(java.net.DatagramPacket dp, boolean out){
return true;
}
/**
Does nothing.
*/
public void endSession(){
}
/**
Convinience routine for selecting SOCKSv5 authentication.
<p>
This method reads in authentication methods that client supports,
checks wether it supports given method. If it does, the notification
method is written back to client, that this method have been chosen
for authentication. If given method was not found, authentication
failure message is send to client ([5,FF]).
@param in Input stream, version byte should be removed from the stream
before calling this method.
@param out Output stream.
@param methodId Method which should be selected.
@return true if methodId was found, false otherwise.
*/
static public boolean selectSocks5Authentication(InputStream in,
OutputStream out,
int methodId)
throws IOException{
int num_methods = in.read();
if (num_methods <= 0) return false;
byte method_ids[] = new byte[num_methods];
byte response[] = new byte[2];
boolean found = false;
response[0] = (byte) 5; //SOCKS version
response[1] = (byte) 0xFF; //Not found, we are pessimistic
int bread = 0; //bytes read so far
while(bread < num_methods)
bread += in.read(method_ids,bread,num_methods-bread);
for(int i=0;i<num_methods;++i)
if(method_ids[i] == methodId){
found = true;
response[1] = (byte) methodId;
break;
}
out.write(response);
return found;
}
}
|
Java
|
package net.sourceforge.jsocks.server;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.DatagramPacket;
import java.net.Socket;
import net.sourceforge.jsocks.ProxyMessage;
import net.sourceforge.jsocks.UDPEncapsulation;
/**
Classes implementing this interface should provide socks server with
authentication and authorization of users.
**/
public interface ServerAuthenticator{
/**
This method is called when a new connection accepted by the server.
<p>
At this point no data have been extracted from the connection. It is
responsibility of this method to ensure that the next byte in the
stream after this method have been called is the first byte of the
socks request message. For SOCKSv4 there is no authentication data and
the first byte in the stream is part of the request. With SOCKSv5 however
there is an authentication data first. It is expected that implementaions
will process this authentication data.
<p>
If authentication was successful an instance of ServerAuthentication
should be returned, it later will be used by the server to perform
authorization and some other things. If authentication fails null should
be returned, or an exception may be thrown.
@param s Accepted Socket.
@return An instance of ServerAuthenticator to be used for this connection
or null
*/
ServerAuthenticator startSession(Socket s) throws IOException;
/**
This method should return input stream which should be used on the
accepted socket.
<p>
SOCKSv5 allows to have multiple authentication methods, and these methods
might require some kind of transformations being made on the data.
<p>
This method is called on the object returned from the startSession
function.
*/
InputStream getInputStream();
/**
This method should return output stream to use to write to the accepted
socket.
<p>
SOCKSv5 allows to have multiple authentication methods, and these methods
might require some kind of transformations being made on the data.
<p>
This method is called on the object returned from the startSession
function.
*/
OutputStream getOutputStream();
/**
This method should return UDPEncapsulation, which should be used
on the datagrams being send in/out.
<p>
If no transformation should be done on the datagrams, this method
should return null.
<p>
This method is called on the object returned from the startSession
function.
*/
UDPEncapsulation getUdpEncapsulation();
/**
This method is called when a request have been read.
<p>
Implementation should decide wether to grant request or not. Returning
true implies granting the request, false means request should be rejected.
<p>
This method is called on the object returned from the startSession
function.
@param msg Request message.
@return true to grant request, false to reject it.
*/
boolean checkRequest(ProxyMessage msg);
/**
This method is called when datagram is received by the server.
<p>
Implementaions should decide wether it should be forwarded or dropped.
It is expecteed that implementation will use datagram address and port
information to make a decision, as well as anything else. Address and
port of the datagram are always correspond to remote machine. It is
either destination or source address. If out is true address is destination
address, else it is a source address, address of the machine from which
datagram have been received for the client.
<p>
Implementaions should return true if the datagram is to be forwarded, and
false if the datagram should be dropped.
<p>
This method is called on the object returned from the startSession
function.
@param out If true the datagram is being send out(from the client),
otherwise it is an incoming datagram.
@return True to forward datagram false drop it silently.
*/
boolean checkRequest(DatagramPacket dp, boolean out);
/**
This method is called when session is completed. Either due to normal
termination or due to any error condition.
<p>
This method is called on the object returned from the startSession
function.
*/
void endSession();
}
|
Java
|
package net.sourceforge.jsocks;
import java.io.IOException;
import java.io.InputStream;
import java.io.InterruptedIOException;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
/**
Abstract class Proxy, base for classes Socks4Proxy and Socks5Proxy.
Defines methods for specifying default proxy, to be
used by all classes of this package.
*/
public abstract class Proxy{
//Data members
//protected InetRange directHosts = new InetRange();
protected InetAddress proxyIP = null;
protected String proxyHost = null;
protected int proxyPort;
protected Socket proxySocket = null;
protected InputStream in;
protected OutputStream out;
protected int version;
protected Proxy chainProxy = null;
//Protected static/class variables
protected static Proxy defaultProxy = null;
//Constructors
//====================
Proxy(String proxyHost, int proxyPort) throws UnknownHostException {
this.proxyHost = proxyHost;
this.proxyIP = InetAddress.getByName(proxyHost);
this.proxyPort = proxyPort;
}
Proxy(Proxy chainProxy,InetAddress proxyIP,int proxyPort){
this.chainProxy = chainProxy;
this.proxyIP = proxyIP;
this.proxyPort = proxyPort;
}
Proxy(InetAddress proxyIP,int proxyPort){
this.proxyIP = proxyIP;
this.proxyPort = proxyPort;
}
Proxy(Proxy p){
this.proxyIP = p.proxyIP;
this.proxyPort = p.proxyPort;
this.version = p.version;
}
//Public instance methods
//========================
/**
Get the port on which proxy server is running.
* @return Proxy port.
*/
public int getPort(){
return proxyPort;
}
/**
Get the ip address of the proxy server host.
* @return Proxy InetAddress.
*/
public InetAddress getInetAddress(){
return proxyIP;
}
/**
Get string representation of this proxy.
* @returns string in the form:proxyHost:proxyPort \t Version versionNumber
*/
public String toString(){
return (""+proxyIP.getHostName()+":"+proxyPort+"\tVersion "+version);
}
//Public Static(Class) Methods
//==============================
/**
* Sets SOCKS4 proxy as default.
@param hostName Host name on which SOCKS4 server is running.
@param port Port on which SOCKS4 server is running.
@param user Username to use for communications with proxy.
*/
public static void setDefaultProxy(String hostName,int port,String user)
throws UnknownHostException{
defaultProxy = new Socks4Proxy(hostName,port,user);
}
/**
* Sets SOCKS4 proxy as default.
@param ipAddress Host address on which SOCKS4 server is running.
@param port Port on which SOCKS4 server is running.
@param user Username to use for communications with proxy.
*/
public static void setDefaultProxy(InetAddress ipAddress,int port,
String user){
defaultProxy = new Socks4Proxy(ipAddress,port,user);
}
/**
* Sets SOCKS5 proxy as default.
* Default proxy only supports no-authentication.
@param hostName Host name on which SOCKS5 server is running.
@param port Port on which SOCKS5 server is running.
*/
public static void setDefaultProxy(String hostName,int port)
throws UnknownHostException{
defaultProxy = new Socks5Proxy(hostName,port);
}
/**
* Sets SOCKS5 proxy as default.
* Default proxy only supports no-authentication.
@param ipAddress Host address on which SOCKS5 server is running.
@param port Port on which SOCKS5 server is running.
*/
public static void setDefaultProxy(InetAddress ipAddress,int port){
defaultProxy = new Socks5Proxy(ipAddress,port);
}
/**
* Sets default proxy.
@param p Proxy to use as default proxy.
*/
public static void setDefaultProxy(Proxy p){
defaultProxy = p;
}
/**
Get current default proxy.
* @return Current default proxy, or null if none is set.
*/
public static Proxy getDefaultProxy(){
return defaultProxy;
}
/**
Parses strings in the form: host[:port:user:password], and creates
proxy from information obtained from parsing.
<p>
Defaults: port = 1080.<br>
If user specified but not password, creates Socks4Proxy, if user
not specified creates Socks5Proxy, if both user and password are
speciefied creates Socks5Proxy with user/password authentication.
@param proxy_entry String in the form host[:port:user:password]
@return Proxy created from the string, null if entry was somehow
invalid(host unknown for example, or empty string)
*/
public static Proxy parseProxy(String proxy_entry){
String proxy_host;
int proxy_port = 1080;
String proxy_user = null;
String proxy_password = null;
Proxy proxy;
java.util.StringTokenizer st = new java.util.StringTokenizer(
proxy_entry,":");
if(st.countTokens() < 1) return null;
proxy_host = st.nextToken();
if(st.hasMoreTokens())
try{
proxy_port = Integer.parseInt(st.nextToken().trim());
}catch(NumberFormatException nfe){}
if(st.hasMoreTokens())
proxy_user = st.nextToken();
if(st.hasMoreTokens())
proxy_password = st.nextToken();
try{
if(proxy_user == null)
proxy = new Socks5Proxy(proxy_host,proxy_port);
else if(proxy_password == null)
proxy = new Socks4Proxy(proxy_host,proxy_port,proxy_user);
else{
proxy = new Socks5Proxy(proxy_host,proxy_port);
/*
UserPasswordAuthentication upa = new UserPasswordAuthentication(
proxy_user, proxy_password);
((Socks5Proxy)proxy).setAuthenticationMethod(upa.METHOD_ID,upa);
*/
}
}catch(UnknownHostException uhe){
return null;
}
return proxy;
}
//Protected Methods
//=================
protected void startSession()throws SocksException{
try{
proxySocket = new Socket(proxyIP,proxyPort);
in = proxySocket.getInputStream();
out = proxySocket.getOutputStream();
}catch(SocksException se){
throw se;
}catch(IOException io_ex){
throw new SocksException(SOCKS_PROXY_IO_ERROR,""+io_ex);
}
}
protected abstract Proxy copy();
protected abstract ProxyMessage formMessage(int cmd,InetAddress ip,int port);
protected abstract ProxyMessage formMessage(int cmd,String host,int port)
throws UnknownHostException;
protected abstract ProxyMessage formMessage(InputStream in)
throws SocksException,
IOException;
protected ProxyMessage connect(InetAddress ip,int port)
throws SocksException{
try{
startSession();
ProxyMessage request = formMessage(SOCKS_CMD_CONNECT,
ip,port);
return exchange(request);
}catch(SocksException se){
endSession();
throw se;
}
}
protected ProxyMessage connect(String host,int port)
throws UnknownHostException,SocksException{
try{
startSession();
ProxyMessage request = formMessage(SOCKS_CMD_CONNECT,
host,port);
return exchange(request);
}catch(SocksException se){
endSession();
throw se;
}
}
protected ProxyMessage bind(InetAddress ip,int port)
throws SocksException{
try{
startSession();
ProxyMessage request = formMessage(SOCKS_CMD_BIND,
ip,port);
return exchange(request);
}catch(SocksException se){
endSession();
throw se;
}
}
protected ProxyMessage bind(String host,int port)
throws UnknownHostException,SocksException{
try{
startSession();
ProxyMessage request = formMessage(SOCKS_CMD_BIND,
host,port);
return exchange(request);
}catch(SocksException se){
endSession();
throw se;
}
}
protected ProxyMessage accept()
throws IOException,SocksException{
ProxyMessage msg;
try{
msg = formMessage(in);
}catch(InterruptedIOException iioe){
throw iioe;
}catch(IOException io_ex){
endSession();
throw new SocksException(SOCKS_PROXY_IO_ERROR,"While Trying accept:"
+io_ex);
}
return msg;
}
protected ProxyMessage udpAssociate(InetAddress ip,int port)
throws SocksException{
try{
startSession();
ProxyMessage request = formMessage(SOCKS_CMD_UDP_ASSOCIATE,
ip,port);
if(request != null)
return exchange(request);
}catch(SocksException se){
endSession();
throw se;
}
//Only get here if request was null
endSession();
throw new SocksException(SOCKS_METHOD_NOTSUPPORTED,
"This version of proxy does not support UDP associate, use version 5");
}
protected ProxyMessage udpAssociate(String host,int port)
throws UnknownHostException,SocksException{
try{
startSession();
ProxyMessage request = formMessage(SOCKS_CMD_UDP_ASSOCIATE,
host,port);
if(request != null) return exchange(request);
}catch(SocksException se){
endSession();
throw se;
}
//Only get here if request was null
endSession();
throw new SocksException(SOCKS_METHOD_NOTSUPPORTED,
"This version of proxy does not support UDP associate, use version 5");
}
protected void endSession(){
try{
if(proxySocket!=null) proxySocket.close();
proxySocket = null;
}catch(IOException io_ex){
}
}
/**
*Sends the request to SOCKS server
*/
protected void sendMsg(ProxyMessage msg)throws SocksException,
IOException{
msg.write(out);
}
/**
* Reads the reply from the SOCKS server
*/
protected ProxyMessage readMsg()throws SocksException,
IOException{
return formMessage(in);
}
/**
*Sends the request reads reply and returns it
*throws exception if something wrong with IO
*or the reply code is not zero
*/
protected ProxyMessage exchange(ProxyMessage request)
throws SocksException{
ProxyMessage reply;
try{
request.write(out);
reply = formMessage(in);
}catch(SocksException s_ex){
throw s_ex;
}catch(IOException ioe){
throw(new SocksException(SOCKS_PROXY_IO_ERROR,""+ioe));
}
return reply;
}
//Private methods
//===============
//Constants
public static final int SOCKS_SUCCESS =0;
public static final int SOCKS_FAILURE =1;
public static final int SOCKS_BADCONNECT =2;
public static final int SOCKS_BADNETWORK =3;
public static final int SOCKS_HOST_UNREACHABLE =4;
public static final int SOCKS_CONNECTION_REFUSED =5;
public static final int SOCKS_TTL_EXPIRE =6;
public static final int SOCKS_CMD_NOT_SUPPORTED =7;
public static final int SOCKS_ADDR_NOT_SUPPORTED =8;
public static final int SOCKS_NO_PROXY =1<<16;
public static final int SOCKS_PROXY_NO_CONNECT =2<<16;
public static final int SOCKS_PROXY_IO_ERROR =3<<16;
public static final int SOCKS_AUTH_NOT_SUPPORTED =4<<16;
public static final int SOCKS_AUTH_FAILURE =5<<16;
public static final int SOCKS_JUST_ERROR =6<<16;
public static final int SOCKS_DIRECT_FAILED =7<<16;
public static final int SOCKS_METHOD_NOTSUPPORTED =8<<16;
public static final int SOCKS_CMD_CONNECT =0x1;
static final int SOCKS_CMD_BIND =0x2;
static final int SOCKS_CMD_UDP_ASSOCIATE =0x3;
}
|
Java
|
package net.sourceforge.jsocks;
import java.net.*;
import java.io.*;
/**
Datagram socket to interract through the firewall.<BR>
Can be used same way as the normal DatagramSocket. One should
be carefull though with the datagram sizes used, as additional data
is present in both incomming and outgoing datagrams.
<p>
SOCKS5 protocol allows to send host address as either:
<ul>
<li> IPV4, normal 4 byte address. (10 bytes header size)
<li> IPV6, version 6 ip address (not supported by Java as for now).
22 bytes header size.
<li> Host name,(7+length of the host name bytes header size).
</ul>
As with other Socks equivalents, direct addresses are handled
transparently, that is data will be send directly when required
by the proxy settings.
<p>
<b>NOTE:</b><br>
Unlike other SOCKS Sockets, it <b>does not</b> support proxy chaining,
and will throw an exception if proxy has a chain proxy attached. The
reason for that is not my laziness, but rather the restrictions of
the SOCKSv5 protocol. Basicaly SOCKSv5 proxy server, needs to know from
which host:port datagrams will be send for association, and returns address
to which datagrams should be send by the client, but it does not
inform client from which host:port it is going to send datagrams, in fact
there is even no guarantee they will be send at all and from the same address
each time.
*/
public class Socks5DatagramSocket extends DatagramSocket{
InetAddress relayIP;
int relayPort;
Socks5Proxy proxy;
private boolean server_mode = false;
UDPEncapsulation encapsulation;
/**
Construct Datagram socket for communication over SOCKS5 proxy
server. This constructor uses default proxy, the one set with
Proxy.setDefaultProxy() method. If default proxy is not set or
it is set to version4 proxy, which does not support datagram
forwarding, throws SocksException.
*/
public Socks5DatagramSocket() throws SocksException,
IOException{
this(Proxy.defaultProxy,0,null);
}
/**
Construct Datagram socket for communication over SOCKS5 proxy
server. And binds it to the specified local port.
This constructor uses default proxy, the one set with
Proxy.setDefaultProxy() method. If default proxy is not set or
it is set to version4 proxy, which does not support datagram
forwarding, throws SocksException.
*/
public Socks5DatagramSocket(int port) throws SocksException,
IOException{
this(Proxy.defaultProxy,port,null);
}
/**
Construct Datagram socket for communication over SOCKS5 proxy
server. And binds it to the specified local port and address.
This constructor uses default proxy, the one set with
Proxy.setDefaultProxy() method. If default proxy is not set or
it is set to version4 proxy, which does not support datagram
forwarding, throws SocksException.
*/
public Socks5DatagramSocket(int port,InetAddress ip) throws SocksException,
IOException{
this(Proxy.defaultProxy,port,ip);
}
/**
Constructs datagram socket for communication over specified proxy.
And binds it to the given local address and port. Address of null
and port of 0, signify any availabale port/address.
Might throw SocksException, if:
<ol>
<li> Given version of proxy does not support UDP_ASSOCIATE.
<li> Proxy can't be reached.
<li> Authorization fails.
<li> Proxy does not want to perform udp forwarding, for any reason.
</ol>
Might throw IOException if binding dtagram socket to given address/port
fails.
See java.net.DatagramSocket for more details.
*/
public Socks5DatagramSocket(Proxy p,int port,InetAddress ip)
throws SocksException,
IOException{
super(port,ip);
if(p == null) throw new SocksException(Proxy.SOCKS_NO_PROXY);
if(!(p instanceof Socks5Proxy))
throw new SocksException(-1,"Datagram Socket needs Proxy version 5");
if(p.chainProxy != null)
throw new SocksException(Proxy.SOCKS_JUST_ERROR,
"Datagram Sockets do not support proxy chaining.");
proxy =(Socks5Proxy) p.copy();
ProxyMessage msg = proxy.udpAssociate(super.getLocalAddress(),
super.getLocalPort());
relayIP = msg.ip;
if(relayIP.getHostAddress().equals("0.0.0.0")) relayIP = proxy.proxyIP;
relayPort = msg.port;
encapsulation = proxy.udp_encapsulation;
//debug("Datagram Socket:"+getLocalAddress()+":"+getLocalPort()+"\n");
//debug("Socks5Datagram: "+relayIP+":"+relayPort+"\n");
}
/**
Used by UDPRelayServer.
*/
Socks5DatagramSocket(boolean server_mode,UDPEncapsulation encapsulation,
InetAddress relayIP,int relayPort)
throws IOException{
super();
this.server_mode = server_mode;
this.relayIP = relayIP;
this.relayPort = relayPort;
this.encapsulation = encapsulation;
this.proxy = null;
}
/**
Sends the Datagram either through the proxy or directly depending
on current proxy settings and destination address. <BR>
<B> NOTE: </B> DatagramPacket size should be at least 10 bytes less
than the systems limit.
<P>
See documentation on java.net.DatagramSocket
for full details on how to use this method.
@param dp Datagram to send.
@throws IOException If error happens with I/O.
*/
public void send(DatagramPacket dp) throws IOException{
//If the host should be accessed directly, send it as is.
if(!server_mode){
super.send(dp);
//debug("Sending directly:");
return;
}
byte[] head = formHeader(dp.getAddress(),dp.getPort());
byte[] buf = new byte[head.length + dp.getLength()];
byte[] data = dp.getData();
//Merge head and data
System.arraycopy(head,0,buf,0,head.length);
//System.arraycopy(data,dp.getOffset(),buf,head.length,dp.getLength());
System.arraycopy(data,0,buf,head.length,dp.getLength());
if(encapsulation != null)
buf = encapsulation.udpEncapsulate(buf,true);
super.send(new DatagramPacket(buf,buf.length,relayIP,relayPort));
}
/**
This method allows to send datagram packets with address type DOMAINNAME.
SOCKS5 allows to specify host as names rather than ip addresses.Using
this method one can send udp datagrams through the proxy, without having
to know the ip address of the destination host.
<p>
If proxy specified for that socket has an option resolveAddrLocally set
to true host will be resolved, and the datagram will be send with address
type IPV4, if resolve fails, UnknownHostException is thrown.
@param dp Datagram to send, it should contain valid port and data
@param host Host name to which datagram should be send.
@throws IOException If error happens with I/O, or the host can't be
resolved when proxy settings say that hosts should be resolved locally.
@see Socks5Proxy#resolveAddrLocally(boolean)
*/
public void send(DatagramPacket dp, String host) throws IOException {
dp.setAddress(InetAddress.getByName(host));
super.send(dp);
}
/**
* Receives udp packet. If packet have arrived from the proxy relay server,
* it is processed and address and port of the packet are set to the
* address and port of sending host.<BR>
* If the packet arrived from anywhere else it is not changed.<br>
* <B> NOTE: </B> DatagramPacket size should be at least 10 bytes bigger
* than the largest packet you expect (this is for IPV4 addresses).
* For hostnames and IPV6 it is even more.
@param dp Datagram in which all relevent information will be copied.
*/
public void receive(DatagramPacket dp) throws IOException{
super.receive(dp);
if(server_mode){
//Drop all datagrams not from relayIP/relayPort
int init_length = dp.getLength();
int initTimeout = getSoTimeout();
long startTime = System.currentTimeMillis();
while(!relayIP.equals(dp.getAddress()) ||
relayPort != dp.getPort()){
//Restore datagram size
dp.setLength(init_length);
//If there is a non-infinit timeout on this socket
//Make sure that it happens no matter how often unexpected
//packets arrive.
if(initTimeout != 0){
int newTimeout = initTimeout - (int)(System.currentTimeMillis() -
startTime);
if(newTimeout <= 0) throw new InterruptedIOException(
"In Socks5DatagramSocket->receive()");
setSoTimeout(newTimeout);
}
super.receive(dp);
}
//Restore timeout settings
if(initTimeout != 0) setSoTimeout(initTimeout);
}else if(!relayIP.equals(dp.getAddress()) ||
relayPort != dp.getPort())
return; // Recieved direct packet
//If the datagram is not from the relay server, return it it as is.
byte[] data;
data = dp.getData();
if(encapsulation != null)
data = encapsulation.udpEncapsulate(data,false);
int offset = 0; //Java 1.1
//int offset = dp.getOffset(); //Java 1.2
ByteArrayInputStream bIn = new ByteArrayInputStream(data,offset,
dp.getLength());
ProxyMessage msg = new Socks5Message(bIn);
dp.setPort(msg.port);
dp.setAddress(msg.getInetAddress());
//what wasn't read by the Message is the data
int data_length = bIn.available();
//Shift data to the left
System.arraycopy(data,offset+dp.getLength()-data_length,
data,offset,data_length);
dp.setLength(data_length);
}
/**
* Returns port assigned by the proxy, to which datagrams are relayed.
* It is not the same port to which other party should send datagrams.
@return Port assigned by socks server to which datagrams are send
for association.
*/
public int getLocalPort(){
if(server_mode) return super.getLocalPort();
return relayPort;
}
/**
* Address assigned by the proxy, to which datagrams are send for relay.
* It is not necesseraly the same address, to which other party should send
* datagrams.
@return Address to which datagrams are send for association.
*/
public InetAddress getLocalAddress(){
if(server_mode) return super.getLocalAddress();
return relayIP;
}
/**
* Closes datagram socket, and proxy connection.
*/
public void close(){
if(!server_mode) proxy.endSession();
super.close();
}
/**
This method checks wether proxy still runs udp forwarding service
for this socket.
<p>
This methods checks wether the primary connection to proxy server
is active. If it is, chances are that proxy continues to forward
datagrams being send from this socket. If it was closed, most likely
datagrams are no longer being forwarded by the server.
<p>
Proxy might decide to stop forwarding datagrams, in which case it
should close primary connection. This method allows to check, wether
this have been done.
<p>
You can specify timeout for which we should be checking EOF condition
on the primary connection. Timeout is in milliseconds. Specifying 0 as
timeout implies infinity, in which case method will block, until
connection to proxy is closed or an error happens, and then return false.
<p>
One possible scenario is to call isProxyactive(0) in separate thread,
and once it returned notify other threads about this event.
@param timeout For how long this method should block, before returning.
@return true if connection to proxy is active, false if eof or error
condition have been encountered on the connection.
*/
public boolean isProxyAlive(int timeout){
if(server_mode) return false;
if(proxy != null){
try{
proxy.proxySocket.setSoTimeout(timeout);
int eof = proxy.in.read();
if(eof < 0) return false; // EOF encountered.
else return true; // This really should not happen
}catch(InterruptedIOException iioe){
return true; // read timed out.
}catch(IOException ioe){
return false;
}
}
return false;
}
//PRIVATE METHODS
//////////////////
private byte[] formHeader(InetAddress ip, int port){
Socks5Message request = new Socks5Message(0,ip,port);
request.data[0] = 0;
return request.data;
}
/*======================================================================
//Mainly Test functions
//////////////////////
private String bytes2String(byte[] b){
String s="";
char[] hex_digit = { '0','1','2','3','4','5','6','7','8','9',
'A','B','C','D','E','F'};
for(int i=0;i<b.length;++i){
int i1 = (b[i] & 0xF0) >> 4;
int i2 = b[i] & 0xF;
s+=hex_digit[i1];
s+=hex_digit[i2];
s+=" ";
}
return s;
}
private static final void debug(String s){
if(DEBUG)
System.out.print(s);
}
private static final boolean DEBUG = true;
public static void usage(){
System.err.print(
"Usage: java Socks.SocksDatagramSocket host port [socksHost socksPort]\n");
}
static final int defaultProxyPort = 1080; //Default Port
static final String defaultProxyHost = "www-proxy"; //Default proxy
public static void main(String args[]){
int port;
String host;
int proxyPort;
String proxyHost;
InetAddress ip;
if(args.length > 1 && args.length < 5){
try{
host = args[0];
port = Integer.parseInt(args[1]);
proxyPort =(args.length > 3)? Integer.parseInt(args[3])
: defaultProxyPort;
host = args[0];
ip = InetAddress.getByName(host);
proxyHost =(args.length > 2)? args[2]
: defaultProxyHost;
Proxy.setDefaultProxy(proxyHost,proxyPort);
Proxy p = Proxy.getDefaultProxy();
p.addDirect("lux");
DatagramSocket ds = new Socks5DatagramSocket();
BufferedReader in = new BufferedReader(
new InputStreamReader(System.in));
String s;
System.out.print("Enter line:");
s = in.readLine();
while(s != null){
byte[] data = (s+"\r\n").getBytes();
DatagramPacket dp = new DatagramPacket(data,0,data.length,
ip,port);
System.out.println("Sending to: "+ip+":"+port);
ds.send(dp);
dp = new DatagramPacket(new byte[1024],1024);
System.out.println("Trying to recieve on port:"+
ds.getLocalPort());
ds.receive(dp);
System.out.print("Recieved:\n"+
"From:"+dp.getAddress()+":"+dp.getPort()+
"\n\n"+
new String(dp.getData(),dp.getOffset(),dp.getLength())+"\n"
);
System.out.print("Enter line:");
s = in.readLine();
}
ds.close();
System.exit(1);
}catch(SocksException s_ex){
System.err.println("SocksException:"+s_ex);
s_ex.printStackTrace();
System.exit(1);
}catch(IOException io_ex){
io_ex.printStackTrace();
System.exit(1);
}catch(NumberFormatException num_ex){
usage();
num_ex.printStackTrace();
System.exit(1);
}
}else{
usage();
}
}
*/
}
|
Java
|
package net.sourceforge.jsocks;
/**
Exception thrown by various socks classes to indicate errors
with protocol or unsuccessful server responses.
*/
public class SocksException extends java.io.IOException{
private static final long serialVersionUID = 6141184566248512277L;
/**
Construct a SocksException with given error code.
<p>
Tries to look up message which corresponds to this error code.
@param errCode Error code for this exception.
*/
public SocksException(int errCode){
this.errCode = errCode;
if((errCode >> 16) == 0){
//Server reply error message
errString = errCode <= serverReplyMessage.length ?
serverReplyMessage[errCode] :
UNASSIGNED_ERROR_MESSAGE;
}else{
//Local error
errCode = (errCode >> 16) -1;
errString = errCode <= localErrorMessage.length ?
localErrorMessage[errCode] :
UNASSIGNED_ERROR_MESSAGE;
}
}
/**
Constructs a SocksException with given error code and message.
@param errCode Error code.
@param errString Error Message.
*/
public SocksException(int errCode,String errString){
this.errCode = errCode;
this.errString = errString;
}
/**
Get the error code associated with this exception.
@return Error code associated with this exception.
*/
public int getErrorCode(){
return errCode;
}
/**
Get human readable representation of this exception.
@return String represntation of this exception.
*/
public String toString(){
return errString;
}
static final String UNASSIGNED_ERROR_MESSAGE =
"Unknown error message";
static final String serverReplyMessage[] = {
"Succeeded",
"General SOCKS server failure",
"Connection not allowed by ruleset",
"Network unreachable",
"Host unreachable",
"Connection refused",
"TTL expired",
"Command not supported",
"Address type not supported" };
static final String localErrorMessage[] ={
"SOCKS server not specified",
"Unable to contact SOCKS server",
"IO error",
"None of Authentication methods are supported",
"Authentication failed",
"General SOCKS fault" };
String errString;
public int errCode;
}//End of SocksException class
|
Java
|
/*
* Copyright (C) 2007 The Android Open Source Project
*
* 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 com.google.ase;
import java.io.FileDescriptor;
/**
* Tools for executing commands.
*/
public class Exec {
/**
* @param cmd
* The command to execute
* @param arg0
* The first argument to the command, may be null
* @param arg1
* the second argument to the command, may be null
* @return the file descriptor of the started process.
*
*/
public static FileDescriptor createSubprocess(String cmd, String arg0, String arg1) {
return createSubprocess(cmd, arg0, arg1, null);
}
/**
* @param cmd
* The command to execute
* @param arg0
* The first argument to the command, may be null
* @param arg1
* the second argument to the command, may be null
* @param processId
* A one-element array to which the process ID of the started process will be written.
* @return the file descriptor of the started process.
*
*/
public static native FileDescriptor createSubprocess(String cmd, String arg0, String arg1,
int[] processId);
public static native void setPtyWindowSize(FileDescriptor fd, int row, int col, int xpixel,
int ypixel);
/**
* Causes the calling thread to wait for the process associated with the receiver to finish
* executing.
*
* @return The exit value of the Process being waited on
*
*/
public static native int waitFor(int processId);
static {
System.loadLibrary("com_google_ase_Exec");
}
}
|
Java
|
package com.trilead.ssh2;
/**
* An abstract marker interface implemented by all proxy data implementations.
*
* @see HTTPProxyData
*
* @author Christian Plattner, plattner@trilead.com
* @version $Id: ProxyData.java,v 1.1 2007/10/15 12:49:56 cplattne Exp $
*/
public abstract interface ProxyData
{
}
|
Java
|
package com.trilead.ssh2;
import java.io.BufferedOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintStream;
import java.nio.charset.Charset;
import java.util.HashMap;
import java.util.Vector;
import com.trilead.ssh2.packets.TypesReader;
import com.trilead.ssh2.packets.TypesWriter;
import com.trilead.ssh2.sftp.AttribFlags;
import com.trilead.ssh2.sftp.ErrorCodes;
import com.trilead.ssh2.sftp.Packet;
/**
* A <code>SFTPv3Client</code> represents a SFTP (protocol version 3)
* client connection tunnelled over a SSH-2 connection. This is a very simple
* (synchronous) implementation.
* <p>
* Basically, most methods in this class map directly to one of
* the packet types described in draft-ietf-secsh-filexfer-02.txt.
* <p>
* Note: this is experimental code.
* <p>
* Error handling: the methods of this class throw IOExceptions. However, unless
* there is catastrophic failure, exceptions of the type {@link SFTPv3Client} will
* be thrown (a subclass of IOException). Therefore, you can implement more verbose
* behavior by checking if a thrown exception if of this type. If yes, then you
* can cast the exception and access detailed information about the failure.
* <p>
* Notes about file names, directory names and paths, copy-pasted
* from the specs:
* <ul>
* <li>SFTP v3 represents file names as strings. File names are
* assumed to use the slash ('/') character as a directory separator.</li>
* <li>File names starting with a slash are "absolute", and are relative to
* the root of the file system. Names starting with any other character
* are relative to the user's default directory (home directory).</li>
* <li>Servers SHOULD interpret a path name component ".." as referring to
* the parent directory, and "." as referring to the current directory.
* If the server implementation limits access to certain parts of the
* file system, it must be extra careful in parsing file names when
* enforcing such restrictions. There have been numerous reported
* security bugs where a ".." in a path name has allowed access outside
* the intended area.</li>
* <li>An empty path name is valid, and it refers to the user's default
* directory (usually the user's home directory).</li>
* </ul>
* <p>
* If you are still not tired then please go on and read the comment for
* {@link #setCharset(String)}.
*
* @author Christian Plattner, plattner@trilead.com
* @version $Id: SFTPv3Client.java,v 1.3 2008/04/01 12:38:09 cplattne Exp $
*/
public class SFTPv3Client
{
final Connection conn;
final Session sess;
final PrintStream debug;
boolean flag_closed = false;
InputStream is;
OutputStream os;
int protocol_version = 0;
HashMap server_extensions = new HashMap();
int next_request_id = 1000;
String charsetName = null;
/**
* Create a SFTP v3 client.
*
* @param conn The underlying SSH-2 connection to be used.
* @param debug
* @throws IOException
*
* @deprecated this constructor (debug version) will disappear in the future,
* use {@link #SFTPv3Client(Connection)} instead.
*/
public SFTPv3Client(Connection conn, PrintStream debug) throws IOException
{
if (conn == null)
throw new IllegalArgumentException("Cannot accept null argument!");
this.conn = conn;
this.debug = debug;
if (debug != null)
debug.println("Opening session and starting SFTP subsystem.");
sess = conn.openSession();
sess.startSubSystem("sftp");
is = sess.getStdout();
os = new BufferedOutputStream(sess.getStdin(), 2048);
if ((is == null) || (os == null))
throw new IOException("There is a problem with the streams of the underlying channel.");
init();
}
/**
* Create a SFTP v3 client.
*
* @param conn The underlying SSH-2 connection to be used.
* @throws IOException
*/
public SFTPv3Client(Connection conn) throws IOException
{
this(conn, null);
}
/**
* Set the charset used to convert between Java Unicode Strings and byte encodings
* used by the server for paths and file names. Unfortunately, the SFTP v3 draft
* says NOTHING about such conversions (well, with the exception of error messages
* which have to be in UTF-8). Newer drafts specify to use UTF-8 for file names
* (if I remember correctly). However, a quick test using OpenSSH serving a EXT-3
* filesystem has shown that UTF-8 seems to be a bad choice for SFTP v3 (tested with
* filenames containing german umlauts). "windows-1252" seems to work better for Europe.
* Luckily, "windows-1252" is the platform default in my case =).
* <p>
* If you don't set anything, then the platform default will be used (this is the default
* behavior).
*
* @see #getCharset()
*
* @param charset the name of the charset to be used or <code>null</code> to use the platform's
* default encoding.
* @throws IOException
*/
public void setCharset(String charset) throws IOException
{
if (charset == null)
{
charsetName = charset;
return;
}
try
{
Charset.forName(charset);
}
catch (Exception e)
{
throw (IOException) new IOException("This charset is not supported").initCause(e);
}
charsetName = charset;
}
/**
* The currently used charset for filename encoding/decoding.
*
* @see #setCharset(String)
*
* @return The name of the charset (<code>null</code> if the platform's default charset is being used)
*/
public String getCharset()
{
return charsetName;
}
private final void checkHandleValidAndOpen(SFTPv3FileHandle handle) throws IOException
{
if (handle.client != this)
throw new IOException("The file handle was created with another SFTPv3FileHandle instance.");
if (handle.isClosed == true)
throw new IOException("The file handle is closed.");
}
private final void sendMessage(int type, int requestId, byte[] msg, int off, int len) throws IOException
{
int msglen = len + 1;
if (type != Packet.SSH_FXP_INIT)
msglen += 4;
os.write(msglen >> 24);
os.write(msglen >> 16);
os.write(msglen >> 8);
os.write(msglen);
os.write(type);
if (type != Packet.SSH_FXP_INIT)
{
os.write(requestId >> 24);
os.write(requestId >> 16);
os.write(requestId >> 8);
os.write(requestId);
}
os.write(msg, off, len);
os.flush();
}
private final void sendMessage(int type, int requestId, byte[] msg) throws IOException
{
sendMessage(type, requestId, msg, 0, msg.length);
}
private final void readBytes(byte[] buff, int pos, int len) throws IOException
{
while (len > 0)
{
int count = is.read(buff, pos, len);
if (count < 0)
throw new IOException("Unexpected end of sftp stream.");
if ((count == 0) || (count > len))
throw new IOException("Underlying stream implementation is bogus!");
len -= count;
pos += count;
}
}
/**
* Read a message and guarantee that the <b>contents</b> is not larger than
* <code>maxlen</code> bytes.
* <p>
* Note: receiveMessage(34000) actually means that the message may be up to 34004
* bytes (the length attribute preceeding the contents is 4 bytes).
*
* @param maxlen
* @return the message contents
* @throws IOException
*/
private final byte[] receiveMessage(int maxlen) throws IOException
{
byte[] msglen = new byte[4];
readBytes(msglen, 0, 4);
int len = (((msglen[0] & 0xff) << 24) | ((msglen[1] & 0xff) << 16) | ((msglen[2] & 0xff) << 8) | (msglen[3] & 0xff));
if ((len > maxlen) || (len <= 0))
throw new IOException("Illegal sftp packet len: " + len);
byte[] msg = new byte[len];
readBytes(msg, 0, len);
return msg;
}
private final int generateNextRequestID()
{
synchronized (this)
{
return next_request_id++;
}
}
private final void closeHandle(byte[] handle) throws IOException
{
int req_id = generateNextRequestID();
TypesWriter tw = new TypesWriter();
tw.writeString(handle, 0, handle.length);
sendMessage(Packet.SSH_FXP_CLOSE, req_id, tw.getBytes());
expectStatusOKMessage(req_id);
}
private SFTPv3FileAttributes readAttrs(TypesReader tr) throws IOException
{
/*
* uint32 flags
* uint64 size present only if flag SSH_FILEXFER_ATTR_SIZE
* uint32 uid present only if flag SSH_FILEXFER_ATTR_V3_UIDGID
* uint32 gid present only if flag SSH_FILEXFER_ATTR_V3_UIDGID
* uint32 permissions present only if flag SSH_FILEXFER_ATTR_PERMISSIONS
* uint32 atime present only if flag SSH_FILEXFER_ATTR_V3_ACMODTIME
* uint32 mtime present only if flag SSH_FILEXFER_ATTR_V3_ACMODTIME
* uint32 extended_count present only if flag SSH_FILEXFER_ATTR_EXTENDED
* string extended_type
* string extended_data
* ... more extended data (extended_type - extended_data pairs),
* so that number of pairs equals extended_count
*/
SFTPv3FileAttributes fa = new SFTPv3FileAttributes();
int flags = tr.readUINT32();
if ((flags & AttribFlags.SSH_FILEXFER_ATTR_SIZE) != 0)
{
if (debug != null)
debug.println("SSH_FILEXFER_ATTR_SIZE");
fa.size = new Long(tr.readUINT64());
}
if ((flags & AttribFlags.SSH_FILEXFER_ATTR_V3_UIDGID) != 0)
{
if (debug != null)
debug.println("SSH_FILEXFER_ATTR_V3_UIDGID");
fa.uid = new Integer(tr.readUINT32());
fa.gid = new Integer(tr.readUINT32());
}
if ((flags & AttribFlags.SSH_FILEXFER_ATTR_PERMISSIONS) != 0)
{
if (debug != null)
debug.println("SSH_FILEXFER_ATTR_PERMISSIONS");
fa.permissions = new Integer(tr.readUINT32());
}
if ((flags & AttribFlags.SSH_FILEXFER_ATTR_V3_ACMODTIME) != 0)
{
if (debug != null)
debug.println("SSH_FILEXFER_ATTR_V3_ACMODTIME");
fa.atime = new Long(((long)tr.readUINT32()) & 0xffffffffl);
fa.mtime = new Long(((long)tr.readUINT32()) & 0xffffffffl);
}
if ((flags & AttribFlags.SSH_FILEXFER_ATTR_EXTENDED) != 0)
{
int count = tr.readUINT32();
if (debug != null)
debug.println("SSH_FILEXFER_ATTR_EXTENDED (" + count + ")");
/* Read it anyway to detect corrupt packets */
while (count > 0)
{
tr.readByteString();
tr.readByteString();
count--;
}
}
return fa;
}
/**
* Retrieve the file attributes of an open file.
*
* @param handle a SFTPv3FileHandle handle.
* @return a SFTPv3FileAttributes object.
* @throws IOException
*/
public SFTPv3FileAttributes fstat(SFTPv3FileHandle handle) throws IOException
{
checkHandleValidAndOpen(handle);
int req_id = generateNextRequestID();
TypesWriter tw = new TypesWriter();
tw.writeString(handle.fileHandle, 0, handle.fileHandle.length);
if (debug != null)
{
debug.println("Sending SSH_FXP_FSTAT...");
debug.flush();
}
sendMessage(Packet.SSH_FXP_FSTAT, req_id, tw.getBytes());
byte[] resp = receiveMessage(34000);
if (debug != null)
{
debug.println("Got REPLY.");
debug.flush();
}
TypesReader tr = new TypesReader(resp);
int t = tr.readByte();
int rep_id = tr.readUINT32();
if (rep_id != req_id)
throw new IOException("The server sent an invalid id field.");
if (t == Packet.SSH_FXP_ATTRS)
{
return readAttrs(tr);
}
if (t != Packet.SSH_FXP_STATUS)
throw new IOException("The SFTP server sent an unexpected packet type (" + t + ")");
int errorCode = tr.readUINT32();
throw new SFTPException(tr.readString(), errorCode);
}
private SFTPv3FileAttributes statBoth(String path, int statMethod) throws IOException
{
int req_id = generateNextRequestID();
TypesWriter tw = new TypesWriter();
tw.writeString(path, charsetName);
if (debug != null)
{
debug.println("Sending SSH_FXP_STAT/SSH_FXP_LSTAT...");
debug.flush();
}
sendMessage(statMethod, req_id, tw.getBytes());
byte[] resp = receiveMessage(34000);
if (debug != null)
{
debug.println("Got REPLY.");
debug.flush();
}
TypesReader tr = new TypesReader(resp);
int t = tr.readByte();
int rep_id = tr.readUINT32();
if (rep_id != req_id)
throw new IOException("The server sent an invalid id field.");
if (t == Packet.SSH_FXP_ATTRS)
{
return readAttrs(tr);
}
if (t != Packet.SSH_FXP_STATUS)
throw new IOException("The SFTP server sent an unexpected packet type (" + t + ")");
int errorCode = tr.readUINT32();
throw new SFTPException(tr.readString(), errorCode);
}
/**
* Retrieve the file attributes of a file. This method
* follows symbolic links on the server.
*
* @see #lstat(String)
*
* @param path See the {@link SFTPv3Client comment} for the class for more details.
* @return a SFTPv3FileAttributes object.
* @throws IOException
*/
public SFTPv3FileAttributes stat(String path) throws IOException
{
return statBoth(path, Packet.SSH_FXP_STAT);
}
/**
* Retrieve the file attributes of a file. This method
* does NOT follow symbolic links on the server.
*
* @see #stat(String)
*
* @param path See the {@link SFTPv3Client comment} for the class for more details.
* @return a SFTPv3FileAttributes object.
* @throws IOException
*/
public SFTPv3FileAttributes lstat(String path) throws IOException
{
return statBoth(path, Packet.SSH_FXP_LSTAT);
}
/**
* Read the target of a symbolic link.
*
* @param path See the {@link SFTPv3Client comment} for the class for more details.
* @return The target of the link.
* @throws IOException
*/
public String readLink(String path) throws IOException
{
int req_id = generateNextRequestID();
TypesWriter tw = new TypesWriter();
tw.writeString(path, charsetName);
if (debug != null)
{
debug.println("Sending SSH_FXP_READLINK...");
debug.flush();
}
sendMessage(Packet.SSH_FXP_READLINK, req_id, tw.getBytes());
byte[] resp = receiveMessage(34000);
if (debug != null)
{
debug.println("Got REPLY.");
debug.flush();
}
TypesReader tr = new TypesReader(resp);
int t = tr.readByte();
int rep_id = tr.readUINT32();
if (rep_id != req_id)
throw new IOException("The server sent an invalid id field.");
if (t == Packet.SSH_FXP_NAME)
{
int count = tr.readUINT32();
if (count != 1)
throw new IOException("The server sent an invalid SSH_FXP_NAME packet.");
return tr.readString(charsetName);
}
if (t != Packet.SSH_FXP_STATUS)
throw new IOException("The SFTP server sent an unexpected packet type (" + t + ")");
int errorCode = tr.readUINT32();
throw new SFTPException(tr.readString(), errorCode);
}
private void expectStatusOKMessage(int id) throws IOException
{
byte[] resp = receiveMessage(34000);
if (debug != null)
{
debug.println("Got REPLY.");
debug.flush();
}
TypesReader tr = new TypesReader(resp);
int t = tr.readByte();
int rep_id = tr.readUINT32();
if (rep_id != id)
throw new IOException("The server sent an invalid id field.");
if (t != Packet.SSH_FXP_STATUS)
throw new IOException("The SFTP server sent an unexpected packet type (" + t + ")");
int errorCode = tr.readUINT32();
if (errorCode == ErrorCodes.SSH_FX_OK)
return;
throw new SFTPException(tr.readString(), errorCode);
}
/**
* Modify the attributes of a file. Used for operations such as changing
* the ownership, permissions or access times, as well as for truncating a file.
*
* @param path See the {@link SFTPv3Client comment} for the class for more details.
* @param attr A SFTPv3FileAttributes object. Specifies the modifications to be
* made to the attributes of the file. Empty fields will be ignored.
* @throws IOException
*/
public void setstat(String path, SFTPv3FileAttributes attr) throws IOException
{
int req_id = generateNextRequestID();
TypesWriter tw = new TypesWriter();
tw.writeString(path, charsetName);
tw.writeBytes(createAttrs(attr));
if (debug != null)
{
debug.println("Sending SSH_FXP_SETSTAT...");
debug.flush();
}
sendMessage(Packet.SSH_FXP_SETSTAT, req_id, tw.getBytes());
expectStatusOKMessage(req_id);
}
/**
* Modify the attributes of a file. Used for operations such as changing
* the ownership, permissions or access times, as well as for truncating a file.
*
* @param handle a SFTPv3FileHandle handle
* @param attr A SFTPv3FileAttributes object. Specifies the modifications to be
* made to the attributes of the file. Empty fields will be ignored.
* @throws IOException
*/
public void fsetstat(SFTPv3FileHandle handle, SFTPv3FileAttributes attr) throws IOException
{
checkHandleValidAndOpen(handle);
int req_id = generateNextRequestID();
TypesWriter tw = new TypesWriter();
tw.writeString(handle.fileHandle, 0, handle.fileHandle.length);
tw.writeBytes(createAttrs(attr));
if (debug != null)
{
debug.println("Sending SSH_FXP_FSETSTAT...");
debug.flush();
}
sendMessage(Packet.SSH_FXP_FSETSTAT, req_id, tw.getBytes());
expectStatusOKMessage(req_id);
}
/**
* Create a symbolic link on the server. Creates a link "src" that points
* to "target".
*
* @param src See the {@link SFTPv3Client comment} for the class for more details.
* @param target See the {@link SFTPv3Client comment} for the class for more details.
* @throws IOException
*/
public void createSymlink(String src, String target) throws IOException
{
int req_id = generateNextRequestID();
/* Either I am too stupid to understand the SFTP draft
* or the OpenSSH guys changed the semantics of src and target.
*/
TypesWriter tw = new TypesWriter();
tw.writeString(target, charsetName);
tw.writeString(src, charsetName);
if (debug != null)
{
debug.println("Sending SSH_FXP_SYMLINK...");
debug.flush();
}
sendMessage(Packet.SSH_FXP_SYMLINK, req_id, tw.getBytes());
expectStatusOKMessage(req_id);
}
/**
* Have the server canonicalize any given path name to an absolute path.
* This is useful for converting path names containing ".." components or
* relative pathnames without a leading slash into absolute paths.
*
* @param path See the {@link SFTPv3Client comment} for the class for more details.
* @return An absolute path.
* @throws IOException
*/
public String canonicalPath(String path) throws IOException
{
int req_id = generateNextRequestID();
TypesWriter tw = new TypesWriter();
tw.writeString(path, charsetName);
if (debug != null)
{
debug.println("Sending SSH_FXP_REALPATH...");
debug.flush();
}
sendMessage(Packet.SSH_FXP_REALPATH, req_id, tw.getBytes());
byte[] resp = receiveMessage(34000);
if (debug != null)
{
debug.println("Got REPLY.");
debug.flush();
}
TypesReader tr = new TypesReader(resp);
int t = tr.readByte();
int rep_id = tr.readUINT32();
if (rep_id != req_id)
throw new IOException("The server sent an invalid id field.");
if (t == Packet.SSH_FXP_NAME)
{
int count = tr.readUINT32();
if (count != 1)
throw new IOException("The server sent an invalid SSH_FXP_NAME packet.");
return tr.readString(charsetName);
}
if (t != Packet.SSH_FXP_STATUS)
throw new IOException("The SFTP server sent an unexpected packet type (" + t + ")");
int errorCode = tr.readUINT32();
throw new SFTPException(tr.readString(), errorCode);
}
private final Vector scanDirectory(byte[] handle) throws IOException
{
Vector files = new Vector();
while (true)
{
int req_id = generateNextRequestID();
TypesWriter tw = new TypesWriter();
tw.writeString(handle, 0, handle.length);
if (debug != null)
{
debug.println("Sending SSH_FXP_READDIR...");
debug.flush();
}
sendMessage(Packet.SSH_FXP_READDIR, req_id, tw.getBytes());
/* Some servers send here a packet with size > 34000 */
/* To whom it may concern: please learn to read the specs. */
byte[] resp = receiveMessage(65536);
if (debug != null)
{
debug.println("Got REPLY.");
debug.flush();
}
TypesReader tr = new TypesReader(resp);
int t = tr.readByte();
int rep_id = tr.readUINT32();
if (rep_id != req_id)
throw new IOException("The server sent an invalid id field.");
if (t == Packet.SSH_FXP_NAME)
{
int count = tr.readUINT32();
if (debug != null)
debug.println("Parsing " + count + " name entries...");
while (count > 0)
{
SFTPv3DirectoryEntry dirEnt = new SFTPv3DirectoryEntry();
dirEnt.filename = tr.readString(charsetName);
dirEnt.longEntry = tr.readString(charsetName);
dirEnt.attributes = readAttrs(tr);
files.addElement(dirEnt);
if (debug != null)
debug.println("File: '" + dirEnt.filename + "'");
count--;
}
continue;
}
if (t != Packet.SSH_FXP_STATUS)
throw new IOException("The SFTP server sent an unexpected packet type (" + t + ")");
int errorCode = tr.readUINT32();
if (errorCode == ErrorCodes.SSH_FX_EOF)
return files;
throw new SFTPException(tr.readString(), errorCode);
}
}
private final byte[] openDirectory(String path) throws IOException
{
int req_id = generateNextRequestID();
TypesWriter tw = new TypesWriter();
tw.writeString(path, charsetName);
if (debug != null)
{
debug.println("Sending SSH_FXP_OPENDIR...");
debug.flush();
}
sendMessage(Packet.SSH_FXP_OPENDIR, req_id, tw.getBytes());
byte[] resp = receiveMessage(34000);
TypesReader tr = new TypesReader(resp);
int t = tr.readByte();
int rep_id = tr.readUINT32();
if (rep_id != req_id)
throw new IOException("The server sent an invalid id field.");
if (t == Packet.SSH_FXP_HANDLE)
{
if (debug != null)
{
debug.println("Got SSH_FXP_HANDLE.");
debug.flush();
}
byte[] handle = tr.readByteString();
return handle;
}
if (t != Packet.SSH_FXP_STATUS)
throw new IOException("The SFTP server sent an unexpected packet type (" + t + ")");
int errorCode = tr.readUINT32();
String errorMessage = tr.readString();
throw new SFTPException(errorMessage, errorCode);
}
private final String expandString(byte[] b, int off, int len)
{
StringBuffer sb = new StringBuffer();
for (int i = 0; i < len; i++)
{
int c = b[off + i] & 0xff;
if ((c >= 32) && (c <= 126))
{
sb.append((char) c);
}
else
{
sb.append("{0x" + Integer.toHexString(c) + "}");
}
}
return sb.toString();
}
private void init() throws IOException
{
/* Send SSH_FXP_INIT (version 3) */
final int client_version = 3;
if (debug != null)
debug.println("Sending SSH_FXP_INIT (" + client_version + ")...");
TypesWriter tw = new TypesWriter();
tw.writeUINT32(client_version);
sendMessage(Packet.SSH_FXP_INIT, 0, tw.getBytes());
/* Receive SSH_FXP_VERSION */
if (debug != null)
debug.println("Waiting for SSH_FXP_VERSION...");
TypesReader tr = new TypesReader(receiveMessage(34000)); /* Should be enough for any reasonable server */
int type = tr.readByte();
if (type != Packet.SSH_FXP_VERSION)
{
throw new IOException("The server did not send a SSH_FXP_VERSION packet (got " + type + ")");
}
protocol_version = tr.readUINT32();
if (debug != null)
debug.println("SSH_FXP_VERSION: protocol_version = " + protocol_version);
if (protocol_version != 3)
throw new IOException("Server version " + protocol_version + " is currently not supported");
/* Read and save extensions (if any) for later use */
while (tr.remain() != 0)
{
String name = tr.readString();
byte[] value = tr.readByteString();
server_extensions.put(name, value);
if (debug != null)
debug.println("SSH_FXP_VERSION: extension: " + name + " = '" + expandString(value, 0, value.length)
+ "'");
}
}
/**
* Returns the negotiated SFTP protocol version between the client and the server.
*
* @return SFTP protocol version, i.e., "3".
*
*/
public int getProtocolVersion()
{
return protocol_version;
}
/**
* Close this SFTP session. NEVER forget to call this method to free up
* resources - even if you got an exception from one of the other methods.
* Sometimes these other methods may throw an exception, saying that the
* underlying channel is closed (this can happen, e.g., if the other server
* sent a close message.) However, as long as you have not called the
* <code>close()</code> method, you are likely wasting resources.
*
*/
public void close()
{
sess.close();
}
/**
* List the contents of a directory.
*
* @param dirName See the {@link SFTPv3Client comment} for the class for more details.
* @return A Vector containing {@link SFTPv3DirectoryEntry} objects.
* @throws IOException
*/
public Vector ls(String dirName) throws IOException
{
byte[] handle = openDirectory(dirName);
Vector result = scanDirectory(handle);
closeHandle(handle);
return result;
}
/**
* Create a new directory.
*
* @param dirName See the {@link SFTPv3Client comment} for the class for more details.
* @param posixPermissions the permissions for this directory, e.g., "0700" (remember that
* this is octal noation). The server will likely apply a umask.
*
* @throws IOException
*/
public void mkdir(String dirName, int posixPermissions) throws IOException
{
int req_id = generateNextRequestID();
TypesWriter tw = new TypesWriter();
tw.writeString(dirName, charsetName);
tw.writeUINT32(AttribFlags.SSH_FILEXFER_ATTR_PERMISSIONS);
tw.writeUINT32(posixPermissions);
sendMessage(Packet.SSH_FXP_MKDIR, req_id, tw.getBytes());
expectStatusOKMessage(req_id);
}
/**
* Remove a file.
*
* @param fileName See the {@link SFTPv3Client comment} for the class for more details.
* @throws IOException
*/
public void rm(String fileName) throws IOException
{
int req_id = generateNextRequestID();
TypesWriter tw = new TypesWriter();
tw.writeString(fileName, charsetName);
sendMessage(Packet.SSH_FXP_REMOVE, req_id, tw.getBytes());
expectStatusOKMessage(req_id);
}
/**
* Remove an empty directory.
*
* @param dirName See the {@link SFTPv3Client comment} for the class for more details.
* @throws IOException
*/
public void rmdir(String dirName) throws IOException
{
int req_id = generateNextRequestID();
TypesWriter tw = new TypesWriter();
tw.writeString(dirName, charsetName);
sendMessage(Packet.SSH_FXP_RMDIR, req_id, tw.getBytes());
expectStatusOKMessage(req_id);
}
/**
* Move a file or directory.
*
* @param oldPath See the {@link SFTPv3Client comment} for the class for more details.
* @param newPath See the {@link SFTPv3Client comment} for the class for more details.
* @throws IOException
*/
public void mv(String oldPath, String newPath) throws IOException
{
int req_id = generateNextRequestID();
TypesWriter tw = new TypesWriter();
tw.writeString(oldPath, charsetName);
tw.writeString(newPath, charsetName);
sendMessage(Packet.SSH_FXP_RENAME, req_id, tw.getBytes());
expectStatusOKMessage(req_id);
}
/**
* Open a file for reading.
*
* @param fileName See the {@link SFTPv3Client comment} for the class for more details.
* @return a SFTPv3FileHandle handle
* @throws IOException
*/
public SFTPv3FileHandle openFileRO(String fileName) throws IOException
{
return openFile(fileName, 0x00000001, null); // SSH_FXF_READ
}
/**
* Open a file for reading and writing.
*
* @param fileName See the {@link SFTPv3Client comment} for the class for more details.
* @return a SFTPv3FileHandle handle
* @throws IOException
*/
public SFTPv3FileHandle openFileRW(String fileName) throws IOException
{
return openFile(fileName, 0x00000003, null); // SSH_FXF_READ | SSH_FXF_WRITE
}
// Append is broken (already in the specification, because there is no way to
// send a write operation (what offset to use??))
// public SFTPv3FileHandle openFileRWAppend(String fileName) throws IOException
// {
// return openFile(fileName, 0x00000007, null); // SSH_FXF_READ | SSH_FXF_WRITE | SSH_FXF_APPEND
// }
/**
* Create a file and open it for reading and writing.
* Same as {@link #createFile(String, SFTPv3FileAttributes) createFile(fileName, null)}.
*
* @param fileName See the {@link SFTPv3Client comment} for the class for more details.
* @return a SFTPv3FileHandle handle
* @throws IOException
*/
public SFTPv3FileHandle createFile(String fileName) throws IOException
{
return createFile(fileName, null);
}
/**
* Create a file and open it for reading and writing.
* You can specify the default attributes of the file (the server may or may
* not respect your wishes).
*
* @param fileName See the {@link SFTPv3Client comment} for the class for more details.
* @param attr may be <code>null</code> to use server defaults. Probably only
* the <code>uid</code>, <code>gid</code> and <code>permissions</code>
* (remember the server may apply a umask) entries of the {@link SFTPv3FileHandle}
* structure make sense. You need only to set those fields where you want
* to override the server's defaults.
* @return a SFTPv3FileHandle handle
* @throws IOException
*/
public SFTPv3FileHandle createFile(String fileName, SFTPv3FileAttributes attr) throws IOException
{
return openFile(fileName, 0x00000008 | 0x00000003, attr); // SSH_FXF_CREAT | SSH_FXF_READ | SSH_FXF_WRITE
}
/**
* Create a file (truncate it if it already exists) and open it for reading and writing.
* Same as {@link #createFileTruncate(String, SFTPv3FileAttributes) createFileTruncate(fileName, null)}.
*
* @param fileName See the {@link SFTPv3Client comment} for the class for more details.
* @return a SFTPv3FileHandle handle
* @throws IOException
*/
public SFTPv3FileHandle createFileTruncate(String fileName) throws IOException
{
return createFileTruncate(fileName, null);
}
/**
* reate a file (truncate it if it already exists) and open it for reading and writing.
* You can specify the default attributes of the file (the server may or may
* not respect your wishes).
*
* @param fileName See the {@link SFTPv3Client comment} for the class for more details.
* @param attr may be <code>null</code> to use server defaults. Probably only
* the <code>uid</code>, <code>gid</code> and <code>permissions</code>
* (remember the server may apply a umask) entries of the {@link SFTPv3FileHandle}
* structure make sense. You need only to set those fields where you want
* to override the server's defaults.
* @return a SFTPv3FileHandle handle
* @throws IOException
*/
public SFTPv3FileHandle createFileTruncate(String fileName, SFTPv3FileAttributes attr) throws IOException
{
return openFile(fileName, 0x00000018 | 0x00000003, attr); // SSH_FXF_CREAT | SSH_FXF_TRUNC | SSH_FXF_READ | SSH_FXF_WRITE
}
private byte[] createAttrs(SFTPv3FileAttributes attr)
{
TypesWriter tw = new TypesWriter();
int attrFlags = 0;
if (attr == null)
{
tw.writeUINT32(0);
}
else
{
if (attr.size != null)
attrFlags = attrFlags | AttribFlags.SSH_FILEXFER_ATTR_SIZE;
if ((attr.uid != null) && (attr.gid != null))
attrFlags = attrFlags | AttribFlags.SSH_FILEXFER_ATTR_V3_UIDGID;
if (attr.permissions != null)
attrFlags = attrFlags | AttribFlags.SSH_FILEXFER_ATTR_PERMISSIONS;
if ((attr.atime != null) && (attr.mtime != null))
attrFlags = attrFlags | AttribFlags.SSH_FILEXFER_ATTR_V3_ACMODTIME;
tw.writeUINT32(attrFlags);
if (attr.size != null)
tw.writeUINT64(attr.size.longValue());
if ((attr.uid != null) && (attr.gid != null))
{
tw.writeUINT32(attr.uid.intValue());
tw.writeUINT32(attr.gid.intValue());
}
if (attr.permissions != null)
tw.writeUINT32(attr.permissions.intValue());
if ((attr.atime != null) && (attr.mtime != null))
{
tw.writeUINT32(attr.atime.intValue());
tw.writeUINT32(attr.mtime.intValue());
}
}
return tw.getBytes();
}
private SFTPv3FileHandle openFile(String fileName, int flags, SFTPv3FileAttributes attr) throws IOException
{
int req_id = generateNextRequestID();
TypesWriter tw = new TypesWriter();
tw.writeString(fileName, charsetName);
tw.writeUINT32(flags);
tw.writeBytes(createAttrs(attr));
if (debug != null)
{
debug.println("Sending SSH_FXP_OPEN...");
debug.flush();
}
sendMessage(Packet.SSH_FXP_OPEN, req_id, tw.getBytes());
byte[] resp = receiveMessage(34000);
TypesReader tr = new TypesReader(resp);
int t = tr.readByte();
int rep_id = tr.readUINT32();
if (rep_id != req_id)
throw new IOException("The server sent an invalid id field.");
if (t == Packet.SSH_FXP_HANDLE)
{
if (debug != null)
{
debug.println("Got SSH_FXP_HANDLE.");
debug.flush();
}
return new SFTPv3FileHandle(this, tr.readByteString());
}
if (t != Packet.SSH_FXP_STATUS)
throw new IOException("The SFTP server sent an unexpected packet type (" + t + ")");
int errorCode = tr.readUINT32();
String errorMessage = tr.readString();
throw new SFTPException(errorMessage, errorCode);
}
/**
* Read bytes from a file. No more than 32768 bytes may be read at once.
* Be aware that the semantics of read() are different than for Java streams.
* <p>
* <ul>
* <li>The server will read as many bytes as it can from the file (up to <code>len</code>),
* and return them.</li>
* <li>If EOF is encountered before reading any data, <code>-1</code> is returned.
* <li>If an error occurs, an exception is thrown</li>.
* <li>For normal disk files, it is guaranteed that the server will return the specified
* number of bytes, or up to end of file. For, e.g., device files this may return
* fewer bytes than requested.</li>
* </ul>
*
* @param handle a SFTPv3FileHandle handle
* @param fileOffset offset (in bytes) in the file
* @param dst the destination byte array
* @param dstoff offset in the destination byte array
* @param len how many bytes to read, 0 < len <= 32768 bytes
* @return the number of bytes that could be read, may be less than requested if
* the end of the file is reached, -1 is returned in case of <code>EOF</code>
* @throws IOException
*/
public int read(SFTPv3FileHandle handle, long fileOffset, byte[] dst, int dstoff, int len) throws IOException
{
checkHandleValidAndOpen(handle);
if ((len > 32768) || (len <= 0))
throw new IllegalArgumentException("invalid len argument");
int req_id = generateNextRequestID();
TypesWriter tw = new TypesWriter();
tw.writeString(handle.fileHandle, 0, handle.fileHandle.length);
tw.writeUINT64(fileOffset);
tw.writeUINT32(len);
if (debug != null)
{
debug.println("Sending SSH_FXP_READ...");
debug.flush();
}
sendMessage(Packet.SSH_FXP_READ, req_id, tw.getBytes());
byte[] resp = receiveMessage(34000);
TypesReader tr = new TypesReader(resp);
int t = tr.readByte();
int rep_id = tr.readUINT32();
if (rep_id != req_id)
throw new IOException("The server sent an invalid id field.");
if (t == Packet.SSH_FXP_DATA)
{
if (debug != null)
{
debug.println("Got SSH_FXP_DATA...");
debug.flush();
}
int readLen = tr.readUINT32();
if ((readLen < 0) || (readLen > len))
throw new IOException("The server sent an invalid length field.");
tr.readBytes(dst, dstoff, readLen);
return readLen;
}
if (t != Packet.SSH_FXP_STATUS)
throw new IOException("The SFTP server sent an unexpected packet type (" + t + ")");
int errorCode = tr.readUINT32();
if (errorCode == ErrorCodes.SSH_FX_EOF)
{
if (debug != null)
{
debug.println("Got SSH_FX_EOF.");
debug.flush();
}
return -1;
}
String errorMessage = tr.readString();
throw new SFTPException(errorMessage, errorCode);
}
/**
* Write bytes to a file. If <code>len</code> > 32768, then the write operation will
* be split into multiple writes.
*
* @param handle a SFTPv3FileHandle handle.
* @param fileOffset offset (in bytes) in the file.
* @param src the source byte array.
* @param srcoff offset in the source byte array.
* @param len how many bytes to write.
* @throws IOException
*/
public void write(SFTPv3FileHandle handle, long fileOffset, byte[] src, int srcoff, int len) throws IOException
{
checkHandleValidAndOpen(handle);
while (len > 0)
{
int writeRequestLen = len;
if (writeRequestLen > 32768)
writeRequestLen = 32768;
int req_id = generateNextRequestID();
TypesWriter tw = new TypesWriter();
tw.writeString(handle.fileHandle, 0, handle.fileHandle.length);
tw.writeUINT64(fileOffset);
tw.writeString(src, srcoff, writeRequestLen);
if (debug != null)
{
debug.println("Sending SSH_FXP_WRITE...");
debug.flush();
}
sendMessage(Packet.SSH_FXP_WRITE, req_id, tw.getBytes());
fileOffset += writeRequestLen;
srcoff += writeRequestLen;
len -= writeRequestLen;
byte[] resp = receiveMessage(34000);
TypesReader tr = new TypesReader(resp);
int t = tr.readByte();
int rep_id = tr.readUINT32();
if (rep_id != req_id)
throw new IOException("The server sent an invalid id field.");
if (t != Packet.SSH_FXP_STATUS)
throw new IOException("The SFTP server sent an unexpected packet type (" + t + ")");
int errorCode = tr.readUINT32();
if (errorCode == ErrorCodes.SSH_FX_OK)
continue;
String errorMessage = tr.readString();
throw new SFTPException(errorMessage, errorCode);
}
}
/**
* Close a file.
*
* @param handle a SFTPv3FileHandle handle
* @throws IOException
*/
public void closeFile(SFTPv3FileHandle handle) throws IOException
{
if (handle == null)
throw new IllegalArgumentException("the handle argument may not be null");
try
{
if (handle.isClosed == false)
{
closeHandle(handle.fileHandle);
}
}
finally
{
handle.isClosed = true;
}
}
}
|
Java
|
package com.trilead.ssh2;
/**
* An <code>InteractiveCallback</code> is used to respond to challenges sent
* by the server if authentication mode "keyboard-interactive" is selected.
*
* @see Connection#authenticateWithKeyboardInteractive(String,
* String[], InteractiveCallback)
*
* @author Christian Plattner, plattner@trilead.com
* @version $Id: InteractiveCallback.java,v 1.1 2007/10/15 12:49:56 cplattne Exp $
*/
public interface InteractiveCallback
{
/**
* This callback interface is used during a "keyboard-interactive"
* authentication. Every time the server sends a set of challenges (however,
* most often just one challenge at a time), this callback function will be
* called to give your application a chance to talk to the user and to
* determine the response(s).
* <p>
* Some copy-paste information from the standard: a command line interface
* (CLI) client SHOULD print the name and instruction (if non-empty), adding
* newlines. Then for each prompt in turn, the client SHOULD display the
* prompt and read the user input. The name and instruction fields MAY be
* empty strings, the client MUST be prepared to handle this correctly. The
* prompt field(s) MUST NOT be empty strings.
* <p>
* Please refer to draft-ietf-secsh-auth-kbdinteract-XX.txt for the details.
* <p>
* Note: clients SHOULD use control character filtering as discussed in
* RFC4251 to avoid attacks by including
* terminal control characters in the fields to be displayed.
*
* @param name
* the name String sent by the server.
* @param instruction
* the instruction String sent by the server.
* @param numPrompts
* number of prompts - may be zero (in this case, you should just
* return a String array of length zero).
* @param prompt
* an array (length <code>numPrompts</code>) of Strings
* @param echo
* an array (length <code>numPrompts</code>) of booleans. For
* each prompt, the corresponding echo field indicates whether or
* not the user input should be echoed as characters are typed.
* @return an array of reponses - the array size must match the parameter
* <code>numPrompts</code>.
*/
public String[] replyToChallenge(String name, String instruction, int numPrompts, String[] prompt, boolean[] echo)
throws Exception;
}
|
Java
|
package com.trilead.ssh2;
/**
* A <code>DHGexParameters</code> object can be used to specify parameters for
* the diffie-hellman group exchange.
* <p>
* Depending on which constructor is used, either the use of a
* <code>SSH_MSG_KEX_DH_GEX_REQUEST</code> or <code>SSH_MSG_KEX_DH_GEX_REQUEST_OLD</code>
* can be forced.
*
* @see Connection#setDHGexParameters(DHGexParameters)
* @author Christian Plattner, plattner@trilead.com
* @version $Id: DHGexParameters.java,v 1.1 2007/10/15 12:49:56 cplattne Exp $
*/
public class DHGexParameters
{
private final int min_group_len;
private final int pref_group_len;
private final int max_group_len;
private static final int MIN_ALLOWED = 1024;
private static final int MAX_ALLOWED = 8192;
/**
* Same as calling {@link #DHGexParameters(int, int, int) DHGexParameters(1024, 1024, 4096)}.
* This is also the default used by the Connection class.
*
*/
public DHGexParameters()
{
this(1024, 1024, 4096);
}
/**
* This constructor can be used to force the sending of a
* <code>SSH_MSG_KEX_DH_GEX_REQUEST_OLD</code> request.
* Internally, the minimum and maximum group lengths will
* be set to zero.
*
* @param pref_group_len has to be >= 1024 and <= 8192
*/
public DHGexParameters(int pref_group_len)
{
if ((pref_group_len < MIN_ALLOWED) || (pref_group_len > MAX_ALLOWED))
throw new IllegalArgumentException("pref_group_len out of range!");
this.pref_group_len = pref_group_len;
this.min_group_len = 0;
this.max_group_len = 0;
}
/**
* This constructor can be used to force the sending of a
* <code>SSH_MSG_KEX_DH_GEX_REQUEST</code> request.
* <p>
* Note: older OpenSSH servers don't understand this request, in which
* case you should use the {@link #DHGexParameters(int)} constructor.
* <p>
* All values have to be >= 1024 and <= 8192. Furthermore,
* min_group_len <= pref_group_len <= max_group_len.
*
* @param min_group_len
* @param pref_group_len
* @param max_group_len
*/
public DHGexParameters(int min_group_len, int pref_group_len, int max_group_len)
{
if ((min_group_len < MIN_ALLOWED) || (min_group_len > MAX_ALLOWED))
throw new IllegalArgumentException("min_group_len out of range!");
if ((pref_group_len < MIN_ALLOWED) || (pref_group_len > MAX_ALLOWED))
throw new IllegalArgumentException("pref_group_len out of range!");
if ((max_group_len < MIN_ALLOWED) || (max_group_len > MAX_ALLOWED))
throw new IllegalArgumentException("max_group_len out of range!");
if ((pref_group_len < min_group_len) || (pref_group_len > max_group_len))
throw new IllegalArgumentException("pref_group_len is incompatible with min and max!");
if (max_group_len < min_group_len)
throw new IllegalArgumentException("max_group_len must not be smaller than min_group_len!");
this.min_group_len = min_group_len;
this.pref_group_len = pref_group_len;
this.max_group_len = max_group_len;
}
/**
* Get the maximum group length.
*
* @return the maximum group length, may be <code>zero</code> if
* SSH_MSG_KEX_DH_GEX_REQUEST_OLD should be requested
*/
public int getMax_group_len()
{
return max_group_len;
}
/**
* Get the minimum group length.
*
* @return minimum group length, may be <code>zero</code> if
* SSH_MSG_KEX_DH_GEX_REQUEST_OLD should be requested
*/
public int getMin_group_len()
{
return min_group_len;
}
/**
* Get the preferred group length.
*
* @return the preferred group length
*/
public int getPref_group_len()
{
return pref_group_len;
}
}
|
Java
|
package com.trilead.ssh2;
/**
* A <code>ConnectionMonitor</code> is used to get notified when the
* underlying socket of a connection is closed.
*
* @author Christian Plattner, plattner@trilead.com
* @version $Id: ConnectionMonitor.java,v 1.1 2007/10/15 12:49:56 cplattne Exp $
*/
public interface ConnectionMonitor
{
/**
* This method is called after the connection's underlying
* socket has been closed. E.g., due to the {@link Connection#close()} request of the
* user, if the peer closed the connection, due to a fatal error during connect()
* (also if the socket cannot be established) or if a fatal error occured on
* an established connection.
* <p>
* This is an experimental feature.
* <p>
* You MUST NOT make any assumption about the thread that invokes this method.
* <p>
* <b>Please note: if the connection is not connected (e.g., there was no successful
* connect() call), then the invocation of {@link Connection#close()} will NOT trigger
* this method.</b>
*
* @see Connection#addConnectionMonitor(ConnectionMonitor)
*
* @param reason Includes an indication why the socket was closed.
*/
public void connectionLost(Throwable reason);
}
|
Java
|
package com.trilead.ssh2;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
/**
* A very basic <code>SCPClient</code> that can be used to copy files from/to
* the SSH-2 server. On the server side, the "scp" program must be in the PATH.
* <p>
* This scp client is thread safe - you can download (and upload) different sets
* of files concurrently without any troubles. The <code>SCPClient</code> is
* actually mapping every request to a distinct {@link Session}.
*
* @author Christian Plattner, plattner@trilead.com
* @version $Id: SCPClient.java,v 1.2 2008/04/01 12:38:09 cplattne Exp $
*/
public class SCPClient
{
Connection conn;
class LenNamePair
{
long length;
String filename;
}
public SCPClient(Connection conn)
{
if (conn == null)
throw new IllegalArgumentException("Cannot accept null argument!");
this.conn = conn;
}
private void readResponse(InputStream is) throws IOException
{
int c = is.read();
if (c == 0)
return;
if (c == -1)
throw new IOException("Remote scp terminated unexpectedly.");
if ((c != 1) && (c != 2))
throw new IOException("Remote scp sent illegal error code.");
if (c == 2)
throw new IOException("Remote scp terminated with error.");
String err = receiveLine(is);
throw new IOException("Remote scp terminated with error (" + err + ").");
}
private String receiveLine(InputStream is) throws IOException
{
StringBuffer sb = new StringBuffer(30);
while (true)
{
/*
* This is a random limit - if your path names are longer, then
* adjust it
*/
if (sb.length() > 8192)
throw new IOException("Remote scp sent a too long line");
int c = is.read();
if (c < 0)
throw new IOException("Remote scp terminated unexpectedly.");
if (c == '\n')
break;
sb.append((char) c);
}
return sb.toString();
}
private LenNamePair parseCLine(String line) throws IOException
{
/* Minimum line: "xxxx y z" ---> 8 chars */
long len;
if (line.length() < 8)
throw new IOException("Malformed C line sent by remote SCP binary, line too short.");
if ((line.charAt(4) != ' ') || (line.charAt(5) == ' '))
throw new IOException("Malformed C line sent by remote SCP binary.");
int length_name_sep = line.indexOf(' ', 5);
if (length_name_sep == -1)
throw new IOException("Malformed C line sent by remote SCP binary.");
String length_substring = line.substring(5, length_name_sep);
String name_substring = line.substring(length_name_sep + 1);
if ((length_substring.length() <= 0) || (name_substring.length() <= 0))
throw new IOException("Malformed C line sent by remote SCP binary.");
if ((6 + length_substring.length() + name_substring.length()) != line.length())
throw new IOException("Malformed C line sent by remote SCP binary.");
try
{
len = Long.parseLong(length_substring);
}
catch (NumberFormatException e)
{
throw new IOException("Malformed C line sent by remote SCP binary, cannot parse file length.");
}
if (len < 0)
throw new IOException("Malformed C line sent by remote SCP binary, illegal file length.");
LenNamePair lnp = new LenNamePair();
lnp.length = len;
lnp.filename = name_substring;
return lnp;
}
private void sendBytes(Session sess, byte[] data, String fileName, String mode) throws IOException
{
OutputStream os = sess.getStdin();
InputStream is = new BufferedInputStream(sess.getStdout(), 512);
readResponse(is);
String cline = "C" + mode + " " + data.length + " " + fileName + "\n";
os.write(cline.getBytes("ISO-8859-1"));
os.flush();
readResponse(is);
os.write(data, 0, data.length);
os.write(0);
os.flush();
readResponse(is);
os.write("E\n".getBytes("ISO-8859-1"));
os.flush();
}
private void sendFiles(Session sess, String[] files, String[] remoteFiles, String mode) throws IOException
{
byte[] buffer = new byte[8192];
OutputStream os = new BufferedOutputStream(sess.getStdin(), 40000);
InputStream is = new BufferedInputStream(sess.getStdout(), 512);
readResponse(is);
for (int i = 0; i < files.length; i++)
{
File f = new File(files[i]);
long remain = f.length();
String remoteName;
if ((remoteFiles != null) && (remoteFiles.length > i) && (remoteFiles[i] != null))
remoteName = remoteFiles[i];
else
remoteName = f.getName();
String cline = "C" + mode + " " + remain + " " + remoteName + "\n";
os.write(cline.getBytes("ISO-8859-1"));
os.flush();
readResponse(is);
FileInputStream fis = null;
try
{
fis = new FileInputStream(f);
while (remain > 0)
{
int trans;
if (remain > buffer.length)
trans = buffer.length;
else
trans = (int) remain;
if (fis.read(buffer, 0, trans) != trans)
throw new IOException("Cannot read enough from local file " + files[i]);
os.write(buffer, 0, trans);
remain -= trans;
}
}
finally
{
if (fis != null)
fis.close();
}
os.write(0);
os.flush();
readResponse(is);
}
os.write("E\n".getBytes("ISO-8859-1"));
os.flush();
}
private void receiveFiles(Session sess, OutputStream[] targets) throws IOException
{
byte[] buffer = new byte[8192];
OutputStream os = new BufferedOutputStream(sess.getStdin(), 512);
InputStream is = new BufferedInputStream(sess.getStdout(), 40000);
os.write(0x0);
os.flush();
for (int i = 0; i < targets.length; i++)
{
LenNamePair lnp = null;
while (true)
{
int c = is.read();
if (c < 0)
throw new IOException("Remote scp terminated unexpectedly.");
String line = receiveLine(is);
if (c == 'T')
{
/* Ignore modification times */
continue;
}
if ((c == 1) || (c == 2))
throw new IOException("Remote SCP error: " + line);
if (c == 'C')
{
lnp = parseCLine(line);
break;
}
throw new IOException("Remote SCP error: " + ((char) c) + line);
}
os.write(0x0);
os.flush();
long remain = lnp.length;
while (remain > 0)
{
int trans;
if (remain > buffer.length)
trans = buffer.length;
else
trans = (int) remain;
int this_time_received = is.read(buffer, 0, trans);
if (this_time_received < 0)
{
throw new IOException("Remote scp terminated connection unexpectedly");
}
targets[i].write(buffer, 0, this_time_received);
remain -= this_time_received;
}
readResponse(is);
os.write(0x0);
os.flush();
}
}
private void receiveFiles(Session sess, String[] files, String target) throws IOException
{
byte[] buffer = new byte[8192];
OutputStream os = new BufferedOutputStream(sess.getStdin(), 512);
InputStream is = new BufferedInputStream(sess.getStdout(), 40000);
os.write(0x0);
os.flush();
for (int i = 0; i < files.length; i++)
{
LenNamePair lnp = null;
while (true)
{
int c = is.read();
if (c < 0)
throw new IOException("Remote scp terminated unexpectedly.");
String line = receiveLine(is);
if (c == 'T')
{
/* Ignore modification times */
continue;
}
if ((c == 1) || (c == 2))
throw new IOException("Remote SCP error: " + line);
if (c == 'C')
{
lnp = parseCLine(line);
break;
}
throw new IOException("Remote SCP error: " + ((char) c) + line);
}
os.write(0x0);
os.flush();
File f = new File(target + File.separatorChar + lnp.filename);
FileOutputStream fop = null;
try
{
fop = new FileOutputStream(f);
long remain = lnp.length;
while (remain > 0)
{
int trans;
if (remain > buffer.length)
trans = buffer.length;
else
trans = (int) remain;
int this_time_received = is.read(buffer, 0, trans);
if (this_time_received < 0)
{
throw new IOException("Remote scp terminated connection unexpectedly");
}
fop.write(buffer, 0, this_time_received);
remain -= this_time_received;
}
}
finally
{
if (fop != null)
fop.close();
}
readResponse(is);
os.write(0x0);
os.flush();
}
}
/**
* Copy a local file to a remote directory, uses mode 0600 when creating the
* file on the remote side.
*
* @param localFile
* Path and name of local file.
* @param remoteTargetDirectory
* Remote target directory. Use an empty string to specify the
* default directory.
*
* @throws IOException
*/
public void put(String localFile, String remoteTargetDirectory) throws IOException
{
put(new String[] { localFile }, remoteTargetDirectory, "0600");
}
/**
* Copy a set of local files to a remote directory, uses mode 0600 when
* creating files on the remote side.
*
* @param localFiles
* Paths and names of local file names.
* @param remoteTargetDirectory
* Remote target directory. Use an empty string to specify the
* default directory.
*
* @throws IOException
*/
public void put(String[] localFiles, String remoteTargetDirectory) throws IOException
{
put(localFiles, remoteTargetDirectory, "0600");
}
/**
* Copy a local file to a remote directory, uses the specified mode when
* creating the file on the remote side.
*
* @param localFile
* Path and name of local file.
* @param remoteTargetDirectory
* Remote target directory. Use an empty string to specify the
* default directory.
* @param mode
* a four digit string (e.g., 0644, see "man chmod", "man open")
* @throws IOException
*/
public void put(String localFile, String remoteTargetDirectory, String mode) throws IOException
{
put(new String[] { localFile }, remoteTargetDirectory, mode);
}
/**
* Copy a local file to a remote directory, uses the specified mode and
* remote filename when creating the file on the remote side.
*
* @param localFile
* Path and name of local file.
* @param remoteFileName
* The name of the file which will be created in the remote
* target directory.
* @param remoteTargetDirectory
* Remote target directory. Use an empty string to specify the
* default directory.
* @param mode
* a four digit string (e.g., 0644, see "man chmod", "man open")
* @throws IOException
*/
public void put(String localFile, String remoteFileName, String remoteTargetDirectory, String mode)
throws IOException
{
put(new String[] { localFile }, new String[] { remoteFileName }, remoteTargetDirectory, mode);
}
/**
* Create a remote file and copy the contents of the passed byte array into
* it. Uses mode 0600 for creating the remote file.
*
* @param data
* the data to be copied into the remote file.
* @param remoteFileName
* The name of the file which will be created in the remote
* target directory.
* @param remoteTargetDirectory
* Remote target directory. Use an empty string to specify the
* default directory.
* @throws IOException
*/
public void put(byte[] data, String remoteFileName, String remoteTargetDirectory) throws IOException
{
put(data, remoteFileName, remoteTargetDirectory, "0600");
}
/**
* Create a remote file and copy the contents of the passed byte array into
* it. The method use the specified mode when creating the file on the
* remote side.
*
* @param data
* the data to be copied into the remote file.
* @param remoteFileName
* The name of the file which will be created in the remote
* target directory.
* @param remoteTargetDirectory
* Remote target directory. Use an empty string to specify the
* default directory.
* @param mode
* a four digit string (e.g., 0644, see "man chmod", "man open")
* @throws IOException
*/
public void put(byte[] data, String remoteFileName, String remoteTargetDirectory, String mode) throws IOException
{
Session sess = null;
if ((remoteFileName == null) || (remoteTargetDirectory == null) || (mode == null))
throw new IllegalArgumentException("Null argument.");
if (mode.length() != 4)
throw new IllegalArgumentException("Invalid mode.");
for (int i = 0; i < mode.length(); i++)
if (Character.isDigit(mode.charAt(i)) == false)
throw new IllegalArgumentException("Invalid mode.");
remoteTargetDirectory = remoteTargetDirectory.trim();
remoteTargetDirectory = (remoteTargetDirectory.length() > 0) ? remoteTargetDirectory : ".";
String cmd = "scp -t -d " + remoteTargetDirectory;
try
{
sess = conn.openSession();
sess.execCommand(cmd);
sendBytes(sess, data, remoteFileName, mode);
}
catch (IOException e)
{
throw (IOException) new IOException("Error during SCP transfer.").initCause(e);
}
finally
{
if (sess != null)
sess.close();
}
}
/**
* Copy a set of local files to a remote directory, uses the specified mode
* when creating the files on the remote side.
*
* @param localFiles
* Paths and names of the local files.
* @param remoteTargetDirectory
* Remote target directory. Use an empty string to specify the
* default directory.
* @param mode
* a four digit string (e.g., 0644, see "man chmod", "man open")
* @throws IOException
*/
public void put(String[] localFiles, String remoteTargetDirectory, String mode) throws IOException
{
put(localFiles, null, remoteTargetDirectory, mode);
}
public void put(String[] localFiles, String[] remoteFiles, String remoteTargetDirectory, String mode)
throws IOException
{
Session sess = null;
/*
* remoteFiles may be null, indicating that the local filenames shall be
* used
*/
if ((localFiles == null) || (remoteTargetDirectory == null) || (mode == null))
throw new IllegalArgumentException("Null argument.");
if (mode.length() != 4)
throw new IllegalArgumentException("Invalid mode.");
for (int i = 0; i < mode.length(); i++)
if (Character.isDigit(mode.charAt(i)) == false)
throw new IllegalArgumentException("Invalid mode.");
if (localFiles.length == 0)
return;
remoteTargetDirectory = remoteTargetDirectory.trim();
remoteTargetDirectory = (remoteTargetDirectory.length() > 0) ? remoteTargetDirectory : ".";
String cmd = "scp -t -d " + remoteTargetDirectory;
for (int i = 0; i < localFiles.length; i++)
{
if (localFiles[i] == null)
throw new IllegalArgumentException("Cannot accept null filename.");
}
try
{
sess = conn.openSession();
sess.execCommand(cmd);
sendFiles(sess, localFiles, remoteFiles, mode);
}
catch (IOException e)
{
throw (IOException) new IOException("Error during SCP transfer.").initCause(e);
}
finally
{
if (sess != null)
sess.close();
}
}
/**
* Download a file from the remote server to a local directory.
*
* @param remoteFile
* Path and name of the remote file.
* @param localTargetDirectory
* Local directory to put the downloaded file.
*
* @throws IOException
*/
public void get(String remoteFile, String localTargetDirectory) throws IOException
{
get(new String[] { remoteFile }, localTargetDirectory);
}
/**
* Download a file from the remote server and pipe its contents into an
* <code>OutputStream</code>. Please note that, to enable flexible usage
* of this method, the <code>OutputStream</code> will not be closed nor
* flushed.
*
* @param remoteFile
* Path and name of the remote file.
* @param target
* OutputStream where the contents of the file will be sent to.
* @throws IOException
*/
public void get(String remoteFile, OutputStream target) throws IOException
{
get(new String[] { remoteFile }, new OutputStream[] { target });
}
private void get(String remoteFiles[], OutputStream[] targets) throws IOException
{
Session sess = null;
if ((remoteFiles == null) || (targets == null))
throw new IllegalArgumentException("Null argument.");
if (remoteFiles.length != targets.length)
throw new IllegalArgumentException("Length of arguments does not match.");
if (remoteFiles.length == 0)
return;
String cmd = "scp -f";
for (int i = 0; i < remoteFiles.length; i++)
{
if (remoteFiles[i] == null)
throw new IllegalArgumentException("Cannot accept null filename.");
String tmp = remoteFiles[i].trim();
if (tmp.length() == 0)
throw new IllegalArgumentException("Cannot accept empty filename.");
cmd += (" " + tmp);
}
try
{
sess = conn.openSession();
sess.execCommand(cmd);
receiveFiles(sess, targets);
}
catch (IOException e)
{
throw (IOException) new IOException("Error during SCP transfer.").initCause(e);
}
finally
{
if (sess != null)
sess.close();
}
}
/**
* Download a set of files from the remote server to a local directory.
*
* @param remoteFiles
* Paths and names of the remote files.
* @param localTargetDirectory
* Local directory to put the downloaded files.
*
* @throws IOException
*/
public void get(String remoteFiles[], String localTargetDirectory) throws IOException
{
Session sess = null;
if ((remoteFiles == null) || (localTargetDirectory == null))
throw new IllegalArgumentException("Null argument.");
if (remoteFiles.length == 0)
return;
String cmd = "scp -f";
for (int i = 0; i < remoteFiles.length; i++)
{
if (remoteFiles[i] == null)
throw new IllegalArgumentException("Cannot accept null filename.");
String tmp = remoteFiles[i].trim();
if (tmp.length() == 0)
throw new IllegalArgumentException("Cannot accept empty filename.");
cmd += (" " + tmp);
}
try
{
sess = conn.openSession();
sess.execCommand(cmd);
receiveFiles(sess, remoteFiles, localTargetDirectory);
}
catch (IOException e)
{
throw (IOException) new IOException("Error during SCP transfer.").initCause(e);
}
finally
{
if (sess != null)
sess.close();
}
}
}
|
Java
|
package com.trilead.ssh2;
import java.io.IOException;
/**
* May be thrown upon connect() if a HTTP proxy is being used.
*
* @see Connection#connect()
* @see Connection#setProxyData(ProxyData)
*
* @author Christian Plattner, plattner@trilead.com
* @version $Id: HTTPProxyException.java,v 1.1 2007/10/15 12:49:56 cplattne Exp $
*/
public class HTTPProxyException extends IOException
{
private static final long serialVersionUID = 2241537397104426186L;
public final String httpResponse;
public final int httpErrorCode;
public HTTPProxyException(String httpResponse, int httpErrorCode)
{
super("HTTP Proxy Error (" + httpErrorCode + " " + httpResponse + ")");
this.httpResponse = httpResponse;
this.httpErrorCode = httpErrorCode;
}
}
|
Java
|
package com.trilead.ssh2.sftp;
/**
*
* SFTP Error Codes
*
* @author Christian Plattner, plattner@trilead.com
* @version $Id: ErrorCodes.java,v 1.1 2007/10/15 12:49:55 cplattne Exp $
*
*/
public class ErrorCodes
{
public static final int SSH_FX_OK = 0;
public static final int SSH_FX_EOF = 1;
public static final int SSH_FX_NO_SUCH_FILE = 2;
public static final int SSH_FX_PERMISSION_DENIED = 3;
public static final int SSH_FX_FAILURE = 4;
public static final int SSH_FX_BAD_MESSAGE = 5;
public static final int SSH_FX_NO_CONNECTION = 6;
public static final int SSH_FX_CONNECTION_LOST = 7;
public static final int SSH_FX_OP_UNSUPPORTED = 8;
public static final int SSH_FX_INVALID_HANDLE = 9;
public static final int SSH_FX_NO_SUCH_PATH = 10;
public static final int SSH_FX_FILE_ALREADY_EXISTS = 11;
public static final int SSH_FX_WRITE_PROTECT = 12;
public static final int SSH_FX_NO_MEDIA = 13;
public static final int SSH_FX_NO_SPACE_ON_FILESYSTEM = 14;
public static final int SSH_FX_QUOTA_EXCEEDED = 15;
public static final int SSH_FX_UNKNOWN_PRINCIPAL = 16;
public static final int SSH_FX_LOCK_CONFLICT = 17;
public static final int SSH_FX_DIR_NOT_EMPTY = 18;
public static final int SSH_FX_NOT_A_DIRECTORY = 19;
public static final int SSH_FX_INVALID_FILENAME = 20;
public static final int SSH_FX_LINK_LOOP = 21;
public static final int SSH_FX_CANNOT_DELETE = 22;
public static final int SSH_FX_INVALID_PARAMETER = 23;
public static final int SSH_FX_FILE_IS_A_DIRECTORY = 24;
public static final int SSH_FX_BYTE_RANGE_LOCK_CONFLICT = 25;
public static final int SSH_FX_BYTE_RANGE_LOCK_REFUSED = 26;
public static final int SSH_FX_DELETE_PENDING = 27;
public static final int SSH_FX_FILE_CORRUPT = 28;
public static final int SSH_FX_OWNER_INVALID = 29;
public static final int SSH_FX_GROUP_INVALID = 30;
public static final int SSH_FX_NO_MATCHING_BYTE_RANGE_LOCK = 31;
private static final String[][] messages = {
{ "SSH_FX_OK", "Indicates successful completion of the operation." },
{ "SSH_FX_EOF",
"An attempt to read past the end-of-file was made; or, there are no more directory entries to return." },
{ "SSH_FX_NO_SUCH_FILE", "A reference was made to a file which does not exist." },
{ "SSH_FX_PERMISSION_DENIED", "The user does not have sufficient permissions to perform the operation." },
{ "SSH_FX_FAILURE", "An error occurred, but no specific error code exists to describe the failure." },
{ "SSH_FX_BAD_MESSAGE", "A badly formatted packet or other SFTP protocol incompatibility was detected." },
{ "SSH_FX_NO_CONNECTION", "There is no connection to the server." },
{ "SSH_FX_CONNECTION_LOST", "The connection to the server was lost." },
{ "SSH_FX_OP_UNSUPPORTED",
"An attempted operation could not be completed by the server because the server does not support the operation." },
{ "SSH_FX_INVALID_HANDLE", "The handle value was invalid." },
{ "SSH_FX_NO_SUCH_PATH", "The file path does not exist or is invalid." },
{ "SSH_FX_FILE_ALREADY_EXISTS", "The file already exists." },
{ "SSH_FX_WRITE_PROTECT", "The file is on read-only media, or the media is write protected." },
{ "SSH_FX_NO_MEDIA",
"The requested operation cannot be completed because there is no media available in the drive." },
{ "SSH_FX_NO_SPACE_ON_FILESYSTEM",
"The requested operation cannot be completed because there is insufficient free space on the filesystem." },
{ "SSH_FX_QUOTA_EXCEEDED",
"The operation cannot be completed because it would exceed the user's storage quota." },
{
"SSH_FX_UNKNOWN_PRINCIPAL",
"A principal referenced by the request (either the 'owner', 'group', or 'who' field of an ACL), was unknown. The error specific data contains the problematic names." },
{ "SSH_FX_LOCK_CONFLICT", "The file could not be opened because it is locked by another process." },
{ "SSH_FX_DIR_NOT_EMPTY", "The directory is not empty." },
{ "SSH_FX_NOT_A_DIRECTORY", "The specified file is not a directory." },
{ "SSH_FX_INVALID_FILENAME", "The filename is not valid." },
{ "SSH_FX_LINK_LOOP",
"Too many symbolic links encountered or, an SSH_FXF_NOFOLLOW open encountered a symbolic link as the final component." },
{ "SSH_FX_CANNOT_DELETE",
"The file cannot be deleted. One possible reason is that the advisory READONLY attribute-bit is set." },
{ "SSH_FX_INVALID_PARAMETER",
"One of the parameters was out of range, or the parameters specified cannot be used together." },
{ "SSH_FX_FILE_IS_A_DIRECTORY",
"The specified file was a directory in a context where a directory cannot be used." },
{ "SSH_FX_BYTE_RANGE_LOCK_CONFLICT",
" A read or write operation failed because another process's mandatory byte-range lock overlaps with the request." },
{ "SSH_FX_BYTE_RANGE_LOCK_REFUSED", "A request for a byte range lock was refused." },
{ "SSH_FX_DELETE_PENDING", "An operation was attempted on a file for which a delete operation is pending." },
{ "SSH_FX_FILE_CORRUPT", "The file is corrupt; an filesystem integrity check should be run." },
{ "SSH_FX_OWNER_INVALID", "The principal specified can not be assigned as an owner of a file." },
{ "SSH_FX_GROUP_INVALID", "The principal specified can not be assigned as the primary group of a file." },
{ "SSH_FX_NO_MATCHING_BYTE_RANGE_LOCK",
"The requested operation could not be completed because the specifed byte range lock has not been granted." },
};
public static final String[] getDescription(int errorCode)
{
if ((errorCode < 0) || (errorCode >= messages.length))
return null;
return messages[errorCode];
}
}
|
Java
|
package com.trilead.ssh2.sftp;
/**
*
* Values for the 'text-hint' field in the SFTP ATTRS data type.
*
* @author Christian Plattner, plattner@trilead.com
* @version $Id: AttrTextHints.java,v 1.1 2007/10/15 12:49:55 cplattne Exp $
*
*/
public class AttrTextHints
{
/**
* The server knows the file is a text file, and should be opened
* using the SSH_FXF_ACCESS_TEXT_MODE flag.
*/
public static final int SSH_FILEXFER_ATTR_KNOWN_TEXT = 0x00;
/**
* The server has applied a heuristic or other mechanism and
* believes that the file should be opened with the
* SSH_FXF_ACCESS_TEXT_MODE flag.
*/
public static final int SSH_FILEXFER_ATTR_GUESSED_TEXT = 0x01;
/**
* The server knows the file has binary content.
*/
public static final int SSH_FILEXFER_ATTR_KNOWN_BINARY = 0x02;
/**
* The server has applied a heuristic or other mechanism and
* believes has binary content, and should not be opened with the
* SSH_FXF_ACCESS_TEXT_MODE flag.
*/
public static final int SSH_FILEXFER_ATTR_GUESSED_BINARY = 0x03;
}
|
Java
|
package com.trilead.ssh2.sftp;
/**
*
* SFTP Attribute Bits for the "attrib-bits" and "attrib-bits-valid" fields
* of the SFTP ATTR data type.
* <p>
* Yes, these are the "attrib-bits", even though they have "_FLAGS_" in
* their name. Don't ask - I did not invent it.
* <p>
* "<i>These fields, taken together, reflect various attributes of the file
* or directory, on the server. Bits not set in 'attrib-bits-valid' MUST be
* ignored in the 'attrib-bits' field. This allows both the server and the
* client to communicate only the bits it knows about without inadvertently
* twiddling bits they don't understand.</i>"
*
* @author Christian Plattner, plattner@trilead.com
* @version $Id: AttribBits.java,v 1.1 2007/10/15 12:49:55 cplattne Exp $
*
*/
public class AttribBits
{
/**
* Advisory, read-only bit. This bit is not part of the access
* control information on the file, but is rather an advisory field
* indicating that the file should not be written.
*/
public static final int SSH_FILEXFER_ATTR_FLAGS_READONLY = 0x00000001;
/**
* The file is part of the operating system.
*/
public static final int SSH_FILEXFER_ATTR_FLAGS_SYSTEM = 0x00000002;
/**
* File SHOULD NOT be shown to user unless specifically requested.
* For example, most UNIX systems SHOULD set this bit if the filename
* begins with a 'period'. This bit may be read-only (see section 5.4 of
* the SFTP standard draft). Most UNIX systems will not allow this to be
* changed.
*/
public static final int SSH_FILEXFER_ATTR_FLAGS_HIDDEN = 0x00000004;
/**
* This attribute applies only to directories. This attribute is
* always read-only, and cannot be modified. This attribute means
* that files and directory names in this directory should be compared
* without regard to case.
* <p>
* It is recommended that where possible, the server's filesystem be
* allowed to do comparisons. For example, if a client wished to prompt
* a user before overwriting a file, it should not compare the new name
* with the previously retrieved list of names in the directory. Rather,
* it should first try to create the new file by specifying
* SSH_FXF_CREATE_NEW flag. Then, if this fails and returns
* SSH_FX_FILE_ALREADY_EXISTS, it should prompt the user and then retry
* the create specifying SSH_FXF_CREATE_TRUNCATE.
* <p>
* Unless otherwise specified, filenames are assumed to be case sensitive.
*/
public static final int SSH_FILEXFER_ATTR_FLAGS_CASE_INSENSITIVE = 0x00000008;
/**
* The file should be included in backup / archive operations.
*/
public static final int SSH_FILEXFER_ATTR_FLAGS_ARCHIVE = 0x00000010;
/**
* The file is stored on disk using file-system level transparent
* encryption. This flag does not affect the file data on the wire
* (for either READ or WRITE requests.)
*/
public static final int SSH_FILEXFER_ATTR_FLAGS_ENCRYPTED = 0x00000020;
/**
* The file is stored on disk using file-system level transparent
* compression. This flag does not affect the file data on the wire.
*/
public static final int SSH_FILEXFER_ATTR_FLAGS_COMPRESSED = 0x00000040;
/**
* The file is a sparse file; this means that file blocks that have
* not been explicitly written are not stored on disk. For example, if
* a client writes a buffer at 10 M from the beginning of the file,
* the blocks between the previous EOF marker and the 10 M offset would
* not consume physical disk space.
* <p>
* Some servers may store all files as sparse files, in which case
* this bit will be unconditionally set. Other servers may not have
* a mechanism for determining if the file is sparse, and so the file
* MAY be stored sparse even if this flag is not set.
*/
public static final int SSH_FILEXFER_ATTR_FLAGS_SPARSE = 0x00000080;
/**
* Opening the file without either the SSH_FXF_ACCESS_APPEND_DATA or
* the SSH_FXF_ACCESS_APPEND_DATA_ATOMIC flag (see section 8.1.1.3
* of the SFTP standard draft) MUST result in an
* SSH_FX_INVALID_PARAMETER error.
*/
public static final int SSH_FILEXFER_ATTR_FLAGS_APPEND_ONLY = 0x00000100;
/**
* The file cannot be deleted or renamed, no hard link can be created
* to this file, and no data can be written to the file.
* <p>
* This bit implies a stronger level of protection than
* SSH_FILEXFER_ATTR_FLAGS_READONLY, the file permission mask or ACLs.
* Typically even the superuser cannot write to immutable files, and
* only the superuser can set or remove the bit.
*/
public static final int SSH_FILEXFER_ATTR_FLAGS_IMMUTABLE = 0x00000200;
/**
* When the file is modified, the changes are written synchronously
* to the disk.
*/
public static final int SSH_FILEXFER_ATTR_FLAGS_SYNC = 0x00000400;
/**
* The server MAY include this bit in a directory listing or realpath
* response. It indicates there was a failure in the translation to UTF-8.
* If this flag is included, the server SHOULD also include the
* UNTRANSLATED_NAME attribute.
*/
public static final int SSH_FILEXFER_ATTR_FLAGS_TRANSLATION_ERR = 0x00000800;
}
|
Java
|
package com.trilead.ssh2.sftp;
/**
*
* Types for the 'type' field in the SFTP ATTRS data type.
* <p>
* "<i>On a POSIX system, these values would be derived from the mode field
* of the stat structure. SPECIAL should be used for files that are of
* a known type which cannot be expressed in the protocol. UNKNOWN
* should be used if the type is not known.</i>"
*
* @author Christian Plattner, plattner@trilead.com
* @version $Id: AttribTypes.java,v 1.1 2007/10/15 12:49:55 cplattne Exp $
*
*/
public class AttribTypes
{
public static final int SSH_FILEXFER_TYPE_REGULAR = 1;
public static final int SSH_FILEXFER_TYPE_DIRECTORY = 2;
public static final int SSH_FILEXFER_TYPE_SYMLINK = 3;
public static final int SSH_FILEXFER_TYPE_SPECIAL = 4;
public static final int SSH_FILEXFER_TYPE_UNKNOWN = 5;
public static final int SSH_FILEXFER_TYPE_SOCKET = 6;
public static final int SSH_FILEXFER_TYPE_CHAR_DEVICE = 7;
public static final int SSH_FILEXFER_TYPE_BLOCK_DEVICE = 8;
public static final int SSH_FILEXFER_TYPE_FIFO = 9;
}
|
Java
|
package com.trilead.ssh2.sftp;
/**
*
* Attribute Flags. The 'valid-attribute-flags' field in
* the SFTP ATTRS data type specifies which of the fields are actually present.
*
* @author Christian Plattner, plattner@trilead.com
* @version $Id: AttribFlags.java,v 1.1 2007/10/15 12:49:55 cplattne Exp $
*
*/
public class AttribFlags
{
/**
* Indicates that the 'allocation-size' field is present.
*/
public static final int SSH_FILEXFER_ATTR_SIZE = 0x00000001;
/** Protocol version 6:
* 0x00000002 was used in a previous version of this protocol.
* It is now a reserved value and MUST NOT appear in the mask.
* Some future version of this protocol may reuse this value.
*/
public static final int SSH_FILEXFER_ATTR_V3_UIDGID = 0x00000002;
/**
* Indicates that the 'permissions' field is present.
*/
public static final int SSH_FILEXFER_ATTR_PERMISSIONS = 0x00000004;
/**
* Indicates that the 'atime' and 'mtime' field are present
* (protocol v3).
*/
public static final int SSH_FILEXFER_ATTR_V3_ACMODTIME = 0x00000008;
/**
* Indicates that the 'atime' field is present.
*/
public static final int SSH_FILEXFER_ATTR_ACCESSTIME = 0x00000008;
/**
* Indicates that the 'createtime' field is present.
*/
public static final int SSH_FILEXFER_ATTR_CREATETIME = 0x00000010;
/**
* Indicates that the 'mtime' field is present.
*/
public static final int SSH_FILEXFER_ATTR_MODIFYTIME = 0x00000020;
/**
* Indicates that the 'acl' field is present.
*/
public static final int SSH_FILEXFER_ATTR_ACL = 0x00000040;
/**
* Indicates that the 'owner' and 'group' fields are present.
*/
public static final int SSH_FILEXFER_ATTR_OWNERGROUP = 0x00000080;
/**
* Indicates that additionally to the 'atime', 'createtime',
* 'mtime' and 'ctime' fields (if present), there is also
* 'atime-nseconds', 'createtime-nseconds', 'mtime-nseconds'
* and 'ctime-nseconds'.
*/
public static final int SSH_FILEXFER_ATTR_SUBSECOND_TIMES = 0x00000100;
/**
* Indicates that the 'attrib-bits' and 'attrib-bits-valid'
* fields are present.
*/
public static final int SSH_FILEXFER_ATTR_BITS = 0x00000200;
/**
* Indicates that the 'allocation-size' field is present.
*/
public static final int SSH_FILEXFER_ATTR_ALLOCATION_SIZE = 0x00000400;
/**
* Indicates that the 'text-hint' field is present.
*/
public static final int SSH_FILEXFER_ATTR_TEXT_HINT = 0x00000800;
/**
* Indicates that the 'mime-type' field is present.
*/
public static final int SSH_FILEXFER_ATTR_MIME_TYPE = 0x00001000;
/**
* Indicates that the 'link-count' field is present.
*/
public static final int SSH_FILEXFER_ATTR_LINK_COUNT = 0x00002000;
/**
* Indicates that the 'untranslated-name' field is present.
*/
public static final int SSH_FILEXFER_ATTR_UNTRANSLATED_NAME = 0x00004000;
/**
* Indicates that the 'ctime' field is present.
*/
public static final int SSH_FILEXFER_ATTR_CTIME = 0x00008000;
/**
* Indicates that the 'extended-count' field (and probablby some
* 'extensions') is present.
*/
public static final int SSH_FILEXFER_ATTR_EXTENDED = 0x80000000;
}
|
Java
|
package com.trilead.ssh2.sftp;
/**
*
* SFTP Open Flags.
*
* The following table is provided to assist in mapping POSIX semantics
* to equivalent SFTP file open parameters:
* <p>
* TODO: This comment should be moved to the open method.
* <p>
* <ul>
* <li>O_RDONLY
* <ul><li>desired-access = READ_DATA | READ_ATTRIBUTES</li></ul>
* </li>
* </ul>
* <ul>
* <li>O_WRONLY
* <ul><li>desired-access = WRITE_DATA | WRITE_ATTRIBUTES</li></ul>
* </li>
* </ul>
* <ul>
* <li>O_RDWR
* <ul><li>desired-access = READ_DATA | READ_ATTRIBUTES | WRITE_DATA | WRITE_ATTRIBUTES</li></ul>
* </li>
* </ul>
* <ul>
* <li>O_APPEND
* <ul>
* <li>desired-access = WRITE_DATA | WRITE_ATTRIBUTES | APPEND_DATA</li>
* <li>flags = SSH_FXF_ACCESS_APPEND_DATA and or SSH_FXF_ACCESS_APPEND_DATA_ATOMIC</li>
* </ul>
* </li>
* </ul>
* <ul>
* <li>O_CREAT
* <ul>
* <li>flags = SSH_FXF_OPEN_OR_CREATE</li>
* </ul>
* </li>
* </ul>
* <ul>
* <li>O_TRUNC
* <ul>
* <li>flags = SSH_FXF_TRUNCATE_EXISTING</li>
* </ul>
* </li>
* </ul>
* <ul>
* <li>O_TRUNC|O_CREATE
* <ul>
* <li>flags = SSH_FXF_CREATE_TRUNCATE</li>
* </ul>
* </li>
* </ul>
*
* @author Christian Plattner, plattner@trilead.com
* @version $Id: OpenFlags.java,v 1.1 2007/10/15 12:49:55 cplattne Exp $
*/
public class OpenFlags
{
/**
* Disposition is a 3 bit field that controls how the file is opened.
* The server MUST support these bits (possible enumaration values:
* SSH_FXF_CREATE_NEW, SSH_FXF_CREATE_TRUNCATE, SSH_FXF_OPEN_EXISTING,
* SSH_FXF_OPEN_OR_CREATE or SSH_FXF_TRUNCATE_EXISTING).
*/
public static final int SSH_FXF_ACCESS_DISPOSITION = 0x00000007;
/**
* A new file is created; if the file already exists, the server
* MUST return status SSH_FX_FILE_ALREADY_EXISTS.
*/
public static final int SSH_FXF_CREATE_NEW = 0x00000000;
/**
* A new file is created; if the file already exists, it is opened
* and truncated.
*/
public static final int SSH_FXF_CREATE_TRUNCATE = 0x00000001;
/**
* An existing file is opened. If the file does not exist, the
* server MUST return SSH_FX_NO_SUCH_FILE. If a directory in the
* path does not exist, the server SHOULD return
* SSH_FX_NO_SUCH_PATH. It is also acceptable if the server
* returns SSH_FX_NO_SUCH_FILE in this case.
*/
public static final int SSH_FXF_OPEN_EXISTING = 0x00000002;
/**
* If the file exists, it is opened. If the file does not exist,
* it is created.
*/
public static final int SSH_FXF_OPEN_OR_CREATE = 0x00000003;
/**
* An existing file is opened and truncated. If the file does not
* exist, the server MUST return the same error codes as defined
* for SSH_FXF_OPEN_EXISTING.
*/
public static final int SSH_FXF_TRUNCATE_EXISTING = 0x00000004;
/**
* Data is always written at the end of the file. The offset field
* of the SSH_FXP_WRITE requests are ignored.
* <p>
* Data is not required to be appended atomically. This means that
* if multiple writers attempt to append data simultaneously, data
* from the first may be lost. However, data MAY be appended
* atomically.
*/
public static final int SSH_FXF_ACCESS_APPEND_DATA = 0x00000008;
/**
* Data is always written at the end of the file. The offset field
* of the SSH_FXP_WRITE requests are ignored.
* <p>
* Data MUST be written atomically so that there is no chance that
* multiple appenders can collide and result in data being lost.
* <p>
* If both append flags are specified, the server SHOULD use atomic
* append if it is available, but SHOULD use non-atomic appends
* otherwise. The server SHOULD NOT fail the request in this case.
*/
public static final int SSH_FXF_ACCESS_APPEND_DATA_ATOMIC = 0x00000010;
/**
* Indicates that the server should treat the file as text and
* convert it to the canonical newline convention in use.
* (See Determining Server Newline Convention in section 5.3 in the
* SFTP standard draft).
* <p>
* When a file is opened with this flag, the offset field in the read
* and write functions is ignored.
* <p>
* Servers MUST process multiple, parallel reads and writes correctly
* in this mode. Naturally, it is permissible for them to do this by
* serializing the requests.
* <p>
* Clients SHOULD use the SSH_FXF_ACCESS_APPEND_DATA flag to append
* data to a text file rather then using write with a calculated offset.
*/
public static final int SSH_FXF_ACCESS_TEXT_MODE = 0x00000020;
/**
* The server MUST guarantee that no other handle has been opened
* with ACE4_READ_DATA access, and that no other handle will be
* opened with ACE4_READ_DATA access until the client closes the
* handle. (This MUST apply both to other clients and to other
* processes on the server.)
* <p>
* If there is a conflicting lock the server MUST return
* SSH_FX_LOCK_CONFLICT. If the server cannot make the locking
* guarantee, it MUST return SSH_FX_OP_UNSUPPORTED.
* <p>
* Other handles MAY be opened for ACE4_WRITE_DATA or any other
* combination of accesses, as long as ACE4_READ_DATA is not included
* in the mask.
*/
public static final int SSH_FXF_ACCESS_BLOCK_READ = 0x00000040;
/**
* The server MUST guarantee that no other handle has been opened
* with ACE4_WRITE_DATA or ACE4_APPEND_DATA access, and that no other
* handle will be opened with ACE4_WRITE_DATA or ACE4_APPEND_DATA
* access until the client closes the handle. (This MUST apply both
* to other clients and to other processes on the server.)
* <p>
* If there is a conflicting lock the server MUST return
* SSH_FX_LOCK_CONFLICT. If the server cannot make the locking
* guarantee, it MUST return SSH_FX_OP_UNSUPPORTED.
* <p>
* Other handles MAY be opened for ACE4_READ_DATA or any other
* combination of accesses, as long as neither ACE4_WRITE_DATA nor
* ACE4_APPEND_DATA are included in the mask.
*/
public static final int SSH_FXF_ACCESS_BLOCK_WRITE = 0x00000080;
/**
* The server MUST guarantee that no other handle has been opened
* with ACE4_DELETE access, opened with the
* SSH_FXF_ACCESS_DELETE_ON_CLOSE flag set, and that no other handle
* will be opened with ACE4_DELETE access or with the
* SSH_FXF_ACCESS_DELETE_ON_CLOSE flag set, and that the file itself
* is not deleted in any other way until the client closes the handle.
* <p>
* If there is a conflicting lock the server MUST return
* SSH_FX_LOCK_CONFLICT. If the server cannot make the locking
* guarantee, it MUST return SSH_FX_OP_UNSUPPORTED.
*/
public static final int SSH_FXF_ACCESS_BLOCK_DELETE = 0x00000100;
/**
* If this bit is set, the above BLOCK modes are advisory. In advisory
* mode, only other accesses that specify a BLOCK mode need be
* considered when determining whether the BLOCK can be granted,
* and the server need not prevent I/O operations that violate the
* block mode.
* <p>
* The server MAY perform mandatory locking even if the BLOCK_ADVISORY
* bit is set.
*/
public static final int SSH_FXF_ACCESS_BLOCK_ADVISORY = 0x00000200;
/**
* If the final component of the path is a symlink, then the open
* MUST fail, and the error SSH_FX_LINK_LOOP MUST be returned.
*/
public static final int SSH_FXF_ACCESS_NOFOLLOW = 0x00000400;
/**
* The file should be deleted when the last handle to it is closed.
* (The last handle may not be an sftp-handle.) This MAY be emulated
* by a server if the OS doesn't support it by deleting the file when
* this handle is closed.
* <p>
* It is implementation specific whether the directory entry is
* removed immediately or when the handle is closed.
*/
public static final int SSH_FXF_ACCESS_DELETE_ON_CLOSE = 0x00000800;
}
|
Java
|
package com.trilead.ssh2.sftp;
/**
*
* SFTP Paket Types
*
* @author Christian Plattner, plattner@trilead.com
* @version $Id: Packet.java,v 1.1 2007/10/15 12:49:55 cplattne Exp $
*
*/
public class Packet
{
public static final int SSH_FXP_INIT = 1;
public static final int SSH_FXP_VERSION = 2;
public static final int SSH_FXP_OPEN = 3;
public static final int SSH_FXP_CLOSE = 4;
public static final int SSH_FXP_READ = 5;
public static final int SSH_FXP_WRITE = 6;
public static final int SSH_FXP_LSTAT = 7;
public static final int SSH_FXP_FSTAT = 8;
public static final int SSH_FXP_SETSTAT = 9;
public static final int SSH_FXP_FSETSTAT = 10;
public static final int SSH_FXP_OPENDIR = 11;
public static final int SSH_FXP_READDIR = 12;
public static final int SSH_FXP_REMOVE = 13;
public static final int SSH_FXP_MKDIR = 14;
public static final int SSH_FXP_RMDIR = 15;
public static final int SSH_FXP_REALPATH = 16;
public static final int SSH_FXP_STAT = 17;
public static final int SSH_FXP_RENAME = 18;
public static final int SSH_FXP_READLINK = 19;
public static final int SSH_FXP_SYMLINK = 20;
public static final int SSH_FXP_STATUS = 101;
public static final int SSH_FXP_HANDLE = 102;
public static final int SSH_FXP_DATA = 103;
public static final int SSH_FXP_NAME = 104;
public static final int SSH_FXP_ATTRS = 105;
public static final int SSH_FXP_EXTENDED = 200;
public static final int SSH_FXP_EXTENDED_REPLY = 201;
}
|
Java
|
package com.trilead.ssh2.sftp;
/**
*
* Permissions for the 'permissions' field in the SFTP ATTRS data type.
* <p>
* "<i>The 'permissions' field contains a bit mask specifying file permissions.
* These permissions correspond to the st_mode field of the stat structure
* defined by POSIX [IEEE.1003-1.1996].</i>"
*
* @author Christian Plattner, plattner@trilead.com
* @version $Id: AttribPermissions.java,v 1.1 2007/10/15 12:49:55 cplattne Exp $
*
*/
public class AttribPermissions
{
/* Octal values! */
public static final int S_IRUSR = 0400;
public static final int S_IWUSR = 0200;
public static final int S_IXUSR = 0100;
public static final int S_IRGRP = 0040;
public static final int S_IWGRP = 0020;
public static final int S_IXGRP = 0010;
public static final int S_IROTH = 0004;
public static final int S_IWOTH = 0002;
public static final int S_IXOTH = 0001;
public static final int S_ISUID = 04000;
public static final int S_ISGID = 02000;
public static final int S_ISVTX = 01000;
}
|
Java
|
/*
* 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 com.trilead.ssh2.compression;
import com.jcraft.jzlib.JZlib;
import com.jcraft.jzlib.ZStream;
/**
* @author Kenny Root
*
*/
public class Zlib implements ICompressor {
static private final int DEFAULT_BUF_SIZE = 4096;
static private final int LEVEL = 5;
private ZStream deflate;
private byte[] deflate_tmpbuf;
private ZStream inflate;
private byte[] inflate_tmpbuf;
private byte[] inflated_buf;
public Zlib() {
deflate = new ZStream();
inflate = new ZStream();
deflate.deflateInit(LEVEL);
inflate.inflateInit();
deflate_tmpbuf = new byte[DEFAULT_BUF_SIZE];
inflate_tmpbuf = new byte[DEFAULT_BUF_SIZE];
inflated_buf = new byte[DEFAULT_BUF_SIZE];
}
public boolean canCompressPreauth() {
return true;
}
public int getBufferSize() {
return DEFAULT_BUF_SIZE;
}
public int compress(byte[] buf, int start, int len, byte[] output) {
deflate.next_in = buf;
deflate.next_in_index = start;
deflate.avail_in = len - start;
if ((buf.length + 1024) > deflate_tmpbuf.length) {
deflate_tmpbuf = new byte[buf.length + 1024];
}
deflate.next_out = deflate_tmpbuf;
deflate.next_out_index = 0;
deflate.avail_out = output.length;
if (deflate.deflate(JZlib.Z_PARTIAL_FLUSH) != JZlib.Z_OK) {
System.err.println("compress: compression failure");
}
if (deflate.avail_in > 0) {
System.err.println("compress: deflated data too large");
}
int outputlen = output.length - deflate.avail_out;
System.arraycopy(deflate_tmpbuf, 0, output, 0, outputlen);
return outputlen;
}
public byte[] uncompress(byte[] buffer, int start, int[] length) {
int inflated_end = 0;
inflate.next_in = buffer;
inflate.next_in_index = start;
inflate.avail_in = length[0];
while (true) {
inflate.next_out = inflate_tmpbuf;
inflate.next_out_index = 0;
inflate.avail_out = DEFAULT_BUF_SIZE;
int status = inflate.inflate(JZlib.Z_PARTIAL_FLUSH);
switch (status) {
case JZlib.Z_OK:
if (inflated_buf.length < inflated_end + DEFAULT_BUF_SIZE
- inflate.avail_out) {
byte[] foo = new byte[inflated_end + DEFAULT_BUF_SIZE
- inflate.avail_out];
System.arraycopy(inflated_buf, 0, foo, 0, inflated_end);
inflated_buf = foo;
}
System.arraycopy(inflate_tmpbuf, 0, inflated_buf, inflated_end,
DEFAULT_BUF_SIZE - inflate.avail_out);
inflated_end += (DEFAULT_BUF_SIZE - inflate.avail_out);
length[0] = inflated_end;
break;
case JZlib.Z_BUF_ERROR:
if (inflated_end > buffer.length - start) {
byte[] foo = new byte[inflated_end + start];
System.arraycopy(buffer, 0, foo, 0, start);
System.arraycopy(inflated_buf, 0, foo, start, inflated_end);
buffer = foo;
} else {
System.arraycopy(inflated_buf, 0, buffer, start,
inflated_end);
}
length[0] = inflated_end;
return buffer;
default:
System.err.println("uncompress: inflate returnd " + status);
return null;
}
}
}
}
|
Java
|
/*
* 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 com.trilead.ssh2.compression;
/**
* Defines how zlib@openssh.org compression works.
* See
* http://www.openssh.org/txt/draft-miller-secsh-compression-delayed-00.txt
* compression is disabled until userauth has occurred.
*
* @author Matt Johnston
*
*/
public class ZlibOpenSSH extends Zlib {
public boolean canCompressPreauth() {
return false;
}
}
|
Java
|
/*
* 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 com.trilead.ssh2.compression;
import java.util.Vector;
/**
* @author Kenny Root
*
*/
public class CompressionFactory {
static class CompressorEntry
{
String type;
String compressorClass;
public CompressorEntry(String type, String compressorClass)
{
this.type = type;
this.compressorClass = compressorClass;
}
}
static Vector<CompressorEntry> compressors = new Vector<CompressorEntry>();
static
{
/* Higher Priority First */
compressors.addElement(new CompressorEntry("zlib", "com.trilead.ssh2.compression.Zlib"));
compressors.addElement(new CompressorEntry("zlib@openssh.com", "com.trilead.ssh2.compression.ZlibOpenSSH"));
compressors.addElement(new CompressorEntry("none", ""));
}
public static String[] getDefaultCompressorList()
{
String list[] = new String[compressors.size()];
for (int i = 0; i < compressors.size(); i++)
{
CompressorEntry ce = compressors.elementAt(i);
list[i] = new String(ce.type);
}
return list;
}
public static void checkCompressorList(String[] compressorCandidates)
{
for (int i = 0; i < compressorCandidates.length; i++)
getEntry(compressorCandidates[i]);
}
public static ICompressor createCompressor(String type)
{
try
{
CompressorEntry ce = getEntry(type);
if ("".equals(ce.compressorClass))
return null;
Class<?> cc = Class.forName(ce.compressorClass);
ICompressor cmp = (ICompressor) cc.newInstance();
return cmp;
}
catch (Exception e)
{
throw new IllegalArgumentException("Cannot instantiate " + type);
}
}
private static CompressorEntry getEntry(String type)
{
for (int i = 0; i < compressors.size(); i++)
{
CompressorEntry ce = compressors.elementAt(i);
if (ce.type.equals(type))
return ce;
}
throw new IllegalArgumentException("Unkown algorithm " + type);
}
}
|
Java
|
/*
* 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 com.trilead.ssh2.compression;
/**
* @author Kenny Root
*
*/
public interface ICompressor {
int getBufferSize();
int compress(byte[] buf, int start, int len, byte[] output);
byte[] uncompress(byte[] buf, int start, int[] len);
boolean canCompressPreauth();
}
|
Java
|
package com.trilead.ssh2;
/**
* A <code>SFTPv3FileAttributes</code> object represents detail information
* about a file on the server. Not all fields may/must be present.
*
* @author Christian Plattner, plattner@trilead.com
* @version $Id: SFTPv3FileAttributes.java,v 1.2 2008/04/01 12:38:09 cplattne Exp $
*/
public class SFTPv3FileAttributes
{
/**
* The SIZE attribute. <code>NULL</code> if not present.
*/
public Long size = null;
/**
* The UID attribute. <code>NULL</code> if not present.
*/
public Integer uid = null;
/**
* The GID attribute. <code>NULL</code> if not present.
*/
public Integer gid = null;
/**
* The POSIX permissions. <code>NULL</code> if not present.
* <p>
* Here is a list:
* <p>
* <pre>Note: these numbers are all OCTAL.
*
* S_IFMT 0170000 bitmask for the file type bitfields
* S_IFSOCK 0140000 socket
* S_IFLNK 0120000 symbolic link
* S_IFREG 0100000 regular file
* S_IFBLK 0060000 block device
* S_IFDIR 0040000 directory
* S_IFCHR 0020000 character device
* S_IFIFO 0010000 fifo
* S_ISUID 0004000 set UID bit
* S_ISGID 0002000 set GID bit
* S_ISVTX 0001000 sticky bit
*
* S_IRWXU 00700 mask for file owner permissions
* S_IRUSR 00400 owner has read permission
* S_IWUSR 00200 owner has write permission
* S_IXUSR 00100 owner has execute permission
* S_IRWXG 00070 mask for group permissions
* S_IRGRP 00040 group has read permission
* S_IWGRP 00020 group has write permission
* S_IXGRP 00010 group has execute permission
* S_IRWXO 00007 mask for permissions for others (not in group)
* S_IROTH 00004 others have read permission
* S_IWOTH 00002 others have write permisson
* S_IXOTH 00001 others have execute permission
* </pre>
*/
public Integer permissions = null;
/**
* The ATIME attribute. Represented as seconds from Jan 1, 1970 in UTC.
* <code>NULL</code> if not present.
*/
public Long atime = null;
/**
* The MTIME attribute. Represented as seconds from Jan 1, 1970 in UTC.
* <code>NULL</code> if not present.
*/
public Long mtime = null;
/**
* Checks if this entry is a directory.
*
* @return Returns true if permissions are available and they indicate
* that this entry represents a directory.
*/
public boolean isDirectory()
{
if (permissions == null)
return false;
return ((permissions.intValue() & 0040000) != 0);
}
/**
* Checks if this entry is a regular file.
*
* @return Returns true if permissions are available and they indicate
* that this entry represents a regular file.
*/
public boolean isRegularFile()
{
if (permissions == null)
return false;
return ((permissions.intValue() & 0100000) != 0);
}
/**
* Checks if this entry is a a symlink.
*
* @return Returns true if permissions are available and they indicate
* that this entry represents a symlink.
*/
public boolean isSymlink()
{
if (permissions == null)
return false;
return ((permissions.intValue() & 0120000) != 0);
}
/**
* Turn the POSIX permissions into a 7 digit octal representation.
* Note: the returned value is first masked with <code>0177777</code>.
*
* @return <code>NULL</code> if permissions are not available.
*/
public String getOctalPermissions()
{
if (permissions == null)
return null;
String res = Integer.toString(permissions.intValue() & 0177777, 8);
StringBuffer sb = new StringBuffer();
int leadingZeros = 7 - res.length();
while (leadingZeros > 0)
{
sb.append('0');
leadingZeros--;
}
sb.append(res);
return sb.toString();
}
}
|
Java
|
package com.trilead.ssh2;
/**
* A <code>SFTPv3FileHandle</code>.
*
* @author Christian Plattner, plattner@trilead.com
* @version $Id: SFTPv3FileHandle.java,v 1.1 2007/10/15 12:49:56 cplattne Exp $
*/
public class SFTPv3FileHandle
{
final SFTPv3Client client;
final byte[] fileHandle;
boolean isClosed = false;
/* The constructor is NOT public */
SFTPv3FileHandle(SFTPv3Client client, byte[] h)
{
this.client = client;
this.fileHandle = h;
}
/**
* Get the SFTPv3Client instance which created this handle.
*
* @return A SFTPv3Client instance.
*/
public SFTPv3Client getClient()
{
return client;
}
/**
* Check if this handle was closed with the {@link SFTPv3Client#closeFile(SFTPv3FileHandle)} method
* of the <code>SFTPv3Client</code> instance which created the handle.
*
* @return if the handle is closed.
*/
public boolean isClosed()
{
return isClosed;
}
}
|
Java
|
package com.trilead.ssh2;
import java.util.Map;
/**
* AuthAgentCallback.
*
* @author Kenny Root
* @version $Id$
*/
public interface AuthAgentCallback {
/**
* @return array of blobs containing the OpenSSH-format encoded public keys
*/
Map<String,byte[]> retrieveIdentities();
/**
* @param key A <code>RSAPrivateKey</code> or <code>DSAPrivateKey</code>
* containing a DSA or RSA private key of
* the user in Trilead object format.
* @param comment comment associated with this key
* @param confirmUse whether to prompt before using this key
* @param lifetime lifetime in seconds for key to be remembered
* @return success or failure
*/
boolean addIdentity(Object key, String comment, boolean confirmUse, int lifetime);
/**
* @param publicKey byte blob containing the OpenSSH-format encoded public key
* @return success or failure
*/
boolean removeIdentity(byte[] publicKey);
/**
* @return success or failure
*/
boolean removeAllIdentities();
/**
* @param publicKey byte blob containing the OpenSSH-format encoded public key
* @return A <code>RSAPrivateKey</code> or <code>DSAPrivateKey</code>
* containing a DSA or RSA private key of
* the user in Trilead object format.
*/
Object getPrivateKey(byte[] publicKey);
/**
* @return
*/
boolean isAgentLocked();
/**
* @param lockPassphrase
*/
boolean setAgentLock(String lockPassphrase);
/**
* @param unlockPassphrase
* @return
*/
boolean requestAgentUnlock(String unlockPassphrase);
}
|
Java
|
package com.trilead.ssh2.packets;
import java.io.IOException;
import java.math.BigInteger;
/**
* PacketKexDHReply.
*
* @author Christian Plattner, plattner@trilead.com
* @version $Id: PacketKexDHReply.java,v 1.1 2007/10/15 12:49:55 cplattne Exp $
*/
public class PacketKexDHReply
{
byte[] payload;
byte[] hostKey;
BigInteger f;
byte[] signature;
public PacketKexDHReply(byte payload[], int off, int len) throws IOException
{
this.payload = new byte[len];
System.arraycopy(payload, off, this.payload, 0, len);
TypesReader tr = new TypesReader(payload, off, len);
int packet_type = tr.readByte();
if (packet_type != Packets.SSH_MSG_KEXDH_REPLY)
throw new IOException("This is not a SSH_MSG_KEXDH_REPLY! ("
+ packet_type + ")");
hostKey = tr.readByteString();
f = tr.readMPINT();
signature = tr.readByteString();
if (tr.remain() != 0) throw new IOException("PADDING IN SSH_MSG_KEXDH_REPLY!");
}
public BigInteger getF()
{
return f;
}
public byte[] getHostKey()
{
return hostKey;
}
public byte[] getSignature()
{
return signature;
}
}
|
Java
|
package com.trilead.ssh2.packets;
import java.io.IOException;
/**
* PacketServiceRequest.
*
* @author Christian Plattner, plattner@trilead.com
* @version $Id: PacketServiceRequest.java,v 1.1 2007/10/15 12:49:55 cplattne Exp $
*/
public class PacketServiceRequest
{
byte[] payload;
String serviceName;
public PacketServiceRequest(String serviceName)
{
this.serviceName = serviceName;
}
public PacketServiceRequest(byte payload[], int off, int len) throws IOException
{
this.payload = new byte[len];
System.arraycopy(payload, off, this.payload, 0, len);
TypesReader tr = new TypesReader(payload, off, len);
int packet_type = tr.readByte();
if (packet_type != Packets.SSH_MSG_SERVICE_REQUEST)
throw new IOException("This is not a SSH_MSG_SERVICE_REQUEST! ("
+ packet_type + ")");
serviceName = tr.readString();
if (tr.remain() != 0)
throw new IOException("Padding in SSH_MSG_SERVICE_REQUEST packet!");
}
public byte[] getPayload()
{
if (payload == null)
{
TypesWriter tw = new TypesWriter();
tw.writeByte(Packets.SSH_MSG_SERVICE_REQUEST);
tw.writeString(serviceName);
payload = tw.getBytes();
}
return payload;
}
}
|
Java
|
package com.trilead.ssh2.packets;
import com.trilead.ssh2.DHGexParameters;
/**
* PacketKexDhGexRequest.
*
* @author Christian Plattner, plattner@trilead.com
* @version $Id: PacketKexDhGexRequest.java,v 1.1 2007/10/15 12:49:55 cplattne Exp $
*/
public class PacketKexDhGexRequest
{
byte[] payload;
int min;
int n;
int max;
public PacketKexDhGexRequest(DHGexParameters para)
{
this.min = para.getMin_group_len();
this.n = para.getPref_group_len();
this.max = para.getMax_group_len();
}
public byte[] getPayload()
{
if (payload == null)
{
TypesWriter tw = new TypesWriter();
tw.writeByte(Packets.SSH_MSG_KEX_DH_GEX_REQUEST);
tw.writeUINT32(min);
tw.writeUINT32(n);
tw.writeUINT32(max);
payload = tw.getBytes();
}
return payload;
}
}
|
Java
|
package com.trilead.ssh2.packets;
import java.io.IOException;
/**
* PacketUserauthRequestPassword.
*
* @author Christian Plattner, plattner@trilead.com
* @version $Id: PacketUserauthRequestNone.java,v 1.1 2007/10/15 12:49:55 cplattne Exp $
*/
public class PacketUserauthRequestNone
{
byte[] payload;
String userName;
String serviceName;
public PacketUserauthRequestNone(String serviceName, String user)
{
this.serviceName = serviceName;
this.userName = user;
}
public PacketUserauthRequestNone(byte payload[], int off, int len) throws IOException
{
this.payload = new byte[len];
System.arraycopy(payload, off, this.payload, 0, len);
TypesReader tr = new TypesReader(payload, off, len);
int packet_type = tr.readByte();
if (packet_type != Packets.SSH_MSG_USERAUTH_REQUEST)
throw new IOException("This is not a SSH_MSG_USERAUTH_REQUEST! (" + packet_type + ")");
userName = tr.readString();
serviceName = tr.readString();
String method = tr.readString();
if (method.equals("none") == false)
throw new IOException("This is not a SSH_MSG_USERAUTH_REQUEST with type none!");
if (tr.remain() != 0)
throw new IOException("Padding in SSH_MSG_USERAUTH_REQUEST packet!");
}
public byte[] getPayload()
{
if (payload == null)
{
TypesWriter tw = new TypesWriter();
tw.writeByte(Packets.SSH_MSG_USERAUTH_REQUEST);
tw.writeString(userName);
tw.writeString(serviceName);
tw.writeString("none");
payload = tw.getBytes();
}
return payload;
}
}
|
Java
|
package com.trilead.ssh2.packets;
import java.io.UnsupportedEncodingException;
import java.math.BigInteger;
/**
* TypesWriter.
*
* @author Christian Plattner, plattner@trilead.com
* @version $Id: TypesWriter.java,v 1.2 2008/04/01 12:38:09 cplattne Exp $
*/
public class TypesWriter
{
byte arr[];
int pos;
public TypesWriter()
{
arr = new byte[256];
pos = 0;
}
private void resize(int len)
{
byte new_arr[] = new byte[len];
System.arraycopy(arr, 0, new_arr, 0, arr.length);
arr = new_arr;
}
public int length()
{
return pos;
}
public byte[] getBytes()
{
byte[] dst = new byte[pos];
System.arraycopy(arr, 0, dst, 0, pos);
return dst;
}
public void getBytes(byte dst[])
{
System.arraycopy(arr, 0, dst, 0, pos);
}
public void writeUINT32(int val, int off)
{
if ((off + 4) > arr.length)
resize(off + 32);
arr[off++] = (byte) (val >> 24);
arr[off++] = (byte) (val >> 16);
arr[off++] = (byte) (val >> 8);
arr[off++] = (byte) val;
}
public void writeUINT32(int val)
{
writeUINT32(val, pos);
pos += 4;
}
public void writeUINT64(long val)
{
if ((pos + 8) > arr.length)
resize(arr.length + 32);
arr[pos++] = (byte) (val >> 56);
arr[pos++] = (byte) (val >> 48);
arr[pos++] = (byte) (val >> 40);
arr[pos++] = (byte) (val >> 32);
arr[pos++] = (byte) (val >> 24);
arr[pos++] = (byte) (val >> 16);
arr[pos++] = (byte) (val >> 8);
arr[pos++] = (byte) val;
}
public void writeBoolean(boolean v)
{
if ((pos + 1) > arr.length)
resize(arr.length + 32);
arr[pos++] = v ? (byte) 1 : (byte) 0;
}
public void writeByte(int v, int off)
{
if ((off + 1) > arr.length)
resize(off + 32);
arr[off] = (byte) v;
}
public void writeByte(int v)
{
writeByte(v, pos);
pos++;
}
public void writeMPInt(BigInteger b)
{
byte raw[] = b.toByteArray();
if ((raw.length == 1) && (raw[0] == 0))
writeUINT32(0); /* String with zero bytes of data */
else
writeString(raw, 0, raw.length);
}
public void writeBytes(byte[] buff)
{
writeBytes(buff, 0, buff.length);
}
public void writeBytes(byte[] buff, int off, int len)
{
if ((pos + len) > arr.length)
resize(arr.length + len + 32);
System.arraycopy(buff, off, arr, pos, len);
pos += len;
}
public void writeString(byte[] buff, int off, int len)
{
writeUINT32(len);
writeBytes(buff, off, len);
}
public void writeString(String v)
{
byte[] b;
try
{
/* All Java JVMs must support ISO-8859-1 */
b = v.getBytes("ISO-8859-1");
}
catch (UnsupportedEncodingException ignore)
{
b = v.getBytes();
}
writeUINT32(b.length);
writeBytes(b, 0, b.length);
}
public void writeString(String v, String charsetName) throws UnsupportedEncodingException
{
byte[] b = (charsetName == null) ? v.getBytes() : v.getBytes(charsetName);
writeUINT32(b.length);
writeBytes(b, 0, b.length);
}
public void writeNameList(String v[])
{
StringBuffer sb = new StringBuffer();
for (int i = 0; i < v.length; i++)
{
if (i > 0)
sb.append(',');
sb.append(v[i]);
}
writeString(sb.toString());
}
}
|
Java
|
package com.trilead.ssh2.packets;
import java.math.BigInteger;
/**
* PacketKexDhGexInit.
*
* @author Christian Plattner, plattner@trilead.com
* @version $Id: PacketKexDhGexInit.java,v 1.1 2007/10/15 12:49:55 cplattne Exp $
*/
public class PacketKexDhGexInit
{
byte[] payload;
BigInteger e;
public PacketKexDhGexInit(BigInteger e)
{
this.e = e;
}
public byte[] getPayload()
{
if (payload == null)
{
TypesWriter tw = new TypesWriter();
tw.writeByte(Packets.SSH_MSG_KEX_DH_GEX_INIT);
tw.writeMPInt(e);
payload = tw.getBytes();
}
return payload;
}
}
|
Java
|
package com.trilead.ssh2.packets;
import java.io.IOException;
import java.math.BigInteger;
/**
* PacketKexDhGexGroup.
*
* @author Christian Plattner, plattner@trilead.com
* @version $Id: PacketKexDhGexGroup.java,v 1.1 2007/10/15 12:49:55 cplattne Exp $
*/
public class PacketKexDhGexGroup
{
byte[] payload;
BigInteger p;
BigInteger g;
public PacketKexDhGexGroup(byte payload[], int off, int len) throws IOException
{
this.payload = new byte[len];
System.arraycopy(payload, off, this.payload, 0, len);
TypesReader tr = new TypesReader(payload, off, len);
int packet_type = tr.readByte();
if (packet_type != Packets.SSH_MSG_KEX_DH_GEX_GROUP)
throw new IllegalArgumentException(
"This is not a SSH_MSG_KEX_DH_GEX_GROUP! (" + packet_type
+ ")");
p = tr.readMPINT();
g = tr.readMPINT();
if (tr.remain() != 0)
throw new IOException("PADDING IN SSH_MSG_KEX_DH_GEX_GROUP!");
}
public BigInteger getG()
{
return g;
}
public BigInteger getP()
{
return p;
}
}
|
Java
|
package com.trilead.ssh2.packets;
import java.io.IOException;
/**
* PacketChannelWindowAdjust.
*
* @author Christian Plattner, plattner@trilead.com
* @version $Id: PacketChannelWindowAdjust.java,v 1.1 2007/10/15 12:49:55 cplattne Exp $
*/
public class PacketChannelWindowAdjust
{
byte[] payload;
public int recipientChannelID;
public int windowChange;
public PacketChannelWindowAdjust(int recipientChannelID, int windowChange)
{
this.recipientChannelID = recipientChannelID;
this.windowChange = windowChange;
}
public PacketChannelWindowAdjust(byte payload[], int off, int len) throws IOException
{
this.payload = new byte[len];
System.arraycopy(payload, off, this.payload, 0, len);
TypesReader tr = new TypesReader(payload, off, len);
int packet_type = tr.readByte();
if (packet_type != Packets.SSH_MSG_CHANNEL_WINDOW_ADJUST)
throw new IOException(
"This is not a SSH_MSG_CHANNEL_WINDOW_ADJUST! ("
+ packet_type + ")");
recipientChannelID = tr.readUINT32();
windowChange = tr.readUINT32();
if (tr.remain() != 0)
throw new IOException("Padding in SSH_MSG_CHANNEL_WINDOW_ADJUST packet!");
}
public byte[] getPayload()
{
if (payload == null)
{
TypesWriter tw = new TypesWriter();
tw.writeByte(Packets.SSH_MSG_CHANNEL_WINDOW_ADJUST);
tw.writeUINT32(recipientChannelID);
tw.writeUINT32(windowChange);
payload = tw.getBytes();
}
return payload;
}
}
|
Java
|
package com.trilead.ssh2.packets;
import java.io.IOException;
import java.math.BigInteger;
/**
* PacketKexDhGexReply.
*
* @author Christian Plattner, plattner@trilead.com
* @version $Id: PacketKexDhGexReply.java,v 1.1 2007/10/15 12:49:55 cplattne Exp $
*/
public class PacketKexDhGexReply
{
byte[] payload;
byte[] hostKey;
BigInteger f;
byte[] signature;
public PacketKexDhGexReply(byte payload[], int off, int len) throws IOException
{
this.payload = new byte[len];
System.arraycopy(payload, off, this.payload, 0, len);
TypesReader tr = new TypesReader(payload, off, len);
int packet_type = tr.readByte();
if (packet_type != Packets.SSH_MSG_KEX_DH_GEX_REPLY)
throw new IOException("This is not a SSH_MSG_KEX_DH_GEX_REPLY! (" + packet_type + ")");
hostKey = tr.readByteString();
f = tr.readMPINT();
signature = tr.readByteString();
if (tr.remain() != 0)
throw new IOException("PADDING IN SSH_MSG_KEX_DH_GEX_REPLY!");
}
public BigInteger getF()
{
return f;
}
public byte[] getHostKey()
{
return hostKey;
}
public byte[] getSignature()
{
return signature;
}
}
|
Java
|
package com.trilead.ssh2.packets;
/**
* PacketGlobalCancelForwardRequest.
*
* @author Christian Plattner, plattner@trilead.com
* @version $Id: PacketGlobalCancelForwardRequest.java,v 1.1 2007/10/15 12:49:55
* cplattne Exp $
*/
public class PacketGlobalCancelForwardRequest
{
byte[] payload;
public boolean wantReply;
public String bindAddress;
public int bindPort;
public PacketGlobalCancelForwardRequest(boolean wantReply, String bindAddress, int bindPort)
{
this.wantReply = wantReply;
this.bindAddress = bindAddress;
this.bindPort = bindPort;
}
public byte[] getPayload()
{
if (payload == null)
{
TypesWriter tw = new TypesWriter();
tw.writeByte(Packets.SSH_MSG_GLOBAL_REQUEST);
tw.writeString("cancel-tcpip-forward");
tw.writeBoolean(wantReply);
tw.writeString(bindAddress);
tw.writeUINT32(bindPort);
payload = tw.getBytes();
}
return payload;
}
}
|
Java
|
package com.trilead.ssh2.packets;
/**
* PacketSessionSubsystemRequest.
*
* @author Christian Plattner, plattner@trilead.com
* @version $Id: PacketSessionSubsystemRequest.java,v 1.1 2007/10/15 12:49:55 cplattne Exp $
*/
public class PacketSessionSubsystemRequest
{
byte[] payload;
public int recipientChannelID;
public boolean wantReply;
public String subsystem;
public PacketSessionSubsystemRequest(int recipientChannelID, boolean wantReply, String subsystem)
{
this.recipientChannelID = recipientChannelID;
this.wantReply = wantReply;
this.subsystem = subsystem;
}
public byte[] getPayload()
{
if (payload == null)
{
TypesWriter tw = new TypesWriter();
tw.writeByte(Packets.SSH_MSG_CHANNEL_REQUEST);
tw.writeUINT32(recipientChannelID);
tw.writeString("subsystem");
tw.writeBoolean(wantReply);
tw.writeString(subsystem);
payload = tw.getBytes();
tw.getBytes(payload);
}
return payload;
}
}
|
Java
|
package com.trilead.ssh2.packets;
/**
* PacketSessionExecCommand.
*
* @author Christian Plattner, plattner@trilead.com
* @version $Id: PacketSessionExecCommand.java,v 1.1 2007/10/15 12:49:55 cplattne Exp $
*/
public class PacketSessionExecCommand
{
byte[] payload;
public int recipientChannelID;
public boolean wantReply;
public String command;
public PacketSessionExecCommand(int recipientChannelID, boolean wantReply, String command)
{
this.recipientChannelID = recipientChannelID;
this.wantReply = wantReply;
this.command = command;
}
public byte[] getPayload()
{
if (payload == null)
{
TypesWriter tw = new TypesWriter();
tw.writeByte(Packets.SSH_MSG_CHANNEL_REQUEST);
tw.writeUINT32(recipientChannelID);
tw.writeString("exec");
tw.writeBoolean(wantReply);
tw.writeString(command);
payload = tw.getBytes();
}
return payload;
}
}
|
Java
|
package com.trilead.ssh2.packets;
import java.io.IOException;
/**
* PacketUserauthBanner.
*
* @author Christian Plattner, plattner@trilead.com
* @version $Id: PacketUserauthFailure.java,v 1.1 2007/10/15 12:49:55 cplattne Exp $
*/
public class PacketUserauthFailure
{
byte[] payload;
String[] authThatCanContinue;
boolean partialSuccess;
public PacketUserauthFailure(String[] authThatCanContinue, boolean partialSuccess)
{
this.authThatCanContinue = authThatCanContinue;
this.partialSuccess = partialSuccess;
}
public PacketUserauthFailure(byte payload[], int off, int len) throws IOException
{
this.payload = new byte[len];
System.arraycopy(payload, off, this.payload, 0, len);
TypesReader tr = new TypesReader(payload, off, len);
int packet_type = tr.readByte();
if (packet_type != Packets.SSH_MSG_USERAUTH_FAILURE)
throw new IOException("This is not a SSH_MSG_USERAUTH_FAILURE! (" + packet_type + ")");
authThatCanContinue = tr.readNameList();
partialSuccess = tr.readBoolean();
if (tr.remain() != 0)
throw new IOException("Padding in SSH_MSG_USERAUTH_FAILURE packet!");
}
public String[] getAuthThatCanContinue()
{
return authThatCanContinue;
}
public boolean isPartialSuccess()
{
return partialSuccess;
}
}
|
Java
|
package com.trilead.ssh2.packets;
/**
* PacketSessionStartShell.
*
* @author Christian Plattner, plattner@trilead.com
* @version $Id: PacketSessionStartShell.java,v 1.1 2007/10/15 12:49:55 cplattne Exp $
*/
public class PacketSessionStartShell
{
byte[] payload;
public int recipientChannelID;
public boolean wantReply;
public PacketSessionStartShell(int recipientChannelID, boolean wantReply)
{
this.recipientChannelID = recipientChannelID;
this.wantReply = wantReply;
}
public byte[] getPayload()
{
if (payload == null)
{
TypesWriter tw = new TypesWriter();
tw.writeByte(Packets.SSH_MSG_CHANNEL_REQUEST);
tw.writeUINT32(recipientChannelID);
tw.writeString("shell");
tw.writeBoolean(wantReply);
payload = tw.getBytes();
}
return payload;
}
}
|
Java
|
package com.trilead.ssh2.packets;
import java.io.IOException;
import java.math.BigInteger;
import com.trilead.ssh2.util.Tokenizer;
/**
* TypesReader.
*
* @author Christian Plattner, plattner@trilead.com
* @version $Id: TypesReader.java,v 1.2 2008/04/01 12:38:09 cplattne Exp $
*/
public class TypesReader
{
byte[] arr;
int pos = 0;
int max = 0;
public TypesReader(byte[] arr)
{
this.arr = arr;
pos = 0;
max = arr.length;
}
public TypesReader(byte[] arr, int off)
{
this.arr = arr;
this.pos = off;
this.max = arr.length;
if ((pos < 0) || (pos > arr.length))
throw new IllegalArgumentException("Illegal offset.");
}
public TypesReader(byte[] arr, int off, int len)
{
this.arr = arr;
this.pos = off;
this.max = off + len;
if ((pos < 0) || (pos > arr.length))
throw new IllegalArgumentException("Illegal offset.");
if ((max < 0) || (max > arr.length))
throw new IllegalArgumentException("Illegal length.");
}
public int readByte() throws IOException
{
if (pos >= max)
throw new IOException("Packet too short.");
return (arr[pos++] & 0xff);
}
public byte[] readBytes(int len) throws IOException
{
if ((pos + len) > max)
throw new IOException("Packet too short.");
byte[] res = new byte[len];
System.arraycopy(arr, pos, res, 0, len);
pos += len;
return res;
}
public void readBytes(byte[] dst, int off, int len) throws IOException
{
if ((pos + len) > max)
throw new IOException("Packet too short.");
System.arraycopy(arr, pos, dst, off, len);
pos += len;
}
public boolean readBoolean() throws IOException
{
if (pos >= max)
throw new IOException("Packet too short.");
return (arr[pos++] != 0);
}
public int readUINT32() throws IOException
{
if ((pos + 4) > max)
throw new IOException("Packet too short.");
return ((arr[pos++] & 0xff) << 24) | ((arr[pos++] & 0xff) << 16) | ((arr[pos++] & 0xff) << 8)
| (arr[pos++] & 0xff);
}
public long readUINT64() throws IOException
{
if ((pos + 8) > max)
throw new IOException("Packet too short.");
long high = ((arr[pos++] & 0xff) << 24) | ((arr[pos++] & 0xff) << 16) | ((arr[pos++] & 0xff) << 8)
| (arr[pos++] & 0xff); /* sign extension may take place - will be shifted away =) */
long low = ((arr[pos++] & 0xff) << 24) | ((arr[pos++] & 0xff) << 16) | ((arr[pos++] & 0xff) << 8)
| (arr[pos++] & 0xff); /* sign extension may take place - handle below */
return (high << 32) | (low & 0xffffffffl); /* see Java language spec (15.22.1, 5.6.2) */
}
public BigInteger readMPINT() throws IOException
{
BigInteger b;
byte raw[] = readByteString();
if (raw.length == 0)
b = BigInteger.ZERO;
else
b = new BigInteger(raw);
return b;
}
public byte[] readByteString() throws IOException
{
int len = readUINT32();
if ((len + pos) > max)
throw new IOException("Malformed SSH byte string.");
byte[] res = new byte[len];
System.arraycopy(arr, pos, res, 0, len);
pos += len;
return res;
}
public String readString(String charsetName) throws IOException
{
int len = readUINT32();
if ((len + pos) > max)
throw new IOException("Malformed SSH string.");
String res = (charsetName == null) ? new String(arr, pos, len) : new String(arr, pos, len, charsetName);
pos += len;
return res;
}
public String readString() throws IOException
{
int len = readUINT32();
if ((len + pos) > max)
throw new IOException("Malformed SSH string.");
String res = new String(arr, pos, len, "ISO-8859-1");
pos += len;
return res;
}
public String[] readNameList() throws IOException
{
return Tokenizer.parseTokens(readString(), ',');
}
public int remain()
{
return max - pos;
}
}
|
Java
|
package com.trilead.ssh2.packets;
import java.io.IOException;
/**
* PacketUserauthRequestPassword.
*
* @author Christian Plattner, plattner@trilead.com
* @version $Id: PacketUserauthRequestPassword.java,v 1.1 2007/10/15 12:49:55 cplattne Exp $
*/
public class PacketUserauthRequestPassword
{
byte[] payload;
String userName;
String serviceName;
String password;
public PacketUserauthRequestPassword(String serviceName, String user, String pass)
{
this.serviceName = serviceName;
this.userName = user;
this.password = pass;
}
public PacketUserauthRequestPassword(byte payload[], int off, int len) throws IOException
{
this.payload = new byte[len];
System.arraycopy(payload, off, this.payload, 0, len);
TypesReader tr = new TypesReader(payload, off, len);
int packet_type = tr.readByte();
if (packet_type != Packets.SSH_MSG_USERAUTH_REQUEST)
throw new IOException("This is not a SSH_MSG_USERAUTH_REQUEST! (" + packet_type + ")");
userName = tr.readString();
serviceName = tr.readString();
String method = tr.readString();
if (method.equals("password") == false)
throw new IOException("This is not a SSH_MSG_USERAUTH_REQUEST with type password!");
/* ... */
if (tr.remain() != 0)
throw new IOException("Padding in SSH_MSG_USERAUTH_REQUEST packet!");
}
public byte[] getPayload()
{
if (payload == null)
{
TypesWriter tw = new TypesWriter();
tw.writeByte(Packets.SSH_MSG_USERAUTH_REQUEST);
tw.writeString(userName);
tw.writeString(serviceName);
tw.writeString("password");
tw.writeBoolean(false);
tw.writeString(password);
payload = tw.getBytes();
}
return payload;
}
}
|
Java
|
package com.trilead.ssh2.packets;
import java.io.IOException;
/**
* PacketChannelOpenFailure.
*
* @author Christian Plattner, plattner@trilead.com
* @version $Id: PacketChannelOpenFailure.java,v 1.1 2007/10/15 12:49:55 cplattne Exp $
*/
public class PacketChannelOpenFailure
{
byte[] payload;
public int recipientChannelID;
public int reasonCode;
public String description;
public String languageTag;
public PacketChannelOpenFailure(int recipientChannelID, int reasonCode, String description,
String languageTag)
{
this.recipientChannelID = recipientChannelID;
this.reasonCode = reasonCode;
this.description = description;
this.languageTag = languageTag;
}
public PacketChannelOpenFailure(byte payload[], int off, int len) throws IOException
{
this.payload = new byte[len];
System.arraycopy(payload, off, this.payload, 0, len);
TypesReader tr = new TypesReader(payload, off, len);
int packet_type = tr.readByte();
if (packet_type != Packets.SSH_MSG_CHANNEL_OPEN_FAILURE)
throw new IOException(
"This is not a SSH_MSG_CHANNEL_OPEN_FAILURE! ("
+ packet_type + ")");
recipientChannelID = tr.readUINT32();
reasonCode = tr.readUINT32();
description = tr.readString();
languageTag = tr.readString();
if (tr.remain() != 0)
throw new IOException("Padding in SSH_MSG_CHANNEL_OPEN_FAILURE packet!");
}
public byte[] getPayload()
{
if (payload == null)
{
TypesWriter tw = new TypesWriter();
tw.writeByte(Packets.SSH_MSG_CHANNEL_OPEN_FAILURE);
tw.writeUINT32(recipientChannelID);
tw.writeUINT32(reasonCode);
tw.writeString(description);
tw.writeString(languageTag);
payload = tw.getBytes();
}
return payload;
}
}
|
Java
|
package com.trilead.ssh2.packets;
import java.io.IOException;
/**
* PacketNewKeys.
*
* @author Christian Plattner, plattner@trilead.com
* @version $Id: PacketNewKeys.java,v 1.1 2007/10/15 12:49:55 cplattne Exp $
*/
public class PacketNewKeys
{
byte[] payload;
public PacketNewKeys()
{
}
public PacketNewKeys(byte payload[], int off, int len) throws IOException
{
this.payload = new byte[len];
System.arraycopy(payload, off, this.payload, 0, len);
TypesReader tr = new TypesReader(payload, off, len);
int packet_type = tr.readByte();
if (packet_type != Packets.SSH_MSG_NEWKEYS)
throw new IOException("This is not a SSH_MSG_NEWKEYS! ("
+ packet_type + ")");
if (tr.remain() != 0)
throw new IOException("Padding in SSH_MSG_NEWKEYS packet!");
}
public byte[] getPayload()
{
if (payload == null)
{
TypesWriter tw = new TypesWriter();
tw.writeByte(Packets.SSH_MSG_NEWKEYS);
payload = tw.getBytes();
}
return payload;
}
}
|
Java
|
package com.trilead.ssh2.packets;
/**
* PacketGlobalAuthAgent.
*
* @author Kenny Root, kenny@the-b.org
* @version $Id$
*/
public class PacketChannelAuthAgentReq
{
byte[] payload;
public int recipientChannelID;
public PacketChannelAuthAgentReq(int recipientChannelID)
{
this.recipientChannelID = recipientChannelID;
}
public byte[] getPayload()
{
if (payload == null)
{
TypesWriter tw = new TypesWriter();
tw.writeByte(Packets.SSH_MSG_CHANNEL_REQUEST);
tw.writeUINT32(recipientChannelID);
tw.writeString("auth-agent-req@openssh.com");
tw.writeBoolean(true); // want reply
payload = tw.getBytes();
}
return payload;
}
}
|
Java
|
package com.trilead.ssh2.packets;
public class PacketSessionPtyResize {
byte[] payload;
public int recipientChannelID;
public int width;
public int height;
public int pixelWidth;
public int pixelHeight;
public PacketSessionPtyResize(int recipientChannelID, int width, int height, int pixelWidth, int pixelHeight) {
this.recipientChannelID = recipientChannelID;
this.width = width;
this.height = height;
this.pixelWidth = pixelWidth;
this.pixelHeight = pixelHeight;
}
public byte[] getPayload()
{
if (payload == null)
{
TypesWriter tw = new TypesWriter();
tw.writeByte(Packets.SSH_MSG_CHANNEL_REQUEST);
tw.writeUINT32(recipientChannelID);
tw.writeString("window-change");
tw.writeBoolean(false);
tw.writeUINT32(width);
tw.writeUINT32(height);
tw.writeUINT32(pixelWidth);
tw.writeUINT32(pixelHeight);
payload = tw.getBytes();
}
return payload;
}
}
|
Java
|
package com.trilead.ssh2.packets;
import java.io.IOException;
/**
* PacketUserauthRequestPublicKey.
*
* @author Christian Plattner, plattner@trilead.com
* @version $Id: PacketUserauthRequestPublicKey.java,v 1.1 2007/10/15 12:49:55 cplattne Exp $
*/
public class PacketUserauthRequestPublicKey
{
byte[] payload;
String userName;
String serviceName;
String password;
String pkAlgoName;
byte[] pk;
byte[] sig;
public PacketUserauthRequestPublicKey(String serviceName, String user,
String pkAlgorithmName, byte[] pk, byte[] sig)
{
this.serviceName = serviceName;
this.userName = user;
this.pkAlgoName = pkAlgorithmName;
this.pk = pk;
this.sig = sig;
}
public PacketUserauthRequestPublicKey(byte payload[], int off, int len) throws IOException
{
this.payload = new byte[len];
System.arraycopy(payload, off, this.payload, 0, len);
TypesReader tr = new TypesReader(payload, off, len);
int packet_type = tr.readByte();
if (packet_type != Packets.SSH_MSG_USERAUTH_REQUEST)
throw new IOException("This is not a SSH_MSG_USERAUTH_REQUEST! ("
+ packet_type + ")");
throw new IOException("Not implemented!");
}
public byte[] getPayload()
{
if (payload == null)
{
TypesWriter tw = new TypesWriter();
tw.writeByte(Packets.SSH_MSG_USERAUTH_REQUEST);
tw.writeString(userName);
tw.writeString(serviceName);
tw.writeString("publickey");
tw.writeBoolean(true);
tw.writeString(pkAlgoName);
tw.writeString(pk, 0, pk.length);
tw.writeString(sig, 0, sig.length);
payload = tw.getBytes();
}
return payload;
}
}
|
Java
|
package com.trilead.ssh2.packets;
import java.io.IOException;
/**
* PacketIgnore.
*
* @author Christian Plattner, plattner@trilead.com
* @version $Id: PacketIgnore.java,v 1.1 2007/10/15 12:49:55 cplattne Exp $
*/
public class PacketIgnore
{
byte[] payload;
byte[] data;
public void setData(byte[] data)
{
this.data = data;
payload = null;
}
public PacketIgnore()
{
}
public PacketIgnore(byte payload[], int off, int len) throws IOException
{
this.payload = new byte[len];
System.arraycopy(payload, off, this.payload, 0, len);
TypesReader tr = new TypesReader(payload, off, len);
int packet_type = tr.readByte();
if (packet_type != Packets.SSH_MSG_IGNORE)
throw new IOException("This is not a SSH_MSG_IGNORE packet! (" + packet_type + ")");
/* Could parse String body */
}
public byte[] getPayload()
{
if (payload == null)
{
TypesWriter tw = new TypesWriter();
tw.writeByte(Packets.SSH_MSG_IGNORE);
if (data != null)
tw.writeString(data, 0, data.length);
else
tw.writeString("");
payload = tw.getBytes();
}
return payload;
}
}
|
Java
|
package com.trilead.ssh2.packets;
/**
* Packets.
*
* @author Christian Plattner, plattner@trilead.com
* @version $Id: Packets.java,v 1.1 2007/10/15 12:49:55 cplattne Exp $
*/
public class Packets
{
public static final int SSH_MSG_DISCONNECT = 1;
public static final int SSH_MSG_IGNORE = 2;
public static final int SSH_MSG_UNIMPLEMENTED = 3;
public static final int SSH_MSG_DEBUG = 4;
public static final int SSH_MSG_SERVICE_REQUEST = 5;
public static final int SSH_MSG_SERVICE_ACCEPT = 6;
public static final int SSH_MSG_KEXINIT = 20;
public static final int SSH_MSG_NEWKEYS = 21;
public static final int SSH_MSG_KEXDH_INIT = 30;
public static final int SSH_MSG_KEXDH_REPLY = 31;
public static final int SSH_MSG_KEX_DH_GEX_REQUEST_OLD = 30;
public static final int SSH_MSG_KEX_DH_GEX_REQUEST = 34;
public static final int SSH_MSG_KEX_DH_GEX_GROUP = 31;
public static final int SSH_MSG_KEX_DH_GEX_INIT = 32;
public static final int SSH_MSG_KEX_DH_GEX_REPLY = 33;
public static final int SSH_MSG_USERAUTH_REQUEST = 50;
public static final int SSH_MSG_USERAUTH_FAILURE = 51;
public static final int SSH_MSG_USERAUTH_SUCCESS = 52;
public static final int SSH_MSG_USERAUTH_BANNER = 53;
public static final int SSH_MSG_USERAUTH_INFO_REQUEST = 60;
public static final int SSH_MSG_USERAUTH_INFO_RESPONSE = 61;
public static final int SSH_MSG_GLOBAL_REQUEST = 80;
public static final int SSH_MSG_REQUEST_SUCCESS = 81;
public static final int SSH_MSG_REQUEST_FAILURE = 82;
public static final int SSH_MSG_CHANNEL_OPEN = 90;
public static final int SSH_MSG_CHANNEL_OPEN_CONFIRMATION = 91;
public static final int SSH_MSG_CHANNEL_OPEN_FAILURE = 92;
public static final int SSH_MSG_CHANNEL_WINDOW_ADJUST = 93;
public static final int SSH_MSG_CHANNEL_DATA = 94;
public static final int SSH_MSG_CHANNEL_EXTENDED_DATA = 95;
public static final int SSH_MSG_CHANNEL_EOF = 96;
public static final int SSH_MSG_CHANNEL_CLOSE = 97;
public static final int SSH_MSG_CHANNEL_REQUEST = 98;
public static final int SSH_MSG_CHANNEL_SUCCESS = 99;
public static final int SSH_MSG_CHANNEL_FAILURE = 100;
public static final int SSH_EXTENDED_DATA_STDERR = 1;
public static final int SSH_DISCONNECT_HOST_NOT_ALLOWED_TO_CONNECT = 1;
public static final int SSH_DISCONNECT_PROTOCOL_ERROR = 2;
public static final int SSH_DISCONNECT_KEY_EXCHANGE_FAILED = 3;
public static final int SSH_DISCONNECT_RESERVED = 4;
public static final int SSH_DISCONNECT_MAC_ERROR = 5;
public static final int SSH_DISCONNECT_COMPRESSION_ERROR = 6;
public static final int SSH_DISCONNECT_SERVICE_NOT_AVAILABLE = 7;
public static final int SSH_DISCONNECT_PROTOCOL_VERSION_NOT_SUPPORTED = 8;
public static final int SSH_DISCONNECT_HOST_KEY_NOT_VERIFIABLE = 9;
public static final int SSH_DISCONNECT_CONNECTION_LOST = 10;
public static final int SSH_DISCONNECT_BY_APPLICATION = 11;
public static final int SSH_DISCONNECT_TOO_MANY_CONNECTIONS = 12;
public static final int SSH_DISCONNECT_AUTH_CANCELLED_BY_USER = 13;
public static final int SSH_DISCONNECT_NO_MORE_AUTH_METHODS_AVAILABLE = 14;
public static final int SSH_DISCONNECT_ILLEGAL_USER_NAME = 15;
public static final int SSH_OPEN_ADMINISTRATIVELY_PROHIBITED = 1;
public static final int SSH_OPEN_CONNECT_FAILED = 2;
public static final int SSH_OPEN_UNKNOWN_CHANNEL_TYPE = 3;
public static final int SSH_OPEN_RESOURCE_SHORTAGE = 4;
private static final String[] reverseNames = new String[101];
static
{
reverseNames[1] = "SSH_MSG_DISCONNECT";
reverseNames[2] = "SSH_MSG_IGNORE";
reverseNames[3] = "SSH_MSG_UNIMPLEMENTED";
reverseNames[4] = "SSH_MSG_DEBUG";
reverseNames[5] = "SSH_MSG_SERVICE_REQUEST";
reverseNames[6] = "SSH_MSG_SERVICE_ACCEPT";
reverseNames[20] = "SSH_MSG_KEXINIT";
reverseNames[21] = "SSH_MSG_NEWKEYS";
reverseNames[30] = "SSH_MSG_KEXDH_INIT";
reverseNames[31] = "SSH_MSG_KEXDH_REPLY/SSH_MSG_KEX_DH_GEX_GROUP";
reverseNames[32] = "SSH_MSG_KEX_DH_GEX_INIT";
reverseNames[33] = "SSH_MSG_KEX_DH_GEX_REPLY";
reverseNames[34] = "SSH_MSG_KEX_DH_GEX_REQUEST";
reverseNames[50] = "SSH_MSG_USERAUTH_REQUEST";
reverseNames[51] = "SSH_MSG_USERAUTH_FAILURE";
reverseNames[52] = "SSH_MSG_USERAUTH_SUCCESS";
reverseNames[53] = "SSH_MSG_USERAUTH_BANNER";
reverseNames[60] = "SSH_MSG_USERAUTH_INFO_REQUEST";
reverseNames[61] = "SSH_MSG_USERAUTH_INFO_RESPONSE";
reverseNames[80] = "SSH_MSG_GLOBAL_REQUEST";
reverseNames[81] = "SSH_MSG_REQUEST_SUCCESS";
reverseNames[82] = "SSH_MSG_REQUEST_FAILURE";
reverseNames[90] = "SSH_MSG_CHANNEL_OPEN";
reverseNames[91] = "SSH_MSG_CHANNEL_OPEN_CONFIRMATION";
reverseNames[92] = "SSH_MSG_CHANNEL_OPEN_FAILURE";
reverseNames[93] = "SSH_MSG_CHANNEL_WINDOW_ADJUST";
reverseNames[94] = "SSH_MSG_CHANNEL_DATA";
reverseNames[95] = "SSH_MSG_CHANNEL_EXTENDED_DATA";
reverseNames[96] = "SSH_MSG_CHANNEL_EOF";
reverseNames[97] = "SSH_MSG_CHANNEL_CLOSE";
reverseNames[98] = "SSH_MSG_CHANNEL_REQUEST";
reverseNames[99] = "SSH_MSG_CHANNEL_SUCCESS";
reverseNames[100] = "SSH_MSG_CHANNEL_FAILURE";
}
public static final String getMessageName(int type)
{
String res = null;
if ((type >= 0) && (type < reverseNames.length))
{
res = reverseNames[type];
}
return (res == null) ? ("UNKNOWN MSG " + type) : res;
}
// public static final void debug(String tag, byte[] msg)
// {
// System.err.println(tag + " Type: " + msg[0] + ", LEN: " + msg.length);
//
// for (int i = 0; i < msg.length; i++)
// {
// if (((msg[i] >= 'a') && (msg[i] <= 'z')) || ((msg[i] >= 'A') && (msg[i] <= 'Z'))
// || ((msg[i] >= '0') && (msg[i] <= '9')) || (msg[i] == ' '))
// System.err.print((char) msg[i]);
// else
// System.err.print(".");
// }
// System.err.println();
// System.err.flush();
// }
}
|
Java
|
package com.trilead.ssh2.packets;
import java.io.IOException;
/**
* PacketUserauthInfoRequest.
*
* @author Christian Plattner, plattner@trilead.com
* @version $Id: PacketUserauthInfoRequest.java,v 1.1 2007/10/15 12:49:55 cplattne Exp $
*/
public class PacketUserauthInfoRequest
{
byte[] payload;
String name;
String instruction;
String languageTag;
int numPrompts;
String prompt[];
boolean echo[];
public PacketUserauthInfoRequest(byte payload[], int off, int len) throws IOException
{
this.payload = new byte[len];
System.arraycopy(payload, off, this.payload, 0, len);
TypesReader tr = new TypesReader(payload, off, len);
int packet_type = tr.readByte();
if (packet_type != Packets.SSH_MSG_USERAUTH_INFO_REQUEST)
throw new IOException("This is not a SSH_MSG_USERAUTH_INFO_REQUEST! (" + packet_type + ")");
name = tr.readString();
instruction = tr.readString();
languageTag = tr.readString();
numPrompts = tr.readUINT32();
prompt = new String[numPrompts];
echo = new boolean[numPrompts];
for (int i = 0; i < numPrompts; i++)
{
prompt[i] = tr.readString();
echo[i] = tr.readBoolean();
}
if (tr.remain() != 0)
throw new IOException("Padding in SSH_MSG_USERAUTH_INFO_REQUEST packet!");
}
public boolean[] getEcho()
{
return echo;
}
public String getInstruction()
{
return instruction;
}
public String getLanguageTag()
{
return languageTag;
}
public String getName()
{
return name;
}
public int getNumPrompts()
{
return numPrompts;
}
public String[] getPrompt()
{
return prompt;
}
}
|
Java
|
package com.trilead.ssh2.packets;
/**
* PacketUserauthRequestInteractive.
*
* @author Christian Plattner, plattner@trilead.com
* @version $Id: PacketUserauthRequestInteractive.java,v 1.1 2007/10/15 12:49:55 cplattne Exp $
*/
public class PacketUserauthRequestInteractive
{
byte[] payload;
String userName;
String serviceName;
String[] submethods;
public PacketUserauthRequestInteractive(String serviceName, String user, String[] submethods)
{
this.serviceName = serviceName;
this.userName = user;
this.submethods = submethods;
}
public byte[] getPayload()
{
if (payload == null)
{
TypesWriter tw = new TypesWriter();
tw.writeByte(Packets.SSH_MSG_USERAUTH_REQUEST);
tw.writeString(userName);
tw.writeString(serviceName);
tw.writeString("keyboard-interactive");
tw.writeString(""); // draft-ietf-secsh-newmodes-04.txt says that
// the language tag should be empty.
tw.writeNameList(submethods);
payload = tw.getBytes();
}
return payload;
}
}
|
Java
|
package com.trilead.ssh2.packets;
/**
* PacketChannelTrileadPing.
*
* @author Christian Plattner, plattner@trilead.com
* @version $Id: PacketChannelTrileadPing.java,v 1.1 2008/03/03 07:01:36
* cplattne Exp $
*/
public class PacketChannelTrileadPing
{
byte[] payload;
public int recipientChannelID;
public PacketChannelTrileadPing(int recipientChannelID)
{
this.recipientChannelID = recipientChannelID;
}
public byte[] getPayload()
{
if (payload == null)
{
TypesWriter tw = new TypesWriter();
tw.writeByte(Packets.SSH_MSG_CHANNEL_REQUEST);
tw.writeUINT32(recipientChannelID);
tw.writeString("trilead-ping");
tw.writeBoolean(true);
payload = tw.getBytes();
}
return payload;
}
}
|
Java
|
package com.trilead.ssh2.packets;
/**
* PacketOpenDirectTCPIPChannel.
*
* @author Christian Plattner, plattner@trilead.com
* @version $Id: PacketOpenDirectTCPIPChannel.java,v 1.1 2007/10/15 12:49:55 cplattne Exp $
*/
public class PacketOpenDirectTCPIPChannel
{
byte[] payload;
int channelID;
int initialWindowSize;
int maxPacketSize;
String host_to_connect;
int port_to_connect;
String originator_IP_address;
int originator_port;
public PacketOpenDirectTCPIPChannel(int channelID, int initialWindowSize, int maxPacketSize,
String host_to_connect, int port_to_connect, String originator_IP_address,
int originator_port)
{
this.channelID = channelID;
this.initialWindowSize = initialWindowSize;
this.maxPacketSize = maxPacketSize;
this.host_to_connect = host_to_connect;
this.port_to_connect = port_to_connect;
this.originator_IP_address = originator_IP_address;
this.originator_port = originator_port;
}
public byte[] getPayload()
{
if (payload == null)
{
TypesWriter tw = new TypesWriter();
tw.writeByte(Packets.SSH_MSG_CHANNEL_OPEN);
tw.writeString("direct-tcpip");
tw.writeUINT32(channelID);
tw.writeUINT32(initialWindowSize);
tw.writeUINT32(maxPacketSize);
tw.writeString(host_to_connect);
tw.writeUINT32(port_to_connect);
tw.writeString(originator_IP_address);
tw.writeUINT32(originator_port);
payload = tw.getBytes();
}
return payload;
}
}
|
Java
|
package com.trilead.ssh2.packets;
import java.io.IOException;
/**
* PacketOpenSessionChannel.
*
* @author Christian Plattner, plattner@trilead.com
* @version $Id: PacketOpenSessionChannel.java,v 1.1 2007/10/15 12:49:55 cplattne Exp $
*/
public class PacketOpenSessionChannel
{
byte[] payload;
int channelID;
int initialWindowSize;
int maxPacketSize;
public PacketOpenSessionChannel(int channelID, int initialWindowSize,
int maxPacketSize)
{
this.channelID = channelID;
this.initialWindowSize = initialWindowSize;
this.maxPacketSize = maxPacketSize;
}
public PacketOpenSessionChannel(byte payload[], int off, int len) throws IOException
{
this.payload = new byte[len];
System.arraycopy(payload, off, this.payload, 0, len);
TypesReader tr = new TypesReader(payload);
int packet_type = tr.readByte();
if (packet_type != Packets.SSH_MSG_CHANNEL_OPEN)
throw new IOException("This is not a SSH_MSG_CHANNEL_OPEN! ("
+ packet_type + ")");
channelID = tr.readUINT32();
initialWindowSize = tr.readUINT32();
maxPacketSize = tr.readUINT32();
if (tr.remain() != 0)
throw new IOException("Padding in SSH_MSG_CHANNEL_OPEN packet!");
}
public byte[] getPayload()
{
if (payload == null)
{
TypesWriter tw = new TypesWriter();
tw.writeByte(Packets.SSH_MSG_CHANNEL_OPEN);
tw.writeString("session");
tw.writeUINT32(channelID);
tw.writeUINT32(initialWindowSize);
tw.writeUINT32(maxPacketSize);
payload = tw.getBytes();
}
return payload;
}
}
|
Java
|
package com.trilead.ssh2.packets;
/**
* PacketSessionX11Request.
*
* @author Christian Plattner, plattner@trilead.com
* @version $Id: PacketSessionX11Request.java,v 1.1 2007/10/15 12:49:55 cplattne Exp $
*/
public class PacketSessionX11Request
{
byte[] payload;
public int recipientChannelID;
public boolean wantReply;
public boolean singleConnection;
String x11AuthenticationProtocol;
String x11AuthenticationCookie;
int x11ScreenNumber;
public PacketSessionX11Request(int recipientChannelID, boolean wantReply, boolean singleConnection,
String x11AuthenticationProtocol, String x11AuthenticationCookie, int x11ScreenNumber)
{
this.recipientChannelID = recipientChannelID;
this.wantReply = wantReply;
this.singleConnection = singleConnection;
this.x11AuthenticationProtocol = x11AuthenticationProtocol;
this.x11AuthenticationCookie = x11AuthenticationCookie;
this.x11ScreenNumber = x11ScreenNumber;
}
public byte[] getPayload()
{
if (payload == null)
{
TypesWriter tw = new TypesWriter();
tw.writeByte(Packets.SSH_MSG_CHANNEL_REQUEST);
tw.writeUINT32(recipientChannelID);
tw.writeString("x11-req");
tw.writeBoolean(wantReply);
tw.writeBoolean(singleConnection);
tw.writeString(x11AuthenticationProtocol);
tw.writeString(x11AuthenticationCookie);
tw.writeUINT32(x11ScreenNumber);
payload = tw.getBytes();
}
return payload;
}
}
|
Java
|
package com.trilead.ssh2.packets;
import com.trilead.ssh2.DHGexParameters;
/**
* PacketKexDhGexRequestOld.
*
* @author Christian Plattner, plattner@trilead.com
* @version $Id: PacketKexDhGexRequestOld.java,v 1.1 2007/10/15 12:49:55 cplattne Exp $
*/
public class PacketKexDhGexRequestOld
{
byte[] payload;
int n;
public PacketKexDhGexRequestOld(DHGexParameters para)
{
this.n = para.getPref_group_len();
}
public byte[] getPayload()
{
if (payload == null)
{
TypesWriter tw = new TypesWriter();
tw.writeByte(Packets.SSH_MSG_KEX_DH_GEX_REQUEST_OLD);
tw.writeUINT32(n);
payload = tw.getBytes();
}
return payload;
}
}
|
Java
|
package com.trilead.ssh2.packets;
import java.io.IOException;
/**
* PacketUserauthBanner.
*
* @author Christian Plattner, plattner@trilead.com
* @version $Id: PacketUserauthBanner.java,v 1.1 2007/10/15 12:49:55 cplattne Exp $
*/
public class PacketUserauthBanner
{
byte[] payload;
String message;
String language;
public PacketUserauthBanner(String message, String language)
{
this.message = message;
this.language = language;
}
public String getBanner()
{
return message;
}
public PacketUserauthBanner(byte payload[], int off, int len) throws IOException
{
this.payload = new byte[len];
System.arraycopy(payload, off, this.payload, 0, len);
TypesReader tr = new TypesReader(payload, off, len);
int packet_type = tr.readByte();
if (packet_type != Packets.SSH_MSG_USERAUTH_BANNER)
throw new IOException("This is not a SSH_MSG_USERAUTH_BANNER! (" + packet_type + ")");
message = tr.readString("UTF-8");
language = tr.readString();
if (tr.remain() != 0)
throw new IOException("Padding in SSH_MSG_USERAUTH_REQUEST packet!");
}
public byte[] getPayload()
{
if (payload == null)
{
TypesWriter tw = new TypesWriter();
tw.writeByte(Packets.SSH_MSG_USERAUTH_BANNER);
tw.writeString(message);
tw.writeString(language);
payload = tw.getBytes();
}
return payload;
}
}
|
Java
|
package com.trilead.ssh2.packets;
/**
* PacketUserauthInfoResponse.
*
* @author Christian Plattner, plattner@trilead.com
* @version $Id: PacketUserauthInfoResponse.java,v 1.1 2007/10/15 12:49:55 cplattne Exp $
*/
public class PacketUserauthInfoResponse
{
byte[] payload;
String[] responses;
public PacketUserauthInfoResponse(String[] responses)
{
this.responses = responses;
}
public byte[] getPayload()
{
if (payload == null)
{
TypesWriter tw = new TypesWriter();
tw.writeByte(Packets.SSH_MSG_USERAUTH_INFO_RESPONSE);
tw.writeUINT32(responses.length);
for (int i = 0; i < responses.length; i++)
tw.writeString(responses[i]);
payload = tw.getBytes();
}
return payload;
}
}
|
Java
|
package com.trilead.ssh2.packets;
/**
* PacketSessionPtyRequest.
*
* @author Christian Plattner, plattner@trilead.com
* @version $Id: PacketSessionPtyRequest.java,v 1.1 2007/10/15 12:49:55 cplattne Exp $
*/
public class PacketSessionPtyRequest
{
byte[] payload;
public int recipientChannelID;
public boolean wantReply;
public String term;
public int character_width;
public int character_height;
public int pixel_width;
public int pixel_height;
public byte[] terminal_modes;
public PacketSessionPtyRequest(int recipientChannelID, boolean wantReply, String term,
int character_width, int character_height, int pixel_width, int pixel_height,
byte[] terminal_modes)
{
this.recipientChannelID = recipientChannelID;
this.wantReply = wantReply;
this.term = term;
this.character_width = character_width;
this.character_height = character_height;
this.pixel_width = pixel_width;
this.pixel_height = pixel_height;
this.terminal_modes = terminal_modes;
}
public byte[] getPayload()
{
if (payload == null)
{
TypesWriter tw = new TypesWriter();
tw.writeByte(Packets.SSH_MSG_CHANNEL_REQUEST);
tw.writeUINT32(recipientChannelID);
tw.writeString("pty-req");
tw.writeBoolean(wantReply);
tw.writeString(term);
tw.writeUINT32(character_width);
tw.writeUINT32(character_height);
tw.writeUINT32(pixel_width);
tw.writeUINT32(pixel_height);
tw.writeString(terminal_modes, 0, terminal_modes.length);
payload = tw.getBytes();
}
return payload;
}
}
|
Java
|
package com.trilead.ssh2.packets;
import java.io.IOException;
/**
* PacketDisconnect.
*
* @author Christian Plattner, plattner@trilead.com
* @version $Id: PacketDisconnect.java,v 1.2 2008/04/01 12:38:09 cplattne Exp $
*/
public class PacketDisconnect
{
byte[] payload;
int reason;
String desc;
String lang;
public PacketDisconnect(byte payload[], int off, int len) throws IOException
{
this.payload = new byte[len];
System.arraycopy(payload, off, this.payload, 0, len);
TypesReader tr = new TypesReader(payload, off, len);
int packet_type = tr.readByte();
if (packet_type != Packets.SSH_MSG_DISCONNECT)
throw new IOException("This is not a Disconnect Packet! (" + packet_type + ")");
reason = tr.readUINT32();
desc = tr.readString();
lang = tr.readString();
}
public PacketDisconnect(int reason, String desc, String lang)
{
this.reason = reason;
this.desc = desc;
this.lang = lang;
}
public byte[] getPayload()
{
if (payload == null)
{
TypesWriter tw = new TypesWriter();
tw.writeByte(Packets.SSH_MSG_DISCONNECT);
tw.writeUINT32(reason);
tw.writeString(desc);
tw.writeString(lang);
payload = tw.getBytes();
}
return payload;
}
}
|
Java
|
package com.trilead.ssh2.packets;
import java.io.IOException;
/**
* PacketServiceAccept.
*
* @author Christian Plattner, plattner@trilead.com
* @version $Id: PacketServiceAccept.java,v 1.2 2008/04/01 12:38:09 cplattne Exp $
*/
public class PacketServiceAccept
{
byte[] payload;
String serviceName;
public PacketServiceAccept(String serviceName)
{
this.serviceName = serviceName;
}
public PacketServiceAccept(byte payload[], int off, int len) throws IOException
{
this.payload = new byte[len];
System.arraycopy(payload, off, this.payload, 0, len);
TypesReader tr = new TypesReader(payload, off, len);
int packet_type = tr.readByte();
if (packet_type != Packets.SSH_MSG_SERVICE_ACCEPT)
throw new IOException("This is not a SSH_MSG_SERVICE_ACCEPT! (" + packet_type + ")");
/* Be clever in case the server is not. Some servers seem to violate RFC4253 */
if (tr.remain() > 0)
{
serviceName = tr.readString();
}
else
{
serviceName = "";
}
if (tr.remain() != 0)
throw new IOException("Padding in SSH_MSG_SERVICE_ACCEPT packet!");
}
public byte[] getPayload()
{
if (payload == null)
{
TypesWriter tw = new TypesWriter();
tw.writeByte(Packets.SSH_MSG_SERVICE_ACCEPT);
tw.writeString(serviceName);
payload = tw.getBytes();
}
return payload;
}
}
|
Java
|
package com.trilead.ssh2.packets;
import java.math.BigInteger;
/**
* PacketKexDHInit.
*
* @author Christian Plattner, plattner@trilead.com
* @version $Id: PacketKexDHInit.java,v 1.1 2007/10/15 12:49:55 cplattne Exp $
*/
public class PacketKexDHInit
{
byte[] payload;
BigInteger e;
public PacketKexDHInit(BigInteger e)
{
this.e = e;
}
public byte[] getPayload()
{
if (payload == null)
{
TypesWriter tw = new TypesWriter();
tw.writeByte(Packets.SSH_MSG_KEXDH_INIT);
tw.writeMPInt(e);
payload = tw.getBytes();
}
return payload;
}
}
|
Java
|
package com.trilead.ssh2.packets;
import java.io.IOException;
/**
* PacketChannelOpenConfirmation.
*
* @author Christian Plattner, plattner@trilead.com
* @version $Id: PacketChannelOpenConfirmation.java,v 1.1 2007/10/15 12:49:55 cplattne Exp $
*/
public class PacketChannelOpenConfirmation
{
byte[] payload;
public int recipientChannelID;
public int senderChannelID;
public int initialWindowSize;
public int maxPacketSize;
public PacketChannelOpenConfirmation(int recipientChannelID, int senderChannelID, int initialWindowSize,
int maxPacketSize)
{
this.recipientChannelID = recipientChannelID;
this.senderChannelID = senderChannelID;
this.initialWindowSize = initialWindowSize;
this.maxPacketSize = maxPacketSize;
}
public PacketChannelOpenConfirmation(byte payload[], int off, int len) throws IOException
{
this.payload = new byte[len];
System.arraycopy(payload, off, this.payload, 0, len);
TypesReader tr = new TypesReader(payload, off, len);
int packet_type = tr.readByte();
if (packet_type != Packets.SSH_MSG_CHANNEL_OPEN_CONFIRMATION)
throw new IOException(
"This is not a SSH_MSG_CHANNEL_OPEN_CONFIRMATION! ("
+ packet_type + ")");
recipientChannelID = tr.readUINT32();
senderChannelID = tr.readUINT32();
initialWindowSize = tr.readUINT32();
maxPacketSize = tr.readUINT32();
if (tr.remain() != 0)
throw new IOException("Padding in SSH_MSG_CHANNEL_OPEN_CONFIRMATION packet!");
}
public byte[] getPayload()
{
if (payload == null)
{
TypesWriter tw = new TypesWriter();
tw.writeByte(Packets.SSH_MSG_CHANNEL_OPEN_CONFIRMATION);
tw.writeUINT32(recipientChannelID);
tw.writeUINT32(senderChannelID);
tw.writeUINT32(initialWindowSize);
tw.writeUINT32(maxPacketSize);
payload = tw.getBytes();
}
return payload;
}
}
|
Java
|
package com.trilead.ssh2.packets;
import java.io.IOException;
import java.security.SecureRandom;
import com.trilead.ssh2.compression.CompressionFactory;
import com.trilead.ssh2.crypto.CryptoWishList;
import com.trilead.ssh2.transport.KexParameters;
/**
* PacketKexInit.
*
* @author Christian Plattner, plattner@trilead.com
* @version $Id: PacketKexInit.java,v 1.1 2007/10/15 12:49:55 cplattne Exp $
*/
public class PacketKexInit
{
byte[] payload;
KexParameters kp = new KexParameters();
public PacketKexInit(CryptoWishList cwl, SecureRandom rnd)
{
kp.cookie = new byte[16];
rnd.nextBytes(kp.cookie);
kp.kex_algorithms = cwl.kexAlgorithms;
kp.server_host_key_algorithms = cwl.serverHostKeyAlgorithms;
kp.encryption_algorithms_client_to_server = cwl.c2s_enc_algos;
kp.encryption_algorithms_server_to_client = cwl.s2c_enc_algos;
kp.mac_algorithms_client_to_server = cwl.c2s_mac_algos;
kp.mac_algorithms_server_to_client = cwl.s2c_mac_algos;
kp.compression_algorithms_client_to_server = cwl.c2s_comp_algos;
kp.compression_algorithms_server_to_client = cwl.s2c_comp_algos;
kp.languages_client_to_server = new String[] {};
kp.languages_server_to_client = new String[] {};
kp.first_kex_packet_follows = false;
kp.reserved_field1 = 0;
}
public PacketKexInit(byte payload[], int off, int len) throws IOException
{
this.payload = new byte[len];
System.arraycopy(payload, off, this.payload, 0, len);
TypesReader tr = new TypesReader(payload, off, len);
int packet_type = tr.readByte();
if (packet_type != Packets.SSH_MSG_KEXINIT)
throw new IOException("This is not a KexInitPacket! (" + packet_type + ")");
kp.cookie = tr.readBytes(16);
kp.kex_algorithms = tr.readNameList();
kp.server_host_key_algorithms = tr.readNameList();
kp.encryption_algorithms_client_to_server = tr.readNameList();
kp.encryption_algorithms_server_to_client = tr.readNameList();
kp.mac_algorithms_client_to_server = tr.readNameList();
kp.mac_algorithms_server_to_client = tr.readNameList();
kp.compression_algorithms_client_to_server = tr.readNameList();
kp.compression_algorithms_server_to_client = tr.readNameList();
kp.languages_client_to_server = tr.readNameList();
kp.languages_server_to_client = tr.readNameList();
kp.first_kex_packet_follows = tr.readBoolean();
kp.reserved_field1 = tr.readUINT32();
if (tr.remain() != 0)
throw new IOException("Padding in KexInitPacket!");
}
public byte[] getPayload()
{
if (payload == null)
{
TypesWriter tw = new TypesWriter();
tw.writeByte(Packets.SSH_MSG_KEXINIT);
tw.writeBytes(kp.cookie, 0, 16);
tw.writeNameList(kp.kex_algorithms);
tw.writeNameList(kp.server_host_key_algorithms);
tw.writeNameList(kp.encryption_algorithms_client_to_server);
tw.writeNameList(kp.encryption_algorithms_server_to_client);
tw.writeNameList(kp.mac_algorithms_client_to_server);
tw.writeNameList(kp.mac_algorithms_server_to_client);
tw.writeNameList(kp.compression_algorithms_client_to_server);
tw.writeNameList(kp.compression_algorithms_server_to_client);
tw.writeNameList(kp.languages_client_to_server);
tw.writeNameList(kp.languages_server_to_client);
tw.writeBoolean(kp.first_kex_packet_follows);
tw.writeUINT32(kp.reserved_field1);
payload = tw.getBytes();
}
return payload;
}
public KexParameters getKexParameters()
{
return kp;
}
public String[] getCompression_algorithms_client_to_server()
{
return kp.compression_algorithms_client_to_server;
}
public String[] getCompression_algorithms_server_to_client()
{
return kp.compression_algorithms_server_to_client;
}
public byte[] getCookie()
{
return kp.cookie;
}
public String[] getEncryption_algorithms_client_to_server()
{
return kp.encryption_algorithms_client_to_server;
}
public String[] getEncryption_algorithms_server_to_client()
{
return kp.encryption_algorithms_server_to_client;
}
public boolean isFirst_kex_packet_follows()
{
return kp.first_kex_packet_follows;
}
public String[] getKex_algorithms()
{
return kp.kex_algorithms;
}
public String[] getLanguages_client_to_server()
{
return kp.languages_client_to_server;
}
public String[] getLanguages_server_to_client()
{
return kp.languages_server_to_client;
}
public String[] getMac_algorithms_client_to_server()
{
return kp.mac_algorithms_client_to_server;
}
public String[] getMac_algorithms_server_to_client()
{
return kp.mac_algorithms_server_to_client;
}
public int getReserved_field1()
{
return kp.reserved_field1;
}
public String[] getServer_host_key_algorithms()
{
return kp.server_host_key_algorithms;
}
}
|
Java
|
package com.trilead.ssh2.packets;
/**
* PacketGlobalTrileadPing.
*
* @author Christian Plattner, plattner@trilead.com
* @version $Id: PacketGlobalTrileadPing.java,v 1.1 2008/03/03 07:01:36 cplattne Exp $
*/
public class PacketGlobalTrileadPing
{
byte[] payload;
public PacketGlobalTrileadPing()
{
}
public byte[] getPayload()
{
if (payload == null)
{
TypesWriter tw = new TypesWriter();
tw.writeByte(Packets.SSH_MSG_GLOBAL_REQUEST);
tw.writeString("trilead-ping");
tw.writeBoolean(true);
payload = tw.getBytes();
}
return payload;
}
}
|
Java
|
package com.trilead.ssh2.packets;
/**
* PacketGlobalForwardRequest.
*
* @author Christian Plattner, plattner@trilead.com
* @version $Id: PacketGlobalForwardRequest.java,v 1.1 2007/10/15 12:49:55 cplattne Exp $
*/
public class PacketGlobalForwardRequest
{
byte[] payload;
public boolean wantReply;
public String bindAddress;
public int bindPort;
public PacketGlobalForwardRequest(boolean wantReply, String bindAddress, int bindPort)
{
this.wantReply = wantReply;
this.bindAddress = bindAddress;
this.bindPort = bindPort;
}
public byte[] getPayload()
{
if (payload == null)
{
TypesWriter tw = new TypesWriter();
tw.writeByte(Packets.SSH_MSG_GLOBAL_REQUEST);
tw.writeString("tcpip-forward");
tw.writeBoolean(wantReply);
tw.writeString(bindAddress);
tw.writeUINT32(bindPort);
payload = tw.getBytes();
}
return payload;
}
}
|
Java
|
package com.trilead.ssh2;
import java.io.IOException;
import java.net.InetSocketAddress;
import com.trilead.ssh2.channel.ChannelManager;
import com.trilead.ssh2.channel.LocalAcceptThread;
/**
* A <code>LocalPortForwarder</code> forwards TCP/IP connections to a local
* port via the secure tunnel to another host (which may or may not be identical
* to the remote SSH-2 server). Checkout {@link Connection#createLocalPortForwarder(int, String, int)}
* on how to create one.
*
* @author Christian Plattner, plattner@trilead.com
* @version $Id: LocalPortForwarder.java,v 1.1 2007/10/15 12:49:56 cplattne Exp $
*/
public class LocalPortForwarder
{
ChannelManager cm;
String host_to_connect;
int port_to_connect;
LocalAcceptThread lat;
LocalPortForwarder(ChannelManager cm, int local_port, String host_to_connect, int port_to_connect)
throws IOException
{
this.cm = cm;
this.host_to_connect = host_to_connect;
this.port_to_connect = port_to_connect;
lat = new LocalAcceptThread(cm, local_port, host_to_connect, port_to_connect);
lat.setDaemon(true);
lat.start();
}
LocalPortForwarder(ChannelManager cm, InetSocketAddress addr, String host_to_connect, int port_to_connect)
throws IOException
{
this.cm = cm;
this.host_to_connect = host_to_connect;
this.port_to_connect = port_to_connect;
lat = new LocalAcceptThread(cm, addr, host_to_connect, port_to_connect);
lat.setDaemon(true);
lat.start();
}
/**
* Stop TCP/IP forwarding of newly arriving connections.
*
* @throws IOException
*/
public void close() throws IOException
{
lat.stopWorking();
}
}
|
Java
|
package com.trilead.ssh2;
import java.io.CharArrayWriter;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.SocketTimeoutException;
import java.security.SecureRandom;
import java.util.Vector;
import com.trilead.ssh2.auth.AuthenticationManager;
import com.trilead.ssh2.channel.ChannelManager;
import com.trilead.ssh2.crypto.CryptoWishList;
import com.trilead.ssh2.crypto.cipher.BlockCipherFactory;
import com.trilead.ssh2.crypto.digest.MAC;
import com.trilead.ssh2.log.Logger;
import com.trilead.ssh2.packets.PacketIgnore;
import com.trilead.ssh2.transport.KexManager;
import com.trilead.ssh2.transport.TransportManager;
import com.trilead.ssh2.util.TimeoutService;
import com.trilead.ssh2.util.TimeoutService.TimeoutToken;
/**
* A <code>Connection</code> is used to establish an encrypted TCP/IP
* connection to a SSH-2 server.
* <p>
* Typically, one
* <ol>
* <li>creates a {@link #Connection(String) Connection} object.</li>
* <li>calls the {@link #connect() connect()} method.</li>
* <li>calls some of the authentication methods (e.g.,
* {@link #authenticateWithPublicKey(String, File, String) authenticateWithPublicKey()}).</li>
* <li>calls one or several times the {@link #openSession() openSession()}
* method.</li>
* <li>finally, one must close the connection and release resources with the
* {@link #close() close()} method.</li>
* </ol>
*
* @author Christian Plattner, plattner@trilead.com
* @version $Id: Connection.java,v 1.3 2008/04/01 12:38:09 cplattne Exp $
*/
public class Connection
{
/**
* The identifier presented to the SSH-2 server.
*/
public final static String identification = "TrileadSSH2Java_213";
/**
* Will be used to generate all random data needed for the current
* connection. Note: SecureRandom.nextBytes() is thread safe.
*/
private SecureRandom generator;
/**
* Unless you know what you are doing, you will never need this.
*
* @return The list of supported cipher algorithms by this implementation.
*/
public static synchronized String[] getAvailableCiphers()
{
return BlockCipherFactory.getDefaultCipherList();
}
/**
* Unless you know what you are doing, you will never need this.
*
* @return The list of supported MAC algorthims by this implementation.
*/
public static synchronized String[] getAvailableMACs()
{
return MAC.getMacList();
}
/**
* Unless you know what you are doing, you will never need this.
*
* @return The list of supported server host key algorthims by this
* implementation.
*/
public static synchronized String[] getAvailableServerHostKeyAlgorithms()
{
return KexManager.getDefaultServerHostkeyAlgorithmList();
}
private AuthenticationManager am;
private boolean authenticated = false;
private boolean compression = false;
private ChannelManager cm;
private CryptoWishList cryptoWishList = new CryptoWishList();
private DHGexParameters dhgexpara = new DHGexParameters();
private final String hostname;
private final int port;
private TransportManager tm;
private boolean tcpNoDelay = false;
private ProxyData proxyData = null;
private Vector<ConnectionMonitor> connectionMonitors = new Vector<ConnectionMonitor>();
/**
* Prepares a fresh <code>Connection</code> object which can then be used
* to establish a connection to the specified SSH-2 server.
* <p>
* Same as {@link #Connection(String, int) Connection(hostname, 22)}.
*
* @param hostname
* the hostname of the SSH-2 server.
*/
public Connection(String hostname)
{
this(hostname, 22);
}
/**
* Prepares a fresh <code>Connection</code> object which can then be used
* to establish a connection to the specified SSH-2 server.
*
* @param hostname
* the host where we later want to connect to.
* @param port
* port on the server, normally 22.
*/
public Connection(String hostname, int port)
{
this.hostname = hostname;
this.port = port;
}
/**
* After a successful connect, one has to authenticate oneself. This method
* is based on DSA (it uses DSA to sign a challenge sent by the server).
* <p>
* If the authentication phase is complete, <code>true</code> will be
* returned. If the server does not accept the request (or if further
* authentication steps are needed), <code>false</code> is returned and
* one can retry either by using this or any other authentication method
* (use the <code>getRemainingAuthMethods</code> method to get a list of
* the remaining possible methods).
*
* @param user
* A <code>String</code> holding the username.
* @param pem
* A <code>String</code> containing the DSA private key of the
* user in OpenSSH key format (PEM, you can't miss the
* "-----BEGIN DSA PRIVATE KEY-----" tag). The string may contain
* linefeeds.
* @param password
* If the PEM string is 3DES encrypted ("DES-EDE3-CBC"), then you
* must specify the password. Otherwise, this argument will be
* ignored and can be set to <code>null</code>.
*
* @return whether the connection is now authenticated.
* @throws IOException
*
* @deprecated You should use one of the
* {@link #authenticateWithPublicKey(String, File, String) authenticateWithPublicKey()}
* methods, this method is just a wrapper for it and will
* disappear in future builds.
*
*/
public synchronized boolean authenticateWithDSA(String user, String pem, String password) throws IOException
{
if (tm == null)
throw new IllegalStateException("Connection is not established!");
if (authenticated)
throw new IllegalStateException("Connection is already authenticated!");
if (am == null)
am = new AuthenticationManager(tm);
if (cm == null)
cm = new ChannelManager(tm);
if (user == null)
throw new IllegalArgumentException("user argument is null");
if (pem == null)
throw new IllegalArgumentException("pem argument is null");
authenticated = am.authenticatePublicKey(user, pem.toCharArray(), password, getOrCreateSecureRND());
return authenticated;
}
/**
* A wrapper that calls
* {@link #authenticateWithKeyboardInteractive(String, String[], InteractiveCallback)
* authenticateWithKeyboardInteractivewith} a <code>null</code> submethod
* list.
*
* @param user
* A <code>String</code> holding the username.
* @param cb
* An <code>InteractiveCallback</code> which will be used to
* determine the responses to the questions asked by the server.
* @return whether the connection is now authenticated.
* @throws IOException
*/
public synchronized boolean authenticateWithKeyboardInteractive(String user, InteractiveCallback cb)
throws IOException
{
return authenticateWithKeyboardInteractive(user, null, cb);
}
/**
* After a successful connect, one has to authenticate oneself. This method
* is based on "keyboard-interactive", specified in
* draft-ietf-secsh-auth-kbdinteract-XX. Basically, you have to define a
* callback object which will be feeded with challenges generated by the
* server. Answers are then sent back to the server. It is possible that the
* callback will be called several times during the invocation of this
* method (e.g., if the server replies to the callback's answer(s) with
* another challenge...)
* <p>
* If the authentication phase is complete, <code>true</code> will be
* returned. If the server does not accept the request (or if further
* authentication steps are needed), <code>false</code> is returned and
* one can retry either by using this or any other authentication method
* (use the <code>getRemainingAuthMethods</code> method to get a list of
* the remaining possible methods).
* <p>
* Note: some SSH servers advertise "keyboard-interactive", however, any
* interactive request will be denied (without having sent any challenge to
* the client).
*
* @param user
* A <code>String</code> holding the username.
* @param submethods
* An array of submethod names, see
* draft-ietf-secsh-auth-kbdinteract-XX. May be <code>null</code>
* to indicate an empty list.
* @param cb
* An <code>InteractiveCallback</code> which will be used to
* determine the responses to the questions asked by the server.
*
* @return whether the connection is now authenticated.
* @throws IOException
*/
public synchronized boolean authenticateWithKeyboardInteractive(String user, String[] submethods,
InteractiveCallback cb) throws IOException
{
if (cb == null)
throw new IllegalArgumentException("Callback may not ne NULL!");
if (tm == null)
throw new IllegalStateException("Connection is not established!");
if (authenticated)
throw new IllegalStateException("Connection is already authenticated!");
if (am == null)
am = new AuthenticationManager(tm);
if (cm == null)
cm = new ChannelManager(tm);
if (user == null)
throw new IllegalArgumentException("user argument is null");
authenticated = am.authenticateInteractive(user, submethods, cb);
return authenticated;
}
/**
* After a successful connect, one has to authenticate oneself. This method
* sends username and password to the server.
* <p>
* If the authentication phase is complete, <code>true</code> will be
* returned. If the server does not accept the request (or if further
* authentication steps are needed), <code>false</code> is returned and
* one can retry either by using this or any other authentication method
* (use the <code>getRemainingAuthMethods</code> method to get a list of
* the remaining possible methods).
* <p>
* Note: if this method fails, then please double-check that it is actually
* offered by the server (use
* {@link #getRemainingAuthMethods(String) getRemainingAuthMethods()}.
* <p>
* Often, password authentication is disabled, but users are not aware of
* it. Many servers only offer "publickey" and "keyboard-interactive".
* However, even though "keyboard-interactive" *feels* like password
* authentication (e.g., when using the putty or openssh clients) it is
* *not* the same mechanism.
*
* @param user
* @param password
* @return if the connection is now authenticated.
* @throws IOException
*/
public synchronized boolean authenticateWithPassword(String user, String password) throws IOException
{
if (tm == null)
throw new IllegalStateException("Connection is not established!");
if (authenticated)
throw new IllegalStateException("Connection is already authenticated!");
if (am == null)
am = new AuthenticationManager(tm);
if (cm == null)
cm = new ChannelManager(tm);
if (user == null)
throw new IllegalArgumentException("user argument is null");
if (password == null)
throw new IllegalArgumentException("password argument is null");
authenticated = am.authenticatePassword(user, password);
return authenticated;
}
/**
* After a successful connect, one has to authenticate oneself. This method
* can be used to explicitly use the special "none" authentication method
* (where only a username has to be specified).
* <p>
* Note 1: The "none" method may always be tried by clients, however as by
* the specs, the server will not explicitly announce it. In other words,
* the "none" token will never show up in the list returned by
* {@link #getRemainingAuthMethods(String)}.
* <p>
* Note 2: no matter which one of the authenticateWithXXX() methods you
* call, the library will always issue exactly one initial "none"
* authentication request to retrieve the initially allowed list of
* authentication methods by the server. Please read RFC 4252 for the
* details.
* <p>
* If the authentication phase is complete, <code>true</code> will be
* returned. If further authentication steps are needed, <code>false</code>
* is returned and one can retry by any other authentication method (use the
* <code>getRemainingAuthMethods</code> method to get a list of the
* remaining possible methods).
*
* @param user
* @return if the connection is now authenticated.
* @throws IOException
*/
public synchronized boolean authenticateWithNone(String user) throws IOException
{
if (tm == null)
throw new IllegalStateException("Connection is not established!");
if (authenticated)
throw new IllegalStateException("Connection is already authenticated!");
if (am == null)
am = new AuthenticationManager(tm);
if (cm == null)
cm = new ChannelManager(tm);
if (user == null)
throw new IllegalArgumentException("user argument is null");
/* Trigger the sending of the PacketUserauthRequestNone packet */
/* (if not already done) */
authenticated = am.authenticateNone(user);
return authenticated;
}
/**
* After a successful connect, one has to authenticate oneself. The
* authentication method "publickey" works by signing a challenge sent by
* the server. The signature is either DSA or RSA based - it just depends on
* the type of private key you specify, either a DSA or RSA private key in
* PEM format. And yes, this is may seem to be a little confusing, the
* method is called "publickey" in the SSH-2 protocol specification, however
* since we need to generate a signature, you actually have to supply a
* private key =).
* <p>
* The private key contained in the PEM file may also be encrypted
* ("Proc-Type: 4,ENCRYPTED"). The library supports DES-CBC and DES-EDE3-CBC
* encryption, as well as the more exotic PEM encrpytions AES-128-CBC,
* AES-192-CBC and AES-256-CBC.
* <p>
* If the authentication phase is complete, <code>true</code> will be
* returned. If the server does not accept the request (or if further
* authentication steps are needed), <code>false</code> is returned and
* one can retry either by using this or any other authentication method
* (use the <code>getRemainingAuthMethods</code> method to get a list of
* the remaining possible methods).
* <p>
* NOTE PUTTY USERS: Event though your key file may start with
* "-----BEGIN..." it is not in the expected format. You have to convert it
* to the OpenSSH key format by using the "puttygen" tool (can be downloaded
* from the Putty website). Simply load your key and then use the
* "Conversions/Export OpenSSH key" functionality to get a proper PEM file.
*
* @param user
* A <code>String</code> holding the username.
* @param pemPrivateKey
* A <code>char[]</code> containing a DSA or RSA private key of
* the user in OpenSSH key format (PEM, you can't miss the
* "-----BEGIN DSA PRIVATE KEY-----" or "-----BEGIN RSA PRIVATE
* KEY-----" tag). The char array may contain
* linebreaks/linefeeds.
* @param password
* If the PEM structure is encrypted ("Proc-Type: 4,ENCRYPTED")
* then you must specify a password. Otherwise, this argument
* will be ignored and can be set to <code>null</code>.
*
* @return whether the connection is now authenticated.
* @throws IOException
*/
public synchronized boolean authenticateWithPublicKey(String user, char[] pemPrivateKey, String password)
throws IOException
{
if (tm == null)
throw new IllegalStateException("Connection is not established!");
if (authenticated)
throw new IllegalStateException("Connection is already authenticated!");
if (am == null)
am = new AuthenticationManager(tm);
if (cm == null)
cm = new ChannelManager(tm);
if (user == null)
throw new IllegalArgumentException("user argument is null");
if (pemPrivateKey == null)
throw new IllegalArgumentException("pemPrivateKey argument is null");
authenticated = am.authenticatePublicKey(user, pemPrivateKey, password, getOrCreateSecureRND());
return authenticated;
}
/**
* After a successful connect, one has to authenticate oneself. The
* authentication method "publickey" works by signing a challenge sent by
* the server. The signature is either DSA or RSA based - it just depends on
* the type of private key you specify, either a DSA or RSA private key in
* PEM format. And yes, this is may seem to be a little confusing, the
* method is called "publickey" in the SSH-2 protocol specification, however
* since we need to generate a signature, you actually have to supply a
* private key =).
* <p>
* If the authentication phase is complete, <code>true</code> will be
* returned. If the server does not accept the request (or if further
* authentication steps are needed), <code>false</code> is returned and
* one can retry either by using this or any other authentication method
* (use the <code>getRemainingAuthMethods</code> method to get a list of
* the remaining possible methods).
*
* @param user
* A <code>String</code> holding the username.
* @param key
* A <code>RSAPrivateKey</code> or <code>DSAPrivateKey</code>
* containing a DSA or RSA private key of
* the user in Trilead object format.
*
* @return whether the connection is now authenticated.
* @throws IOException
*/
public synchronized boolean authenticateWithPublicKey(String user, Object key)
throws IOException
{
if (tm == null)
throw new IllegalStateException("Connection is not established!");
if (authenticated)
throw new IllegalStateException("Connection is already authenticated!");
if (am == null)
am = new AuthenticationManager(tm);
if (cm == null)
cm = new ChannelManager(tm);
if (user == null)
throw new IllegalArgumentException("user argument is null");
if (key == null)
throw new IllegalArgumentException("Key argument is null");
authenticated = am.authenticatePublicKey(user, key, getOrCreateSecureRND());
return authenticated;
}
/**
* A convenience wrapper function which reads in a private key (PEM format,
* either DSA or RSA) and then calls
* <code>authenticateWithPublicKey(String, char[], String)</code>.
* <p>
* NOTE PUTTY USERS: Event though your key file may start with
* "-----BEGIN..." it is not in the expected format. You have to convert it
* to the OpenSSH key format by using the "puttygen" tool (can be downloaded
* from the Putty website). Simply load your key and then use the
* "Conversions/Export OpenSSH key" functionality to get a proper PEM file.
*
* @param user
* A <code>String</code> holding the username.
* @param pemFile
* A <code>File</code> object pointing to a file containing a
* DSA or RSA private key of the user in OpenSSH key format (PEM,
* you can't miss the "-----BEGIN DSA PRIVATE KEY-----" or
* "-----BEGIN RSA PRIVATE KEY-----" tag).
* @param password
* If the PEM file is encrypted then you must specify the
* password. Otherwise, this argument will be ignored and can be
* set to <code>null</code>.
*
* @return whether the connection is now authenticated.
* @throws IOException
*/
public synchronized boolean authenticateWithPublicKey(String user, File pemFile, String password)
throws IOException
{
if (pemFile == null)
throw new IllegalArgumentException("pemFile argument is null");
char[] buff = new char[256];
CharArrayWriter cw = new CharArrayWriter();
FileReader fr = new FileReader(pemFile);
while (true)
{
int len = fr.read(buff);
if (len < 0)
break;
cw.write(buff, 0, len);
}
fr.close();
return authenticateWithPublicKey(user, cw.toCharArray(), password);
}
/**
* Add a {@link ConnectionMonitor} to this connection. Can be invoked at any
* time, but it is best to add connection monitors before invoking
* <code>connect()</code> to avoid glitches (e.g., you add a connection
* monitor after a successful connect(), but the connection has died in the
* mean time. Then, your connection monitor won't be notified.)
* <p>
* You can add as many monitors as you like.
*
* @see ConnectionMonitor
*
* @param cmon
* An object implementing the <code>ConnectionMonitor</code>
* interface.
*/
public synchronized void addConnectionMonitor(ConnectionMonitor cmon)
{
if (cmon == null)
throw new IllegalArgumentException("cmon argument is null");
connectionMonitors.addElement(cmon);
if (tm != null)
tm.setConnectionMonitors(connectionMonitors);
}
/**
* Controls whether compression is used on the link or not.
* <p>
* Note: This can only be called before connect()
* @param enabled whether to enable compression
* @throws IOException
*/
public synchronized void setCompression(boolean enabled) throws IOException {
if (tm != null)
throw new IOException("Connection to " + hostname + " is already in connected state!");
compression = enabled;
}
/**
* Close the connection to the SSH-2 server. All assigned sessions will be
* closed, too. Can be called at any time. Don't forget to call this once
* you don't need a connection anymore - otherwise the receiver thread may
* run forever.
*/
public synchronized void close()
{
Throwable t = new Throwable("Closed due to user request.");
close(t, false);
}
private void close(Throwable t, boolean hard)
{
if (cm != null)
cm.closeAllChannels();
if (tm != null)
{
tm.close(t, hard == false);
tm = null;
}
am = null;
cm = null;
authenticated = false;
}
/**
* Same as
* {@link #connect(ServerHostKeyVerifier, int, int) connect(null, 0, 0)}.
*
* @return see comments for the
* {@link #connect(ServerHostKeyVerifier, int, int) connect(ServerHostKeyVerifier, int, int)}
* method.
* @throws IOException
*/
public synchronized ConnectionInfo connect() throws IOException
{
return connect(null, 0, 0);
}
/**
* Same as
* {@link #connect(ServerHostKeyVerifier, int, int) connect(verifier, 0, 0)}.
*
* @return see comments for the
* {@link #connect(ServerHostKeyVerifier, int, int) connect(ServerHostKeyVerifier, int, int)}
* method.
* @throws IOException
*/
public synchronized ConnectionInfo connect(ServerHostKeyVerifier verifier) throws IOException
{
return connect(verifier, 0, 0);
}
/**
* Connect to the SSH-2 server and, as soon as the server has presented its
* host key, use the
* {@link ServerHostKeyVerifier#verifyServerHostKey(String, int, String,
* byte[]) ServerHostKeyVerifier.verifyServerHostKey()} method of the
* <code>verifier</code> to ask for permission to proceed. If
* <code>verifier</code> is <code>null</code>, then any host key will
* be accepted - this is NOT recommended, since it makes man-in-the-middle
* attackes VERY easy (somebody could put a proxy SSH server between you and
* the real server).
* <p>
* Note: The verifier will be called before doing any crypto calculations
* (i.e., diffie-hellman). Therefore, if you don't like the presented host
* key then no CPU cycles are wasted (and the evil server has less
* information about us).
* <p>
* However, it is still possible that the server presented a fake host key:
* the server cheated (typically a sign for a man-in-the-middle attack) and
* is not able to generate a signature that matches its host key. Don't
* worry, the library will detect such a scenario later when checking the
* signature (the signature cannot be checked before having completed the
* diffie-hellman exchange).
* <p>
* Note 2: The {@link ServerHostKeyVerifier#verifyServerHostKey(String, int,
* String, byte[]) ServerHostKeyVerifier.verifyServerHostKey()} method will
* *NOT* be called from the current thread, the call is being made from a
* background thread (there is a background dispatcher thread for every
* established connection).
* <p>
* Note 3: This method will block as long as the key exchange of the
* underlying connection has not been completed (and you have not specified
* any timeouts).
* <p>
* Note 4: If you want to re-use a connection object that was successfully
* connected, then you must call the {@link #close()} method before invoking
* <code>connect()</code> again.
*
* @param verifier
* An object that implements the {@link ServerHostKeyVerifier}
* interface. Pass <code>null</code> to accept any server host
* key - NOT recommended.
*
* @param connectTimeout
* Connect the underlying TCP socket to the server with the given
* timeout value (non-negative, in milliseconds). Zero means no
* timeout. If a proxy is being used (see
* {@link #setProxyData(ProxyData)}), then this timeout is used
* for the connection establishment to the proxy.
*
* @param kexTimeout
* Timeout for complete connection establishment (non-negative,
* in milliseconds). Zero means no timeout. The timeout counts
* from the moment you invoke the connect() method and is
* cancelled as soon as the first key-exchange round has
* finished. It is possible that the timeout event will be fired
* during the invocation of the <code>verifier</code> callback,
* but it will only have an effect after the
* <code>verifier</code> returns.
*
* @return A {@link ConnectionInfo} object containing the details of the
* established connection.
*
* @throws IOException
* If any problem occurs, e.g., the server's host key is not
* accepted by the <code>verifier</code> or there is problem
* during the initial crypto setup (e.g., the signature sent by
* the server is wrong).
* <p>
* In case of a timeout (either connectTimeout or kexTimeout) a
* SocketTimeoutException is thrown.
* <p>
* An exception may also be thrown if the connection was already
* successfully connected (no matter if the connection broke in
* the mean time) and you invoke <code>connect()</code> again
* without having called {@link #close()} first.
* <p>
* If a HTTP proxy is being used and the proxy refuses the
* connection, then a {@link HTTPProxyException} may be thrown,
* which contains the details returned by the proxy. If the
* proxy is buggy and does not return a proper HTTP response,
* then a normal IOException is thrown instead.
*/
public synchronized ConnectionInfo connect(ServerHostKeyVerifier verifier, int connectTimeout, int kexTimeout)
throws IOException
{
final class TimeoutState
{
boolean isCancelled = false;
boolean timeoutSocketClosed = false;
}
if (tm != null)
throw new IOException("Connection to " + hostname + " is already in connected state!");
if (connectTimeout < 0)
throw new IllegalArgumentException("connectTimeout must be non-negative!");
if (kexTimeout < 0)
throw new IllegalArgumentException("kexTimeout must be non-negative!");
final TimeoutState state = new TimeoutState();
tm = new TransportManager(hostname, port);
tm.setConnectionMonitors(connectionMonitors);
// Don't offer compression if not requested
if (!compression) {
cryptoWishList.c2s_comp_algos = new String[] { "none" };
cryptoWishList.s2c_comp_algos = new String[] { "none" };
}
/*
* Make sure that the runnable below will observe the new value of "tm"
* and "state" (the runnable will be executed in a different thread,
* which may be already running, that is why we need a memory barrier
* here). See also the comment in Channel.java if you are interested in
* the details.
*
* OKOK, this is paranoid since adding the runnable to the todo list of
* the TimeoutService will ensure that all writes have been flushed
* before the Runnable reads anything (there is a synchronized block in
* TimeoutService.addTimeoutHandler).
*/
synchronized (tm)
{
/* We could actually synchronize on anything. */
}
try
{
TimeoutToken token = null;
if (kexTimeout > 0)
{
final Runnable timeoutHandler = new Runnable()
{
public void run()
{
synchronized (state)
{
if (state.isCancelled)
return;
state.timeoutSocketClosed = true;
tm.close(new SocketTimeoutException("The connect timeout expired"), false);
}
}
};
long timeoutHorizont = System.currentTimeMillis() + kexTimeout;
token = TimeoutService.addTimeoutHandler(timeoutHorizont, timeoutHandler);
}
try
{
tm.initialize(cryptoWishList, verifier, dhgexpara, connectTimeout, getOrCreateSecureRND(), proxyData);
}
catch (SocketTimeoutException se)
{
throw (SocketTimeoutException) new SocketTimeoutException(
"The connect() operation on the socket timed out.").initCause(se);
}
tm.setTcpNoDelay(tcpNoDelay);
/* Wait until first KEX has finished */
ConnectionInfo ci = tm.getConnectionInfo(1);
/* Now try to cancel the timeout, if needed */
if (token != null)
{
TimeoutService.cancelTimeoutHandler(token);
/* Were we too late? */
synchronized (state)
{
if (state.timeoutSocketClosed)
throw new IOException("This exception will be replaced by the one below =)");
/*
* Just in case the "cancelTimeoutHandler" invocation came
* just a little bit too late but the handler did not enter
* the semaphore yet - we can still stop it.
*/
state.isCancelled = true;
}
}
return ci;
}
catch (SocketTimeoutException ste)
{
throw ste;
}
catch (IOException e1)
{
/* This will also invoke any registered connection monitors */
close(new Throwable("There was a problem during connect."), false);
synchronized (state)
{
/*
* Show a clean exception, not something like "the socket is
* closed!?!"
*/
if (state.timeoutSocketClosed)
throw new SocketTimeoutException("The kexTimeout (" + kexTimeout + " ms) expired.");
}
/* Do not wrap a HTTPProxyException */
if (e1 instanceof HTTPProxyException)
throw e1;
throw (IOException) new IOException("There was a problem while connecting to " + hostname + ":" + port)
.initCause(e1);
}
}
/**
* Creates a new {@link LocalPortForwarder}. A
* <code>LocalPortForwarder</code> forwards TCP/IP connections that arrive
* at a local port via the secure tunnel to another host (which may or may
* not be identical to the remote SSH-2 server).
* <p>
* This method must only be called after one has passed successfully the
* authentication step. There is no limit on the number of concurrent
* forwardings.
*
* @param local_port
* the local port the LocalPortForwarder shall bind to.
* @param host_to_connect
* target address (IP or hostname)
* @param port_to_connect
* target port
* @return A {@link LocalPortForwarder} object.
* @throws IOException
*/
public synchronized LocalPortForwarder createLocalPortForwarder(int local_port, String host_to_connect,
int port_to_connect) throws IOException
{
if (tm == null)
throw new IllegalStateException("Cannot forward ports, you need to establish a connection first.");
if (!authenticated)
throw new IllegalStateException("Cannot forward ports, connection is not authenticated.");
return new LocalPortForwarder(cm, local_port, host_to_connect, port_to_connect);
}
/**
* Creates a new {@link LocalPortForwarder}. A
* <code>LocalPortForwarder</code> forwards TCP/IP connections that arrive
* at a local port via the secure tunnel to another host (which may or may
* not be identical to the remote SSH-2 server).
* <p>
* This method must only be called after one has passed successfully the
* authentication step. There is no limit on the number of concurrent
* forwardings.
*
* @param addr
* specifies the InetSocketAddress where the local socket shall
* be bound to.
* @param host_to_connect
* target address (IP or hostname)
* @param port_to_connect
* target port
* @return A {@link LocalPortForwarder} object.
* @throws IOException
*/
public synchronized LocalPortForwarder createLocalPortForwarder(InetSocketAddress addr, String host_to_connect,
int port_to_connect) throws IOException
{
if (tm == null)
throw new IllegalStateException("Cannot forward ports, you need to establish a connection first.");
if (!authenticated)
throw new IllegalStateException("Cannot forward ports, connection is not authenticated.");
return new LocalPortForwarder(cm, addr, host_to_connect, port_to_connect);
}
/**
* Creates a new {@link LocalStreamForwarder}. A
* <code>LocalStreamForwarder</code> manages an Input/Outputstream pair
* that is being forwarded via the secure tunnel into a TCP/IP connection to
* another host (which may or may not be identical to the remote SSH-2
* server).
*
* @param host_to_connect
* @param port_to_connect
* @return A {@link LocalStreamForwarder} object.
* @throws IOException
*/
public synchronized LocalStreamForwarder createLocalStreamForwarder(String host_to_connect, int port_to_connect)
throws IOException
{
if (tm == null)
throw new IllegalStateException("Cannot forward, you need to establish a connection first.");
if (!authenticated)
throw new IllegalStateException("Cannot forward, connection is not authenticated.");
return new LocalStreamForwarder(cm, host_to_connect, port_to_connect);
}
/**
* Creates a new {@link DynamicPortForwarder}. A
* <code>DynamicPortForwarder</code> forwards TCP/IP connections that arrive
* at a local port via the secure tunnel to another host that is chosen via
* the SOCKS protocol.
* <p>
* This method must only be called after one has passed successfully the
* authentication step. There is no limit on the number of concurrent
* forwardings.
*
* @param local_port
* @return A {@link DynamicPortForwarder} object.
* @throws IOException
*/
public synchronized DynamicPortForwarder createDynamicPortForwarder(int local_port) throws IOException
{
if (tm == null)
throw new IllegalStateException("Cannot forward ports, you need to establish a connection first.");
if (!authenticated)
throw new IllegalStateException("Cannot forward ports, connection is not authenticated.");
return new DynamicPortForwarder(cm, local_port);
}
/**
* Creates a new {@link DynamicPortForwarder}. A
* <code>DynamicPortForwarder</code> forwards TCP/IP connections that arrive
* at a local port via the secure tunnel to another host that is chosen via
* the SOCKS protocol.
* <p>
* This method must only be called after one has passed successfully the
* authentication step. There is no limit on the number of concurrent
* forwardings.
*
* @param addr
* specifies the InetSocketAddress where the local socket shall
* be bound to.
* @return A {@link DynamicPortForwarder} object.
* @throws IOException
*/
public synchronized DynamicPortForwarder createDynamicPortForwarder(InetSocketAddress addr) throws IOException
{
if (tm == null)
throw new IllegalStateException("Cannot forward ports, you need to establish a connection first.");
if (!authenticated)
throw new IllegalStateException("Cannot forward ports, connection is not authenticated.");
return new DynamicPortForwarder(cm, addr);
}
/**
* Create a very basic {@link SCPClient} that can be used to copy files
* from/to the SSH-2 server.
* <p>
* Works only after one has passed successfully the authentication step.
* There is no limit on the number of concurrent SCP clients.
* <p>
* Note: This factory method will probably disappear in the future.
*
* @return A {@link SCPClient} object.
* @throws IOException
*/
public synchronized SCPClient createSCPClient() throws IOException
{
if (tm == null)
throw new IllegalStateException("Cannot create SCP client, you need to establish a connection first.");
if (!authenticated)
throw new IllegalStateException("Cannot create SCP client, connection is not authenticated.");
return new SCPClient(this);
}
/**
* Force an asynchronous key re-exchange (the call does not block). The
* latest values set for MAC, Cipher and DH group exchange parameters will
* be used. If a key exchange is currently in progress, then this method has
* the only effect that the so far specified parameters will be used for the
* next (server driven) key exchange.
* <p>
* Note: This implementation will never start a key exchange (other than the
* initial one) unless you or the SSH-2 server ask for it.
*
* @throws IOException
* In case of any failure behind the scenes.
*/
public synchronized void forceKeyExchange() throws IOException
{
if (tm == null)
throw new IllegalStateException("You need to establish a connection first.");
tm.forceKeyExchange(cryptoWishList, dhgexpara);
}
/**
* Returns the hostname that was passed to the constructor.
*
* @return the hostname
*/
public synchronized String getHostname()
{
return hostname;
}
/**
* Returns the port that was passed to the constructor.
*
* @return the TCP port
*/
public synchronized int getPort()
{
return port;
}
/**
* Returns a {@link ConnectionInfo} object containing the details of the
* connection. Can be called as soon as the connection has been established
* (successfully connected).
*
* @return A {@link ConnectionInfo} object.
* @throws IOException
* In case of any failure behind the scenes.
*/
public synchronized ConnectionInfo getConnectionInfo() throws IOException
{
if (tm == null)
throw new IllegalStateException(
"Cannot get details of connection, you need to establish a connection first.");
return tm.getConnectionInfo(1);
}
/**
* After a successful connect, one has to authenticate oneself. This method
* can be used to tell which authentication methods are supported by the
* server at a certain stage of the authentication process (for the given
* username).
* <p>
* Note 1: the username will only be used if no authentication step was done
* so far (it will be used to ask the server for a list of possible
* authentication methods by sending the initial "none" request). Otherwise,
* this method ignores the user name and returns a cached method list (which
* is based on the information contained in the last negative server
* response).
* <p>
* Note 2: the server may return method names that are not supported by this
* implementation.
* <p>
* After a successful authentication, this method must not be called
* anymore.
*
* @param user
* A <code>String</code> holding the username.
*
* @return a (possibly emtpy) array holding authentication method names.
* @throws IOException
*/
public synchronized String[] getRemainingAuthMethods(String user) throws IOException
{
if (user == null)
throw new IllegalArgumentException("user argument may not be NULL!");
if (tm == null)
throw new IllegalStateException("Connection is not established!");
if (authenticated)
throw new IllegalStateException("Connection is already authenticated!");
if (am == null)
am = new AuthenticationManager(tm);
if (cm == null)
cm = new ChannelManager(tm);
return am.getRemainingMethods(user);
}
/**
* Determines if the authentication phase is complete. Can be called at any
* time.
*
* @return <code>true</code> if no further authentication steps are
* needed.
*/
public synchronized boolean isAuthenticationComplete()
{
return authenticated;
}
/**
* Returns true if there was at least one failed authentication request and
* the last failed authentication request was marked with "partial success"
* by the server. This is only needed in the rare case of SSH-2 server
* setups that cannot be satisfied with a single successful authentication
* request (i.e., multiple authentication steps are needed.)
* <p>
* If you are interested in the details, then have a look at RFC4252.
*
* @return if the there was a failed authentication step and the last one
* was marked as a "partial success".
*/
public synchronized boolean isAuthenticationPartialSuccess()
{
if (am == null)
return false;
return am.getPartialSuccess();
}
/**
* Checks if a specified authentication method is available. This method is
* actually just a wrapper for {@link #getRemainingAuthMethods(String)
* getRemainingAuthMethods()}.
*
* @param user
* A <code>String</code> holding the username.
* @param method
* An authentication method name (e.g., "publickey", "password",
* "keyboard-interactive") as specified by the SSH-2 standard.
* @return if the specified authentication method is currently available.
* @throws IOException
*/
public synchronized boolean isAuthMethodAvailable(String user, String method) throws IOException
{
if (method == null)
throw new IllegalArgumentException("method argument may not be NULL!");
String methods[] = getRemainingAuthMethods(user);
for (int i = 0; i < methods.length; i++)
{
if (methods[i].compareTo(method) == 0)
return true;
}
return false;
}
private final SecureRandom getOrCreateSecureRND()
{
if (generator == null)
generator = new SecureRandom();
return generator;
}
/**
* Open a new {@link Session} on this connection. Works only after one has
* passed successfully the authentication step. There is no limit on the
* number of concurrent sessions.
*
* @return A {@link Session} object.
* @throws IOException
*/
public synchronized Session openSession() throws IOException
{
if (tm == null)
throw new IllegalStateException("Cannot open session, you need to establish a connection first.");
if (!authenticated)
throw new IllegalStateException("Cannot open session, connection is not authenticated.");
return new Session(cm, getOrCreateSecureRND());
}
/**
* Send an SSH_MSG_IGNORE packet. This method will generate a random data
* attribute (length between 0 (invlusive) and 16 (exclusive) bytes,
* contents are random bytes).
* <p>
* This method must only be called once the connection is established.
*
* @throws IOException
*/
public synchronized void sendIgnorePacket() throws IOException
{
SecureRandom rnd = getOrCreateSecureRND();
byte[] data = new byte[rnd.nextInt(16)];
rnd.nextBytes(data);
sendIgnorePacket(data);
}
/**
* Send an SSH_MSG_IGNORE packet with the given data attribute.
* <p>
* This method must only be called once the connection is established.
*
* @throws IOException
*/
public synchronized void sendIgnorePacket(byte[] data) throws IOException
{
if (data == null)
throw new IllegalArgumentException("data argument must not be null.");
if (tm == null)
throw new IllegalStateException(
"Cannot send SSH_MSG_IGNORE packet, you need to establish a connection first.");
PacketIgnore pi = new PacketIgnore();
pi.setData(data);
tm.sendMessage(pi.getPayload());
}
/**
* Removes duplicates from a String array, keeps only first occurence of
* each element. Does not destroy order of elements; can handle nulls. Uses
* a very efficient O(N^2) algorithm =)
*
* @param list
* a String array.
* @return a cleaned String array.
*/
private String[] removeDuplicates(String[] list)
{
if ((list == null) || (list.length < 2))
return list;
String[] list2 = new String[list.length];
int count = 0;
for (int i = 0; i < list.length; i++)
{
boolean duplicate = false;
String element = list[i];
for (int j = 0; j < count; j++)
{
if (((element == null) && (list2[j] == null)) || ((element != null) && (element.equals(list2[j]))))
{
duplicate = true;
break;
}
}
if (duplicate)
continue;
list2[count++] = list[i];
}
if (count == list2.length)
return list2;
String[] tmp = new String[count];
System.arraycopy(list2, 0, tmp, 0, count);
return tmp;
}
/**
* Unless you know what you are doing, you will never need this.
*
* @param ciphers
*/
public synchronized void setClient2ServerCiphers(String[] ciphers)
{
if ((ciphers == null) || (ciphers.length == 0))
throw new IllegalArgumentException();
ciphers = removeDuplicates(ciphers);
BlockCipherFactory.checkCipherList(ciphers);
cryptoWishList.c2s_enc_algos = ciphers;
}
/**
* Unless you know what you are doing, you will never need this.
*
* @param macs
*/
public synchronized void setClient2ServerMACs(String[] macs)
{
if ((macs == null) || (macs.length == 0))
throw new IllegalArgumentException();
macs = removeDuplicates(macs);
MAC.checkMacList(macs);
cryptoWishList.c2s_mac_algos = macs;
}
/**
* Sets the parameters for the diffie-hellman group exchange. Unless you
* know what you are doing, you will never need this. Default values are
* defined in the {@link DHGexParameters} class.
*
* @param dgp
* {@link DHGexParameters}, non null.
*
*/
public synchronized void setDHGexParameters(DHGexParameters dgp)
{
if (dgp == null)
throw new IllegalArgumentException();
dhgexpara = dgp;
}
/**
* Unless you know what you are doing, you will never need this.
*
* @param ciphers
*/
public synchronized void setServer2ClientCiphers(String[] ciphers)
{
if ((ciphers == null) || (ciphers.length == 0))
throw new IllegalArgumentException();
ciphers = removeDuplicates(ciphers);
BlockCipherFactory.checkCipherList(ciphers);
cryptoWishList.s2c_enc_algos = ciphers;
}
/**
* Unless you know what you are doing, you will never need this.
*
* @param macs
*/
public synchronized void setServer2ClientMACs(String[] macs)
{
if ((macs == null) || (macs.length == 0))
throw new IllegalArgumentException();
macs = removeDuplicates(macs);
MAC.checkMacList(macs);
cryptoWishList.s2c_mac_algos = macs;
}
/**
* Define the set of allowed server host key algorithms to be used for the
* following key exchange operations.
* <p>
* Unless you know what you are doing, you will never need this.
*
* @param algos
* An array of allowed server host key algorithms. SSH-2 defines
* <code>ssh-dss</code> and <code>ssh-rsa</code>. The
* entries of the array must be ordered after preference, i.e.,
* the entry at index 0 is the most preferred one. You must
* specify at least one entry.
*/
public synchronized void setServerHostKeyAlgorithms(String[] algos)
{
if ((algos == null) || (algos.length == 0))
throw new IllegalArgumentException();
algos = removeDuplicates(algos);
KexManager.checkServerHostkeyAlgorithmsList(algos);
cryptoWishList.serverHostKeyAlgorithms = algos;
}
/**
* Enable/disable TCP_NODELAY (disable/enable Nagle's algorithm) on the
* underlying socket.
* <p>
* Can be called at any time. If the connection has not yet been established
* then the passed value will be stored and set after the socket has been
* set up. The default value that will be used is <code>false</code>.
*
* @param enable
* the argument passed to the <code>Socket.setTCPNoDelay()</code>
* method.
* @throws IOException
*/
public synchronized void setTCPNoDelay(boolean enable) throws IOException
{
tcpNoDelay = enable;
if (tm != null)
tm.setTcpNoDelay(enable);
}
/**
* Used to tell the library that the connection shall be established through
* a proxy server. It only makes sense to call this method before calling
* the {@link #connect() connect()} method.
* <p>
* At the moment, only HTTP proxies are supported.
* <p>
* Note: This method can be called any number of times. The
* {@link #connect() connect()} method will use the value set in the last
* preceding invocation of this method.
*
* @see HTTPProxyData
*
* @param proxyData
* Connection information about the proxy. If <code>null</code>,
* then no proxy will be used (non surprisingly, this is also the
* default).
*/
public synchronized void setProxyData(ProxyData proxyData)
{
this.proxyData = proxyData;
}
/**
* Request a remote port forwarding. If successful, then forwarded
* connections will be redirected to the given target address. You can
* cancle a requested remote port forwarding by calling
* {@link #cancelRemotePortForwarding(int) cancelRemotePortForwarding()}.
* <p>
* A call of this method will block until the peer either agreed or
* disagreed to your request-
* <p>
* Note 1: this method typically fails if you
* <ul>
* <li>pass a port number for which the used remote user has not enough
* permissions (i.e., port < 1024)</li>
* <li>or pass a port number that is already in use on the remote server</li>
* <li>or if remote port forwarding is disabled on the server.</li>
* </ul>
* <p>
* Note 2: (from the openssh man page): By default, the listening socket on
* the server will be bound to the loopback interface only. This may be
* overriden by specifying a bind address. Specifying a remote bind address
* will only succeed if the server's <b>GatewayPorts</b> option is enabled
* (see sshd_config(5)).
*
* @param bindAddress
* address to bind to on the server:
* <ul>
* <li>"" means that connections are to be accepted on all
* protocol families supported by the SSH implementation</li>
* <li>"0.0.0.0" means to listen on all IPv4 addresses</li>
* <li>"::" means to listen on all IPv6 addresses</li>
* <li>"localhost" means to listen on all protocol families
* supported by the SSH implementation on loopback addresses
* only, [RFC3330] and RFC3513]</li>
* <li>"127.0.0.1" and "::1" indicate listening on the loopback
* interfaces for IPv4 and IPv6 respectively</li>
* </ul>
* @param bindPort
* port number to bind on the server (must be > 0)
* @param targetAddress
* the target address (IP or hostname)
* @param targetPort
* the target port
* @throws IOException
*/
public synchronized void requestRemotePortForwarding(String bindAddress, int bindPort, String targetAddress,
int targetPort) throws IOException
{
if (tm == null)
throw new IllegalStateException("You need to establish a connection first.");
if (!authenticated)
throw new IllegalStateException("The connection is not authenticated.");
if ((bindAddress == null) || (targetAddress == null) || (bindPort <= 0) || (targetPort <= 0))
throw new IllegalArgumentException();
cm.requestGlobalForward(bindAddress, bindPort, targetAddress, targetPort);
}
/**
* Cancel an earlier requested remote port forwarding. Currently active
* forwardings will not be affected (e.g., disrupted). Note that further
* connection forwarding requests may be received until this method has
* returned.
*
* @param bindPort
* the allocated port number on the server
* @throws IOException
* if the remote side refuses the cancel request or another low
* level error occurs (e.g., the underlying connection is
* closed)
*/
public synchronized void cancelRemotePortForwarding(int bindPort) throws IOException
{
if (tm == null)
throw new IllegalStateException("You need to establish a connection first.");
if (!authenticated)
throw new IllegalStateException("The connection is not authenticated.");
cm.requestCancelGlobalForward(bindPort);
}
/**
* Provide your own instance of SecureRandom. Can be used, e.g., if you want
* to seed the used SecureRandom generator manually.
* <p>
* The SecureRandom instance is used during key exchanges, public key
* authentication, x11 cookie generation and the like.
*
* @param rnd
* a SecureRandom instance
*/
public synchronized void setSecureRandom(SecureRandom rnd)
{
if (rnd == null)
throw new IllegalArgumentException();
this.generator = rnd;
}
/**
* Enable/disable debug logging. <b>Only do this when requested by Trilead
* support.</b>
* <p>
* For speed reasons, some static variables used to check whether debugging
* is enabled are not protected with locks. In other words, if you
* dynamicaly enable/disable debug logging, then some threads may still use
* the old setting. To be on the safe side, enable debugging before doing
* the <code>connect()</code> call.
*
* @param enable
* on/off
* @param logger
* a {@link DebugLogger DebugLogger} instance, <code>null</code>
* means logging using the simple logger which logs all messages
* to to stderr. Ignored if enabled is <code>false</code>
*/
public synchronized void enableDebugging(boolean enable, DebugLogger logger)
{
Logger.enabled = enable;
if (enable == false)
{
Logger.logger = null;
}
else
{
if (logger == null)
{
logger = new DebugLogger()
{
public void log(int level, String className, String message)
{
long now = System.currentTimeMillis();
System.err.println(now + " : " + className + ": " + message);
}
};
}
Logger.logger = logger;
}
}
/**
* This method can be used to perform end-to-end connection testing. It
* sends a 'ping' message to the server and waits for the 'pong' from the
* server.
* <p>
* When this method throws an exception, then you can assume that the
* connection should be abandoned.
* <p>
* Note: Works only after one has passed successfully the authentication
* step.
* <p>
* Implementation details: this method sends a SSH_MSG_GLOBAL_REQUEST
* request ('trilead-ping') to the server and waits for the
* SSH_MSG_REQUEST_FAILURE reply packet from the server.
*
* @throws IOException
* in case of any problem
*/
public synchronized void ping() throws IOException
{
if (tm == null)
throw new IllegalStateException("You need to establish a connection first.");
if (!authenticated)
throw new IllegalStateException("The connection is not authenticated.");
cm.requestGlobalTrileadPing();
}
}
|
Java
|
package com.trilead.ssh2;
/**
* A callback interface used to implement a client specific method of checking
* server host keys.
*
* @author Christian Plattner, plattner@trilead.com
* @version $Id: ServerHostKeyVerifier.java,v 1.1 2007/10/15 12:49:56 cplattne Exp $
*/
public interface ServerHostKeyVerifier
{
/**
* The actual verifier method, it will be called by the key exchange code
* on EVERY key exchange - this can happen several times during the lifetime
* of a connection.
* <p>
* Note: SSH-2 servers are allowed to change their hostkey at ANY time.
*
* @param hostname the hostname used to create the {@link Connection} object
* @param port the remote TCP port
* @param serverHostKeyAlgorithm the public key algorithm (<code>ssh-rsa</code> or <code>ssh-dss</code>)
* @param serverHostKey the server's public key blob
* @return if the client wants to accept the server's host key - if not, the
* connection will be closed.
* @throws Exception Will be wrapped with an IOException, extended version of returning false =)
*/
public boolean verifyServerHostKey(String hostname, int port, String serverHostKeyAlgorithm, byte[] serverHostKey)
throws Exception;
}
|
Java
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.