This commit is contained in:
2026-07-22 17:42:32 -03:00
commit 3d36f2421e
645 changed files with 163624 additions and 0 deletions
+1
View File
@@ -0,0 +1 @@
/build
+43
View File
@@ -0,0 +1,43 @@
plugins {
id 'com.android.library'
}
android {
namespace 'com.dragonssh.xhttpdemo.core'
compileSdk 36
ndkVersion '27.0.12077973'
defaultConfig {
minSdk 26
targetSdk 36
ndk {
abiFilters 'armeabi-v7a', 'arm64-v8a', 'x86', 'x86_64'
}
}
buildFeatures {
aidl false
buildConfig true
}
externalNativeBuild {
ndkBuild {
path file('src/main/jni/Android.mk')
}
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_17
targetCompatibility JavaVersion.VERSION_17
}
}
dependencies {
implementation 'androidx.appcompat:appcompat:1.7.1'
implementation 'androidx.core:core:1.17.0'
implementation 'androidx.localbroadcastmanager:localbroadcastmanager:1.1.0'
implementation 'com.squareup.okhttp3:okhttp:4.12.0'
implementation 'org.conscrypt:conscrypt-android:2.5.3'
api 'net.i2p.crypto:eddsa:0.3.0'
implementation 'org.connectbot:jbcrypt:1.0.2'
}
+21
View File
@@ -0,0 +1,21 @@
# Add project specific ProGuard rules here.
# By default, the flags in this file are appended to flags specified
# in C:/tools/adt-bundle-windows-x86_64-20131030/sdk/tools/proguard/proguard-android.txt
# You can edit the include path and order by changing the proguardFiles
# directive in build.gradle.
#
# For more details, see
# http://developer.android.com/guide/developing/tools/proguard.html
# Add any project specific keep options here:
# If your project uses WebView with JS, uncomment the following
# and specify the fully qualified class name to the JavaScript interface
# class:
#-keepclassmembers class fqcn.of.javascript.interface.for.webview {
# public *;
#}
-keep class go.** { *; }
-keep class libv2ray.** { *; }
-keep class com.service.** { *; }
+29
View File
@@ -0,0 +1,29 @@
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
<uses-permission android:name="android.permission.FOREGROUND_SERVICE_DATA_SYNC" />
<application>
<receiver
android:name="com.dragonssh.xhttpdemo.core.MainReceiver"
android:exported="false" />
<service
android:name="com.dragonssh.xhttpdemo.core.XHttpSshService"
android:exported="false"
android:foregroundServiceType="dataSync"
android:stopWithTask="false" />
<service
android:name="com.dragonssh.xhttpdemo.core.tunnel.vpn.TunnelVpnService"
android:enabled="true"
android:exported="false"
android:permission="android.permission.BIND_VPN_SERVICE">
<intent-filter>
<action android:name="android.net.VpnService" />
</intent-filter>
</service>
</application>
</manifest>
@@ -0,0 +1,37 @@
package com.dragonssh.xhttpdemo.core;
import android.content.Context;
import android.content.Intent;
import android.content.BroadcastReceiver;
import androidx.localbroadcastmanager.content.LocalBroadcastManager;
import com.dragonssh.xhttpdemo.core.tunnel.TunnelManagerHelper;
public class MainReceiver extends BroadcastReceiver
{
public static final String ACTION_SERVICE_RESTART = "sshTunnelServiceRestsrt",
ACTION_SERVICE_STOP = "sshtunnelservicestop";
@Override
public void onReceive(Context context, Intent intent)
{
String acao = intent.getAction();
if (acao == null) {
return;
}
switch (acao) {
case ACTION_SERVICE_STOP:
TunnelManagerHelper.stopXHttpSsh(context);
break;
case ACTION_SERVICE_RESTART:
Intent restartTunnel = new Intent(XHttpSshService.TUNNEL_SSH_RESTART_SERVICE);
LocalBroadcastManager.getInstance(context)
.sendBroadcast(restartTunnel);
break;
}
}
}
@@ -0,0 +1,282 @@
package com.dragonssh.xhttpdemo.core;
import android.net.TrafficStats;
import android.os.SystemClock;
import java.util.ArrayList;
public class StatisticGraphData
{
private static StatisticGraphData statisticData;
private boolean m_displayDataTransferStats;
private DataTransferStats m_dataTransferStats;
private StatisticGraphData()
{
m_dataTransferStats = new DataTransferStats();
m_displayDataTransferStats = false;
}
public static synchronized StatisticGraphData getStatisticData()
{
if (statisticData == null)
{
statisticData = new StatisticGraphData();
}
return statisticData;
}
public synchronized void setDisplayDataTransferStats(boolean displayDataTransferStats)
{
m_displayDataTransferStats = displayDataTransferStats;
}
public synchronized boolean getDisplayDataTransferStats()
{
return m_displayDataTransferStats;
}
public synchronized DataTransferStats getDataTransferStats()
{
return m_dataTransferStats;
}
public class DataTransferStats
{
private boolean m_isConnected;
private long m_connectedTime;
private long m_totalBytesSent;
private long m_totalBytesReceived;
public final static long SLOW_BUCKET_PERIOD_MILLISECONDS = 5*60*1000;
public final static long FAST_BUCKET_PERIOD_MILLISECONDS = 1000;
public final static int MAX_BUCKETS = 24 * 60 / 5;
private long mLastSent;
private long mSent;
private long mLastReceived;
private long mReceived;
private class Bucket
{
public long m_bytesSent = 0;
public long m_bytesReceived = 0;
}
private ArrayList<Bucket> m_slowBuckets;
private long m_slowBucketsLastStartTime;
private ArrayList<Bucket> m_fastBuckets;
private long m_fastBucketsLastStartTime;
DataTransferStats()
{
m_totalBytesSent = 0;
m_totalBytesReceived = 0;
stop();
}
public synchronized void startSession()
{
resetBytesTransferred();
}
public synchronized void startConnected()
{
this.m_isConnected = true;
this.m_connectedTime = SystemClock.elapsedRealtime();
}
public synchronized void stop()
{
this.m_totalBytesReceived = 0;
this.m_totalBytesSent = 0;
this.m_isConnected = false;
this.m_connectedTime = 0;
resetBytesTransferred();
}
private void resetBytesTransferred()
{
long now = SystemClock.elapsedRealtime();
this.m_slowBucketsLastStartTime = bucketStartTime(now, SLOW_BUCKET_PERIOD_MILLISECONDS);
this.m_slowBuckets = newBuckets();
this.m_fastBucketsLastStartTime = bucketStartTime(now, FAST_BUCKET_PERIOD_MILLISECONDS);
this.m_fastBuckets = newBuckets();
}
public synchronized void addBytesSent(long bytes)
{
this.m_totalBytesSent += bytes;
manageBuckets();
addSentToBuckets(bytes);
}
public synchronized void addBytesReceived(long bytes)
{
this.m_totalBytesReceived += bytes;
manageBuckets();
addReceivedToBuckets(bytes);
}
private long bucketStartTime(long now, long period)
{
return period*(now/period);
}
private ArrayList<Bucket> newBuckets()
{
ArrayList<Bucket> buckets = new ArrayList<Bucket>();
for (int i = 0; i < MAX_BUCKETS; i++)
{
buckets.add(new Bucket());
}
return buckets;
}
private void shiftBuckets(long diff, long period, ArrayList<Bucket> buckets)
{
for (int i = 0; i < diff/period + 1; i++)
{
buckets.add(buckets.size(), new Bucket());
if (buckets.size() >= MAX_BUCKETS)
{
buckets.remove(0);
}
}
}
private void manageBuckets()
{
long now = SystemClock.elapsedRealtime();
long diff = now - this.m_slowBucketsLastStartTime;
if (diff >= SLOW_BUCKET_PERIOD_MILLISECONDS)
{
shiftBuckets(diff, SLOW_BUCKET_PERIOD_MILLISECONDS, m_slowBuckets);
this.m_slowBucketsLastStartTime = bucketStartTime(now, SLOW_BUCKET_PERIOD_MILLISECONDS);
}
diff = now - this.m_fastBucketsLastStartTime;
if (diff >= FAST_BUCKET_PERIOD_MILLISECONDS)
{
shiftBuckets(diff, FAST_BUCKET_PERIOD_MILLISECONDS, m_fastBuckets);
this.m_fastBucketsLastStartTime = bucketStartTime(now, FAST_BUCKET_PERIOD_MILLISECONDS);
}
}
private ArrayList<Long> getSentSeries(ArrayList<Bucket> buckets)
{
ArrayList<Long> series = new ArrayList<Long>();
for (int i = 0; i < buckets.size(); i++)
{
series.add(buckets.get(i).m_bytesSent);
}
return series;
}
private ArrayList<Long> getReceivedSeries(ArrayList<Bucket> buckets)
{
ArrayList<Long> series = new ArrayList<Long>();
for (int i = 0; i < buckets.size(); i++)
{
series.add(buckets.get(i).m_bytesReceived);
}
return series;
}
private void addSentToBuckets(long bytes)
{
this.m_slowBuckets.get(this.m_slowBuckets.size()-1).m_bytesSent += bytes;
this.m_fastBuckets.get(this.m_fastBuckets.size()-1).m_bytesSent += bytes;
}
private void addReceivedToBuckets(long bytes)
{
this.m_slowBuckets.get(this.m_slowBuckets.size()-1).m_bytesReceived += bytes;
this.m_fastBuckets.get(this.m_fastBuckets.size()-1).m_bytesReceived += bytes;
}
public synchronized boolean isConnected()
{
return this.m_isConnected;
}
public synchronized long getElapsedTime()
{
long now = SystemClock.elapsedRealtime();
return now - this.m_connectedTime;
}
public synchronized long getTotalBytesSent()
{
return this.m_totalBytesSent;
}
public synchronized long getTotalBytesReceived()
{
return this.m_totalBytesReceived;
}
public synchronized ArrayList<Long> getSlowSentSeries()
{
manageBuckets();
return getSentSeries(this.m_slowBuckets);
}
public synchronized ArrayList<Long> getSlowReceivedSeries()
{
manageBuckets();
return getReceivedSeries(this.m_slowBuckets);
}
public synchronized ArrayList<Long> getFastSentSeries()
{
manageBuckets();
return getSentSeries(this.m_fastBuckets);
}
public synchronized ArrayList<Long> getFastReceivedSeries()
{
manageBuckets();
return getReceivedSeries(this.m_fastBuckets);
}
public String byteCountToDisplaySize(long bytes, boolean si)
{
// http://stackoverflow.com/questions/3758606/how-to-convert-byte-size-into-human-readable-format-in-java/3758880#3758880
int unit = si ? 1000 : 1024;
if (bytes < unit) return bytes + " B";
int exp = (int) (Math.log(bytes) / Math.log(unit));
String pre = (si ? "kMGTPE" : "KMGTPE").charAt(exp-1) + (si ? "" : "i");
return String.format("%.1f %sB", bytes / Math.pow(unit, exp), pre);
}
public synchronized long getBytesSent() {
long xSent = TrafficStats.getTotalTxBytes();
mSent = xSent - mLastSent;
mLastSent = xSent;
return this.mSent;
}
public synchronized long getBytesReceived()
{
long xReceived = TrafficStats.getTotalRxBytes();
mReceived = xReceived - mLastReceived;
mLastReceived = xReceived;
return this.mReceived;
}
}
}
@@ -0,0 +1,25 @@
package com.dragonssh.xhttpdemo.core;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.content.Context;
import android.os.Build;
/** Creates the quiet foreground-service channel used by the sample. */
public final class XHttpSshCore {
private XHttpSshCore() {}
public static void init(Context context) {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O) return;
NotificationManager manager = context.getSystemService(NotificationManager.class);
if (manager == null) return;
NotificationChannel channel = new NotificationChannel(
XHttpSshService.NOTIFICATION_CHANNEL_ID,
context.getString(R.string.channel_name_background),
NotificationManager.IMPORTANCE_LOW);
channel.setDescription(context.getString(R.string.channel_description_background));
channel.setSound(null, null);
channel.enableVibration(false);
manager.createNotificationChannel(channel);
}
}
@@ -0,0 +1,168 @@
package com.dragonssh.xhttpdemo.core;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.ServiceInfo;
import android.os.Build;
import android.os.Handler;
import android.os.IBinder;
import android.os.Looper;
import androidx.core.app.NotificationCompat;
import androidx.core.app.ServiceCompat;
import androidx.localbroadcastmanager.content.LocalBroadcastManager;
import com.dragonssh.xhttpdemo.core.logger.ConnectionStatus;
import com.dragonssh.xhttpdemo.core.logger.SkStatus;
import com.dragonssh.xhttpdemo.core.tunnel.TunnelManagerThread;
/** Foreground service that owns the SSH/XHTTP transport. */
public final class XHttpSshService extends Service implements SkStatus.StateListener {
public static final String NOTIFICATION_CHANNEL_ID = "xhttp_ssh_status";
public static final int NOTIFICATION_ID = 7001;
public static final String EXTRA_SSH_PASSWORD = "ssh_password";
public static final String TUNNEL_SSH_RESTART_SERVICE =
XHttpSshService.class.getName() + ".RESTART";
public static final String TUNNEL_SSH_STOP_SERVICE =
XHttpSshService.class.getName() + ".STOP";
private final Handler mainHandler = new Handler(Looper.getMainLooper());
private TunnelManagerThread tunnelManager;
private Thread tunnelThread;
private boolean receiverRegistered;
@Override
public void onCreate() {
super.onCreate();
XHttpSshCore.init(this);
registerControlReceiver();
SkStatus.addStateListener(this);
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
ServiceCompat.startForeground(this, NOTIFICATION_ID,
buildNotification(getString(R.string.state_starting)),
ServiceInfo.FOREGROUND_SERVICE_TYPE_DATA_SYNC);
if (tunnelThread == null || !tunnelThread.isAlive()) {
String password = intent != null ? intent.getStringExtra(EXTRA_SSH_PASSWORD) : null;
if (password == null || password.isEmpty()) {
SkStatus.logError("SSH password was not supplied");
stopForeground(STOP_FOREGROUND_REMOVE);
stopSelf(startId);
return START_NOT_STICKY;
}
startTunnel(password);
}
return START_NOT_STICKY;
}
private synchronized void startTunnel(String password) {
tunnelManager = new TunnelManagerThread(mainHandler, this, password);
tunnelManager.setOnStopClientListener(this::finishService);
tunnelThread = new Thread(tunnelManager, "xhttp-ssh-manager");
tunnelThread.start();
}
private synchronized void stopTunnel() {
TunnelManagerThread manager = tunnelManager;
tunnelManager = null;
if (manager != null) manager.stopAll();
Thread thread = tunnelThread;
tunnelThread = null;
if (thread != null) thread.interrupt();
}
private void finishService() {
mainHandler.post(() -> {
stopTunnel();
stopForeground(STOP_FOREGROUND_REMOVE);
stopSelf();
});
}
@Override
public void onDestroy() {
stopTunnel();
if (receiverRegistered) {
LocalBroadcastManager.getInstance(this).unregisterReceiver(controlReceiver);
receiverRegistered = false;
}
SkStatus.removeStateListener(this);
super.onDestroy();
}
@Override
public IBinder onBind(Intent intent) {
return null;
}
private Notification buildNotification(String text) {
Intent open = getPackageManager().getLaunchIntentForPackage(getPackageName());
PendingIntent contentIntent = null;
if (open != null) {
open.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
int flags = PendingIntent.FLAG_UPDATE_CURRENT;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) flags |= PendingIntent.FLAG_IMMUTABLE;
contentIntent = PendingIntent.getActivity(this, 1, open, flags);
}
Intent stop = new Intent(this, MainReceiver.class).setAction(MainReceiver.ACTION_SERVICE_STOP);
int actionFlags = PendingIntent.FLAG_UPDATE_CURRENT;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) actionFlags |= PendingIntent.FLAG_IMMUTABLE;
PendingIntent stopIntent = PendingIntent.getBroadcast(this, 2, stop, actionFlags);
NotificationCompat.Builder builder = new NotificationCompat.Builder(this, NOTIFICATION_CHANNEL_ID)
.setSmallIcon(R.drawable.ic_cloud_black_24dp)
.setContentTitle(getString(R.string.app_name))
.setContentText(text)
.setOngoing(true)
.setOnlyAlertOnce(true)
.setSilent(true)
.setCategory(NotificationCompat.CATEGORY_SERVICE)
.addAction(R.drawable.ic_power_settings_new_black_24dp,
getString(R.string.stop), stopIntent);
if (contentIntent != null) builder.setContentIntent(contentIntent);
return builder.build();
}
@Override
public void updateState(String state, String logMessage, int localizedResId,
ConnectionStatus level, Intent intent) {
String text;
try {
text = getString(localizedResId);
} catch (Exception ignored) {
text = state;
}
NotificationManager nm = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
if (nm != null) nm.notify(NOTIFICATION_ID, buildNotification(text));
}
private void registerControlReceiver() {
IntentFilter filter = new IntentFilter();
filter.addAction(TUNNEL_SSH_STOP_SERVICE);
filter.addAction(TUNNEL_SSH_RESTART_SERVICE);
LocalBroadcastManager.getInstance(this).registerReceiver(controlReceiver, filter);
receiverRegistered = true;
}
private final BroadcastReceiver controlReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
if (intent == null || intent.getAction() == null) return;
if (TUNNEL_SSH_STOP_SERVICE.equals(intent.getAction())) {
finishService();
} else if (TUNNEL_SSH_RESTART_SERVICE.equals(intent.getAction())) {
TunnelManagerThread manager = tunnelManager;
if (manager != null) new Thread(manager::reconnectSSH, "xhttp-manual-reconnect").start();
}
}
};
}
@@ -0,0 +1,111 @@
package com.dragonssh.xhttpdemo.core.config;
import android.content.Context;
import android.content.SharedPreferences;
/**
* Minimal local configuration store for the public sample.
* No online panel, config encryption, import/export, HWID, OTP, or paid-app settings.
*/
public final class Settings implements SettingsConstants {
private final SharedPreferences privatePrefs;
private final SharedPreferences vpnPrefs;
public Settings(Context context) {
Context app = context.getApplicationContext();
privatePrefs = app.getSharedPreferences("xhttp_demo_private", Context.MODE_PRIVATE);
vpnPrefs = app.getSharedPreferences("xhttp_demo_vpn", Context.MODE_PRIVATE);
}
public String getPrivString(String key) {
String fallback = "";
if (PORTA_LOCAL_KEY.equals(key)) fallback = "1080";
if (XHTTP_PATH_KEY.equals(key)) fallback = "/ssh";
if (XHTTP_TLS_KEY.equals(key)) fallback = "1";
return privatePrefs.getString(key, fallback);
}
public SharedPreferences getPrefsPrivate() {
return privatePrefs;
}
public SharedPreferences getVpnPrefs() {
return vpnPrefs;
}
public int getMaximoThreadsSocks() {
return Math.max(1, vpnPrefs.getInt(MAXIMO_THREADS_KEY, 8));
}
public int getSSHPinger() {
return Math.max(0, vpnPrefs.getInt(PINGER_KEY, 3));
}
public boolean ssh_compression() {
return vpnPrefs.getBoolean(SSH_COMPRESSION, false);
}
public boolean getIsDisabledDelaySSH() {
return true;
}
public boolean getDisableIpv6Tunnel() {
return vpnPrefs.getBoolean(DISABLE_IPV6_TUNNEL_KEY, true);
}
public boolean getVpnDnsForward() {
return vpnPrefs.getBoolean(DNSFORWARD_KEY, true);
}
public String getVpnDnsResolver() {
return vpnPrefs.getString(DNSRESOLVER_KEY, "1.1.1.1");
}
public String getVpnDnsResolverSecondary() {
return vpnPrefs.getString(DNSRESOLVER_SECONDARY_KEY, "1.0.0.1");
}
public boolean getVpnUdpForward() {
return vpnPrefs.getBoolean(UDPFORWARD_KEY, true);
}
public String getVpnUdpResolver() {
return vpnPrefs.getString(UDPRESOLVER_KEY, "127.0.0.1:7300");
}
public String[] getVpnBypassList() {
return new String[0];
}
public boolean getIsFilterBypassMode() {
return false;
}
public String[] getFilterApps() {
return new String[0];
}
public boolean getIsTetheringSubnet() {
return false;
}
public static void setDefaultConfig(Context context) {
Settings settings = new Settings(context);
settings.privatePrefs.edit()
.putString(PORTA_LOCAL_KEY, "1080")
.putString(XHTTP_PATH_KEY, "/ssh")
.putString(XHTTP_TLS_KEY, "1")
.apply();
settings.vpnPrefs.edit()
.putBoolean(UDPFORWARD_KEY, true)
.putString(UDPRESOLVER_KEY, "127.0.0.1:7300")
.putBoolean(DNSFORWARD_KEY, true)
.putString(DNSRESOLVER_KEY, "1.1.1.1")
.putString(DNSRESOLVER_SECONDARY_KEY, "1.0.0.1")
.putBoolean(DISABLE_IPV6_TUNNEL_KEY, true)
.putInt(MAXIMO_THREADS_KEY, 8)
.putInt(PINGER_KEY, 3)
.apply();
}
}
@@ -0,0 +1,33 @@
package com.dragonssh.xhttpdemo.core.config;
/** Keys used by the public XHTTP + SSH example. */
public interface SettingsConstants {
// Legacy preference values are kept so upgrades preserve saved configurations.
String XHTTP_ENDPOINT_KEY = "sshServer";
String XHTTP_PORT_KEY = "sshPort";
/** @deprecated Use {@link #XHTTP_ENDPOINT_KEY}. */
@Deprecated String SERVIDOR_KEY = XHTTP_ENDPOINT_KEY;
/** @deprecated Use {@link #XHTTP_PORT_KEY}. */
@Deprecated String SERVIDOR_PORTA_KEY = XHTTP_PORT_KEY;
String USUARIO_KEY = "sshUser";
String SSH_PASSWORD_KEY = "sshPass";
String PORTA_LOCAL_KEY = "localSocksPort";
String SSH_HOST_KEY_PREFIX = "sshHostKey.";
String CUSTOM_SNI = "xhttpSni";
String XHTTP_PATH_KEY = "xhttpPath";
String XHTTP_HOST_KEY = "xhttpHost";
String XHTTP_TLS_KEY = "xhttpTls";
String TLS12 = "tls12";
String DNSFORWARD_KEY = "dnsForward";
String DNSRESOLVER_KEY = "dnsResolver";
String DNSRESOLVER_SECONDARY_KEY = "dnsResolverSecondary";
String UDPFORWARD_KEY = "udpForward";
String UDPRESOLVER_KEY = "udpResolver";
String DISABLE_IPV6_TUNNEL_KEY = "disableIpv6Tunnel";
String MAXIMO_THREADS_KEY = "numberMaxThreadSocks";
String PINGER_KEY = "pingerSSH";
String SSH_COMPRESSION = "sshCompression";
}
@@ -0,0 +1,39 @@
package com.dragonssh.xhttpdemo.core.logger;
import android.os.Parcel;
import android.os.Parcelable;
public enum ConnectionStatus implements Parcelable {
LEVEL_CONNECTED,
LEVEL_CONNECTING_SERVER_REPLIED,
LEVEL_CONNECTING_NO_SERVER_REPLY_YET,
LEVEL_NONETWORK,
LEVEL_NOTCONNECTED,
LEVEL_START,
LEVEL_AUTH_FAILED,
LEVEL_WAITING_FOR_USER_INPUT,
UNKNOWN_LEVEL;
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeInt(ordinal());
}
@Override
public int describeContents() {
return 0;
}
public static final Creator<ConnectionStatus> CREATOR = new Creator<ConnectionStatus>() {
@Override
public ConnectionStatus createFromParcel(Parcel in) {
return ConnectionStatus.values()[in.readInt()];
}
@Override
public ConnectionStatus[] newArray(int size) {
return new ConnectionStatus[size];
}
};
}
@@ -0,0 +1,107 @@
package com.dragonssh.xhttpdemo.core.logger;
import android.content.Context;
import android.os.Parcel;
import android.os.Parcelable;
import java.util.Locale;
/** A small, application-neutral log record for the public example. */
public final class LogItem implements Parcelable {
private final Object[] args;
private final String message;
private final int resourceId;
private final SkStatus.LogLevel level;
private final long logTime;
public LogItem(int resourceId, Object... args) {
this(SkStatus.LogLevel.INFO, resourceId, args);
}
public LogItem(SkStatus.LogLevel level, int verbosityLevel, String message) {
this(level, message);
}
public LogItem(SkStatus.LogLevel level, int resourceId, Object... args) {
this.level = level;
this.resourceId = resourceId;
this.args = args;
this.message = null;
this.logTime = System.currentTimeMillis();
}
public LogItem(SkStatus.LogLevel level, String message) {
this.level = level;
this.message = message;
this.resourceId = 0;
this.args = null;
this.logTime = System.currentTimeMillis();
}
public LogItem(SkStatus.LogLevel level, int resourceId) {
this(level, resourceId, (Object[]) null);
}
private LogItem(Parcel in) {
args = in.readArray(Object.class.getClassLoader());
message = in.readString();
resourceId = in.readInt();
int levelValue = in.readInt();
SkStatus.LogLevel parsed = SkStatus.LogLevel.getEnumByValue(levelValue);
level = parsed != null ? parsed : SkStatus.LogLevel.INFO;
logTime = in.readLong();
}
public SkStatus.LogLevel getLogLevel() {
return level;
}
public long getLogtime() {
return logTime;
}
public String getMessage() {
return message;
}
public String getString(Context context) {
if (message != null) {
return message;
}
if (context == null || resourceId == 0) {
return String.format(Locale.US, "Log resource %d", resourceId);
}
return args == null ? context.getString(resourceId) : context.getString(resourceId, args);
}
@Override
public String toString() {
return getString(null);
}
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeArray(args);
dest.writeString(message);
dest.writeInt(resourceId);
dest.writeInt(level.getInt());
dest.writeLong(logTime);
}
public static final Creator<LogItem> CREATOR = new Creator<LogItem>() {
@Override
public LogItem createFromParcel(Parcel in) {
return new LogItem(in);
}
@Override
public LogItem[] newArray(int size) {
return new LogItem[size];
}
};
}
@@ -0,0 +1,394 @@
package com.dragonssh.xhttpdemo.core.logger;
import java.io.StringWriter;
import java.io.PrintWriter;
import java.util.LinkedList;
import java.util.Vector;
import com.dragonssh.xhttpdemo.core.R;
import android.content.Intent;
import android.content.Context;
import java.util.Locale;
public class SkStatus
{
private static final LinkedList<LogItem> logbuffer;
private static Vector<LogListener> logListener;
private static Vector<StateListener> stateListener;
private static ConnectionStatus mLastLevel = ConnectionStatus.LEVEL_NOTCONNECTED;
private static String mLaststatemsg = "";
private static String mLaststate = "NOPROCESS";
private static int mLastStateresid = R.string.state_noprocess;
private static Intent mLastIntent = null;
static final int MAXLOGENTRIES = 10000;
public static boolean isTunnelActive() {
return mLastLevel != ConnectionStatus.LEVEL_AUTH_FAILED && !(mLastLevel == ConnectionStatus.LEVEL_NOTCONNECTED);
}
public static String getLastState() {
return mLaststate;
}
public static String getLastCleanLogMessage(Context c) {
String message = mLaststatemsg;
switch (mLastLevel) {
case LEVEL_CONNECTED:
String[] parts = mLaststatemsg.split(",");
/*
(a) the integer unix date/time,
(b) the state name,
0 (c) optional descriptive string (used mostly on RECONNECTING
and EXITING to show the reason for the disconnect),
1 (d) optional TUN/TAP local IPv4 address
2 (e) optional address of remote server,
3 (f) optional port of remote server,
4 (g) optional local address,
5 (h) optional local port, and
6 (i) optional TUN/TAP local IPv6 address.
*/
// Return only the assigned IP addresses in the UI
if (parts.length >= 7)
message = String.format(Locale.US, "%s %s", parts[1], parts[6]);
break;
}
while (message.endsWith(","))
message = message.substring(0, message.length() - 1);
String status = mLaststate;
if (status.equals("NOPROCESS"))
return message;
if (mLastStateresid == R.string.state_waitconnectretry) {
return c.getString(R.string.state_waitconnectretry, mLaststatemsg);
}
String prefix = c.getString(mLastStateresid);
if (mLastStateresid == R.string.unknown_state)
message = status + message;
if (message.length() > 0)
prefix += ": ";
return prefix + message;
}
public static enum LogLevel {
INFO(2),
ERROR(-2),
WARNING(1),
VERBOSE(3),
DEBUG(4);
protected int mValue;
LogLevel(int value) {
mValue = value;
}
public int getInt() {
return mValue;
}
public static LogLevel getEnumByValue(int value) {
switch (value) {
case 2:
return INFO;
case -2:
return ERROR;
case 1:
return WARNING;
case 3:
return VERBOSE;
case 4:
return DEBUG;
default:
return null;
}
}
}
static {
logbuffer = new LinkedList<>();
logListener = new Vector<>();
stateListener = new Vector<>();
logInformation();
}
public synchronized static void clearLog() {
logbuffer.clear();
for (LogListener li : logListener) {
li.onClear();
}
// Add the header after listeners clear their UI so it remains visible.
logInformation();
}
public synchronized static LogItem[] getlogbuffer() {
// The stoned way of java to return an array from a vector
// brought to you by eclipse auto complete
return logbuffer.toArray(new LogItem[logbuffer.size()]);
}
private static void logInformation() {
logInfo("DragonSSH XHTTP public example");
}
/**
* Listeners
*/
public interface LogListener {
void newLog(LogItem logItem);
void onClear();
}
public interface StateListener {
void updateState(String state, String logMessage, int localizedResId, ConnectionStatus level, Intent intent);
}
public synchronized static void addLogListener(LogListener ll) {
if (!logListener.contains(ll)) {
logListener.add(ll);
}
}
public synchronized static void removeLogListener(LogListener ll) {
if (logListener.contains(ll)) {
logListener.remove(ll);
}
}
public synchronized static void addStateListener(StateListener sl) {
if (!stateListener.contains(sl)) {
stateListener.add(sl);
if (mLaststate != null)
sl.updateState(mLaststate, mLaststatemsg, mLastStateresid, mLastLevel, mLastIntent);
}
}
public synchronized static void removeStateListener(StateListener sl) {
if (stateListener.contains(sl)) {
stateListener.remove(sl);
}
}
/**
* State
*/
public static final String
SSH_CONECTANDO = "CONECTANDO",
SSH_AGUARDANDO_REDE = "AGUARDANDO",
SSH_AUTENTICANDO = "AUTENTICANDO",
SSH_CONECTADO = "CONECTADO",
SSH_DESCONECTADO = "DESCONECTADO",
SSH_RECONECTANDO = "RECONECTANDO",
SSH_INICIANDO = "INICIANDO",
SSH_PARANDO = "PARANDO";
public static int getLocalizedState(String state) {
switch (state) {
case SSH_CONECTANDO:
return R.string.state_connecting;
case SSH_AGUARDANDO_REDE:
return R.string.state_nonetwork;
case SSH_AUTENTICANDO:
return R.string.state_auth;
case "GET_CONFIG":
return R.string.state_get_config;
case "ASSIGN_IP":
return R.string.state_assign_ip;
case "ADD_ROUTES":
return R.string.state_add_routes;
case SSH_CONECTADO:
return R.string.state_connected;
case SSH_DESCONECTADO:
return R.string.state_disconnected;
case SSH_RECONECTANDO:
return R.string.state_reconnecting;
case SSH_INICIANDO:
return R.string.state_starting;
case SSH_PARANDO:
return R.string.state_stopping;
case "RESOLVE":
return R.string.state_resolve;
case "TCP_CONNECT":
return R.string.state_tcp_connect;
case "AUTH_PENDING":
return R.string.state_auth_pending;
default:
return R.string.unknown_state;
}
}
private static ConnectionStatus getLevel(String state) {
String[] noreplyet = {SSH_INICIANDO, SSH_CONECTANDO, SSH_AGUARDANDO_REDE, SSH_RECONECTANDO, "RESOLVE", "TCP_CONNECT"};
String[] reply = {SSH_AUTENTICANDO, "GET_CONFIG", "ASSIGN_IP", "ADD_ROUTES", "AUTH_PENDING"};
String[] connected = {SSH_CONECTADO};
String[] notconnected = {SSH_DESCONECTADO};
for (String x : noreplyet)
if (state.equals(x))
return ConnectionStatus.LEVEL_CONNECTING_NO_SERVER_REPLY_YET;
for (String x : reply)
if (state.equals(x))
return ConnectionStatus.LEVEL_CONNECTING_SERVER_REPLIED;
for (String x : connected)
if (state.equals(x))
return ConnectionStatus.LEVEL_CONNECTED;
for (String x : notconnected)
if (state.equals(x))
return ConnectionStatus.LEVEL_NOTCONNECTED;
return ConnectionStatus.UNKNOWN_LEVEL;
}
public static void updateStateString(String state, String msg) {
int rid = getLocalizedState(state);
ConnectionStatus level = getLevel(state);
updateStateString(state, msg, rid, level);
}
public synchronized static void updateStateString(String state, String msg, int resid, ConnectionStatus level)
{
updateStateString(state, msg, resid, level, null);
}
public synchronized static void updateStateString(String state, String msg, int resid, ConnectionStatus level, Intent intent) {
// Workound for OpenVPN doing AUTH and wait and being connected
// Simply ignore these state
if (mLastLevel == ConnectionStatus.LEVEL_CONNECTED &&
(state.equals(SSH_AUTENTICANDO))) {
newLogItem(new LogItem((LogLevel.DEBUG), String.format("Ignoring XHTTP SSH status in CONNECTED state (%s->%s): %s", state, level.toString(), msg)));
return;
}
mLaststate = state;
mLaststatemsg = msg;
mLastStateresid = resid;
mLastLevel = level;
mLastIntent = intent;
for (StateListener sl : stateListener) {
sl.updateState(state, msg, resid, level, intent);
}
// State transition: (%s->%s): %s",state,level.toString(),msg)));
}
/**
* NewLog
*/
static void newLogItem(LogItem logItem) {
newLogItem(logItem, false);
}
synchronized static void newLogItem(LogItem logItem, boolean cachedLine) {
if (cachedLine) {
logbuffer.addFirst(logItem);
} else {
logbuffer.addLast(logItem);
}
// Keep a bounded history without deleting a large block of logs at once.
// The previous 1.5x threshold made thousands of older entries disappear
// suddenly, which looked like the log had been cropped.
while (logbuffer.size() > MAXLOGENTRIES)
logbuffer.removeFirst();
for (LogListener ll : logListener) {
ll.newLog(logItem);
}
}
/**
* Logger static methods
*/
public static void logException(String context, Exception e) {
logException(LogLevel.ERROR, context, e);
}
public static void logException(LogLevel ll, String context, Exception e) {
StringWriter sw = new StringWriter();
e.printStackTrace(new PrintWriter(sw));
LogItem li;
if (context != null)
li = new LogItem(ll, String.format("%s: %s, %s", context, e.getMessage(), sw.toString()));
else
li = new LogItem(ll, String.format("Error: %s, %s", e.getMessage(), sw.toString()));
newLogItem(li);
}
public static void logException(Exception e) {
logException(LogLevel.ERROR, null, e);
}
public static void logInfo(String message) {
newLogItem(new LogItem(LogLevel.INFO, message));
}
public static void logDebug(String message) {
newLogItem(new LogItem(LogLevel.DEBUG, message));
}
public static void logInfo(int resourceId, Object... args) {
newLogItem(new LogItem(LogLevel.INFO, resourceId, args));
}
public static void logDebug(int resourceId, Object... args) {
newLogItem(new LogItem(LogLevel.DEBUG, resourceId, args));
}
public static void logError(String msg) {
newLogItem(new LogItem(LogLevel.ERROR, msg));
}
public static void logWarning(int resourceId, Object... args) {
newLogItem(new LogItem(LogLevel.WARNING, resourceId, args));
}
public static void logWarning(String msg) {
newLogItem(new LogItem(LogLevel.WARNING, msg));
}
public static void logError(int resourceId) {
newLogItem(new LogItem(LogLevel.ERROR, resourceId));
}
public static void logError(int resourceId, Object... args) {
newLogItem(new LogItem(LogLevel.ERROR, resourceId, args));
}
}
@@ -0,0 +1,296 @@
package com.dragonssh.xhttpdemo.core.tunnel;
import com.dragonssh.xhttpdemo.core.logger.SkStatus;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketException;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;
/**
* Stable loopback TCP relay used between tun2socks and Trilead's dynamic SOCKS
* forwarder.
*
* <p>The Android VPN always points to this relay. During an SSH/XHTTP reconnect,
* only the relay's backend port changes. Keeping the public SOCKS listener alive
* prevents tun2socks from treating a transient SSH outage as a fatal local proxy
* failure and tearing down the VPN process.</p>
*/
final class PersistentSocksRelay {
private static final String LOOPBACK_HOST = "127.0.0.1";
private static final int ACCEPT_BACKLOG = 128;
private static final int MAX_CLIENTS = 256;
private static final int BACKEND_CONNECT_TIMEOUT_MS = 1500;
private static final int BACKEND_RETRY_DELAY_MS = 150;
private static final long BACKEND_WAIT_TIMEOUT_MS = 90_000L;
private static final int COPY_BUFFER_SIZE = 32 * 1024;
private final int listenPort;
private final Object backendLock = new Object();
private final Semaphore clientSlots = new Semaphore(MAX_CLIENTS);
private final Set<Socket> openSockets = Collections.synchronizedSet(new HashSet<Socket>());
private volatile boolean running;
private volatile int backendPort = -1;
private ServerSocket serverSocket;
private Thread acceptThread;
PersistentSocksRelay(int listenPort) {
this.listenPort = listenPort;
}
synchronized void start() throws IOException {
if (running) {
return;
}
ServerSocket server = new ServerSocket();
server.setReuseAddress(true);
server.bind(new InetSocketAddress(LOOPBACK_HOST, listenPort), ACCEPT_BACKLOG);
serverSocket = server;
running = true;
acceptThread = new Thread(this::acceptLoop, "vpn-socks-relay-accept");
acceptThread.setDaemon(true);
acceptThread.start();
}
boolean isRunning() {
return running;
}
int getListenPort() {
return listenPort;
}
void setBackendPort(int port) {
synchronized (backendLock) {
backendPort = port > 0 ? port : -1;
backendLock.notifyAll();
}
}
void clearBackendPort() {
setBackendPort(-1);
}
synchronized void stop() {
if (!running) {
return;
}
running = false;
clearBackendPort();
ServerSocket server = serverSocket;
serverSocket = null;
closeQuietly(server);
synchronized (openSockets) {
for (Socket socket : openSockets) {
closeQuietly(socket);
}
openSockets.clear();
}
Thread thread = acceptThread;
acceptThread = null;
if (thread != null) {
thread.interrupt();
}
}
private void acceptLoop() {
while (running) {
Socket client = null;
try {
ServerSocket server = serverSocket;
if (server == null) {
break;
}
client = server.accept();
client.setTcpNoDelay(true);
client.setKeepAlive(true);
if (!clientSlots.tryAcquire(1, TimeUnit.SECONDS)) {
closeQuietly(client);
continue;
}
final Socket accepted = client;
openSockets.add(accepted);
Thread worker = new Thread(() -> handleClient(accepted), "vpn-socks-relay-client");
worker.setDaemon(true);
worker.start();
} catch (SocketException e) {
if (running) {
SkStatus.logDebug("SOCKS relay accept failed: " + e.getMessage());
}
break;
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
closeQuietly(client);
break;
} catch (IOException e) {
closeQuietly(client);
if (running) {
SkStatus.logDebug("SOCKS relay accept failed: " + e.getMessage());
}
}
}
}
private void handleClient(Socket client) {
Socket backend = null;
try {
backend = connectBackend();
if (backend == null) {
return;
}
openSockets.add(backend);
relayBidirectional(client, backend);
} catch (IOException ignored) {
// A backend channel closing during reconnect is expected.
} finally {
closeQuietly(client);
closeQuietly(backend);
openSockets.remove(client);
if (backend != null) {
openSockets.remove(backend);
}
clientSlots.release();
}
}
private Socket connectBackend() throws IOException {
final long deadline = System.nanoTime() + TimeUnit.MILLISECONDS.toNanos(BACKEND_WAIT_TIMEOUT_MS);
IOException lastError = null;
while (running && System.nanoTime() < deadline) {
int port = awaitBackendPort(deadline);
if (port <= 0) {
continue;
}
Socket socket = new Socket();
try {
socket.setTcpNoDelay(true);
socket.setKeepAlive(true);
socket.connect(new InetSocketAddress(LOOPBACK_HOST, port),
BACKEND_CONNECT_TIMEOUT_MS);
return socket;
} catch (IOException e) {
lastError = e;
closeQuietly(socket);
try {
Thread.sleep(BACKEND_RETRY_DELAY_MS);
} catch (InterruptedException interrupted) {
Thread.currentThread().interrupt();
return null;
}
}
}
if (lastError != null) {
throw lastError;
}
return null;
}
private int awaitBackendPort(long deadlineNanos) {
synchronized (backendLock) {
while (running && backendPort <= 0) {
long remainingNanos = deadlineNanos - System.nanoTime();
if (remainingNanos <= 0) {
return -1;
}
long waitMillis = Math.max(1L,
Math.min(1000L, TimeUnit.NANOSECONDS.toMillis(remainingNanos)));
try {
backendLock.wait(waitMillis);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
return -1;
}
}
return backendPort;
}
}
private static void relayBidirectional(Socket left, Socket right) throws IOException {
final IOException[] upstreamError = new IOException[1];
Thread upstream = new Thread(() -> {
try {
copy(left, right);
} catch (IOException e) {
upstreamError[0] = e;
} finally {
closeQuietly(left);
closeQuietly(right);
}
}, "vpn-socks-relay-up");
upstream.setDaemon(true);
upstream.start();
try {
copy(right, left);
} finally {
closeQuietly(left);
closeQuietly(right);
try {
upstream.join(1000L);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
if (upstreamError[0] != null) {
throw upstreamError[0];
}
}
private static void copy(Socket source, Socket destination) throws IOException {
InputStream in = source.getInputStream();
OutputStream out = destination.getOutputStream();
byte[] buffer = new byte[COPY_BUFFER_SIZE];
int read;
while ((read = in.read(buffer)) >= 0) {
if (read == 0) {
continue;
}
out.write(buffer, 0, read);
}
}
private static void closeQuietly(Socket socket) {
if (socket == null) {
return;
}
try {
socket.close();
} catch (IOException ignored) {
}
}
private static void closeQuietly(ServerSocket socket) {
if (socket == null) {
return;
}
try {
socket.close();
} catch (IOException ignored) {
}
}
}
@@ -0,0 +1,138 @@
package com.dragonssh.xhttpdemo.core.tunnel;
import java.io.IOException;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.UnknownHostException;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.Security;
import java.security.cert.X509Certificate;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocket;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import android.annotation.SuppressLint;
import android.content.Context;
import com.dragonssh.xhttpdemo.core.config.Settings;
import com.dragonssh.xhttpdemo.core.tunnel.vpn.SocketProtector;
import org.conscrypt.Conscrypt;
import java.security.SecureRandom;
import java.util.Objects;
public class TLSSocketFactory extends SSLSocketFactory {
private SSLSocketFactory internalSSLSocketFactory;
static {
try {
Security.insertProviderAt(Conscrypt.newProvider(), 1);
} catch (NoClassDefFoundError e) {
e.printStackTrace();
}}
public SSLContext sslctx;
private Settings mConfig;
public TLSSocketFactory(Context context) throws KeyManagementException, NoSuchAlgorithmException {
mConfig = new Settings(context);
// For easier debugging purpose, trust all certificates
//dsp = ApplicationBase.getDefSharedPreferences();
TrustManager[] trustAllCerts = new TrustManager[]{
new X509TrustManager() {
public X509Certificate[] getAcceptedIssuers() {
return null;
}
@SuppressLint({"TrustAllX509TrustManager"})
public void checkClientTrusted(X509Certificate[] certs, String authType) {
}
@SuppressLint({"TrustAllX509TrustManager"})
public void checkServerTrusted(X509Certificate[] certs, String authType) {
}
}
};
sslctx = SSLContext.getInstance("TLS");
sslctx.init(null, trustAllCerts, new SecureRandom());
internalSSLSocketFactory = sslctx.getSocketFactory();
}
@Override
public String[] getDefaultCipherSuites() {
return internalSSLSocketFactory.getDefaultCipherSuites();
}
@Override
public String[] getSupportedCipherSuites() {
return internalSSLSocketFactory.getSupportedCipherSuites();
}
@Override
public Socket createSocket() throws IOException {
Socket socket = enableTLSOnSocket(internalSSLSocketFactory.createSocket());
SocketProtector.protect(socket);
return socket;
}
@Override
public Socket createSocket(Socket s, String host, int port, boolean autoClose) throws IOException {
return enableTLSOnSocket(internalSSLSocketFactory.createSocket(s, host, port, autoClose));
}
@Override
public Socket createSocket(String host, int port) throws IOException, UnknownHostException {
Socket socket = createSocket();
socket.connect(new InetSocketAddress(host, port));
return socket;
}
@Override
public Socket createSocket(String host, int port, InetAddress localHost, int localPort) throws IOException, UnknownHostException {
Socket socket = createSocket();
socket.bind(new InetSocketAddress(localHost, localPort));
socket.connect(new InetSocketAddress(host, port));
return socket;
}
@Override
public Socket createSocket(InetAddress host, int port) throws IOException {
Socket socket = createSocket();
socket.connect(new InetSocketAddress(host, port));
return socket;
}
@Override
public Socket createSocket(InetAddress address, int port, InetAddress localAddress, int localPort) throws IOException {
Socket socket = createSocket();
socket.bind(new InetSocketAddress(localAddress, localPort));
socket.connect(new InetSocketAddress(address, port));
return socket;
}
private Socket enableTLSOnSocket(Socket socket) {
if (socket instanceof SSLSocket) {
if (Objects.equals(mConfig.getPrivString(Settings.TLS12), "1")){
((SSLSocket) socket).setEnabledProtocols(new String[]{"TLSv1", "TLSv1.1", "TLSv1.2"});
}else{
((SSLSocket) socket).setEnabledProtocols(new String[]{"TLSv1", "TLSv1.1", "TLSv1.2", "TLSv1.3"});
}
// ((SSLSocket) socket).setEnabledProtocols(((SSLSocket) socket).getSupportedProtocols());
}
return socket;
}
}
@@ -0,0 +1,29 @@
package com.dragonssh.xhttpdemo.core.tunnel;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import androidx.localbroadcastmanager.content.LocalBroadcastManager;
import com.dragonssh.xhttpdemo.core.XHttpSshService;
/** Small public API used by the sample activity. */
public final class TunnelManagerHelper {
private TunnelManagerHelper() {}
public static void startXHttpSsh(Context context, String password) {
Intent intent = new Intent(context, XHttpSshService.class)
.putExtra(XHttpSshService.EXTRA_SSH_PASSWORD, password);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
context.startForegroundService(intent);
} else {
context.startService(intent);
}
}
public static void stopXHttpSsh(Context context) {
LocalBroadcastManager.getInstance(context).sendBroadcast(
new Intent(XHttpSshService.TUNNEL_SSH_STOP_SERVICE));
}
}
@@ -0,0 +1,29 @@
package com.dragonssh.xhttpdemo.core.tunnel;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.Network;
import android.net.NetworkCapabilities;
import android.os.Build;
/** Network check used by the connection and reconnect loops. */
public final class TunnelUtils {
private TunnelUtils() {}
public static boolean isNetworkOnline(Context context) {
ConnectivityManager manager =
(ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
if (manager == null) return false;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
Network network = manager.getActiveNetwork();
if (network == null) return false;
NetworkCapabilities capabilities = manager.getNetworkCapabilities(network);
return capabilities != null
&& capabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET);
}
android.net.NetworkInfo info = manager.getActiveNetworkInfo();
return info != null && info.isConnected();
}
}
@@ -0,0 +1,73 @@
package com.dragonssh.xhttpdemo.core.tunnel;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
/**
* A virtual duplex {@link Socket} handed to the Trilead SSH client by
* {@link XHttpProxy}. Its input stream is the XHTTP downlink (the HTTP/2 GET
* response body) and its output stream is the XHTTP uplink (fed into the HTTP/2
* POST request body). The underlying HTTP/2 connection is managed by OkHttp, so
* this class only bridges the two streams and cleans up on close.
*
* <p>Trilead's {@code TransportManager} only calls {@link #getInputStream()},
* {@link #getOutputStream()}, {@link #close()} and — via {@code Connection} —
* {@link #setTcpNoDelay(boolean)} / {@link #setSoTimeout(int)}. The latter two
* are no-ops here because OkHttp owns the real sockets (read timeout is disabled
* for the streaming tunnel; a stalled SSH handshake is aborted by Trilead's own
* kex-timeout watchdog, which closes this socket).</p>
*/
final class XHttpBridgeSocket extends Socket {
private final InputStream in;
private final OutputStream out;
private final Runnable onClose;
private volatile boolean closed = false;
XHttpBridgeSocket(InputStream in, OutputStream out, Runnable onClose) {
this.in = in;
this.out = out;
this.onClose = onClose;
}
@Override
public InputStream getInputStream() {
return in;
}
@Override
public OutputStream getOutputStream() {
return out;
}
@Override
public void setTcpNoDelay(boolean on) { /* managed by OkHttp */ }
@Override
public void setSoTimeout(int timeout) { /* streaming tunnel: no read timeout */ }
@Override
public boolean isConnected() {
return !closed;
}
@Override
public boolean isClosed() {
return closed;
}
@Override
public synchronized void close() throws IOException {
if (closed) {
return;
}
closed = true;
try { out.close(); } catch (Exception ignored) {}
try { in.close(); } catch (Exception ignored) {}
if (onClose != null) {
try { onClose.run(); } catch (Exception ignored) {}
}
}
}
@@ -0,0 +1,538 @@
package com.dragonssh.xhttpdemo.core.tunnel;
import android.content.Context;
import com.dragonssh.xhttpdemo.core.BuildConfig;
import com.dragonssh.xhttpdemo.core.logger.SkStatus;
import com.dragonssh.xhttpdemo.core.tunnel.vpn.SocketProtector;
import com.trilead.ssh2.ProxyData;
import java.io.ByteArrayOutputStream;
import java.io.FilterInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Arrays;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import javax.net.SocketFactory;
import javax.net.ssl.X509TrustManager;
import okhttp3.Call;
import okhttp3.Dispatcher;
import okhttp3.Dns;
import okhttp3.HttpUrl;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Protocol;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
/**
* XHTTP (SplitHTTP) transport for the SSH tunnel, over <b>HTTP/2</b>.
*
* <p>Implements {@link ProxyData} and returns a
* {@link Socket} whose duplex byte stream is consumed by the Trilead SSH client.
* The SSH stream is carried over the server's native XHTTP inbound as a real
* Xray-style XHTTP client would:</p>
*
* <ul>
* <li><b>Downlink</b> — {@code GET {path}/{session}} : one long-lived streamed
* HTTP/2 response body = server&rarr;client SSH stream (stream-down).</li>
* <li><b>Uplink</b> — {@code POST {path}/{session}/{seq}} : one discrete POST
* per SSH packet, sequence-numbered (packet-up). The server reassembles by
* {@code seq}.</li>
* </ul>
*
* <p><b>Why this exact shape:</b> CDNs (e.g. Azion) buffer HTTP/1.1 and buffer
* streaming request bodies, but pass HTTP/2 responses and discrete POSTs through
* in real time. So the download must be HTTP/2 stream-down and the upload must be
* packet-up — anything else stalls the SSH handshake behind the CDN.</p>
*
* <p><b>Domain fronting:</b> OkHttp derives the TLS SNI from the URL host and the
* HTTP routing host from the request {@code Host} header, so the URL host
* is the SNI (e.g. a carrier "bug" domain) while {@code Host} is the CDN edge,
* and a custom {@link Dns} pins the connection to the configured server IP.</p>
*/
public class XHttpProxy implements ProxyData {
private static final String USER_AGENT =
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0 Safari/537.36";
private static final MediaType OCTET = MediaType.parse("application/octet-stream");
private static final long UPLINK_READ_TIMEOUT_SECONDS = 20;
private static final long UPLINK_CALL_TIMEOUT_SECONDS = 30;
private final String server; // IP/host to actually connect to (the "proxy")
private final int port;
private final boolean useTls;
private final String sni; // TLS SNI (URL host)
private final String path;
private final String host; // XHTTP Host used by the CDN/reverse proxy
private final Context mContext;
private volatile XHttpBridgeSocket bridge;
public XHttpProxy(String server, int port, boolean useTls, String sni, String path, String host, Context context) {
this.server = server;
this.port = port;
this.useTls = useTls;
this.sni = trimOrNull(sni);
this.path = path;
this.host = trimOrNull(host);
this.mContext = context;
}
@Override
public Socket openConnection(String hostname, int port, int connectTimeout, int readTimeout) throws IOException {
final String sessionId = UUID.randomUUID().toString().replace("-", "");
final String urlHost = (useTls && sni != null) ? sni : stripBrackets(server);
final String hostHeader = hostHeader();
final String reqPath = buildPath(sessionId);
final String scheme = useTls ? "https" : "http";
final HttpUrl sessionUrl = new HttpUrl.Builder()
.scheme(scheme)
.host(urlHost)
.port(this.port)
.encodedPath(reqPath)
.build();
if (BuildConfig.DEBUG) {
SkStatus.logInfo("XHTTP(h2): connect=" + server + ":" + this.port
+ " sni=" + (sni != null ? sni : "(none)") + " host=" + hostHeader
+ " url=" + sessionUrl);
} else {
SkStatus.logInfo(useTls
? "Iniciando XHTTP (TLS)..."
: "Iniciando XHTTP (sem TLS)...");
}
final OkHttpClient client = buildClient(connectTimeout);
try {
// --- Downlink: GET, streamed HTTP/2 response body (server -> client) ---
Request getReq = new Request.Builder()
.url(sessionUrl)
.header("Host", hostHeader)
.header("User-Agent", USER_AGENT)
.header("Accept", "*/*")
.get()
.build();
Response dlResp = client.newCall(getReq).execute();
if (!dlResp.isSuccessful() || dlResp.body() == null) {
int code = dlResp.code();
dlResp.close();
throw new IOException("XHTTP download rejected: HTTP " + code);
}
final Response downResp = dlResp;
final InputStream rawDownIn = dlResp.body().byteStream();
final InputStream downIn = new FilterInputStream(rawDownIn) {
private boolean terminationLogged;
private void logTermination(String detail) {
if (!terminationLogged) {
terminationLogged = true;
SkStatus.logError("XHTTP downlink stopped: " + detail);
}
}
@Override public int read() throws IOException {
try {
int value = super.read();
if (value < 0) logTermination("EOF");
return value;
} catch (IOException e) {
logTermination(e.getMessage() != null ? e.getMessage() : e.toString());
throw e;
}
}
@Override public int read(byte[] b, int off, int len) throws IOException {
try {
int count = super.read(b, off, len);
if (count < 0) logTermination("EOF");
return count;
} catch (IOException e) {
logTermination(e.getMessage() != null ? e.getMessage() : e.toString());
throw e;
}
}
};
// h2 is required to traverse CDNs; surface the negotiated protocol so a
// silent fallback to HTTP/1.1 (which CDNs buffer) is visible in the log.
SkStatus.logInfo("XHTTP proto=" + dlResp.protocol());
// --- Uplink: packet-up (one POST per SSH packet) ---
final PacketUpOutputStream upOut =
new PacketUpOutputStream(client, sessionUrl, hostHeader);
Runnable onClose = new Runnable() {
@Override public void run() {
upOut.markClosed();
try { downResp.close(); } catch (Exception ignored) {}
}
};
XHttpBridgeSocket b = new XHttpBridgeSocket(downIn, upOut, onClose);
upOut.setBridge(b);
this.bridge = b;
return b;
} catch (IOException e) {
throw e;
} catch (Exception e) {
throw new IOException("XHTTP connect failed: " + e);
}
}
private OkHttpClient buildClient(int connectTimeout) throws IOException {
// Pin every lookup to the configured server IP (the "proxy"); the URL host
// is used only for SNI / routing, never for DNS.
final InetAddress[] pinned;
try {
pinned = InetAddress.getAllByName(stripBrackets(server));
} catch (UnknownHostException e) {
throw new IOException("XHTTP: cannot resolve server " + server + ": " + e);
}
Dns dns = new Dns() {
@Override public List<InetAddress> lookup(String hostname) {
return Arrays.asList(pinned);
}
};
// This client only needs one stream-down GET plus one packet-up POST at a
// time. Keep a small bounded dispatcher so a transport bug cannot create an
// unbounded HTTP queue inside the VPN process.
Dispatcher dispatcher = new Dispatcher();
dispatcher.setMaxRequests(8);
dispatcher.setMaxRequestsPerHost(8);
OkHttpClient.Builder b = new OkHttpClient.Builder()
.dns(dns)
.dispatcher(dispatcher)
.socketFactory(new ProtectedSocketFactory())
.connectTimeout(connectTimeout > 0 ? connectTimeout : 15000, TimeUnit.MILLISECONDS)
.readTimeout(0, TimeUnit.MILLISECONDS) // streaming download: no read timeout
.writeTimeout(30, TimeUnit.SECONDS)
.callTimeout(0, TimeUnit.MILLISECONDS)
.pingInterval(25, TimeUnit.SECONDS) // keep the h2 connection alive
.retryOnConnectionFailure(false);
if (useTls) {
X509TrustManager trustAll = new X509TrustManager() {
@Override public void checkClientTrusted(java.security.cert.X509Certificate[] c, String a) {}
@Override public void checkServerTrusted(java.security.cert.X509Certificate[] c, String a) {}
@Override public java.security.cert.X509Certificate[] getAcceptedIssuers() {
return new java.security.cert.X509Certificate[0];
}
};
try {
b.sslSocketFactory(new TLSSocketFactory(mContext), trustAll);
} catch (Exception e) {
throw new IOException("XHTTP: TLS setup failed: " + e);
}
b.hostnameVerifier((h, s) -> true);
b.protocols(Arrays.asList(Protocol.HTTP_2, Protocol.HTTP_1_1));
} else {
// Plaintext is only for direct (no-CDN) testing, where HTTP/1.1 streams
// fine; h2 is only required to defeat CDN buffering over TLS.
b.protocols(Arrays.asList(Protocol.HTTP_1_1));
}
return b.build();
}
/** SocketFactory that excludes control sockets from the VPN (avoids routing loops). */
private static final class ProtectedSocketFactory extends SocketFactory {
@Override public Socket createSocket() throws IOException {
Socket s = new Socket();
boolean vpnReady = SocketProtector.isVpnServiceReady();
boolean protectedOk = SocketProtector.protect(s);
/*
* Some Samsung/vendor builds return false here for an unconnected
* socket even though the VPN is valid. Do not destroy the reconnect:
* the active VPN was established with this package UID excluded, so
* this socket is already outside the TUN at the routing-policy layer.
*/
if (vpnReady && !protectedOk && !SocketProtector.isProcessBypassConfigured()) {
try { s.close(); } catch (IOException ignored) {}
throw new IOException("XHTTP control socket has no VPN bypass");
}
if (vpnReady && !protectedOk) {
SkStatus.logDebug("XHTTP protect(Socket) returned false; using package UID VPN bypass");
}
return s;
}
@Override public Socket createSocket(String host, int port) { throw new UnsupportedOperationException(); }
@Override public Socket createSocket(String host, int port, InetAddress lh, int lp) { throw new UnsupportedOperationException(); }
@Override public Socket createSocket(InetAddress host, int port) { throw new UnsupportedOperationException(); }
@Override public Socket createSocket(InetAddress host, int port, InetAddress lh, int lp) { throw new UnsupportedOperationException(); }
}
/**
* Uplink as sequence-numbered POSTs (packet-up): {@code POST {session}/{seq}}.
*
* <p>Sent <b>strictly in order, single-flight</b> — one POST fully completes
* before the next starts. The server sends its {@code 200} only after pushing
* each packet to the SSH reader, so waiting for each response guarantees the
* server receives seq 0,1,2,… in order and its reorder buffer never grows
* (concurrent/out-of-order POSTs used to overflow it and kill the tunnel).</p>
*
* <p>SSH writes just append to a buffer; a single worker thread drains it,
* coalescing whatever accumulated during the previous round-trip into one POST
* (up to {@link #MAX_POST}) so throughput isn't limited to one packet per RTT.
* Writers block once the buffer hits {@link #MAX_BUFFER} (backpressure).</p>
*/
private static final class PacketUpOutputStream extends OutputStream {
private static final int MAX_POST = 900 * 1024; // stay under server per-POST cap (1MB)
private static final int MAX_BUFFER = 8 * 1024 * 1024; // backpressure ceiling
private static final long MAX_BACKPRESSURE_WAIT_MS = 35_000;
private final OkHttpClient uplinkClient;
private final HttpUrl base; // .../{session}
private final String hostHeader;
private final Object lock = new Object();
private final ByteArrayOutputStream buf = new ByteArrayOutputStream();
private long seq = 0; // touched only by the worker thread
private volatile IOException error;
private volatile boolean closed;
private volatile XHttpBridgeSocket bridge;
private volatile Call activeCall;
private final Thread worker;
PacketUpOutputStream(OkHttpClient client, HttpUrl base, String hostHeader) {
// The stream-down call must have no read/call timeout, but packet-up POSTs
// absolutely must. A CDN can keep a POST open forever without returning an
// error; with the old shared no-timeout client the SSH writer blocked, the
// ping thread blocked behind it, and automatic reconnect never ran.
this.uplinkClient = client.newBuilder()
.readTimeout(UPLINK_READ_TIMEOUT_SECONDS, TimeUnit.SECONDS)
.callTimeout(UPLINK_CALL_TIMEOUT_SECONDS, TimeUnit.SECONDS)
.build();
this.base = base;
this.hostHeader = hostHeader;
this.worker = new Thread(this::runUplink, "xhttp-uplink");
this.worker.setDaemon(true);
this.worker.start();
}
void setBridge(XHttpBridgeSocket b) { this.bridge = b; }
void markClosed() {
Call call;
synchronized (lock) {
closed = true;
buf.reset();
call = activeCall;
lock.notifyAll();
}
if (call != null) {
call.cancel();
}
}
@Override public void write(int b) throws IOException {
write(new byte[]{(byte) b}, 0, 1);
}
@Override public void write(byte[] b, int off, int len) throws IOException {
if (len <= 0) {
return;
}
IOException timeoutFailure = null;
synchronized (lock) {
checkState();
// Backpressure: don't let the buffer grow unbounded if SSH out-runs the link.
long deadlineNanos = System.nanoTime() + TimeUnit.MILLISECONDS.toNanos(MAX_BACKPRESSURE_WAIT_MS);
while (buf.size() >= MAX_BUFFER && error == null && !closed) {
long remainingNanos = deadlineNanos - System.nanoTime();
if (remainingNanos <= 0) {
timeoutFailure = new IOException("XHTTP uplink backpressure timed out");
break;
}
waitOn(remainingNanos);
}
if (timeoutFailure == null) {
checkState();
buf.write(b, off, len);
lock.notifyAll();
}
}
if (timeoutFailure != null) {
fail(timeoutFailure);
throw timeoutFailure;
}
}
@Override public void flush() throws IOException {
synchronized (lock) {
checkState();
lock.notifyAll(); // the worker already sends promptly; nudge it
}
}
@Override public void close() {
markClosed();
}
private void runUplink() {
while (true) {
byte[] data;
synchronized (lock) {
while (buf.size() == 0 && !closed && error == null) {
try {
lock.wait();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
fail(new IOException("XHTTP uplink worker interrupted", e));
return;
}
}
if (error != null || closed) {
return;
}
byte[] all = buf.toByteArray();
buf.reset();
if (all.length > MAX_POST) {
data = Arrays.copyOfRange(all, 0, MAX_POST);
buf.write(all, MAX_POST, all.length - MAX_POST); // keep remainder for next round
} else {
data = all;
}
lock.notifyAll(); // release any writer blocked on backpressure
}
if (!sendPacket(data)) {
return; // error already recorded and bridge closed
}
}
}
/** Sends one packet POST synchronously (single-flight) so ordering is guaranteed. */
private boolean sendPacket(byte[] data) {
if (closed) {
return false;
}
long s = seq++;
HttpUrl u = base.newBuilder().addPathSegment(Long.toString(s)).build();
Request req = new Request.Builder()
.url(u)
.header("Host", hostHeader)
.header("User-Agent", USER_AGENT)
.post(RequestBody.create(OCTET, data))
.build();
Call call = uplinkClient.newCall(req);
activeCall = call;
if (closed) {
call.cancel();
activeCall = null;
return false;
}
try (Response r = call.execute()) {
if (!r.isSuccessful()) {
fail(new IOException("XHTTP uplink seq=" + s + " HTTP " + r.code()));
return false;
}
return true;
} catch (IOException e) {
if (closed) {
return false;
}
fail(new IOException("XHTTP uplink seq=" + s + " failed: " + e.getMessage(), e));
return false;
} finally {
if (activeCall == call) {
activeCall = null;
}
}
}
private void fail(IOException e) {
boolean first;
synchronized (lock) {
first = error == null;
if (first) {
error = e;
}
lock.notifyAll();
}
if (first) {
SkStatus.logError("XHTTP uplink stopped: " + e.getMessage());
}
XHttpBridgeSocket b = bridge;
if (b != null) {
try { b.close(); } catch (Exception ignored) {}
}
}
private void waitOn(long remainingNanos) throws IOException {
try {
long waitMillis = remainingNanos / 1_000_000L;
int waitNanos = (int) (remainingNanos % 1_000_000L);
lock.wait(waitMillis, waitNanos);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new IOException("XHTTP uplink interrupted");
}
}
private void checkState() throws IOException {
if (error != null) {
throw error;
}
if (closed) {
throw new IOException("XHTTP uplink closed");
}
}
}
private String buildPath(String sessionId) {
String p = (path == null || path.trim().isEmpty()) ? "/" : path.trim();
if (!p.startsWith("/")) {
p = "/" + p;
}
while (p.endsWith("/")) {
p = p.substring(0, p.length() - 1);
}
return p + "/" + sessionId;
}
private String hostHeader() {
if (host != null) {
return host;
}
if (sni != null) {
return sni;
}
return stripBrackets(server);
}
@Override
public void close() {
XHttpBridgeSocket b = this.bridge;
if (b != null) {
try { b.close(); } catch (IOException ignored) {}
}
}
private static String trimOrNull(String s) {
if (s == null) return null;
s = s.trim();
return s.isEmpty() ? null : s;
}
private static String stripBrackets(String h) {
if (h == null) return null;
if (h.startsWith("[") && h.endsWith("]")) {
return h.substring(1, h.length() - 1);
}
return h;
}
}
@@ -0,0 +1,85 @@
/*
* Copyright (c) 2012-2016 Arne Schwabe
* Distributed under the GNU GPL v2 with additional terms. For full terms see the file doc/LICENSE.txt
*/
package com.dragonssh.xhttpdemo.core.tunnel.vpn;
import java.net.InetAddress;
import java.util.Locale;
public class CIDRIP {
String mIp;
int len;
public CIDRIP(String address, int prefix_length) {
len = prefix_length;
mIp = address;
}
public CIDRIP(String address, long prefix_length) {
len = (int) prefix_length;
mIp = address;
}
@Override
public String toString() {
if (InetAddressUtils.isIPv4Address(mIp)) {
return String.format(Locale.ENGLISH, "%s/%d", mIp, len);
} else if (InetAddressUtils.isIPv6Address(mIp)) {
return String.format(Locale.ENGLISH, "%s/%d", mIp, (long) len);
} else {
return mIp;
}
}
static class InetAddressUtils {
private static final int INET4_ADDRESS_LENGTH = 4;
private static final int INET6_ADDRESS_LENGTH = 16;
public static boolean isIPv4Address(String input) {
try {
InetAddress inetAddress = InetAddress.getByName(input);
return inetAddress.getAddress().length == INET4_ADDRESS_LENGTH;
} catch (Exception e) {
return false;
}
}
public static boolean isIPv6Address(String input) {
try {
InetAddress inetAddress = InetAddress.getByName(input);
return inetAddress.getAddress().length == INET6_ADDRESS_LENGTH;
} catch (Exception e) {
return false;
}
}
}
static long getInt(String ipaddr) {
try {
InetAddress inetAddress = InetAddress.getByName(ipaddr);
byte[] addressBytes = inetAddress.getAddress();
long ip = 0;
if (InetAddressUtils.isIPv4Address(ipaddr)) {
ip += (addressBytes[0] & 0xFFL) << 24;
ip += (addressBytes[1] & 0xFFL) << 16;
ip += (addressBytes[2] & 0xFFL) << 8;
ip += addressBytes[3] & 0xFFL;
} else if (InetAddressUtils.isIPv6Address(ipaddr)) {
for (byte b : addressBytes) {
ip = (ip << 8) | (b & 0xFFL);
}
}
return ip;
} catch (Exception e) {
return 0;
}
}
public long getInt() {
return getInt(mIp);
}
}
@@ -0,0 +1,369 @@
/*
* Copyright (c) 2012-2016 Arne Schwabe
* Distributed under the GNU GPL v2 with additional terms. For full terms see the file doc/LICENSE.txt
*/
package com.dragonssh.xhttpdemo.core.tunnel.vpn;
import android.os.Build;
import androidx.annotation.NonNull;
import java.math.BigInteger;
import java.net.Inet6Address;
import java.util.Collection;
import java.util.Locale;
import java.util.PriorityQueue;
import java.util.TreeSet;
import java.util.Vector;
import com.dragonssh.xhttpdemo.core.BuildConfig;
public class NetworkSpace {
static void assertTrue(boolean f)
{
if (!f)
throw new IllegalStateException();
}
public static class IpAddress implements Comparable<IpAddress> {
private BigInteger netAddress;
public int networkMask;
private boolean included;
private boolean isV4;
private BigInteger firstAddress;
private BigInteger lastAddress;
/**
* sorts the networks with following criteria:
* 1. compares first 1 of the network
* 2. smaller networks are returned as smaller
*/
@Override
public int compareTo(@NonNull IpAddress another) {
int comp = getFirstAddress().compareTo(another.getFirstAddress());
if (comp != 0)
return comp;
if (networkMask > another.networkMask)
return -1;
else if (another.networkMask == networkMask)
return 0;
else
return 1;
}
/**
* Warning ignores the included integer
*
* @param o the object to compare this instance with.
*/
@Override
public boolean equals(Object o) {
if (!(o instanceof IpAddress))
return super.equals(o);
IpAddress on = (IpAddress) o;
return (networkMask == on.networkMask) && on.getFirstAddress().equals(getFirstAddress());
}
public IpAddress(CIDRIP ip, boolean include) {
included = include;
netAddress = BigInteger.valueOf(ip.getInt());
networkMask = ip.len;
isV4 = true;
}
public IpAddress(Inet6Address address, int mask, boolean include) {
networkMask = mask;
included = include;
int s = 128;
netAddress = BigInteger.ZERO;
for (byte b : address.getAddress()) {
s -= 8;
netAddress = netAddress.add(BigInteger.valueOf((b & 0xFF)).shiftLeft(s));
}
}
public BigInteger getLastAddress() {
if (lastAddress == null)
lastAddress = getMaskedAddress(true);
return lastAddress;
}
public BigInteger getFirstAddress() {
if (firstAddress == null)
firstAddress = getMaskedAddress(false);
return firstAddress;
}
private BigInteger getMaskedAddress(boolean one) {
BigInteger numAddress = netAddress;
int numBits;
if (isV4) {
numBits = 32 - networkMask;
} else {
numBits = 128 - networkMask;
}
for (int i = 0; i < numBits; i++) {
if (one)
numAddress = numAddress.setBit(i);
else
numAddress = numAddress.clearBit(i);
}
return numAddress;
}
@Override
public String toString() {
//String in = included ? "+" : "-";
if (isV4)
return String.format(Locale.US, "%s/%d", getIPv4Address(), networkMask);
else
return String.format(Locale.US, "%s/%d", getIPv6Address(), networkMask);
}
IpAddress(BigInteger baseAddress, int mask, boolean included, boolean isV4) {
this.netAddress = baseAddress;
this.networkMask = mask;
this.included = included;
this.isV4 = isV4;
}
public IpAddress[] split() {
IpAddress firstHalf = new IpAddress(getFirstAddress(), networkMask + 1, included, isV4);
IpAddress secondHalf = new IpAddress(firstHalf.getLastAddress().add(BigInteger.ONE), networkMask + 1, included, isV4);
if (BuildConfig.DEBUG)
assertTrue(secondHalf.getLastAddress().equals(getLastAddress()));
return new IpAddress[]{firstHalf, secondHalf};
}
public String getIPv4Address() {
if (BuildConfig.DEBUG) {
assertTrue(isV4);
assertTrue(netAddress.longValue() <= 0xffffffffl);
assertTrue(netAddress.longValue() >= 0);
}
long ip = netAddress.longValue();
return String.format(Locale.US, "%d.%d.%d.%d", (ip >> 24) % 256, (ip >> 16) % 256, (ip >> 8) % 256, ip % 256);
}
public String getIPv6Address() {
if (BuildConfig.DEBUG) assertTrue(!isV4);
BigInteger r = netAddress;
String ipv6str = null;
boolean lastPart = true;
while (r.compareTo(BigInteger.ZERO) == 1) {
long part = r.mod(BigInteger.valueOf(0x10000)).longValue();
if (ipv6str != null || part != 0) {
if (ipv6str == null && !lastPart)
ipv6str = ":";
if (lastPart)
ipv6str = String.format(Locale.US, "%x", part, ipv6str);
else
ipv6str = String.format(Locale.US, "%x:%s", part, ipv6str);
}
r = r.shiftRight(16);
lastPart = false;
}
if (ipv6str == null)
return "::";
return ipv6str;
}
public boolean containsNet(IpAddress network) {
// this.first >= net.first && this.last <= net.last
BigInteger ourFirst = getFirstAddress();
BigInteger ourLast = getLastAddress();
BigInteger netFirst = network.getFirstAddress();
BigInteger netLast = network.getLastAddress();
boolean a = ourFirst.compareTo(netFirst) != 1;
boolean b = ourLast.compareTo(netLast) != -1;
return a && b;
}
}
TreeSet<IpAddress> mIpAddresses = new TreeSet<IpAddress>();
public Collection<IpAddress> getNetworks(boolean included) {
Vector<IpAddress> ips = new Vector<IpAddress>();
for (IpAddress ip : mIpAddresses) {
if (ip.included == included)
ips.add(ip);
}
return ips;
}
public void clear() {
mIpAddresses.clear();
}
public void addIP(CIDRIP cidrIp, boolean include) {
mIpAddresses.add(new IpAddress(cidrIp, include));
}
public void addIPSplit(CIDRIP cidrIp, boolean include) {
IpAddress newIP = new IpAddress(cidrIp, include);
IpAddress[] splitIps = newIP.split();
for (IpAddress split : splitIps)
mIpAddresses.add(split);
}
public void addIPv6(Inet6Address address, int mask, boolean included) {
mIpAddresses.add(new IpAddress(address, mask, included));
}
TreeSet<IpAddress> generateIPList() {
PriorityQueue<IpAddress> networks = new PriorityQueue<IpAddress>(mIpAddresses);
TreeSet<IpAddress> ipsDone = new TreeSet<IpAddress>();
IpAddress currentNet = networks.poll();
if (currentNet == null)
return ipsDone;
while (currentNet != null) {
// Check if it and the next of it are compatible
IpAddress nextNet = networks.poll();
if (BuildConfig.DEBUG) assertTrue(currentNet!=null);
if (nextNet == null || currentNet.getLastAddress().compareTo(nextNet.getFirstAddress()) == -1) {
// Everything good, no overlapping nothing to do
ipsDone.add(currentNet);
currentNet = nextNet;
} else {
// This network is smaller or equal to the next but has the same base address
if (currentNet.getFirstAddress().equals(nextNet.getFirstAddress()) && currentNet.networkMask >= nextNet.networkMask) {
if (currentNet.included == nextNet.included) {
// Included in the next next and same type
// Simply forget our current network
currentNet = nextNet;
} else {
// our currentNet is included in next and types differ. Need to split the next network
IpAddress[] newNets = nextNet.split();
// TODO: The contains method of the Priority is stupid linear search
// First add the second half to keep the order in networks
if (!networks.contains(newNets[1]))
networks.add(newNets[1]);
if (newNets[0].getLastAddress().equals(currentNet.getLastAddress())) {
if (BuildConfig.DEBUG)
assertTrue(newNets[0].networkMask == currentNet.networkMask);
// Don't add the lower half that would conflict with currentNet
} else {
if (!networks.contains(newNets[0]))
networks.add(newNets[0]);
}
// Keep currentNet as is
}
} else {
if (BuildConfig.DEBUG) {
assertTrue(currentNet.networkMask < nextNet.networkMask);
assertTrue(nextNet.getFirstAddress().compareTo(currentNet.getFirstAddress()) == 1);
assertTrue(currentNet.getLastAddress().compareTo(nextNet.getLastAddress()) != -1);
}
// This network is bigger than the next and last ip of current >= next
//noinspection StatementWithEmptyBody
if (currentNet.included == nextNet.included) {
// Next network is in included in our network with the same type,
// simply ignore the next and move on
} else {
// We need to split our network
IpAddress[] newNets = currentNet.split();
if (newNets[1].networkMask == nextNet.networkMask) {
if (BuildConfig.DEBUG) {
assertTrue(newNets[1].getFirstAddress().equals(nextNet.getFirstAddress()));
assertTrue(newNets[1].getLastAddress().equals(currentNet.getLastAddress()));
// split second equal the next network, do not add it
}
networks.add(nextNet);
} else {
// Add the smaller network first
networks.add(newNets[1]);
networks.add(nextNet);
}
currentNet = newNets[0];
}
}
}
}
return ipsDone;
}
public Collection<IpAddress> getPositiveIPList() {
TreeSet<IpAddress> ipsSorted = generateIPList();
Vector<IpAddress> ips = new Vector<IpAddress>();
for (IpAddress ia : ipsSorted) {
if (ia.included)
ips.add(ia);
}
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT) {
// Include postive routes from the original set under < 4.4 since these might overrule the local
// network but only if no smaller negative route exists
for (IpAddress origIp : mIpAddresses) {
if (!origIp.included)
continue;
// The netspace exists
if (ipsSorted.contains(origIp))
continue;
boolean skipIp = false;
// If there is any smaller net that is excluded we may not add the positive route back
for (IpAddress calculatedIp : ipsSorted) {
if (!calculatedIp.included && origIp.containsNet(calculatedIp)) {
skipIp = true;
break;
}
}
if (skipIp)
continue;
// It is safe to include the IP
ips.add(origIp);
}
}
return ips;
}
}
@@ -0,0 +1,143 @@
package com.dragonssh.xhttpdemo.core.tunnel.vpn;
import java.io.File;
import android.content.Context;
import java.io.FileNotFoundException;
import java.io.IOException;
import com.dragonssh.xhttpdemo.core.R;
import com.dragonssh.xhttpdemo.core.util.StreamGobbler;
import com.dragonssh.xhttpdemo.core.util.FileUtils;
import com.dragonssh.xhttpdemo.core.logger.SkStatus;
import com.dragonssh.xhttpdemo.core.util.CustomNativeLoader;
public class Pdnsd extends Thread {
private final static String TAG = "PdnsdThread";
private final static String PDNSD_SERVER = "server {\n label= \"%1$s\";\n ip = %2$s;\n port = %3$d;\n uptest = none;\n }\n";
private final static String PDNSD_SERVER_TEST = "server {\n label= \"%1$s\";\n ip = %2$s;\n port = %3$d;\n reject = ::/0;\n reject_policy = negate;\n reject_recursively = on;\n timeout = 5;\n }\n";
private final static String PDNSD_BIN = "libpdnsd";
private OnPdnsdListener mListener;
public interface OnPdnsdListener {
public void onStart();
public void onStop();
}
private Process mProcess;
private File filePdnsd;
private Context mContext;
private String[] mDnsHosts;
private int mDnsPort;
private String mPdnsdHost;
private int mPdnsdPort;
public Pdnsd(Context context, String[] dnsHosts, int dnsPort, String pdnsdHost, int pdnsdPort) {
mContext = context;
mDnsHosts = dnsHosts;
mDnsPort = dnsPort;
mPdnsdHost = pdnsdHost;
mPdnsdPort = pdnsdPort;
}
@Override
public void run() {
if (mListener != null) {
mListener.onStart();
}
try {
filePdnsd = CustomNativeLoader.loadNativeBinary(mContext, PDNSD_BIN, new File(mContext.getFilesDir(), PDNSD_BIN));
if (filePdnsd == null) {
throw new IOException("Pdnsd binary not found");
}
File fileConf = makePdnsdConf(mContext.getFilesDir(), mDnsHosts, mDnsPort, mPdnsdHost, mPdnsdPort);
String cmdString = filePdnsd.getCanonicalPath() + " -v9 -c " + fileConf.toString();
mProcess = Runtime.getRuntime().exec(cmdString);
StreamGobbler.OnLineListener onLineListener = new StreamGobbler.OnLineListener(){
@Override
public void onLine(String log){
SkStatus.logDebug("Pdnsd: " + log);
}
};
StreamGobbler stdoutGobbler = new StreamGobbler(mProcess.getInputStream(), onLineListener);
StreamGobbler stderrGobbler = new StreamGobbler(mProcess.getErrorStream(), onLineListener);
stdoutGobbler.start();
stderrGobbler.start();
mProcess.waitFor();
} catch (IOException e) {
SkStatus.logException("Pdnsd Error", e);
} catch(Exception e){
SkStatus.logDebug("Pdnsd Error: " + e);
}
mProcess = null;
if (mListener != null) {
mListener.onStop();
}
}
@Override
public synchronized void interrupt()
{
super.interrupt();
if (mProcess != null)
mProcess.destroy();
try {
if (filePdnsd != null)
VpnUtils.killProcess(filePdnsd);
} catch(Exception e) {}
mProcess = null;
filePdnsd = null;
}
private File makePdnsdConf(File fileDir, String[] dnsHosts, int dnsPort, String pdnsdHost, int pdnsdPort) throws FileNotFoundException, IOException {
String content = FileUtils.readFromRaw(mContext, R.raw.pdnsd_local);
// dns servers
StringBuilder server_dns = new StringBuilder();
for (int i = 0; i < dnsHosts.length; i++){
String dnsHost = dnsHosts[i];
server_dns.append(String.format(PDNSD_SERVER, "server" + Integer.toString(i+1), dnsHost, dnsPort));
}
String conf = String.format(content, server_dns.toString(), fileDir.getCanonicalPath(), pdnsdHost, pdnsdPort);
File f = new File(fileDir,"pdnsd.conf");
if (f.exists()) {
f.delete();
}
FileUtils.saveTextFile(f, conf);
File cache = new File(fileDir,"pdnsd.cache");
if (!cache.exists()) {
try {
cache.createNewFile();
} catch (Exception e) {}
}
return f;
}
public void setOnPdnsdListener(OnPdnsdListener listener){
this.mListener = listener;
}
}
@@ -0,0 +1,167 @@
package com.dragonssh.xhttpdemo.core.tunnel.vpn;
import android.net.VpnService;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.net.DatagramSocket;
import java.net.Socket;
/**
* Centralized helper to ensure control sockets (SSH / proxy / TLS) are excluded
* from the VPN routing.
*
* <p>When a VPN is established and a control socket is not protected, Android
* will route that socket into the VPN itself, creating a loop (VPN -> SOCKS ->
* VPN). This is especially visible with IPv6, where ::/0 routing is commonly
* installed.
*/
public final class SocketProtector {
private static volatile VpnService sVpnService;
// True only after the active VPN interface has been established with this
// application UID excluded through Builder.addDisallowedApplication().
// In that mode every control-plane socket created by this process already
// uses the underlying network, even on devices where protect(Socket)
// incorrectly returns false during a reconnect.
private static volatile boolean sProcessBypassConfigured;
// Sockets created before the VpnService instance is available.
// We keep weak refs to avoid leaking in edge cases.
private static final Object sLock = new Object();
private static final List<WeakReference<Object>> sPending = new ArrayList<>();
private SocketProtector() {
}
public static void setVpnService(VpnService vpnService) {
sVpnService = vpnService;
if (vpnService != null) {
flushPending(vpnService);
}
}
/**
* Clears the active VpnService only if it is still the same owner.
* This prevents a stopped XRAY service from clearing the SSH VPN service
* after the user switches modes.
*/
public static void clearVpnService(VpnService vpnService) {
if (vpnService == null) {
return;
}
synchronized (sLock) {
if (sVpnService == vpnService) {
sVpnService = null;
sProcessBypassConfigured = false;
sPending.clear();
}
}
}
public static boolean isVpnServiceReady() {
return sVpnService != null;
}
public static void setProcessBypassConfigured(boolean configured) {
sProcessBypassConfigured = configured;
}
public static boolean isProcessBypassConfigured() {
return sProcessBypassConfigured;
}
public static boolean protect(Socket socket) {
if (socket == null) return false;
final VpnService svc = sVpnService;
if (svc == null) {
enqueue(socket);
return false;
}
return doProtect(svc, socket);
}
public static boolean protect(DatagramSocket socket) {
if (socket == null) return false;
final VpnService svc = sVpnService;
if (svc == null) {
enqueue(socket);
return false;
}
return doProtect(svc, socket);
}
/**
* Protect a raw native socket file descriptor.
*
* Use this from gomobile/JNI callbacks before the native code connects
* the socket. Raw FDs cannot be safely queued: the native side may connect
* or close/reuse the descriptor before the VPN service becomes available.
*/
public static boolean protectFd(int fd) {
if (fd < 0) return false;
final VpnService svc = sVpnService;
if (svc == null) return false;
return doProtectFd(svc, fd);
}
private static void enqueue(Object socket) {
synchronized (sLock) {
// Avoid unlimited growth if protect() is called repeatedly.
if (sPending.size() > 128) {
// Drop oldest.
sPending.remove(0);
}
sPending.add(new WeakReference<>(socket));
}
}
private static void flushPending(VpnService svc) {
final List<Object> toProtect = new ArrayList<>();
synchronized (sLock) {
for (WeakReference<Object> ref : sPending) {
Object obj = ref.get();
if (obj != null) {
toProtect.add(obj);
}
}
sPending.clear();
}
for (Object obj : toProtect) {
if (obj instanceof Socket) {
doProtect(svc, (Socket) obj);
} else if (obj instanceof DatagramSocket) {
doProtect(svc, (DatagramSocket) obj);
}
}
}
private static boolean doProtect(VpnService svc, Socket socket) {
try {
return svc.protect(socket);
} catch (Throwable ignored) {
return false;
}
}
private static boolean doProtect(VpnService svc, DatagramSocket socket) {
try {
return svc.protect(socket);
} catch (Throwable ignored) {
return false;
}
}
private static boolean doProtectFd(VpnService svc, int fd) {
try {
return svc.protect(fd);
} catch (Throwable ignored) {
return false;
}
}
}
@@ -0,0 +1,293 @@
package com.dragonssh.xhttpdemo.core.tunnel.vpn;
import android.os.ParcelFileDescriptor;
import java.io.IOException;
import java.io.File;
import android.net.LocalSocket;
import android.net.LocalSocketAddress;
import java.io.FileDescriptor;
import android.content.Context;
import com.dragonssh.xhttpdemo.core.util.StreamGobbler;
import androidx.core.content.ContextCompat;
import com.dragonssh.xhttpdemo.core.logger.SkStatus;
import com.dragonssh.xhttpdemo.core.util.CustomNativeLoader;
public class Tun2Socks extends Thread implements StreamGobbler.OnLineListener {
private static final String TAG = Tun2Socks.class.getSimpleName();
private static final String TUN2SOCKS_BIN = "libtun2socks";
private OnTun2SocksListener mListener;
public interface OnTun2SocksListener {
public void onStart();
public void onStop();
}
private Process tun2SocksProcess;
private ParcelFileDescriptor mVpnInterfaceFileDescriptor;
private int mVpnInterfaceMTU;
/**
* IPv4 address assigned to the VPN interface. Historically only a single
* IPv4 address was supported. To support IPv6 natively, a separate
* {@code mVpnIp6Address} field has been added. Existing code that
* constructs {@link Tun2Socks} without specifying an IPv6 address will
* continue to work – the IPv6 address will simply remain {@code null} and
* no {@code --netif-ip6addr} argument will be passed to the underlying
* tun2socks binary.
*/
private String mVpnIpAddress;
/**
* IPv6 address assigned to the VPN interface. This may be {@code null}
* when only IPv4 connectivity is required. When provided, the
* constructor will append a {@code --netif-ip6addr} flag when spawning
* the tun2socks process.
*/
private String mVpnIp6Address;
private String mVpnNetMask;
private String mSocksServerAddress;
private String mUdpgwServerAddress;
private String mDnsResolverAddress;
private boolean mUdpgwTransparentDNS;
private Context mContext;
private File fileTun2Socks;
/**
* Construct a {@link Tun2Socks} instance. This constructor has been
* updated to accept an optional IPv6 address. If the provided
* {@code vpnIp6Address} is {@code null} or empty, only an IPv4 address will
* be configured on the tun interface. To maintain backwards
* compatibility with existing callers, an overloaded constructor without
* the {@code vpnIp6Address} parameter is provided below.
*
* @param context the context used to resolve resources
* @param vpnInterfaceFileDescriptor file descriptor of the VPN interface
* @param vpnInterfaceMTU MTU of the VPN interface
* @param vpnIpAddress IPv4 address assigned to the interface
* @param vpnIp6Address IPv6 address assigned to the interface (may be null)
* @param vpnNetMask network mask for the IPv4 address
* @param socksServerAddress address of the SOCKS proxy
* @param udpgwServerAddress address of the UDP gateway (may be null)
* @param dnsResolverAddress address of the DNS resolver (may be null)
* @param udpgwTransparentDNS whether to enable transparent DNS over UDP
*/
public Tun2Socks(Context context, ParcelFileDescriptor vpnInterfaceFileDescriptor, int vpnInterfaceMTU,
String vpnIpAddress, String vpnIp6Address, String vpnNetMask,
String socksServerAddress, String udpgwServerAddress,
String dnsResolverAddress, boolean udpgwTransparentDNS) {
mContext = context;
mVpnInterfaceFileDescriptor = vpnInterfaceFileDescriptor;
mVpnInterfaceMTU = vpnInterfaceMTU;
mVpnIpAddress = vpnIpAddress;
mVpnIp6Address = vpnIp6Address;
mVpnNetMask = vpnNetMask;
mSocksServerAddress = socksServerAddress;
mUdpgwServerAddress = udpgwServerAddress;
mDnsResolverAddress = dnsResolverAddress;
mUdpgwTransparentDNS = udpgwTransparentDNS;
}
/**
* Backwards compatible constructor. Invokes the full constructor without
* assigning an IPv6 address.
*/
public Tun2Socks(Context context, ParcelFileDescriptor vpnInterfaceFileDescriptor, int vpnInterfaceMTU,
String vpnIpAddress, String vpnNetMask, String socksServerAddress,
String udpgwServerAddress, String dnsResolverAddress, boolean udpgwTransparentDNS) {
this(context, vpnInterfaceFileDescriptor, vpnInterfaceMTU, vpnIpAddress, null, vpnNetMask,
socksServerAddress, udpgwServerAddress, dnsResolverAddress, udpgwTransparentDNS);
}
@Override
public void run() {
if (mListener != null) {
mListener.onStart();
}
try {
StringBuilder cmd = new StringBuilder();
//File fileTun2Socks = CustomNativeLoader.loadExecutableBinary(mContext, "libtun2socks.so");
fileTun2Socks = CustomNativeLoader.loadNativeBinary(mContext, TUN2SOCKS_BIN, new File(mContext.getFilesDir(),TUN2SOCKS_BIN));
if (fileTun2Socks == null){
throw new IOException("Tun2Socks binary not found");
}
if (mVpnInterfaceFileDescriptor != null){
File file_path = new File(ContextCompat.getDataDir(mContext), "sock_path");
try {
if (!file_path.exists())
file_path.createNewFile();
} catch(IOException e){
throw new IOException("Failed to create socket file: " + file_path.getCanonicalPath());
}
cmd.append(fileTun2Socks.getCanonicalPath());
// Always configure the IPv4 address on the tun interface
cmd.append(" --netif-ipaddr " + mVpnIpAddress);
// Optionally configure an IPv6 address when provided. When
// mVpnIp6Address is null or empty, no IPv6 address is passed
// to the tun2socks binary. This allows clients to continue
// operating in IPv4-only environments while enabling native
// dual-stack operation when possible.
if (mVpnIp6Address != null && !mVpnIp6Address.isEmpty()) {
cmd.append(" --netif-ip6addr " + mVpnIp6Address);
}
cmd.append(" --netif-netmask " + mVpnNetMask);
cmd.append(" --socks-server-addr " + mSocksServerAddress);
cmd.append(" --tunmtu " + Integer.toString(mVpnInterfaceMTU));
cmd.append(" --tunfd " + mVpnInterfaceFileDescriptor.getFd());
cmd.append(" --sock " + file_path.getAbsolutePath());
cmd.append(" --loglevel " + Integer.toString(3));
if (mUdpgwServerAddress != null) {
if (mUdpgwTransparentDNS) {
cmd.append(" --udpgw-transparent-dns");
}
String udpgwAddr = mUdpgwServerAddress;
// Normalize IPv6 host:port into [host]:port for badvpn-tun2socks parser.
// Accept user input as:
// - host:port (IPv4/hostname)
// - ipv6 (no port) -> default 7300
// - ipv6:port (no brackets) -> brackets will be added
// - [ipv6]:port (already OK)
if (udpgwAddr != null) {
udpgwAddr = udpgwAddr.trim();
if (!udpgwAddr.isEmpty()) {
// If it's a bare IPv6 without brackets and has multiple ':' then bracket it.
boolean looksIpv6 = udpgwAddr.contains(":") && udpgwAddr.indexOf(':') != udpgwAddr.lastIndexOf(':');
if (looksIpv6 && !udpgwAddr.startsWith("[")) {
// Split last ':' as port if present, otherwise default.
int lastColon = udpgwAddr.lastIndexOf(':');
String hostPart = udpgwAddr;
String portPart = "7300";
if (lastColon > 0 && lastColon < udpgwAddr.length() - 1) {
hostPart = udpgwAddr.substring(0, lastColon);
String maybePort = udpgwAddr.substring(lastColon + 1);
if (maybePort.matches("\\d+")) {
portPart = maybePort;
} else {
hostPart = udpgwAddr; // treat as no-port
}
}
udpgwAddr = "[" + hostPart + "]:" + portPart;
} else if (udpgwAddr.matches("^[0-9a-fA-F:]+$")) {
// Pure IPv6 without port
udpgwAddr = "[" + udpgwAddr + "]:7300";
}
}
}
cmd.append(" --udpgw-remote-server-addr " + udpgwAddr);
}
if (mDnsResolverAddress != null) {
cmd.append(" --dnsgw " + mDnsResolverAddress);
}
// Start the native tun2socks process.
tun2SocksProcess = Runtime.getRuntime().exec(cmd.toString());
StreamGobbler stdoutGobbler = new StreamGobbler(tun2SocksProcess.getInputStream(), this);
StreamGobbler stderrGobbler = new StreamGobbler(tun2SocksProcess.getErrorStream(), this);
stdoutGobbler.start();
stderrGobbler.start();
// send Fd
if (!sendFd(mVpnInterfaceFileDescriptor, file_path)) {
throw new IOException("Failed to pass the TUN file descriptor to tun2socks");
}
tun2SocksProcess.waitFor();
}
} catch (IOException e) {
SkStatus.logException("Tun2Socks Error", e);
} catch (Exception e) {
SkStatus.logDebug("Tun2Socks Error: " + e.getMessage());
}
tun2SocksProcess = null;
if (mListener != null) {
mListener.onStop();
}
}
@Override
public synchronized void interrupt()
{
// TODO: Implement this method
super.interrupt();
//net.typeblog.socks.System.jniclose(mVpnInterfaceFileDescriptor.getFd());
if (tun2SocksProcess != null)
tun2SocksProcess.destroy();
try {
if (fileTun2Socks != null)
VpnUtils.killProcess(fileTun2Socks);
} catch (Exception e) {}
tun2SocksProcess = null;
fileTun2Socks = null;
}
public void setOnTun2SocksListener(OnTun2SocksListener listener){
this.mListener = listener;
}
/**
* StreamGobbler OnLine Listener
* implementation
*/
@Override
public void onLine(String log){
SkStatus.logDebug("Tun2Socks: " + log);
}
//----------------------------------------------------------------------------
// Utils
//----------------------------------------------------------------------------
private boolean sendFd(ParcelFileDescriptor fileDescriptor, File toFile) throws InterruptedException {
SkStatus.logDebug("Enviando Fd para sock");
for (int tries = 10; tries >= 0; tries--) {
try {
LocalSocket localSocket = new LocalSocket();
localSocket.connect(new LocalSocketAddress(toFile.getAbsolutePath(), LocalSocketAddress.Namespace.FILESYSTEM));
localSocket.setFileDescriptorsForSend(new FileDescriptor[]{
fileDescriptor.getFileDescriptor()
});
localSocket.getOutputStream().write(42);
localSocket.shutdownOutput();
localSocket.close();
return true;
} catch(IOException unused) {
Thread.sleep(500);
}
/*if (net.typeblog.socks.System.sendfd(fileDescriptor.getFd(), toFile.getAbsolutePath()) != -1) {
return true;
}
try {
Thread.sleep(500);
} catch(InterruptedException e){}*/
}
return false;
}
}
@@ -0,0 +1,479 @@
/*
* Copyright (c) 2015, Psiphon Inc.
* All rights reserved.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package com.dragonssh.xhttpdemo.core.tunnel.vpn;
import static android.system.OsConstants.AF_INET;
import static android.system.OsConstants.AF_INET6;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.net.VpnService;
import android.os.Build;
import android.os.ParcelFileDescriptor;
import java.io.IOException;
import java.util.Arrays;
import java.util.Locale;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicReference;
import com.dragonssh.xhttpdemo.core.config.Settings;
import com.dragonssh.xhttpdemo.core.logger.SkStatus;
/**
* Baseado no Cordova Plugin Tun2Socks
*
* @author dFiR30n
*/
public class Tunnel {
public interface HostService {
public String getAppName();
public Context getContext();
// Object must be a VpnService; Android < 4 cannot reference this class name
public Object getVpnService();
// Object must be a VpnService.Builder;
// Android < 4 cannot reference this class name
public Object newVpnServiceBuilder();
public void onDiagnosticMessage(String message);
public void onTunnelConnected();
public void onVpnEstablished();
public void onTunnelStopped();
}
private final HostService mHostService;
private VpnUtils.PrivateAddress mPrivateAddress;
private AtomicReference<ParcelFileDescriptor> mTunFd;
private AtomicBoolean mRoutingThroughTunnel;
private Tun2Socks mTun2Socks;
private Pdnsd mPdnsd;
private NetworkSpace mRoutes;
private Settings mConfig;
// Only StartNET VPNService instance may exist at a time, as the underlying
// tun2socks implementation contains global state.
private static Tunnel mTunnel;
public static synchronized Tunnel newTunnel(HostService hostService) {
if (mTunnel != null) {
mTunnel.stop();
}
mTunnel = new Tunnel(hostService);
return mTunnel;
}
private Tunnel(HostService hostService) {
mHostService = hostService;
mTunFd = new AtomicReference<ParcelFileDescriptor>();
mRoutingThroughTunnel = new AtomicBoolean(false);
mRoutes = new NetworkSpace();
//org.uproxy.tun2socks.Tun2SocksJni.init();
}
public Object clone() throws CloneNotSupportedException {
throw new CloneNotSupportedException();
}
//----------------------------------------------------------------------------------------------
// Public API
//----------------------------------------------------------------------------------------------
// To start, call in sequence: startRouting(), then startTunneling(). After startRouting()
// succeeds, the caller must call stop() to clean up.
// Returns true when the VPN routing is established; returns false if the VPN could not
// be started due to lack of prepare or revoked permissions (called should re-prepare and
// try again); throws exception for other error conditions.
public synchronized boolean startRouting(TunnelVpnSettings settings) throws java.lang.Exception {
return startVpn(settings.mDnsForward, settings.mDnsResolver, settings.mExcludeIps,
settings.mEnableFilterApps, settings.mFilterBypassMode, settings.mFilterApps, settings.mTetheringSubnet, settings.mDisableIpv6Tunnel);
}
// Starts tun2socks. Returns true on success.
public synchronized boolean startTunneling(String socksServerAddress, String[] dnsResolver, boolean forwardDns, String udpResolver, boolean udpDnsRelay)
throws Exception {
return routeThroughTunnel(socksServerAddress, dnsResolver, forwardDns, udpResolver, udpDnsRelay);
}
// Stops routing traffic through the tunnel by stopping tun2socks.
// The VPN is unaffected by this method.
public synchronized void stopTunneling() {
stopRoutingThroughTunnel();
}
// Note: to avoid deadlock, do not call directly from a HostService callback;
// instead post to a Handler if necessary to trigger from a HostService callback.
public synchronized void stop() {
stopVpn();
}
//----------------------------------------------------------------------------
// VPN Routing
//----------------------------------------------------------------------------
private static final String VPN_INTERFACE_NETMASK = "255.255.255.0";
// IPv6 addressing for the TUN interface and the internal tun2socks router.
// Using an RFC4193 ULA prefix avoids collisions with real networks.
private static final String VPN_INTERFACE_IPV6_ADDRESS = "fd00:1:fd00:1::1";
private static final int VPN_INTERFACE_IPV6_PREFIX_LENGTH = 64;
private static final String VPN_ROUTER_IPV6_ADDRESS = "fd00:1:fd00:1::2";
private static final String DNS_RESOLVER_IP = "8.8.8.8";
private static final int DNS_RESOLVER_PORT = 53;
//private String dns6 = "0";
private int mMtu = 1500;
// Note: Atomic variables used for getting/setting local proxy port, routing flag, and
// tun fd, as these functions may be called via callbacks. Do not use
// synchronized functions as stop() is synchronized and a deadlock is possible as callbacks
// can be called while stop holds the lock.
//
private boolean startVpn(boolean forwardDns, String[] dnsResolver, String[] excludeIps,
boolean enabledFilter, boolean filterBypassMode, String[] filterApps, boolean enableTethering, boolean disableIpv6Tunnel) throws java.lang.Exception {
mPrivateAddress = VpnUtils.selectPrivateAddress();
// Make sure control sockets (SSH/proxy/TLS) are excluded from the VPN.
// This prevents routing loops, especially when IPv6 ::/0 is installed.
SocketProtector.setVpnService((VpnService) mHostService.getVpnService());
// routes list
// For IPv4 we use NetworkSpace to compute a minimal set of routes excluding the server.
// For IPv6, Android does not provide a direct "exclude this single address" API when
// installing ::/0. As a defensive fallback (in addition to VpnService.protect), we build
// a set of IPv6 prefixes that cover all IPv6 addresses *except* the excluded server /128.
// This avoids the control connection being routed into the VPN when the server is IPv6.
String excludedServerIpv6 = null;
for (String ip : excludeIps) {
if (ip != null && ip.contains(":")) {
excludedServerIpv6 = ip;
SkStatus.logInfo("IPV6 DETECTED");
} else {
SkStatus.logInfo("IPV4 DETECTED");
mRoutes.addIP(new CIDRIP(ip, 32), false);
}
}
Locale previousLocale = Locale.getDefault();
final String errorMessage = "startVpn failed";
try {
// Workaround for https://code.google.com/p/android/issues/detail?id=61096
Locale.setDefault(new Locale("en"));
ParcelFileDescriptor tunFd = null;
// Create the Android VPN builder.
VpnService.Builder builder = ((VpnService.Builder) mHostService.newVpnServiceBuilder())
.addAddress(mPrivateAddress.mIpAddress, mPrivateAddress.mPrefixLength)
.allowFamily(AF_INET);
/*
* Keep the VPN implementation's own UID outside the TUN at the Android
* policy layer. All SSH, TLS, proxy and XHTTP control sockets are created
* by this package. Excluding the package prevents those reconnect sockets
* from ever entering tun2socks, even on vendor ROMs where
* VpnService.protect(Socket) returns false for a fresh socket.
*
* The traffic of other applications is still routed through the VPN.
*/
try {
builder.addDisallowedApplication(mHostService.getContext().getPackageName());
} catch (PackageManager.NameNotFoundException e) {
throw new Exception("Unable to exclude VPN control process from TUN", e);
}
if (!disableIpv6Tunnel) {
builder.allowFamily(AF_INET6);
// Configure an IPv6 address on the VPN interface so IPv6 flows can be
// routed through tun2socks. Without an IPv6 address on the interface,
// Android will not reliably deliver IPv6 packets to the TUN device.
builder.addAddress(VPN_INTERFACE_IPV6_ADDRESS, VPN_INTERFACE_IPV6_PREFIX_LENGTH);
if (excludedServerIpv6 != null) {
SkStatus.logInfo("Excluding server IPv6 from VPN routes: " + excludedServerIpv6);
addIpv6RoutesExcludingSingleAddress(builder, excludedServerIpv6);
} else {
builder.addRoute("::", 0);
}
} else {
SkStatus.logInfo("IPv6 tunnel disabled by config");
}
mRoutes.addIP(new CIDRIP("0.0.0.0", 0), true);
mRoutes.addIP(new CIDRIP("10.0.0.0", 8), false);
mRoutes.addIP(new CIDRIP(mPrivateAddress.mSubnet, mPrivateAddress.mPrefixLength), false);
// ainda pra testar, subnet routing pesquisar "allow lan"
if (enableTethering) {
// USB tethering 192.168.42.x
// Wi-Fi tethering 192.168.43.x
mRoutes.addIP(new CIDRIP("192.168.42.0", 23), false);
// Bluetooth tethering 192.168.44.x
mRoutes.addIP(new CIDRIP("192.168.44.0", 24), false);
// Wi-Fi direct 192.168.49.x
mRoutes.addIP(new CIDRIP("192.168.49.0", 24), false);
}
// Add Dns
for (String dns : dnsResolver) {
try {
builder.addDnsServer(dns);
if (CIDRIP.InetAddressUtils.isIPv4Address(dns)) {
SkStatus.logInfo("DNS IPV4 ON");
mRoutes.addIP(new CIDRIP(dns, 32), forwardDns);
}
if (CIDRIP.InetAddressUtils.isIPv6Address(Arrays.toString(excludeIps))) {
SkStatus.logInfo("DNS IPV6 ON");
builder.addDnsServer("2606:4700:4700::1111");
builder.addDnsServer("2606:4700:4700::1001");
}
} catch (IllegalArgumentException iae) {
mHostService.onDiagnosticMessage(String.format("Failed to add DNS server %s: %s", dns, iae.getLocalizedMessage()));
}
}
// set MTU
String release = Build.VERSION.RELEASE;
if ((Build.VERSION.SDK_INT == Build.VERSION_CODES.KITKAT && !release.startsWith("4.4.3")
&& !release.startsWith("4.4.4") && !release.startsWith("4.4.5") && !release.startsWith("4.4.6"))
&& mMtu < 1280) {
SkStatus.logInfo(String.format(Locale.US, "Forcing MTU to 1280 instead of %d to workaround Android Bug #70916", mMtu));
mMtu = 1280;
}
builder.setMtu(mMtu);
// loop routes
NetworkSpace.IpAddress multicastRange = new NetworkSpace.IpAddress(new CIDRIP("224.0.0.0", 3), true);
for (NetworkSpace.IpAddress route : mRoutes.getPositiveIPList()) {
try {
if (multicastRange.containsNet(route))
SkStatus.logDebug("VPN: Ignoring multicast route: " + route.toString());
else
builder.addRoute(route.getIPv4Address(), route.networkMask);
} catch (IllegalArgumentException ia) {
//mHostService.onDiagnosticMessage("Route rejeitada: " + route + " " + ia.getLocalizedMessage());
}
}
// The UID bypass is considered active only after establish() succeeds.
SocketProtector.setProcessBypassConfigured(false);
// TunFd
tunFd = builder
.setSession(mHostService.getAppName())
.establish();
if (tunFd == null) {
// As per http://developer.android.com/reference/android/net/VpnService.Builder.html#establish%28%29,
// this application is no longer prepared or was revoked.
return false;
}
mTunFd.set(tunFd);
SocketProtector.setProcessBypassConfigured(true);
mRoutingThroughTunnel.set(false);
mHostService.onVpnEstablished();
mRoutes.clear();
} catch (IllegalArgumentException e) {
throw new Exception("IllegalArgumentException", e);
} catch (SecurityException e) {
throw new Exception("IllegalArgumentException", e);
} catch (IllegalStateException e) {
throw new Exception("IllegalStateException", e);
} finally {
// Restore the original locale.
Locale.setDefault(previousLocale);
}
return true;
}
private boolean routeThroughTunnel(final String socksServerAddress, final String[] dnsResolver, boolean forwardDns, final String udpResolver, final boolean transparentDns) {
if (!mRoutingThroughTunnel.compareAndSet(false, true)) {
return false;
}
final ParcelFileDescriptor tunFd = mTunFd.get();
if (tunFd == null) {
return false;
}
// Pdnsd
String dnsgwRelay = null;
if (forwardDns) {
int pdnsdPort = VpnUtils.findAvailablePort(8091, 10);
String[] mServidorDNS = dnsResolver;
dnsgwRelay = String.format("%s:%d", mPrivateAddress.mIpAddress, pdnsdPort);
mPdnsd = new Pdnsd(mHostService.getContext(), mServidorDNS, DNS_RESOLVER_PORT,
mPrivateAddress.mIpAddress, pdnsdPort);
mPdnsd.setOnPdnsdListener(new Pdnsd.OnPdnsdListener() {
@Override
public void onStart() {
}
@Override
public void onStop() {
stop();
mHostService.onTunnelStopped();
}
});
mPdnsd.start();
}
// Tun2socks
boolean disableIpv6Tunnel = new Settings(mHostService.getContext()).getDisableIpv6Tunnel();
mTun2Socks = new Tun2Socks(mHostService.getContext(), tunFd, mMtu,
mPrivateAddress.mRouter, disableIpv6Tunnel ? null : VPN_ROUTER_IPV6_ADDRESS, VPN_INTERFACE_NETMASK,
socksServerAddress, udpResolver, dnsgwRelay, transparentDns);
mTun2Socks.setOnTun2SocksListener(new Tun2Socks.OnTun2SocksListener() {
@Override
public void onStart() {
}
@Override
public void onStop() {
stop();
mHostService.onTunnelStopped();
}
});
mTun2Socks.start();
mHostService.onTunnelConnected();
// TODO: should double-check tunnel routing; see:
// https://bitbucket.org/psiphon/psiphon-circumvention-system/src/1dc5e4257dca99790109f3bf374e8ab3a0ead4d7/Android/PsiphonAndroidLibrary/src/com/psiphon3/psiphonlibrary/TunnelCore.java?at=default#cl-779
return true;
}
/**
* Adds IPv6 routes that cover the entire IPv6 space except for a single excluded /128.
*
* <p>This is a defensive fallback for cases where {@link VpnService#protect(java.net.Socket)}
* is not effective on a given device/ROM. For a single excluded address, the complement can be
* represented by at most 128 prefixes.
*/
private static void addIpv6RoutesExcludingSingleAddress(VpnService.Builder builder, String excludedIpv6) {
if (builder == null || excludedIpv6 == null) {
return;
}
try {
java.net.InetAddress ia = java.net.InetAddress.getByName(excludedIpv6);
if (!(ia instanceof java.net.Inet6Address)) {
builder.addRoute("::", 0);
return;
}
final byte[] excluded = ia.getAddress(); // 16 bytes
// For each bit position i, add a prefix (i+1) that matches the excluded address for the
// first i bits and has the i-th bit flipped. The union of these prefixes equals the
// full IPv6 space minus the excluded /128.
for (int i = 0; i < 128; i++) {
byte[] prefix = excluded.clone();
// Flip the i-th bit (MSB-first).
int byteIndex = i / 8;
int bitIndex = 7 - (i % 8);
prefix[byteIndex] = (byte) (prefix[byteIndex] ^ (1 << bitIndex));
// Zero all bits after i to create a proper network prefix address.
int nextBit = i + 1;
int zeroFromByte = nextBit / 8;
int zeroFromBit = 7 - (nextBit % 8);
// If nextBit is byte-aligned, zero whole bytes from there.
if (nextBit % 8 == 0) {
for (int b = zeroFromByte; b < 16; b++) {
prefix[b] = 0;
}
} else {
// Mask the current byte to keep only the prefix bits, then zero subsequent bytes.
int mask = 0xFF << (zeroFromBit + 1);
prefix[zeroFromByte] = (byte) (prefix[zeroFromByte] & mask);
for (int b = zeroFromByte + 1; b < 16; b++) {
prefix[b] = 0;
}
}
String routeAddr = java.net.InetAddress.getByAddress(prefix).getHostAddress();
builder.addRoute(routeAddr, i + 1);
}
} catch (Throwable t) {
// If anything goes wrong, fall back to routing all IPv6 through the VPN.
try {
builder.addRoute("::", 0);
} catch (Throwable ignored) {
}
}
}
private void stopRoutingThroughTunnel() {
if (mTun2Socks != null && mTun2Socks.isAlive()) {
mTun2Socks.interrupt();
}
mTun2Socks = null;
if (mPdnsd != null && mPdnsd.isAlive()) {
mPdnsd.interrupt();
}
mPdnsd = null;
}
private void stopVpn() {
stopRoutingThroughTunnel();
SocketProtector.setProcessBypassConfigured(false);
// Clear only this VPN service instance. A different transport mode may
// already have installed a newer protector owner.
SocketProtector.clearVpnService((VpnService) mHostService.getVpnService());
ParcelFileDescriptor tunFd = mTunFd.getAndSet(null);
if (tunFd != null) {
try {
tunFd.close();
} catch (IOException e) {
}
}
}
}
@@ -0,0 +1,40 @@
package com.dragonssh.xhttpdemo.core.tunnel.vpn;
// Singleton class to maintain state related to VPN Tunnel service.
public class TunnelState {
private static TunnelState m_tunnelState;
public Object clone() throws CloneNotSupportedException {
throw new CloneNotSupportedException();
}
public static synchronized TunnelState getTunnelState() {
if (m_tunnelState == null) {
m_tunnelState = new TunnelState();
}
return m_tunnelState;
}
private TunnelVpnManager m_tunnelManager = null;
private boolean m_startingTunnelManager = false;
private TunnelState() {}
public synchronized void setTunnelManager(TunnelVpnManager tunnelManager) {
m_tunnelManager = tunnelManager;
m_startingTunnelManager = false;
}
public synchronized TunnelVpnManager getTunnelManager() {
return m_tunnelManager;
}
public synchronized void setStartingTunnelManager() {
m_startingTunnelManager = true;
}
public synchronized boolean getStartingTunnelManager() {
return m_startingTunnelManager;
}
};
@@ -0,0 +1,294 @@
package com.dragonssh.xhttpdemo.core.tunnel.vpn;
/*
* Copyright (c) 2016, Psiphon Inc.
* All rights reserved.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
import android.annotation.TargetApi;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.net.VpnService;
import android.os.Build;
import android.util.Log;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicBoolean;
import com.dragonssh.xhttpdemo.core.logger.SkStatus;
import com.dragonssh.xhttpdemo.core.R;
import com.dragonssh.xhttpdemo.core.config.Settings;
public class TunnelVpnManager implements Tunnel.HostService
{
private static final String TAG = "TunnelManager";
public static final String VPN_SETTINGS = "vpnSettings";
private TunnelVpnService m_parentService = null;
private CountDownLatch m_tunnelThreadStopSignal;
private Thread m_tunnelThread;
private AtomicBoolean m_isStopping;
private Tunnel m_tunnel = null;
private AtomicBoolean m_isReconnecting;
private TunnelVpnSettings mSettings;
public interface ManagerListener {
public void onLog(String msg);
}
public TunnelVpnManager(TunnelVpnService parentService)
{
m_parentService = parentService;
m_isStopping = new AtomicBoolean(false);
m_isReconnecting = new AtomicBoolean(false);
m_tunnel = Tunnel.newTunnel(this);
}
// Implementation of android.app.Service.onStartCommand
public int onStartCommand(Intent intent, int flags, int startId)
{
Log.i(TAG, "onStartCommand");
if (intent == null) {
Log.e(TAG, "Failed to receive intent");
m_parentService.broadcastVpnStart(false);
return Service.START_NOT_STICKY;
}
mSettings = intent.getParcelableExtra(VPN_SETTINGS);
if (mSettings == null) {
Log.e(TAG, "Failed to receive the Vpn Settings.");
m_parentService.broadcastVpnStart(false);
return Service.START_NOT_STICKY;
}
if (mSettings.mSocksServer == null)
{
Log.e(TAG, "Failed to receive the socks server address.");
m_parentService.broadcastVpnStart(false);
return Service.START_NOT_STICKY;
}
if (mSettings.mDnsResolver == null)
{
Log.e(TAG, "Failed to receive the dns resolvers.");
m_parentService.broadcastVpnStart(false);
return Service.START_NOT_STICKY;
}
try
{
if (!m_tunnel.startRouting(mSettings))
{
Log.e(TAG, "Failed to establish VPN");
m_parentService.broadcastVpnStart(false);
}
}
catch (Exception e)
{
Log.e(TAG, String.format("Failed to establish VPN: %s", e.getMessage()));
m_parentService.broadcastVpnStart(false);
}
return Service.START_REDELIVER_INTENT;
}
// Implementation of android.app.Service.onDestroy
public void onDestroy()
{
if (m_tunnelThread == null)
{
return;
}
// signalStopService should have been called, but in case is was not, call here.
// If signalStopService was not already called, the join may block the calling
// thread for some time.
signalStopService();
try
{
m_tunnelThread.join();
}
catch (InterruptedException e)
{
Thread.currentThread().interrupt();
}
m_tunnelThreadStopSignal = null;
m_tunnelThread = null;
}
// Signals the runTunnel thread to stop. The thread will self-stop the service.
// This is the preferred method for stopping the tunnel service:
// 1. VpnService doesn't respond to stopService calls
// 2. The UI will not block while waiting for stopService to return
public void signalStopService()
{
if (m_tunnelThreadStopSignal != null)
{
m_tunnelThreadStopSignal.countDown();
}
}
// Stops the tunnel thread and restarts it with |socksServerAddress|.
public void restartTunnel(final String socksServerAddress)
{
Log.i(TAG, "Restarting tunnel.");
if (socksServerAddress == null ||
socksServerAddress.equals(mSettings.mSocksServer))
{
// Don't reconnect if the socks server address hasn't changed.
m_parentService.broadcastVpnStart(true);
return;
}
mSettings.mSocksServer = socksServerAddress;
m_isReconnecting.set(true);
// Signaling stop to the tunnel thread with the reconnect flag set causes
// the thread to stop the tunnel (but not the VPN or the service) and send
// the new SOCKS server address to the DNS resolver before exiting itself.
// When the DNS broadcasts its local address, the tunnel will restart.
signalStopService();
}
private void startTunnel()
{
m_tunnelThreadStopSignal = new CountDownLatch(1);
m_tunnelThread =
new Thread(
new Runnable() {
@Override
public void run()
{
runTunnel(mSettings.mSocksServer, mSettings.mDnsResolver, mSettings.mDnsForward, mSettings.mUdpResolver, mSettings.mUdpDnsRelay);
}
});
m_tunnelThread.start();
}
private void runTunnel(String socksServerAddress, String[] dnsResolver, boolean forwardDns, String udpResolver, boolean udpDnsRelay)
{
m_isStopping.set(false);
try
{
if (!m_tunnel.startTunneling(socksServerAddress, dnsResolver, forwardDns, udpResolver, udpDnsRelay))
{
throw new Exception("application is not prepared or revoked");
}
Log.i(TAG, "VPN service running");
m_parentService.broadcastVpnStart(true);
try
{
m_tunnelThreadStopSignal.await();
}
catch (InterruptedException e)
{
Thread.currentThread().interrupt();
}
m_isStopping.set(true);
}
catch (Exception e)
{
Log.e(TAG, String.format("Start tunnel failed: %s", e.getMessage()));
m_parentService.broadcastVpnStart(false);
}
finally
{
if (m_isReconnecting.get())
{
// Stop tunneling only, not VPN, if reconnecting.
Log.i(TAG, "Stopping tunnel.");
m_tunnel.stopTunneling();
}
else
{
// Stop VPN tunnel and service only if not reconnecting.
Log.i(TAG, "Stopping VPN and tunnel.");
m_tunnel.stop();
m_parentService.stopForeground(true);
m_parentService.stopSelf();
}
m_isReconnecting.set(false);
}
}
//----------------------------------------------------------------------------
// Tunnel.HostService
//----------------------------------------------------------------------------
@Override
public String getAppName()
{
return getContext().getString(R.string.app_name);
}
@Override
public Context getContext()
{
return m_parentService;
}
@Override
public VpnService getVpnService()
{
return m_parentService;
}
@Override
public VpnService.Builder newVpnServiceBuilder()
{
return m_parentService.newBuilder();
}
@Override
public void onDiagnosticMessage(String message)
{
SkStatus.logInfo(message);
}
@Override
public void onTunnelConnected()
{
}
@Override
@TargetApi(Build.VERSION_CODES.M)
public void onVpnEstablished()
{
//SkStatus.logInfo("<strong>VPN Estabelecida</strong>");
startTunnel();
}
@Override
public void onTunnelStopped()
{
if (!m_isStopping.get() && !m_isReconnecting.get()) {
Log.w(TAG, "VPN tunnel process stopped unexpectedly");
SkStatus.logInfo("<strong>VPN tunnel stopped. Reconnecting...</strong>");
m_parentService.broadcastVpnDisconnect();
}
// Release runTunnel() so the VpnService can clean up instead of hanging
// forever while the main SSH service starts a fresh connection.
signalStopService();
}
}
@@ -0,0 +1,121 @@
/*
* Copyright (c) 2016, Psiphon Inc.
* All rights reserved.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package com.dragonssh.xhttpdemo.core.tunnel.vpn;
import android.annotation.TargetApi;
import android.content.Intent;
import android.net.VpnService;
import android.os.Binder;
import android.os.Build;
import android.os.IBinder;
import androidx.localbroadcastmanager.content.LocalBroadcastManager;
import com.dragonssh.xhttpdemo.core.logger.SkStatus;
@TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
public class TunnelVpnService extends VpnService {
private static final String LOG_TAG = "TunnelVpnService";
public static final String TUNNEL_VPN_DISCONNECT_BROADCAST =
"tunnelVpnDisconnectBroadcast";
public static final String TUNNEL_VPN_START_BROADCAST =
"tunnelVpnStartBroadcast";
public static final String TUNNEL_VPN_START_SUCCESS_EXTRA =
"tunnelVpnStartSuccessExtra";
private TunnelVpnManager m_tunnelManager = new TunnelVpnManager(this);
public class LocalBinder extends Binder {
public TunnelVpnService getService() {
return TunnelVpnService.this;
}
}
private final IBinder m_binder = new LocalBinder();
@Override
public IBinder onBind(Intent intent) {
String action = intent.getAction();
if (action != null && action.equals(SERVICE_INTERFACE)) {
return super.onBind(intent);
}
return m_binder;
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
//Log.d(LOG_TAG, "on start");
return m_tunnelManager.onStartCommand(intent, flags, startId);
}
@Override
public void onCreate() {
//Log.d(LOG_TAG, "on create");
SocketProtector.setVpnService(this);
TunnelState.getTunnelState().setTunnelManager(m_tunnelManager);
}
@Override
public void onDestroy() {
SkStatus.logInfo("<strong>VPN service destroyed</strong>");
// Keep the SSH service and the Android VPN state synchronized. If Android
// kills or destroys only the VpnService, the main tunnel manager must be
// notified so it can reconnect instead of leaving the app marked connected
// while the phone VPN interface is gone.
broadcastVpnDisconnect();
TunnelState.getTunnelState().setTunnelManager(null);
SocketProtector.clearVpnService(this);
m_tunnelManager.onDestroy();
super.onDestroy();
}
@Override
public void onRevoke() {
SkStatus.logInfo("<strong>VPN service revoked</strong>");
broadcastVpnDisconnect();
// stopSelf will trigger onDestroy in the main thread.
stopSelf();
}
public VpnService.Builder newBuilder() {
return new VpnService.Builder();
}
// Broadcast non-user-initiated VPN disconnect.
public void broadcastVpnDisconnect() {
dispatchBroadcast(new Intent(TUNNEL_VPN_DISCONNECT_BROADCAST));
}
// Broadcast VPN start. |success| is true if the VPN and tunnel were started
// successfully, and false otherwise.
public void broadcastVpnStart(boolean success) {
Intent vpnStart = new Intent(TUNNEL_VPN_START_BROADCAST);
vpnStart.putExtra(TUNNEL_VPN_START_SUCCESS_EXTRA, success);
dispatchBroadcast(vpnStart);
}
private void dispatchBroadcast(final Intent broadcast) {
LocalBroadcastManager.getInstance(TunnelVpnService.this)
.sendBroadcast(broadcast);
}
}
@@ -0,0 +1,87 @@
package com.dragonssh.xhttpdemo.core.tunnel.vpn;
import android.os.Parcelable;
import android.os.Parcel;
public class TunnelVpnSettings
implements Parcelable {
public String mSocksServer;
public boolean mDnsForward;
public String[] mDnsResolver;
public String mUdpResolver;
public String[] mExcludeIps;
public boolean mUdpDnsRelay;
public boolean mEnableFilterApps;
public boolean mFilterBypassMode;
public String[] mFilterApps;
public boolean mTetheringSubnet;
public boolean mDisableIpv6Tunnel;
public TunnelVpnSettings(String socksServer, boolean dnsForward, String[] dnsResolver,
boolean udpDnsRelay, String udpResolver, String[] excludeIps,
boolean enableFilterApps, boolean filterBypassMode, String[] filterApps,
boolean enableTethering, boolean disableIpv6Tunnel)
{
mSocksServer = socksServer;
mDnsForward = dnsForward;
mUdpDnsRelay = udpDnsRelay;
mDnsResolver = dnsResolver;
mUdpResolver = udpResolver;
mExcludeIps = excludeIps;
mEnableFilterApps = enableFilterApps;
mFilterBypassMode = filterBypassMode;
mFilterApps = filterApps;
mTetheringSubnet = enableTethering;
mDisableIpv6Tunnel = disableIpv6Tunnel;
}
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(mSocksServer);
dest.writeInt(mDnsForward ? 1 : 0);
dest.writeInt(mUdpDnsRelay ? 1 : 0);
dest.writeStringArray(mDnsResolver);
dest.writeString(mUdpResolver);
dest.writeStringArray(mExcludeIps);
dest.writeInt(mFilterBypassMode ? 1 : 0);
dest.writeStringArray(mFilterApps);
dest.writeInt(mEnableFilterApps ? 1 : 0);
dest.writeInt(mTetheringSubnet ? 1 : 0);
dest.writeInt(mDisableIpv6Tunnel ? 1 : 0);
}
public TunnelVpnSettings(Parcel in) {
mSocksServer = in.readString();
mDnsForward = in.readInt() == 1;
mUdpDnsRelay = in.readInt() == 1;
mDnsResolver = in.createStringArray();
mUdpResolver = in.readString();
mExcludeIps = in.createStringArray();
mFilterBypassMode = in.readInt() == 1;
mFilterApps = in.createStringArray();
mEnableFilterApps = in.readInt() == 1;
mTetheringSubnet = in.readInt() == 1;
mDisableIpv6Tunnel = in.readInt() == 1;
}
public static final Creator<TunnelVpnSettings> CREATOR
= new Creator<TunnelVpnSettings>() {
public TunnelVpnSettings createFromParcel(Parcel in) {
return new TunnelVpnSettings(in);
}
public TunnelVpnSettings[] newArray(int size) {
return new TunnelVpnSettings[size];
}
};
}
@@ -0,0 +1,373 @@
package com.dragonssh.xhttpdemo.core.tunnel.vpn;
import android.content.Context;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import static java.lang.Runtime.getRuntime;
import java.util.Map;
import java.util.List;
import java.net.NetworkInterface;
import java.util.Collections;
import java.net.SocketException;
import java.net.InetAddress;
import java.net.Inet4Address;
import java.util.HashMap;
import android.annotation.TargetApi;
import android.os.Build;
import java.util.Collection;
import java.util.ArrayList;
import android.net.ConnectivityManager;
import java.lang.reflect.Method;
import android.net.LinkProperties;
import java.lang.reflect.InvocationTargetException;
import java.util.Iterator;
import java.util.regex.Pattern;
import com.dragonssh.xhttpdemo.core.logger.SkStatus;
import java.net.Socket;
import java.net.SocketAddress;
import java.net.InetSocketAddress;
import java.net.SocketTimeoutException;
public class VpnUtils {
public static int findProcessId(String command) throws IOException {
String[] cmds = {"ps -ef","ps -A","toolbox ps"};
for (int i = 0; i < cmds.length;i++) {
Process procPs = getRuntime().exec(cmds[i]);
BufferedReader reader = new BufferedReader(new InputStreamReader(procPs.getInputStream()));
String line;
while ((line = reader.readLine()) != null) {
if (!line.contains("PID") && line.contains(command)) {
String[] lineParts = line.split("\\s+");
try {
return Integer.parseInt(lineParts[1]); //for most devices it is the second
} catch (NumberFormatException e) {
return Integer.parseInt(lineParts[0]); //but for samsungs it is the first
} finally {
try {
procPs.destroy();
} catch (Exception e) {
}
}
}
}
}
return -1;
}
public static void killProcess(File fileProcBin) throws Exception {
killProcess(fileProcBin, "-9"); // this is -KILL
}
public static int killProcess(File fileProcBin, String signal) throws Exception {
int procId = -1;
int killAttempts = 0;
while ((procId = findProcessId(fileProcBin.getName())) != -1) {
killAttempts++;
String pidString = String.valueOf(procId);
String[] cmds = {"","busybox ","toolbox "};
for (int i = 0; i < cmds.length;i++) {
try {
getRuntime().exec(cmds[i] + "killall " + signal + " " + fileProcBin.getName
());
} catch (IOException ioe) {
}
try {
getRuntime().exec(cmds[i] + "killall " + signal + " " + fileProcBin.getCanonicalPath());
} catch (IOException ioe) {
}
}
killProcess(pidString, signal);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// ignored
}
if (killAttempts > 4)
throw new Exception("Cannot kill: " + fileProcBin.getAbsolutePath());
}
return procId;
}
public static void killProcess(String pidString, String signal) throws Exception {
String[] cmds = {"","toolbox ","busybox "};
for (int i = 0; i < cmds.length;i++) {
try {
getRuntime().exec(cmds[i] + "kill " + signal + " " + pidString);
} catch (IOException ioe) {
SkStatus.logDebug(String.format("error killing process: %s, %s", pidString, ioe.getMessage()));
}
}
}
public static List<String> getActiveNetworkDnsResolver(Context context) throws Exception {
Collection<InetAddress> dnsResolvers = getActiveNetworkDnsResolvers(context);
if (!dnsResolvers.isEmpty()) {
ArrayList<String> lista = new ArrayList<String>();
int max = 2;
Iterator it = dnsResolvers.iterator();
while (it.hasNext()) {
String dnsResolver = it.next().toString();
// strip the leading slash e.g., "/192.168.1.1"
if (dnsResolver.startsWith("/")) {
dnsResolver = dnsResolver.substring(1);
}
// Accept both IPv4 and IPv6 DNS resolvers. Previously IPv6
// addresses were filtered out to avoid issues on devices
// lacking dual-stack support. With native IPv6 forwarding,
// clients may be connected to an IPv6-only network, so we
// no longer discard resolvers containing a colon (':').
lista.add(dnsResolver);
max -= 1;
if (max <= 0) break;
}
return lista;
}
else throw new Exception("no active network DNS resolver");
}
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
private static Collection<InetAddress> getActiveNetworkDnsResolvers(Context context)
throws Exception {
final String errorMessage = "getActiveNetworkDnsResolvers failed";
ArrayList<InetAddress> dnsAddresses = new ArrayList<InetAddress>();
try {
// Hidden API
// - only available in Android 4.0+
// - no guarantee will be available beyond 4.2, or on all vendor devices
ConnectivityManager connectivityManager =
(ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
Class<?> LinkPropertiesClass = Class.forName("android.net.LinkProperties");
Method getActiveLinkPropertiesMethod = ConnectivityManager.class.getMethod("getActiveLinkProperties", new Class []{});
Object linkProperties = getActiveLinkPropertiesMethod.invoke(connectivityManager);
if (linkProperties != null) {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
Method getDnsesMethod = LinkPropertiesClass.getMethod("getDnses", new Class []{});
Collection<?> dnses = (Collection<?>)getDnsesMethod.invoke(linkProperties);
for (Object dns : dnses) {
dnsAddresses.add((InetAddress)dns);
}
} else {
// LinkProperties is public in API 21 (and the DNS function signature has changed)
for (InetAddress dns : ((LinkProperties)linkProperties).getDnsServers()) {
dnsAddresses.add(dns);
}
}
}
} catch (ClassNotFoundException e) {
throw new Exception(errorMessage, e);
} catch (NoSuchMethodException e) {
throw new Exception(errorMessage, e);
} catch (IllegalArgumentException e) {
throw new Exception(errorMessage, e);
} catch (IllegalAccessException e) {
throw new Exception(errorMessage, e);
} catch (InvocationTargetException e) {
throw new Exception(errorMessage, e);
} catch (NullPointerException e) {
throw new Exception(errorMessage, e);
}
return dnsAddresses;
}
private final static String DEFAULT_PRIMARY_DNS_SERVER = "8.8.4.4";
private final static String DEFAULT_SECONDARY_DNS_SERVER = "8.8.8.8";
public static List<String> getNetworkDnsServer(Context context) {
List<String> dnsResolver = new ArrayList<String>();
try {
dnsResolver = VpnUtils.getActiveNetworkDnsResolver(context);
} catch (Exception e) {
dnsResolver.add(DEFAULT_PRIMARY_DNS_SERVER);
dnsResolver.add(DEFAULT_SECONDARY_DNS_SERVER);
}
return dnsResolver;
}
/**
* Utils ip
*/
private static final Pattern IPV4_PATTERN =
Pattern.compile(
"^(25[0-5]|2[0-4]\\d|[0-1]?\\d?\\d)(\\.(25[0-5]|2[0-4]\\d|[0-1]?\\d?\\d)){3}$");
private static final Pattern IPV6_STD_PATTERN =
Pattern.compile(
"^(?:[0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}$");
private static final Pattern IPV6_HEX_COMPRESSED_PATTERN =
Pattern.compile(
"^((?:[0-9A-Fa-f]{1,4}(?::[0-9A-Fa-f]{1,4})*)?)::((?:[0-9A-Fa-f]{1,4}(?::[0-9A-Fa-f]{1,4})*)?)$");
public static boolean isIPv4Address(final String input) {
return IPV4_PATTERN.matcher(input).matches();
}
public static boolean isIPv6StdAddress(final String input) {
return IPV6_STD_PATTERN.matcher(input).matches();
}
public static boolean isIPv6HexCompressedAddress(final String input) {
return IPV6_HEX_COMPRESSED_PATTERN.matcher(input).matches();
}
public static boolean isIPv6Address(final String input) {
return isIPv6StdAddress(input) || isIPv6HexCompressedAddress(input);
}
//----------------------------------------------------------------------------
// Implementation: Network Utils
//----------------------------------------------------------------------------
public static class PrivateAddress
{
public final String mIpAddress;
public final String mSubnet;
public final int mPrefixLength;
public final String mRouter;
public PrivateAddress(String ipAddress, String subnet, int prefixLength, String router)
{
mIpAddress = ipAddress;
mSubnet = subnet;
mPrefixLength = prefixLength;
mRouter = router;
}
}
public static PrivateAddress selectPrivateAddress() throws Exception
{
// Select one of 10.0.0.1, 172.16.0.1, or 192.168.0.1 depending on
// which private address range isn't in use.
Map<String, PrivateAddress> candidates = new HashMap<String, PrivateAddress>();
candidates.put("10", new PrivateAddress("10.0.0.1", "10.0.0.0", 8, "10.0.0.2"));
candidates.put("172", new PrivateAddress("172.16.0.1", "172.16.0.0", 12, "172.16.0.2"));
candidates.put("192", new PrivateAddress("192.168.0.1", "192.168.0.0", 16, "192.168.0.2"));
candidates.put("169", new PrivateAddress("169.254.1.1", "169.254.1.0", 24, "169.254.1.2"));
List<NetworkInterface> netInterfaces;
try
{
netInterfaces = Collections.list(NetworkInterface.getNetworkInterfaces());
}
catch (SocketException e)
{
e.printStackTrace();
throw new Exception("selectPrivateAddress failed", e);
}
for (NetworkInterface netInterface : netInterfaces)
{
for (InetAddress inetAddress : Collections.list(netInterface.getInetAddresses()))
{
if (!inetAddress.isLoopbackAddress() && inetAddress instanceof Inet4Address)
{
String ipAddress = inetAddress.getHostAddress();
if (ipAddress.startsWith("10."))
{
candidates.remove("10");
}
else if (ipAddress.length() >= 6
&& ipAddress.substring(0, 6).compareTo("172.16") >= 0
&& ipAddress.substring(0, 6).compareTo("172.31") <= 0)
{
candidates.remove("172");
}
else if (ipAddress.startsWith("192.168"))
{
candidates.remove("192");
}
}
}
}
if (candidates.size() > 0)
{
return candidates.values().iterator().next();
}
throw new Exception("no private address available");
}
private static boolean isPortAvailable(int port)
{
Socket socket = new Socket();
SocketAddress sockaddr = new InetSocketAddress("127.0.0.1", port);
try
{
socket.connect(sockaddr, 1000);
// The connect succeeded, so there is already something running on that port
return false;
}
catch (SocketTimeoutException e)
{
// The socket is in use, but the server didn't respond quickly enough
return false;
}
catch (IOException e)
{
// The connect failed, so the port is available
return true;
}
finally
{
if (socket != null)
{
try
{
socket.close();
}
catch (IOException e)
{
/* should not be thrown */
}
}
}
}
public static int findAvailablePort(int start_port, int max_increment)
{
for(int port = start_port; port < (start_port + max_increment); port++)
{
if (isPortAvailable(port))
{
return port;
}
}
return 0;
}
}
@@ -0,0 +1,163 @@
package com.dragonssh.xhttpdemo.core.util;
import android.content.Context;
import android.content.pm.ApplicationInfo;
import android.os.Build;
import android.util.Log;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import java.util.List;
import java.util.ArrayList;
import android.text.TextUtils;
public class CustomNativeLoader {
private final static String TAG = "CNL";
private static boolean loadFromZip(Context context, String libname, File destLocalFile, String arch) {
ZipFile zipFile = null;
InputStream stream = null;
try {
zipFile = new ZipFile(context.getApplicationInfo().sourceDir);
ZipEntry entry = zipFile.getEntry("lib/" + arch + "/" + libname + ".so");
if (entry == null) {
entry = zipFile.getEntry("jni/" + arch + "/" + libname + ".so");
if (entry == null)
throw new Exception("Unable to find file in apk:" + "lib/" + arch + "/" + libname);
}
//how we wrap this in another stream because the native .so is zipped itself
stream = zipFile.getInputStream(entry);
OutputStream out = new FileOutputStream(destLocalFile);
byte[] buf = new byte[4096];
int len;
while ((len = stream.read(buf)) > 0) {
Thread.yield();
out.write(buf, 0, len);
}
out.close();
destLocalFile.setReadable(true, false);
destLocalFile.setExecutable(true, false);
destLocalFile.setWritable(true);
return true;
} catch (Exception e) {
Log.e(TAG, e.getMessage());
} finally {
if (stream != null) {
try {
stream.close();
} catch (Exception e) {
Log.e(TAG, e.getMessage());
}
}
if (zipFile != null) {
try {
zipFile.close();
} catch (Exception e) {
Log.e(TAG, e.getMessage());
}
}
}
return false;
}
public static File loadNativeBinary(Context context, String libname, File destLocalFile) {
try {
File fileNativeBin = new File(getNativeLibraryDir(context), libname + ".so");
if (fileNativeBin.exists())
{
if (fileNativeBin.canExecute())
return fileNativeBin;
else
{
setExecutable(fileNativeBin);
if (fileNativeBin.canExecute())
return fileNativeBin;
}
}
else if (destLocalFile.exists()) {
if (destLocalFile.canExecute())
return destLocalFile;
else
{
setExecutable(destLocalFile);
if (destLocalFile.canExecute())
return destLocalFile;
}
}
List<String> abisList = new ArrayList<>();
if (Build.VERSION.SDK_INT >= 21) {
String[] abis = Build.SUPPORTED_ABIS;
if (abis != null) {
for (String abi : abis) {
if (!TextUtils.isEmpty(abi)) {
abisList.add(abi);
}
}
}
}
else {
String[] abis = new String[]{
Build.CPU_ABI,
Build.CPU_ABI2
};
for (String abi : abis) {
if (!TextUtils.isEmpty(abi)) {
abisList.add(abi);
}
}
}
for (String folder : abisList) {
String javaArch = System.getProperty("os.arch");
if (javaArch != null && javaArch.contains("686")) {
folder = "x86";
}
if (loadFromZip(context, libname, destLocalFile, folder)) {
return destLocalFile;
}
}
} catch (Throwable e) {
Log.e(TAG, e.getMessage(), e);
}
return null;
}
private static void setExecutable(File fileBin) {
fileBin.setReadable(true);
fileBin.setExecutable(true);
fileBin.setWritable(false);
fileBin.setWritable(true, true);
}
// Return Full path to the directory where native JNI libraries are stored.
private static String getNativeLibraryDir(Context context) {
ApplicationInfo appInfo = context.getApplicationInfo();
return appInfo.nativeLibraryDir;
}
}
@@ -0,0 +1,76 @@
package com.dragonssh.xhttpdemo.core.util;
import android.content.Context;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Scanner;
public class FileUtils {
private static final String TAG = "FileUtils";
public static void copiarArquivo(InputStream in, OutputStream out) throws IOException {
byte[] buf = new byte[8192];
int len;
try {
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
out.flush();
} finally {
try {
in.close();
} finally {
out.close();
}
}
}
public static String readFromRaw(Context context, int resId) {
InputStream in = context.getResources().openRawResource(resId);
Scanner scanner = new Scanner(in, "UTF-8").useDelimiter("\\A");
StringBuilder sb = new StringBuilder();
while (scanner.hasNext()) {
sb.append(scanner.next());
}
scanner.close();
return sb.toString();
}
public static String readTextFile(File f) {
StringBuilder text = new StringBuilder();
try {
BufferedReader br = new BufferedReader(new FileReader(f));
String st;
while ((st = br.readLine()) != null) {
text.append(st).append('\n');
}
br.close();
return text.toString();
} catch (Exception e) {
return null;
}
}
public static boolean saveTextFile(File file, String contents) {
try {
if (!file.exists()) {
file.createNewFile();
}
FileWriter writer = new FileWriter(file, false);
writer.write(contents);
writer.close();
return true;
} catch (IOException e) {
e.printStackTrace();
return false;
}
}
}
@@ -0,0 +1,54 @@
package com.dragonssh.xhttpdemo.core.util;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.List;
public class StreamGobbler extends Thread {
private final BufferedReader reader;
private List<String> writer;
private StreamGobbler.OnLineListener listener;
public StreamGobbler(InputStream inputStream, List<String> outputList) {
this.reader = new BufferedReader(new InputStreamReader(inputStream));
this.writer = outputList;
}
public StreamGobbler(InputStream inputStream, StreamGobbler.OnLineListener onLineListener) {
this.reader = new BufferedReader(new InputStreamReader(inputStream));
this.listener = onLineListener;
}
public void run() {
while(true) {
try {
String line;
if ((line = this.reader.readLine()) != null) {
if (this.writer != null) {
this.writer.add(line);
}
if (this.listener != null) {
this.listener.onLine(line);
}
continue;
}
} catch (IOException var3) {}
try {
this.reader.close();
} catch (IOException var2) {}
return;
}
}
public interface OnLineListener {
void onLine(String var1);
}
}
@@ -0,0 +1,139 @@
/* -*-mode:java; c-basic-offset:2; -*- */
/*
Copyright (c) 2000-2011 ymnk, JCraft,Inc. All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the distribution.
3. The names of the authors may not be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JCRAFT,
INC. OR ANY CONTRIBUTORS TO THIS SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/*
* This program is based on zlib-1.1.3, so all credit should go authors
* Jean-loup Gailly(jloup@gzip.org) and Mark Adler(madler@alumni.caltech.edu)
* and contributors of zlib.
*/
package com.jcraft.jzlib;
final public class Adler32 implements Checksum {
// largest prime smaller than 65536
static final private int BASE=65521;
// NMAX is the largest n such that 255n(n+1)/2 + (n+1)(BASE-1) <= 2^32-1
static final private int NMAX=5552;
private long s1=1L;
private long s2=0L;
public void reset(long init){
s1=init&0xffff;
s2=(init>>16)&0xffff;
}
public void reset(){
s1=1L;
s2=0L;
}
public long getValue(){
return ((s2<<16)|s1);
}
public void update(byte[] buf, int index, int len){
if(len==1){
s1+=buf[index++]&0xff; s2+=s1;
s1%=BASE;
s2%=BASE;
return;
}
int len1 = len/NMAX;
int len2 = len%NMAX;
while(len1-->0) {
int k=NMAX;
len-=k;
while(k-->0){
s1+=buf[index++]&0xff; s2+=s1;
}
s1%=BASE;
s2%=BASE;
}
int k=len2;
len-=k;
while(k-->0){
s1+=buf[index++]&0xff; s2+=s1;
}
s1%=BASE;
s2%=BASE;
}
public Adler32 copy(){
Adler32 foo = new Adler32();
foo.s1 = this.s1;
foo.s2 = this.s2;
return foo;
}
// The following logic has come from zlib.1.2.
static long combine(long adler1, long adler2, long len2){
long BASEL = (long)BASE;
long sum1;
long sum2;
long rem; // unsigned int
rem = len2 % BASEL;
sum1 = adler1 & 0xffffL;
sum2 = rem * sum1;
sum2 %= BASEL; // MOD(sum2);
sum1 += (adler2 & 0xffffL) + BASEL - 1;
sum2 += ((adler1 >> 16) & 0xffffL) + ((adler2 >> 16) & 0xffffL) + BASEL - rem;
if (sum1 >= BASEL) sum1 -= BASEL;
if (sum1 >= BASEL) sum1 -= BASEL;
if (sum2 >= (BASEL << 1)) sum2 -= (BASEL << 1);
if (sum2 >= BASEL) sum2 -= BASEL;
return sum1 | (sum2 << 16);
}
/*
private java.util.zip.Adler32 adler=new java.util.zip.Adler32();
public void update(byte[] buf, int index, int len){
if(buf==null) {adler.reset();}
else{adler.update(buf, index, len);}
}
public void reset(){
adler.reset();
}
public void reset(long init){
if(init==1L){
adler.reset();
}
else{
System.err.println("unsupported operation");
}
}
public long getValue(){
return adler.getValue();
}
*/
}
@@ -0,0 +1,179 @@
/* -*-mode:java; c-basic-offset:2; -*- */
/*
Copyright (c) 2011 ymnk, JCraft,Inc. All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the distribution.
3. The names of the authors may not be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JCRAFT,
INC. OR ANY CONTRIBUTORS TO THIS SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/*
* This program is based on zlib-1.1.3, so all credit should go authors
* Jean-loup Gailly(jloup@gzip.org) and Mark Adler(madler@alumni.caltech.edu)
* and contributors of zlib.
*/
package com.jcraft.jzlib;
final public class CRC32 implements Checksum {
/*
* The following logic has come from RFC1952.
*/
private int v = 0;
private static int[] crc_table = null;
static {
crc_table = new int[256];
for (int n = 0; n < 256; n++) {
int c = n;
for (int k = 8; --k >= 0; ) {
if ((c & 1) != 0)
c = 0xedb88320 ^ (c >>> 1);
else
c = c >>> 1;
}
crc_table[n] = c;
}
}
public void update (byte[] buf, int index, int len) {
int c = ~v;
while (--len >= 0)
c = crc_table[(c^buf[index++])&0xff]^(c >>> 8);
v = ~c;
}
public void reset(){
v = 0;
}
public void reset(long vv){
v = (int)(vv&0xffffffffL);
}
public long getValue(){
return (long)(v&0xffffffffL);
}
// The following logic has come from zlib.1.2.
private static final int GF2_DIM = 32;
static long combine(long crc1, long crc2, long len2){
long row;
long[] even = new long[GF2_DIM];
long[] odd = new long[GF2_DIM];
// degenerate case (also disallow negative lengths)
if (len2 <= 0)
return crc1;
// put operator for one zero bit in odd
odd[0] = 0xedb88320L; // CRC-32 polynomial
row = 1;
for (int n = 1; n < GF2_DIM; n++) {
odd[n] = row;
row <<= 1;
}
// put operator for two zero bits in even
gf2_matrix_square(even, odd);
// put operator for four zero bits in odd
gf2_matrix_square(odd, even);
// apply len2 zeros to crc1 (first square will put the operator for one
// zero byte, eight zero bits, in even)
do {
// apply zeros operator for this bit of len2
gf2_matrix_square(even, odd);
if ((len2 & 1)!=0)
crc1 = gf2_matrix_times(even, crc1);
len2 >>= 1;
// if no more bits set, then done
if (len2 == 0)
break;
// another iteration of the loop with odd and even swapped
gf2_matrix_square(odd, even);
if ((len2 & 1)!=0)
crc1 = gf2_matrix_times(odd, crc1);
len2 >>= 1;
// if no more bits set, then done
} while (len2 != 0);
/* return combined crc */
crc1 ^= crc2;
return crc1;
}
private static long gf2_matrix_times(long[] mat, long vec){
long sum = 0;
int index = 0;
while (vec!=0) {
if ((vec & 1)!=0)
sum ^= mat[index];
vec >>= 1;
index++;
}
return sum;
}
static final void gf2_matrix_square(long[] square, long[] mat) {
for (int n = 0; n < GF2_DIM; n++)
square[n] = gf2_matrix_times(mat, mat[n]);
}
/*
private java.util.zip.CRC32 crc32 = new java.util.zip.CRC32();
public void update(byte[] buf, int index, int len){
if(buf==null) {crc32.reset();}
else{crc32.update(buf, index, len);}
}
public void reset(){
crc32.reset();
}
public void reset(long init){
if(init==0L){
crc32.reset();
}
else{
System.err.println("unsupported operation");
}
}
public long getValue(){
return crc32.getValue();
}
*/
public CRC32 copy(){
CRC32 foo = new CRC32();
foo.v = this.v;
return foo;
}
public static int[] getCRC32Table(){
int[] tmp = new int[crc_table.length];
System.arraycopy(crc_table, 0, tmp, 0, tmp.length);
return tmp;
}
}
@@ -0,0 +1,43 @@
/* -*-mode:java; c-basic-offset:2; -*- */
/*
Copyright (c) 2011 ymnk, JCraft,Inc. All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the distribution.
3. The names of the authors may not be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JCRAFT,
INC. OR ANY CONTRIBUTORS TO THIS SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/*
* This program is based on zlib-1.1.3, so all credit should go authors
* Jean-loup Gailly(jloup@gzip.org) and Mark Adler(madler@alumni.caltech.edu)
* and contributors of zlib.
*/
package com.jcraft.jzlib;
interface Checksum {
void update(byte[] buf, int index, int len);
void reset();
void reset(long init);
long getValue();
Checksum copy();
}
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,171 @@
/* -*-mode:java; c-basic-offset:2; indent-tabs-mode:nil -*- */
/*
Copyright (c) 2011 ymnk, JCraft,Inc. All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the distribution.
3. The names of the authors may not be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JCRAFT,
INC. OR ANY CONTRIBUTORS TO THIS SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/*
* This program is based on zlib-1.1.3, so all credit should go authors
* Jean-loup Gailly(jloup@gzip.org) and Mark Adler(madler@alumni.caltech.edu)
* and contributors of zlib.
*/
package com.jcraft.jzlib;
final public class Deflater extends ZStream{
static final private int MAX_WBITS=15; // 32K LZ77 window
static final private int DEF_WBITS=MAX_WBITS;
static final private int Z_NO_FLUSH=0;
static final private int Z_PARTIAL_FLUSH=1;
static final private int Z_SYNC_FLUSH=2;
static final private int Z_FULL_FLUSH=3;
static final private int Z_FINISH=4;
static final private int MAX_MEM_LEVEL=9;
static final private int Z_OK=0;
static final private int Z_STREAM_END=1;
static final private int Z_NEED_DICT=2;
static final private int Z_ERRNO=-1;
static final private int Z_STREAM_ERROR=-2;
static final private int Z_DATA_ERROR=-3;
static final private int Z_MEM_ERROR=-4;
static final private int Z_BUF_ERROR=-5;
static final private int Z_VERSION_ERROR=-6;
private boolean finished = false;
public Deflater(){
super();
}
public Deflater(int level) throws GZIPException {
this(level, MAX_WBITS);
}
public Deflater(int level, boolean nowrap) throws GZIPException {
this(level, MAX_WBITS, nowrap);
}
public Deflater(int level, int bits) throws GZIPException {
this(level, bits, false);
}
public Deflater(int level, int bits, boolean nowrap) throws GZIPException {
super();
int ret = init(level, bits, nowrap);
if(ret!=Z_OK)
throw new GZIPException(ret+": "+msg);
}
public Deflater(int level, int bits, int memlevel, JZlib.WrapperType wrapperType) throws GZIPException {
super();
int ret = init(level, bits, memlevel, wrapperType);
if(ret!=Z_OK)
throw new GZIPException(ret+": "+msg);
}
public Deflater(int level, int bits, int memlevel) throws GZIPException {
super();
int ret = init(level, bits, memlevel);
if(ret!=Z_OK)
throw new GZIPException(ret+": "+msg);
}
public int init(int level){
return init(level, MAX_WBITS);
}
public int init(int level, boolean nowrap){
return init(level, MAX_WBITS, nowrap);
}
public int init(int level, int bits){
return init(level, bits, false);
}
public int init(int level, int bits, int memlevel, JZlib.WrapperType wrapperType){
if(bits < 9 || bits > 15){
return Z_STREAM_ERROR;
}
if(wrapperType == JZlib.W_NONE) {
bits *= -1;
}
else if(wrapperType == JZlib.W_GZIP) {
bits += 16;
}
else if(wrapperType == JZlib.W_ANY) {
return Z_STREAM_ERROR;
}
else if(wrapperType == JZlib.W_ZLIB) {
}
return init(level, bits, memlevel);
}
public int init(int level, int bits, int memlevel){
finished = false;
dstate=new Deflate(this);
return dstate.deflateInit(level, bits, memlevel);
}
public int init(int level, int bits, boolean nowrap){
finished = false;
dstate=new Deflate(this);
return dstate.deflateInit(level, nowrap?-bits:bits);
}
public int deflate(int flush){
if(dstate==null){
return Z_STREAM_ERROR;
}
int ret = dstate.deflate(flush);
if(ret == Z_STREAM_END)
finished = true;
return ret;
}
public int end(){
finished = true;
if(dstate==null) return Z_STREAM_ERROR;
int ret=dstate.deflateEnd();
dstate=null;
free();
return ret;
}
public int params(int level, int strategy){
if(dstate==null) return Z_STREAM_ERROR;
return dstate.deflateParams(level, strategy);
}
public int setDictionary (byte[] dictionary, int dictLength){
if(dstate == null)
return Z_STREAM_ERROR;
return dstate.deflateSetDictionary(dictionary, dictLength);
}
public boolean finished(){
return finished;
}
public int copy(Deflater src){
this.finished = src.finished;
return Deflate.deflateCopy(this, src);
}
}
@@ -0,0 +1,181 @@
/* -*-mode:java; c-basic-offset:2; indent-tabs-mode:nil -*- */
/*
Copyright (c) 2011 ymnk, JCraft,Inc. All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the distribution.
3. The names of the authors may not be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JCRAFT,
INC. OR ANY CONTRIBUTORS TO THIS SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.jcraft.jzlib;
import java.io.*;
public class DeflaterOutputStream extends FilterOutputStream {
protected final Deflater deflater;
protected byte[] buffer;
private boolean closed = false;
private boolean syncFlush = false;
private final byte[] buf1 = new byte[1];
protected boolean mydeflater = false;
private boolean close_out = true;
protected static final int DEFAULT_BUFSIZE = 512;
public DeflaterOutputStream(OutputStream out) throws IOException {
this(out,
new Deflater(JZlib.Z_DEFAULT_COMPRESSION),
DEFAULT_BUFSIZE, true);
mydeflater = true;
}
public DeflaterOutputStream(OutputStream out, Deflater def) throws IOException {
this(out, def, DEFAULT_BUFSIZE, true);
}
public DeflaterOutputStream(OutputStream out,
Deflater deflater,
int size) throws IOException {
this(out, deflater, size, true);
}
public DeflaterOutputStream(OutputStream out,
Deflater deflater,
int size,
boolean close_out) throws IOException {
super(out);
if (out == null || deflater == null) {
throw new NullPointerException();
}
else if (size <= 0) {
throw new IllegalArgumentException("buffer size must be greater than 0");
}
this.deflater = deflater;
buffer = new byte[size];
this.close_out = close_out;
}
public void write(int b) throws IOException {
buf1[0] = (byte)(b & 0xff);
write(buf1, 0, 1);
}
public void write(byte[] b, int off, int len) throws IOException {
if (deflater.finished()) {
throw new IOException("finished");
}
else if (off<0 | len<0 | off+len>b.length) {
throw new IndexOutOfBoundsException();
}
else if (len == 0) {
return;
}
else {
int flush = syncFlush ? JZlib.Z_SYNC_FLUSH : JZlib.Z_NO_FLUSH;
deflater.setInput(b, off, len, true);
while (deflater.avail_in>0) {
int err = deflate(flush);
if (err == JZlib.Z_STREAM_END)
break;
}
}
}
public void finish() throws IOException {
while (!deflater.finished()) {
deflate(JZlib.Z_FINISH);
}
}
public void close() throws IOException {
if (!closed) {
finish();
if (mydeflater){
deflater.end();
}
if(close_out)
out.close();
closed = true;
}
}
protected int deflate(int flush) throws IOException {
deflater.setOutput(buffer, 0, buffer.length);
int err = deflater.deflate(flush);
switch(err) {
case JZlib.Z_OK:
case JZlib.Z_STREAM_END:
break;
case JZlib.Z_BUF_ERROR:
if(deflater.avail_in<=0 && flush!=JZlib.Z_FINISH){
// flush() without any data
break;
}
default:
throw new IOException("failed to deflate: error="+err+" avail_out="+deflater.avail_out);
}
int len = deflater.next_out_index;
if (len > 0) {
out.write(buffer, 0, len);
}
return err;
}
public void flush() throws IOException {
if (syncFlush && !deflater.finished()) {
while (true) {
int err = deflate(JZlib.Z_SYNC_FLUSH);
if (deflater.next_out_index < buffer.length)
break;
if (err == JZlib.Z_STREAM_END)
break;
}
}
out.flush();
}
public long getTotalIn() {
return deflater.getTotalIn();
}
public long getTotalOut() {
return deflater.getTotalOut();
}
public void setSyncFlush(boolean syncFlush){
this.syncFlush = syncFlush;
}
public boolean getSyncFlush(){
return this.syncFlush;
}
public Deflater getDeflater(){
return deflater;
}
}
@@ -0,0 +1,44 @@
/* -*-mode:java; c-basic-offset:2; -*- */
/*
Copyright (c) 2011 ymnk, JCraft,Inc. All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the distribution.
3. The names of the authors may not be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JCRAFT,
INC. OR ANY CONTRIBUTORS TO THIS SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/*
* This program is based on zlib-1.1.3, so all credit should go authors
* Jean-loup Gailly(jloup@gzip.org) and Mark Adler(madler@alumni.caltech.edu)
* and contributors of zlib.
*/
package com.jcraft.jzlib;
public class GZIPException extends java.io.IOException {
public GZIPException() {
super();
}
public GZIPException(String s) {
super(s);
}
}
@@ -0,0 +1,214 @@
/* -*-mode:java; c-basic-offset:2; -*- */
/*
Copyright (c) 2011 ymnk, JCraft,Inc. All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the distribution.
3. The names of the authors may not be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JCRAFT,
INC. OR ANY CONTRIBUTORS TO THIS SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/*
* This program is based on zlib-1.1.3, so all credit should go authors
* Jean-loup Gailly(jloup@gzip.org) and Mark Adler(madler@alumni.caltech.edu)
* and contributors of zlib.
*/
package com.jcraft.jzlib;
import java.io.UnsupportedEncodingException;
/**
* @see "http://www.ietf.org/rfc/rfc1952.txt"
*/
public class GZIPHeader implements Cloneable {
public static final byte OS_MSDOS = (byte) 0x00;
public static final byte OS_AMIGA = (byte) 0x01;
public static final byte OS_VMS = (byte) 0x02;
public static final byte OS_UNIX = (byte) 0x03;
public static final byte OS_ATARI = (byte) 0x05;
public static final byte OS_OS2 = (byte) 0x06;
public static final byte OS_MACOS = (byte) 0x07;
public static final byte OS_TOPS20 = (byte) 0x0a;
public static final byte OS_WIN32 = (byte) 0x0b;
public static final byte OS_VMCMS = (byte) 0x04;
public static final byte OS_ZSYSTEM = (byte) 0x08;
public static final byte OS_CPM = (byte) 0x09;
public static final byte OS_QDOS = (byte) 0x0c;
public static final byte OS_RISCOS = (byte) 0x0d;
public static final byte OS_UNKNOWN = (byte) 0xff;
boolean text = false;
private boolean fhcrc = false;
long time;
int xflags;
int os = 255;
byte[] extra;
byte[] name;
byte[] comment;
int hcrc;
long crc;
boolean done = false;
long mtime = 0;
public void setModifiedTime(long mtime) {
this.mtime = mtime;
}
public long getModifiedTime() {
return mtime;
}
public void setOS(int os) {
if((0<=os && os <=13) || os==255)
this.os=os;
else
throw new IllegalArgumentException("os: "+os);
}
public int getOS(){
return os;
}
public void setName(String name) {
try{
this.name=name.getBytes("ISO-8859-1");
}
catch(UnsupportedEncodingException e){
throw new IllegalArgumentException("name must be in ISO-8859-1 "+name);
}
}
public String getName(){
if(name==null) return "";
try {
return new String(name, "ISO-8859-1");
}
catch (UnsupportedEncodingException e) {
throw new InternalError(e.toString());
}
}
public void setComment(String comment) {
try{
this.comment=comment.getBytes("ISO-8859-1");
}
catch(UnsupportedEncodingException e){
throw new IllegalArgumentException("comment must be in ISO-8859-1 "+name);
}
}
public String getComment(){
if(comment==null) return "";
try {
return new String(comment, "ISO-8859-1");
}
catch (UnsupportedEncodingException e) {
throw new InternalError(e.toString());
}
}
public void setCRC(long crc){
this.crc = crc;
}
public long getCRC(){
return crc;
}
void put(Deflate d){
int flag = 0;
if(text){
flag |= 1; // FTEXT
}
if(fhcrc){
flag |= 2; // FHCRC
}
if(extra!=null){
flag |= 4; // FEXTRA
}
if(name!=null){
flag |= 8; // FNAME
}
if(comment!=null){
flag |= 16; // FCOMMENT
}
int xfl = 0;
if(d.level == JZlib.Z_BEST_SPEED){
xfl |= 4;
}
else if (d.level == JZlib.Z_BEST_COMPRESSION){
xfl |= 2;
}
d.put_short((short)0x8b1f); // ID1 ID2
d.put_byte((byte)8); // CM(Compression Method)
d.put_byte((byte)flag);
d.put_byte((byte)mtime);
d.put_byte((byte)(mtime>>8));
d.put_byte((byte)(mtime>>16));
d.put_byte((byte)(mtime>>24));
d.put_byte((byte)xfl);
d.put_byte((byte)os);
if(extra!=null){
d.put_byte((byte)extra.length);
d.put_byte((byte)(extra.length>>8));
d.put_byte(extra, 0, extra.length);
}
if(name!=null){
d.put_byte(name, 0, name.length);
d.put_byte((byte)0);
}
if(comment!=null){
d.put_byte(comment, 0, comment.length);
d.put_byte((byte)0);
}
}
@Override
public Object clone() throws CloneNotSupportedException {
GZIPHeader gheader = (GZIPHeader)super.clone();
byte[] tmp;
if(gheader.extra!=null){
tmp=new byte[gheader.extra.length];
System.arraycopy(gheader.extra, 0, tmp, 0, tmp.length);
gheader.extra = tmp;
}
if(gheader.name!=null){
tmp=new byte[gheader.name.length];
System.arraycopy(gheader.name, 0, tmp, 0, tmp.length);
gheader.name = tmp;
}
if(gheader.comment!=null){
tmp=new byte[gheader.comment.length];
System.arraycopy(gheader.comment, 0, tmp, 0, tmp.length);
gheader.comment = tmp;
}
return gheader;
}
}
@@ -0,0 +1,145 @@
/* -*-mode:java; c-basic-offset:2; indent-tabs-mode:nil -*- */
/*
Copyright (c) 2011 ymnk, JCraft,Inc. All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the distribution.
3. The names of the authors may not be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JCRAFT,
INC. OR ANY CONTRIBUTORS TO THIS SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.jcraft.jzlib;
import java.io.*;
public class GZIPInputStream extends InflaterInputStream {
public GZIPInputStream(InputStream in) throws IOException {
this(in, DEFAULT_BUFSIZE, true);
}
public GZIPInputStream(InputStream in,
int size,
boolean close_in) throws IOException {
this(in, new Inflater(15+16), size, close_in);
myinflater = true;
}
public GZIPInputStream(InputStream in,
Inflater inflater,
int size,
boolean close_in) throws IOException {
super(in, inflater, size, close_in);
}
public long getModifiedtime() {
return inflater.istate.getGZIPHeader().getModifiedTime();
}
public int getOS() {
return inflater.istate.getGZIPHeader().getOS();
}
public String getName() {
return inflater.istate.getGZIPHeader().getName();
}
public String getComment() {
return inflater.istate.getGZIPHeader().getComment();
}
public long getCRC() throws GZIPException {
if(inflater.istate.mode != 12 /*DONE*/)
throw new GZIPException("checksum is not calculated yet.");
return inflater.istate.getGZIPHeader().getCRC();
}
public void readHeader() throws IOException {
byte[] empty = "".getBytes();
inflater.setOutput(empty, 0, 0);
inflater.setInput(empty, 0, 0, false);
byte[] b = new byte[10];
int n = fill(b);
if(n!=10){
if(n>0){
inflater.setInput(b, 0, n, false);
//inflater.next_in_index = n;
inflater.next_in_index = 0;
inflater.avail_in = n;
}
throw new IOException("no input");
}
inflater.setInput(b, 0, n, false);
byte[] b1 = new byte[1];
do{
if(inflater.avail_in<=0){
int i = in.read(b1);
if(i<=0)
throw new IOException("no input");
inflater.setInput(b1, 0, 1, true);
}
int err = inflater.inflate(JZlib.Z_NO_FLUSH);
if(err!=0/*Z_OK*/){
int len = 2048-inflater.next_in.length;
if(len>0){
byte[] tmp = new byte[len];
n = fill(tmp);
if(n>0){
inflater.avail_in += inflater.next_in_index;
inflater.next_in_index = 0;
inflater.setInput(tmp, 0, n, true);
}
}
//inflater.next_in_index = inflater.next_in.length;
inflater.avail_in += inflater.next_in_index;
inflater.next_in_index = 0;
throw new IOException(inflater.msg);
}
}
while(inflater.istate.inParsingHeader());
}
private int fill(byte[] buf) {
int len = buf.length;
int n = 0;
do{
int i = -1;
try {
i = in.read(buf, n, buf.length - n);
}
catch(IOException e){
}
if(i == -1){
break;
}
n+=i;
}
while(n<len);
return n;
}
}
@@ -0,0 +1,90 @@
/* -*-mode:java; c-basic-offset:2; indent-tabs-mode:nil -*- */
/*
Copyright (c) 2011 ymnk, JCraft,Inc. All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the distribution.
3. The names of the authors may not be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JCRAFT,
INC. OR ANY CONTRIBUTORS TO THIS SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.jcraft.jzlib;
import java.io.*;
public class GZIPOutputStream extends DeflaterOutputStream {
public GZIPOutputStream(OutputStream out) throws IOException {
this(out, DEFAULT_BUFSIZE);
}
public GZIPOutputStream(OutputStream out, int size) throws IOException {
this(out, size, true);
}
public GZIPOutputStream(OutputStream out,
int size,
boolean close_out) throws IOException {
this(out,
new Deflater(JZlib.Z_DEFAULT_COMPRESSION, 15+16),
size, close_out);
mydeflater=true;
}
public GZIPOutputStream(OutputStream out,
Deflater deflater,
int size,
boolean close_out) throws IOException{
super(out, deflater, size, close_out);
}
private void check() throws GZIPException {
if(deflater.dstate.status != 42 /*INIT_STATUS*/)
throw new GZIPException("header is already written.");
}
public void setModifiedTime(long mtime) throws GZIPException {
check();
deflater.dstate.getGZIPHeader().setModifiedTime(mtime);
}
public void setOS(int os) throws GZIPException {
check();
deflater.dstate.getGZIPHeader().setOS(os);
}
public void setName(String name) throws GZIPException {
check();
deflater.dstate.getGZIPHeader().setName(name);
}
public void setComment(String comment) throws GZIPException {
check();
deflater.dstate.getGZIPHeader().setComment(comment);
}
public long getCRC() throws GZIPException {
if(deflater.dstate.status != 666 /*FINISH_STATE*/)
throw new GZIPException("checksum is not calculated yet.");
return deflater.dstate.getGZIPHeader().getCRC();
}
}
@@ -0,0 +1,614 @@
/* -*-mode:java; c-basic-offset:2; -*- */
/*
Copyright (c) 2011 ymnk, JCraft,Inc. All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the distribution.
3. The names of the authors may not be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JCRAFT,
INC. OR ANY CONTRIBUTORS TO THIS SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/*
* This program is based on zlib-1.1.3, so all credit should go authors
* Jean-loup Gailly(jloup@gzip.org) and Mark Adler(madler@alumni.caltech.edu)
* and contributors of zlib.
*/
package com.jcraft.jzlib;
final class InfBlocks{
static final private int MANY=1440;
// And'ing with mask[n] masks the lower n bits
static final private int[] inflate_mask = {
0x00000000, 0x00000001, 0x00000003, 0x00000007, 0x0000000f,
0x0000001f, 0x0000003f, 0x0000007f, 0x000000ff, 0x000001ff,
0x000003ff, 0x000007ff, 0x00000fff, 0x00001fff, 0x00003fff,
0x00007fff, 0x0000ffff
};
// Table for deflate from PKZIP's appnote.txt.
static final int[] border = { // Order of the bit length code lengths
16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15
};
static final private int Z_OK=0;
static final private int Z_STREAM_END=1;
static final private int Z_NEED_DICT=2;
static final private int Z_ERRNO=-1;
static final private int Z_STREAM_ERROR=-2;
static final private int Z_DATA_ERROR=-3;
static final private int Z_MEM_ERROR=-4;
static final private int Z_BUF_ERROR=-5;
static final private int Z_VERSION_ERROR=-6;
static final private int TYPE=0; // get type bits (3, including end bit)
static final private int LENS=1; // get lengths for stored
static final private int STORED=2;// processing stored block
static final private int TABLE=3; // get table lengths
static final private int BTREE=4; // get bit lengths tree for a dynamic block
static final private int DTREE=5; // get length, distance trees for a dynamic block
static final private int CODES=6; // processing fixed or dynamic block
static final private int DRY=7; // output remaining window bytes
static final private int DONE=8; // finished last block, done
static final private int BAD=9; // ot a data error--stuck here
int mode; // current inflate_block mode
int left; // if STORED, bytes left to copy
int table; // table lengths (14 bits)
int index; // index into blens (or border)
int[] blens; // bit lengths of codes
int[] bb=new int[1]; // bit length tree depth
int[] tb=new int[1]; // bit length decoding tree
int[] bl=new int[1];
int[] bd=new int[1];
int[][] tl=new int[1][];
int[][] td=new int[1][];
int[] tli=new int[1]; // tl_index
int[] tdi=new int[1]; // td_index
private final InfCodes codes; // if CODES, current state
int last; // true if this block is the last block
// mode independent information
int bitk; // bits in bit buffer
int bitb; // bit buffer
int[] hufts; // single malloc for tree space
byte[] window; // sliding window
int end; // one byte after sliding window
int read; // window read pointer
int write; // window write pointer
private boolean check;
private final InfTree inftree=new InfTree();
private final ZStream z;
InfBlocks(ZStream z, int w){
this.z=z;
this.codes=new InfCodes(this.z, this);
hufts=new int[MANY*3];
window=new byte[w];
end=w;
this.check = (z.istate.wrap==0) ? false : true;
mode = TYPE;
reset();
}
void reset(){
if(mode==BTREE || mode==DTREE){
}
if(mode==CODES){
codes.free(z);
}
mode=TYPE;
bitk=0;
bitb=0;
read=write=0;
if(check){
z.adler.reset();
}
}
int proc(int r){
int t; // temporary storage
int b; // bit buffer
int k; // bits in bit buffer
int p; // input data pointer
int n; // bytes available there
int q; // output window write pointer
int m; // bytes to end of window or read pointer
// copy input/output information to locals (UPDATE macro restores)
{p=z.next_in_index;n=z.avail_in;b=bitb;k=bitk;}
{q=write;m=(int)(q<read?read-q-1:end-q);}
// process input based on current state
while(true){
switch (mode){
case TYPE:
while(k<(3)){
if(n!=0){
r=Z_OK;
}
else{
bitb=b; bitk=k;
z.avail_in=n;
z.total_in+=p-z.next_in_index;z.next_in_index=p;
write=q;
return inflate_flush(r);
};
n--;
b|=(z.next_in[p++]&0xff)<<k;
k+=8;
}
t = (int)(b & 7);
last = t & 1;
switch (t >>> 1){
case 0: // stored
{b>>>=(3);k-=(3);}
t = k & 7; // go to byte boundary
{b>>>=(t);k-=(t);}
mode = LENS; // get length of stored block
break;
case 1: // fixed
InfTree.inflate_trees_fixed(bl, bd, tl, td, z);
codes.init(bl[0], bd[0], tl[0], 0, td[0], 0);
{b>>>=(3);k-=(3);}
mode = CODES;
break;
case 2: // dynamic
{b>>>=(3);k-=(3);}
mode = TABLE;
break;
case 3: // illegal
{b>>>=(3);k-=(3);}
mode = BAD;
z.msg = "invalid block type";
r = Z_DATA_ERROR;
bitb=b; bitk=k;
z.avail_in=n;z.total_in+=p-z.next_in_index;z.next_in_index=p;
write=q;
return inflate_flush(r);
}
break;
case LENS:
while(k<(32)){
if(n!=0){
r=Z_OK;
}
else{
bitb=b; bitk=k;
z.avail_in=n;
z.total_in+=p-z.next_in_index;z.next_in_index=p;
write=q;
return inflate_flush(r);
};
n--;
b|=(z.next_in[p++]&0xff)<<k;
k+=8;
}
if ((((~b) >>> 16) & 0xffff) != (b & 0xffff)){
mode = BAD;
z.msg = "invalid stored block lengths";
r = Z_DATA_ERROR;
bitb=b; bitk=k;
z.avail_in=n;z.total_in+=p-z.next_in_index;z.next_in_index=p;
write=q;
return inflate_flush(r);
}
left = (b & 0xffff);
b = k = 0; // dump bits
mode = left!=0 ? STORED : (last!=0 ? DRY : TYPE);
break;
case STORED:
if (n == 0){
bitb=b; bitk=k;
z.avail_in=n;z.total_in+=p-z.next_in_index;z.next_in_index=p;
write=q;
return inflate_flush(r);
}
if(m==0){
if(q==end&&read!=0){
q=0; m=(int)(q<read?read-q-1:end-q);
}
if(m==0){
write=q;
r=inflate_flush(r);
q=write;m=(int)(q<read?read-q-1:end-q);
if(q==end&&read!=0){
q=0; m=(int)(q<read?read-q-1:end-q);
}
if(m==0){
bitb=b; bitk=k;
z.avail_in=n;z.total_in+=p-z.next_in_index;z.next_in_index=p;
write=q;
return inflate_flush(r);
}
}
}
r=Z_OK;
t = left;
if(t>n) t = n;
if(t>m) t = m;
System.arraycopy(z.next_in, p, window, q, t);
p += t; n -= t;
q += t; m -= t;
if ((left -= t) != 0)
break;
mode = last!=0 ? DRY : TYPE;
break;
case TABLE:
while(k<(14)){
if(n!=0){
r=Z_OK;
}
else{
bitb=b; bitk=k;
z.avail_in=n;
z.total_in+=p-z.next_in_index;z.next_in_index=p;
write=q;
return inflate_flush(r);
};
n--;
b|=(z.next_in[p++]&0xff)<<k;
k+=8;
}
table = t = (b & 0x3fff);
if ((t & 0x1f) > 29 || ((t >> 5) & 0x1f) > 29)
{
mode = BAD;
z.msg = "too many length or distance symbols";
r = Z_DATA_ERROR;
bitb=b; bitk=k;
z.avail_in=n;z.total_in+=p-z.next_in_index;z.next_in_index=p;
write=q;
return inflate_flush(r);
}
t = 258 + (t & 0x1f) + ((t >> 5) & 0x1f);
if(blens==null || blens.length<t){
blens=new int[t];
}
else{
for(int i=0; i<t; i++){blens[i]=0;}
}
{b>>>=(14);k-=(14);}
index = 0;
mode = BTREE;
case BTREE:
while (index < 4 + (table >>> 10)){
while(k<(3)){
if(n!=0){
r=Z_OK;
}
else{
bitb=b; bitk=k;
z.avail_in=n;
z.total_in+=p-z.next_in_index;z.next_in_index=p;
write=q;
return inflate_flush(r);
};
n--;
b|=(z.next_in[p++]&0xff)<<k;
k+=8;
}
blens[border[index++]] = b&7;
{b>>>=(3);k-=(3);}
}
while(index < 19){
blens[border[index++]] = 0;
}
bb[0] = 7;
t = inftree.inflate_trees_bits(blens, bb, tb, hufts, z);
if (t != Z_OK){
r = t;
if (r == Z_DATA_ERROR){
blens=null;
mode = BAD;
}
bitb=b; bitk=k;
z.avail_in=n;z.total_in+=p-z.next_in_index;z.next_in_index=p;
write=q;
return inflate_flush(r);
}
index = 0;
mode = DTREE;
case DTREE:
while (true){
t = table;
if(!(index < 258 + (t & 0x1f) + ((t >> 5) & 0x1f))){
break;
}
int[] h;
int i, j, c;
t = bb[0];
while(k<(t)){
if(n!=0){
r=Z_OK;
}
else{
bitb=b; bitk=k;
z.avail_in=n;
z.total_in+=p-z.next_in_index;z.next_in_index=p;
write=q;
return inflate_flush(r);
};
n--;
b|=(z.next_in[p++]&0xff)<<k;
k+=8;
}
if(tb[0]==-1){
//System.err.println("null...");
}
t=hufts[(tb[0]+(b&inflate_mask[t]))*3+1];
c=hufts[(tb[0]+(b&inflate_mask[t]))*3+2];
if (c < 16){
b>>>=(t);k-=(t);
blens[index++] = c;
}
else { // c == 16..18
i = c == 18 ? 7 : c - 14;
j = c == 18 ? 11 : 3;
while(k<(t+i)){
if(n!=0){
r=Z_OK;
}
else{
bitb=b; bitk=k;
z.avail_in=n;
z.total_in+=p-z.next_in_index;z.next_in_index=p;
write=q;
return inflate_flush(r);
};
n--;
b|=(z.next_in[p++]&0xff)<<k;
k+=8;
}
b>>>=(t);k-=(t);
j += (b & inflate_mask[i]);
b>>>=(i);k-=(i);
i = index;
t = table;
if (i + j > 258 + (t & 0x1f) + ((t >> 5) & 0x1f) ||
(c == 16 && i < 1)){
blens=null;
mode = BAD;
z.msg = "invalid bit length repeat";
r = Z_DATA_ERROR;
bitb=b; bitk=k;
z.avail_in=n;z.total_in+=p-z.next_in_index;z.next_in_index=p;
write=q;
return inflate_flush(r);
}
c = c == 16 ? blens[i-1] : 0;
do{
blens[i++] = c;
}
while (--j!=0);
index = i;
}
}
tb[0]=-1;
{
bl[0] = 9; // must be <= 9 for lookahead assumptions
bd[0] = 6; // must be <= 9 for lookahead assumptions
t = table;
t = inftree.inflate_trees_dynamic(257 + (t & 0x1f),
1 + ((t >> 5) & 0x1f),
blens, bl, bd, tli, tdi, hufts, z);
if (t != Z_OK){
if (t == Z_DATA_ERROR){
blens=null;
mode = BAD;
}
r = t;
bitb=b; bitk=k;
z.avail_in=n;z.total_in+=p-z.next_in_index;z.next_in_index=p;
write=q;
return inflate_flush(r);
}
codes.init(bl[0], bd[0], hufts, tli[0], hufts, tdi[0]);
}
mode = CODES;
case CODES:
bitb=b; bitk=k;
z.avail_in=n; z.total_in+=p-z.next_in_index;z.next_in_index=p;
write=q;
if ((r = codes.proc(r)) != Z_STREAM_END){
return inflate_flush(r);
}
r = Z_OK;
codes.free(z);
p=z.next_in_index; n=z.avail_in;b=bitb;k=bitk;
q=write;m=(int)(q<read?read-q-1:end-q);
if (last==0){
mode = TYPE;
break;
}
mode = DRY;
case DRY:
write=q;
r=inflate_flush(r);
q=write; m=(int)(q<read?read-q-1:end-q);
if (read != write){
bitb=b; bitk=k;
z.avail_in=n;z.total_in+=p-z.next_in_index;z.next_in_index=p;
write=q;
return inflate_flush(r);
}
mode = DONE;
case DONE:
r = Z_STREAM_END;
bitb=b; bitk=k;
z.avail_in=n;z.total_in+=p-z.next_in_index;z.next_in_index=p;
write=q;
return inflate_flush(r);
case BAD:
r = Z_DATA_ERROR;
bitb=b; bitk=k;
z.avail_in=n;z.total_in+=p-z.next_in_index;z.next_in_index=p;
write=q;
return inflate_flush(r);
default:
r = Z_STREAM_ERROR;
bitb=b; bitk=k;
z.avail_in=n;z.total_in+=p-z.next_in_index;z.next_in_index=p;
write=q;
return inflate_flush(r);
}
}
}
void free(){
reset();
window=null;
hufts=null;
//ZFREE(z, s);
}
void set_dictionary(byte[] d, int start, int n){
System.arraycopy(d, start, window, 0, n);
read = write = n;
}
// Returns true if inflate is currently at the end of a block generated
// by Z_SYNC_FLUSH or Z_FULL_FLUSH.
int sync_point(){
return mode == LENS ? 1 : 0;
}
// copy as much as possible from the sliding window to the output area
int inflate_flush(int r){
int n;
int p;
int q;
// local copies of source and destination pointers
p = z.next_out_index;
q = read;
// compute number of bytes to copy as far as end of window
n = (int)((q <= write ? write : end) - q);
if(n > z.avail_out) n = z.avail_out;
if(n!=0 && r == Z_BUF_ERROR) r = Z_OK;
// update counters
z.avail_out -= n;
z.total_out += n;
// update check information
if(check && n>0){
z.adler.update(window, q, n);
}
// copy as far as end of window
System.arraycopy(window, q, z.next_out, p, n);
p += n;
q += n;
// see if more to copy at beginning of window
if (q == end){
// wrap pointers
q = 0;
if (write == end)
write = 0;
// compute bytes to copy
n = write - q;
if (n > z.avail_out) n = z.avail_out;
if (n!=0 && r == Z_BUF_ERROR) r = Z_OK;
// update counters
z.avail_out -= n;
z.total_out += n;
// update check information
if(check && n>0){
z.adler.update(window, q, n);
}
// copy
System.arraycopy(window, q, z.next_out, p, n);
p += n;
q += n;
}
// update pointers
z.next_out_index = p;
read = q;
// done
return r;
}
}
@@ -0,0 +1,610 @@
/* -*-mode:java; c-basic-offset:2; -*- */
/*
Copyright (c) 2000,2001,2002,2003 ymnk, JCraft,Inc. All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the distribution.
3. The names of the authors may not be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JCRAFT,
INC. OR ANY CONTRIBUTORS TO THIS SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/*
* This program is based on zlib-1.1.3, so all credit should go authors
* Jean-loup Gailly(jloup@gzip.org) and Mark Adler(madler@alumni.caltech.edu)
* and contributors of zlib.
*/
package com.jcraft.jzlib;
final class InfCodes{
static final private int[] inflate_mask = {
0x00000000, 0x00000001, 0x00000003, 0x00000007, 0x0000000f,
0x0000001f, 0x0000003f, 0x0000007f, 0x000000ff, 0x000001ff,
0x000003ff, 0x000007ff, 0x00000fff, 0x00001fff, 0x00003fff,
0x00007fff, 0x0000ffff
};
static final private int Z_OK=0;
static final private int Z_STREAM_END=1;
static final private int Z_NEED_DICT=2;
static final private int Z_ERRNO=-1;
static final private int Z_STREAM_ERROR=-2;
static final private int Z_DATA_ERROR=-3;
static final private int Z_MEM_ERROR=-4;
static final private int Z_BUF_ERROR=-5;
static final private int Z_VERSION_ERROR=-6;
// waiting for "i:"=input,
// "o:"=output,
// "x:"=nothing
static final private int START=0; // x: set up for LEN
static final private int LEN=1; // i: get length/literal/eob next
static final private int LENEXT=2; // i: getting length extra (have base)
static final private int DIST=3; // i: get distance next
static final private int DISTEXT=4;// i: getting distance extra
static final private int COPY=5; // o: copying bytes in window, waiting for space
static final private int LIT=6; // o: got literal, waiting for output space
static final private int WASH=7; // o: got eob, possibly still output waiting
static final private int END=8; // x: got eob and all data flushed
static final private int BADCODE=9;// x: got error
int mode; // current inflate_codes mode
// mode dependent information
int len;
int[] tree; // pointer into tree
int tree_index=0;
int need; // bits needed
int lit;
// if EXT or COPY, where and how much
int get; // bits to get for extra
int dist; // distance back to copy from
byte lbits; // ltree bits decoded per branch
byte dbits; // dtree bits decoder per branch
int[] ltree; // literal/length/eob tree
int ltree_index; // literal/length/eob tree
int[] dtree; // distance tree
int dtree_index; // distance tree
private final ZStream z;
private final InfBlocks s;
InfCodes(ZStream z, InfBlocks s){
this.z=z;
this.s=s;
}
void init(int bl, int bd,
int[] tl, int tl_index,
int[] td, int td_index){
mode=START;
lbits=(byte)bl;
dbits=(byte)bd;
ltree=tl;
ltree_index=tl_index;
dtree = td;
dtree_index=td_index;
tree=null;
}
int proc(int r){
int j; // temporary storage
int[] t; // temporary pointer
int tindex; // temporary pointer
int e; // extra bits or operation
int b=0; // bit buffer
int k=0; // bits in bit buffer
int p=0; // input data pointer
int n; // bytes available there
int q; // output window write pointer
int m; // bytes to end of window or read pointer
int f; // pointer to copy strings from
// copy input/output information to locals (UPDATE macro restores)
p=z.next_in_index;n=z.avail_in;b=s.bitb;k=s.bitk;
q=s.write;m=q<s.read?s.read-q-1:s.end-q;
// process input and output based on current state
while (true){
switch (mode){
// waiting for "i:"=input, "o:"=output, "x:"=nothing
case START: // x: set up for LEN
if (m >= 258 && n >= 10){
s.bitb=b;s.bitk=k;
z.avail_in=n;z.total_in+=p-z.next_in_index;z.next_in_index=p;
s.write=q;
r = inflate_fast(lbits, dbits,
ltree, ltree_index,
dtree, dtree_index,
s, z);
p=z.next_in_index;n=z.avail_in;b=s.bitb;k=s.bitk;
q=s.write;m=q<s.read?s.read-q-1:s.end-q;
if (r != Z_OK){
mode = r == Z_STREAM_END ? WASH : BADCODE;
break;
}
}
need = lbits;
tree = ltree;
tree_index=ltree_index;
mode = LEN;
case LEN: // i: get length/literal/eob next
j = need;
while(k<(j)){
if(n!=0)r=Z_OK;
else{
s.bitb=b;s.bitk=k;
z.avail_in=n;z.total_in+=p-z.next_in_index;z.next_in_index=p;
s.write=q;
return s.inflate_flush(r);
}
n--;
b|=(z.next_in[p++]&0xff)<<k;
k+=8;
}
tindex=(tree_index+(b&inflate_mask[j]))*3;
b>>>=(tree[tindex+1]);
k-=(tree[tindex+1]);
e=tree[tindex];
if(e == 0){ // literal
lit = tree[tindex+2];
mode = LIT;
break;
}
if((e & 16)!=0 ){ // length
get = e & 15;
len = tree[tindex+2];
mode = LENEXT;
break;
}
if ((e & 64) == 0){ // next table
need = e;
tree_index = tindex/3+tree[tindex+2];
break;
}
if ((e & 32)!=0){ // end of block
mode = WASH;
break;
}
mode = BADCODE; // invalid code
z.msg = "invalid literal/length code";
r = Z_DATA_ERROR;
s.bitb=b;s.bitk=k;
z.avail_in=n;z.total_in+=p-z.next_in_index;z.next_in_index=p;
s.write=q;
return s.inflate_flush(r);
case LENEXT: // i: getting length extra (have base)
j = get;
while(k<(j)){
if(n!=0)r=Z_OK;
else{
s.bitb=b;s.bitk=k;
z.avail_in=n;z.total_in+=p-z.next_in_index;z.next_in_index=p;
s.write=q;
return s.inflate_flush(r);
}
n--; b|=(z.next_in[p++]&0xff)<<k;
k+=8;
}
len += (b & inflate_mask[j]);
b>>=j;
k-=j;
need = dbits;
tree = dtree;
tree_index=dtree_index;
mode = DIST;
case DIST: // i: get distance next
j = need;
while(k<(j)){
if(n!=0)r=Z_OK;
else{
s.bitb=b;s.bitk=k;
z.avail_in=n;z.total_in+=p-z.next_in_index;z.next_in_index=p;
s.write=q;
return s.inflate_flush(r);
}
n--; b|=(z.next_in[p++]&0xff)<<k;
k+=8;
}
tindex=(tree_index+(b & inflate_mask[j]))*3;
b>>=tree[tindex+1];
k-=tree[tindex+1];
e = (tree[tindex]);
if((e & 16)!=0){ // distance
get = e & 15;
dist = tree[tindex+2];
mode = DISTEXT;
break;
}
if ((e & 64) == 0){ // next table
need = e;
tree_index = tindex/3 + tree[tindex+2];
break;
}
mode = BADCODE; // invalid code
z.msg = "invalid distance code";
r = Z_DATA_ERROR;
s.bitb=b;s.bitk=k;
z.avail_in=n;z.total_in+=p-z.next_in_index;z.next_in_index=p;
s.write=q;
return s.inflate_flush(r);
case DISTEXT: // i: getting distance extra
j = get;
while(k<(j)){
if(n!=0)r=Z_OK;
else{
s.bitb=b;s.bitk=k;
z.avail_in=n;z.total_in+=p-z.next_in_index;z.next_in_index=p;
s.write=q;
return s.inflate_flush(r);
}
n--; b|=(z.next_in[p++]&0xff)<<k;
k+=8;
}
dist += (b & inflate_mask[j]);
b>>=j;
k-=j;
mode = COPY;
case COPY: // o: copying bytes in window, waiting for space
f = q - dist;
while(f < 0){ // modulo window size-"while" instead
f += s.end; // of "if" handles invalid distances
}
while (len!=0){
if(m==0){
if(q==s.end&&s.read!=0){q=0;m=q<s.read?s.read-q-1:s.end-q;}
if(m==0){
s.write=q; r=s.inflate_flush(r);
q=s.write;m=q<s.read?s.read-q-1:s.end-q;
if(q==s.end&&s.read!=0){q=0;m=q<s.read?s.read-q-1:s.end-q;}
if(m==0){
s.bitb=b;s.bitk=k;
z.avail_in=n;z.total_in+=p-z.next_in_index;z.next_in_index=p;
s.write=q;
return s.inflate_flush(r);
}
}
}
s.window[q++]=s.window[f++]; m--;
if (f == s.end)
f = 0;
len--;
}
mode = START;
break;
case LIT: // o: got literal, waiting for output space
if(m==0){
if(q==s.end&&s.read!=0){q=0;m=q<s.read?s.read-q-1:s.end-q;}
if(m==0){
s.write=q; r=s.inflate_flush(r);
q=s.write;m=q<s.read?s.read-q-1:s.end-q;
if(q==s.end&&s.read!=0){q=0;m=q<s.read?s.read-q-1:s.end-q;}
if(m==0){
s.bitb=b;s.bitk=k;
z.avail_in=n;z.total_in+=p-z.next_in_index;z.next_in_index=p;
s.write=q;
return s.inflate_flush(r);
}
}
}
r=Z_OK;
s.window[q++]=(byte)lit; m--;
mode = START;
break;
case WASH: // o: got eob, possibly more output
if (k > 7){ // return unused byte, if any
k -= 8;
n++;
p--; // can always return one
}
s.write=q; r=s.inflate_flush(r);
q=s.write;m=q<s.read?s.read-q-1:s.end-q;
if (s.read != s.write){
s.bitb=b;s.bitk=k;
z.avail_in=n;z.total_in+=p-z.next_in_index;z.next_in_index=p;
s.write=q;
return s.inflate_flush(r);
}
mode = END;
case END:
r = Z_STREAM_END;
s.bitb=b;s.bitk=k;
z.avail_in=n;z.total_in+=p-z.next_in_index;z.next_in_index=p;
s.write=q;
return s.inflate_flush(r);
case BADCODE: // x: got error
r = Z_DATA_ERROR;
s.bitb=b;s.bitk=k;
z.avail_in=n;z.total_in+=p-z.next_in_index;z.next_in_index=p;
s.write=q;
return s.inflate_flush(r);
default:
r = Z_STREAM_ERROR;
s.bitb=b;s.bitk=k;
z.avail_in=n;z.total_in+=p-z.next_in_index;z.next_in_index=p;
s.write=q;
return s.inflate_flush(r);
}
}
}
void free(ZStream z){
// ZFREE(z, c);
}
// Called with number of bytes left to write in window at least 258
// (the maximum string length) and number of input bytes available
// at least ten. The ten bytes are six bytes for the longest length/
// distance pair plus four bytes for overloading the bit buffer.
int inflate_fast(int bl, int bd,
int[] tl, int tl_index,
int[] td, int td_index,
InfBlocks s, ZStream z){
int t; // temporary pointer
int[] tp; // temporary pointer
int tp_index; // temporary pointer
int e; // extra bits or operation
int b; // bit buffer
int k; // bits in bit buffer
int p; // input data pointer
int n; // bytes available there
int q; // output window write pointer
int m; // bytes to end of window or read pointer
int ml; // mask for literal/length tree
int md; // mask for distance tree
int c; // bytes to copy
int d; // distance back to copy from
int r; // copy source pointer
int tp_index_t_3; // (tp_index+t)*3
// load input, output, bit values
p=z.next_in_index;n=z.avail_in;b=s.bitb;k=s.bitk;
q=s.write;m=q<s.read?s.read-q-1:s.end-q;
// initialize masks
ml = inflate_mask[bl];
md = inflate_mask[bd];
// do until not enough input or output space for fast loop
do { // assume called with m >= 258 && n >= 10
// get literal/length code
while(k<(20)){ // max bits for literal/length code
n--;
b|=(z.next_in[p++]&0xff)<<k;k+=8;
}
t= b&ml;
tp=tl;
tp_index=tl_index;
tp_index_t_3=(tp_index+t)*3;
if ((e = tp[tp_index_t_3]) == 0){
b>>=(tp[tp_index_t_3+1]); k-=(tp[tp_index_t_3+1]);
s.window[q++] = (byte)tp[tp_index_t_3+2];
m--;
continue;
}
do {
b>>=(tp[tp_index_t_3+1]); k-=(tp[tp_index_t_3+1]);
if((e&16)!=0){
e &= 15;
c = tp[tp_index_t_3+2] + ((int)b & inflate_mask[e]);
b>>=e; k-=e;
// decode distance base of block to copy
while(k<(15)){ // max bits for distance code
n--;
b|=(z.next_in[p++]&0xff)<<k;k+=8;
}
t= b&md;
tp=td;
tp_index=td_index;
tp_index_t_3=(tp_index+t)*3;
e = tp[tp_index_t_3];
do {
b>>=(tp[tp_index_t_3+1]); k-=(tp[tp_index_t_3+1]);
if((e&16)!=0){
// get extra bits to add to distance base
e &= 15;
while(k<(e)){ // get extra bits (up to 13)
n--;
b|=(z.next_in[p++]&0xff)<<k;k+=8;
}
d = tp[tp_index_t_3+2] + (b&inflate_mask[e]);
b>>=(e); k-=(e);
// do the copy
m -= c;
if (q >= d){ // offset before dest
// just copy
r=q-d;
if(q-r>0 && 2>(q-r)){
s.window[q++]=s.window[r++]; // minimum count is three,
s.window[q++]=s.window[r++]; // so unroll loop a little
c-=2;
}
else{
System.arraycopy(s.window, r, s.window, q, 2);
q+=2; r+=2; c-=2;
}
}
else{ // else offset after destination
r=q-d;
do{
r+=s.end; // force pointer in window
}while(r<0); // covers invalid distances
e=s.end-r;
if(c>e){ // if source crosses,
c-=e; // wrapped copy
if(q-r>0 && e>(q-r)){
do{s.window[q++] = s.window[r++];}
while(--e!=0);
}
else{
System.arraycopy(s.window, r, s.window, q, e);
q+=e; r+=e; e=0;
}
r = 0; // copy rest from start of window
}
}
// copy all or what's left
if(q-r>0 && c>(q-r)){
do{s.window[q++] = s.window[r++];}
while(--c!=0);
}
else{
System.arraycopy(s.window, r, s.window, q, c);
q+=c; r+=c; c=0;
}
break;
}
else if((e&64)==0){
t+=tp[tp_index_t_3+2];
t+=(b&inflate_mask[e]);
tp_index_t_3=(tp_index+t)*3;
e=tp[tp_index_t_3];
}
else{
z.msg = "invalid distance code";
c=z.avail_in-n;c=(k>>3)<c?k>>3:c;n+=c;p-=c;k-=c<<3;
s.bitb=b;s.bitk=k;
z.avail_in=n;z.total_in+=p-z.next_in_index;z.next_in_index=p;
s.write=q;
return Z_DATA_ERROR;
}
}
while(true);
break;
}
if((e&64)==0){
t+=tp[tp_index_t_3+2];
t+=(b&inflate_mask[e]);
tp_index_t_3=(tp_index+t)*3;
if((e=tp[tp_index_t_3])==0){
b>>=(tp[tp_index_t_3+1]); k-=(tp[tp_index_t_3+1]);
s.window[q++]=(byte)tp[tp_index_t_3+2];
m--;
break;
}
}
else if((e&32)!=0){
c=z.avail_in-n;c=(k>>3)<c?k>>3:c;n+=c;p-=c;k-=c<<3;
s.bitb=b;s.bitk=k;
z.avail_in=n;z.total_in+=p-z.next_in_index;z.next_in_index=p;
s.write=q;
return Z_STREAM_END;
}
else{
z.msg="invalid literal/length code";
c=z.avail_in-n;c=(k>>3)<c?k>>3:c;n+=c;p-=c;k-=c<<3;
s.bitb=b;s.bitk=k;
z.avail_in=n;z.total_in+=p-z.next_in_index;z.next_in_index=p;
s.write=q;
return Z_DATA_ERROR;
}
}
while(true);
}
while(m>=258 && n>= 10);
// not enough input or output--restore pointers and return
c=z.avail_in-n;c=(k>>3)<c?k>>3:c;n+=c;p-=c;k-=c<<3;
s.bitb=b;s.bitk=k;
z.avail_in=n;z.total_in+=p-z.next_in_index;z.next_in_index=p;
s.write=q;
return Z_OK;
}
}
@@ -0,0 +1,518 @@
/* -*-mode:java; c-basic-offset:2; indent-tabs-mode:nil -*- */
/*
Copyright (c) 2000,2001,2002,2003 ymnk, JCraft,Inc. All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the distribution.
3. The names of the authors may not be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JCRAFT,
INC. OR ANY CONTRIBUTORS TO THIS SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/*
* This program is based on zlib-1.1.3, so all credit should go authors
* Jean-loup Gailly(jloup@gzip.org) and Mark Adler(madler@alumni.caltech.edu)
* and contributors of zlib.
*/
package com.jcraft.jzlib;
final class InfTree{
static final private int MANY=1440;
static final private int Z_OK=0;
static final private int Z_STREAM_END=1;
static final private int Z_NEED_DICT=2;
static final private int Z_ERRNO=-1;
static final private int Z_STREAM_ERROR=-2;
static final private int Z_DATA_ERROR=-3;
static final private int Z_MEM_ERROR=-4;
static final private int Z_BUF_ERROR=-5;
static final private int Z_VERSION_ERROR=-6;
static final int fixed_bl = 9;
static final int fixed_bd = 5;
static final int[] fixed_tl = {
96,7,256, 0,8,80, 0,8,16, 84,8,115,
82,7,31, 0,8,112, 0,8,48, 0,9,192,
80,7,10, 0,8,96, 0,8,32, 0,9,160,
0,8,0, 0,8,128, 0,8,64, 0,9,224,
80,7,6, 0,8,88, 0,8,24, 0,9,144,
83,7,59, 0,8,120, 0,8,56, 0,9,208,
81,7,17, 0,8,104, 0,8,40, 0,9,176,
0,8,8, 0,8,136, 0,8,72, 0,9,240,
80,7,4, 0,8,84, 0,8,20, 85,8,227,
83,7,43, 0,8,116, 0,8,52, 0,9,200,
81,7,13, 0,8,100, 0,8,36, 0,9,168,
0,8,4, 0,8,132, 0,8,68, 0,9,232,
80,7,8, 0,8,92, 0,8,28, 0,9,152,
84,7,83, 0,8,124, 0,8,60, 0,9,216,
82,7,23, 0,8,108, 0,8,44, 0,9,184,
0,8,12, 0,8,140, 0,8,76, 0,9,248,
80,7,3, 0,8,82, 0,8,18, 85,8,163,
83,7,35, 0,8,114, 0,8,50, 0,9,196,
81,7,11, 0,8,98, 0,8,34, 0,9,164,
0,8,2, 0,8,130, 0,8,66, 0,9,228,
80,7,7, 0,8,90, 0,8,26, 0,9,148,
84,7,67, 0,8,122, 0,8,58, 0,9,212,
82,7,19, 0,8,106, 0,8,42, 0,9,180,
0,8,10, 0,8,138, 0,8,74, 0,9,244,
80,7,5, 0,8,86, 0,8,22, 192,8,0,
83,7,51, 0,8,118, 0,8,54, 0,9,204,
81,7,15, 0,8,102, 0,8,38, 0,9,172,
0,8,6, 0,8,134, 0,8,70, 0,9,236,
80,7,9, 0,8,94, 0,8,30, 0,9,156,
84,7,99, 0,8,126, 0,8,62, 0,9,220,
82,7,27, 0,8,110, 0,8,46, 0,9,188,
0,8,14, 0,8,142, 0,8,78, 0,9,252,
96,7,256, 0,8,81, 0,8,17, 85,8,131,
82,7,31, 0,8,113, 0,8,49, 0,9,194,
80,7,10, 0,8,97, 0,8,33, 0,9,162,
0,8,1, 0,8,129, 0,8,65, 0,9,226,
80,7,6, 0,8,89, 0,8,25, 0,9,146,
83,7,59, 0,8,121, 0,8,57, 0,9,210,
81,7,17, 0,8,105, 0,8,41, 0,9,178,
0,8,9, 0,8,137, 0,8,73, 0,9,242,
80,7,4, 0,8,85, 0,8,21, 80,8,258,
83,7,43, 0,8,117, 0,8,53, 0,9,202,
81,7,13, 0,8,101, 0,8,37, 0,9,170,
0,8,5, 0,8,133, 0,8,69, 0,9,234,
80,7,8, 0,8,93, 0,8,29, 0,9,154,
84,7,83, 0,8,125, 0,8,61, 0,9,218,
82,7,23, 0,8,109, 0,8,45, 0,9,186,
0,8,13, 0,8,141, 0,8,77, 0,9,250,
80,7,3, 0,8,83, 0,8,19, 85,8,195,
83,7,35, 0,8,115, 0,8,51, 0,9,198,
81,7,11, 0,8,99, 0,8,35, 0,9,166,
0,8,3, 0,8,131, 0,8,67, 0,9,230,
80,7,7, 0,8,91, 0,8,27, 0,9,150,
84,7,67, 0,8,123, 0,8,59, 0,9,214,
82,7,19, 0,8,107, 0,8,43, 0,9,182,
0,8,11, 0,8,139, 0,8,75, 0,9,246,
80,7,5, 0,8,87, 0,8,23, 192,8,0,
83,7,51, 0,8,119, 0,8,55, 0,9,206,
81,7,15, 0,8,103, 0,8,39, 0,9,174,
0,8,7, 0,8,135, 0,8,71, 0,9,238,
80,7,9, 0,8,95, 0,8,31, 0,9,158,
84,7,99, 0,8,127, 0,8,63, 0,9,222,
82,7,27, 0,8,111, 0,8,47, 0,9,190,
0,8,15, 0,8,143, 0,8,79, 0,9,254,
96,7,256, 0,8,80, 0,8,16, 84,8,115,
82,7,31, 0,8,112, 0,8,48, 0,9,193,
80,7,10, 0,8,96, 0,8,32, 0,9,161,
0,8,0, 0,8,128, 0,8,64, 0,9,225,
80,7,6, 0,8,88, 0,8,24, 0,9,145,
83,7,59, 0,8,120, 0,8,56, 0,9,209,
81,7,17, 0,8,104, 0,8,40, 0,9,177,
0,8,8, 0,8,136, 0,8,72, 0,9,241,
80,7,4, 0,8,84, 0,8,20, 85,8,227,
83,7,43, 0,8,116, 0,8,52, 0,9,201,
81,7,13, 0,8,100, 0,8,36, 0,9,169,
0,8,4, 0,8,132, 0,8,68, 0,9,233,
80,7,8, 0,8,92, 0,8,28, 0,9,153,
84,7,83, 0,8,124, 0,8,60, 0,9,217,
82,7,23, 0,8,108, 0,8,44, 0,9,185,
0,8,12, 0,8,140, 0,8,76, 0,9,249,
80,7,3, 0,8,82, 0,8,18, 85,8,163,
83,7,35, 0,8,114, 0,8,50, 0,9,197,
81,7,11, 0,8,98, 0,8,34, 0,9,165,
0,8,2, 0,8,130, 0,8,66, 0,9,229,
80,7,7, 0,8,90, 0,8,26, 0,9,149,
84,7,67, 0,8,122, 0,8,58, 0,9,213,
82,7,19, 0,8,106, 0,8,42, 0,9,181,
0,8,10, 0,8,138, 0,8,74, 0,9,245,
80,7,5, 0,8,86, 0,8,22, 192,8,0,
83,7,51, 0,8,118, 0,8,54, 0,9,205,
81,7,15, 0,8,102, 0,8,38, 0,9,173,
0,8,6, 0,8,134, 0,8,70, 0,9,237,
80,7,9, 0,8,94, 0,8,30, 0,9,157,
84,7,99, 0,8,126, 0,8,62, 0,9,221,
82,7,27, 0,8,110, 0,8,46, 0,9,189,
0,8,14, 0,8,142, 0,8,78, 0,9,253,
96,7,256, 0,8,81, 0,8,17, 85,8,131,
82,7,31, 0,8,113, 0,8,49, 0,9,195,
80,7,10, 0,8,97, 0,8,33, 0,9,163,
0,8,1, 0,8,129, 0,8,65, 0,9,227,
80,7,6, 0,8,89, 0,8,25, 0,9,147,
83,7,59, 0,8,121, 0,8,57, 0,9,211,
81,7,17, 0,8,105, 0,8,41, 0,9,179,
0,8,9, 0,8,137, 0,8,73, 0,9,243,
80,7,4, 0,8,85, 0,8,21, 80,8,258,
83,7,43, 0,8,117, 0,8,53, 0,9,203,
81,7,13, 0,8,101, 0,8,37, 0,9,171,
0,8,5, 0,8,133, 0,8,69, 0,9,235,
80,7,8, 0,8,93, 0,8,29, 0,9,155,
84,7,83, 0,8,125, 0,8,61, 0,9,219,
82,7,23, 0,8,109, 0,8,45, 0,9,187,
0,8,13, 0,8,141, 0,8,77, 0,9,251,
80,7,3, 0,8,83, 0,8,19, 85,8,195,
83,7,35, 0,8,115, 0,8,51, 0,9,199,
81,7,11, 0,8,99, 0,8,35, 0,9,167,
0,8,3, 0,8,131, 0,8,67, 0,9,231,
80,7,7, 0,8,91, 0,8,27, 0,9,151,
84,7,67, 0,8,123, 0,8,59, 0,9,215,
82,7,19, 0,8,107, 0,8,43, 0,9,183,
0,8,11, 0,8,139, 0,8,75, 0,9,247,
80,7,5, 0,8,87, 0,8,23, 192,8,0,
83,7,51, 0,8,119, 0,8,55, 0,9,207,
81,7,15, 0,8,103, 0,8,39, 0,9,175,
0,8,7, 0,8,135, 0,8,71, 0,9,239,
80,7,9, 0,8,95, 0,8,31, 0,9,159,
84,7,99, 0,8,127, 0,8,63, 0,9,223,
82,7,27, 0,8,111, 0,8,47, 0,9,191,
0,8,15, 0,8,143, 0,8,79, 0,9,255
};
static final int[] fixed_td = {
80,5,1, 87,5,257, 83,5,17, 91,5,4097,
81,5,5, 89,5,1025, 85,5,65, 93,5,16385,
80,5,3, 88,5,513, 84,5,33, 92,5,8193,
82,5,9, 90,5,2049, 86,5,129, 192,5,24577,
80,5,2, 87,5,385, 83,5,25, 91,5,6145,
81,5,7, 89,5,1537, 85,5,97, 93,5,24577,
80,5,4, 88,5,769, 84,5,49, 92,5,12289,
82,5,13, 90,5,3073, 86,5,193, 192,5,24577
};
// Tables for deflate from PKZIP's appnote.txt.
static final int[] cplens = { // Copy lengths for literal codes 257..285
3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31,
35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0
};
// see note #13 above about 258
static final int[] cplext = { // Extra bits for literal codes 257..285
0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2,
3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 0, 112, 112 // 112==invalid
};
static final int[] cpdist = { // Copy offsets for distance codes 0..29
1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193,
257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145,
8193, 12289, 16385, 24577
};
static final int[] cpdext = { // Extra bits for distance codes
0, 0, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6,
7, 7, 8, 8, 9, 9, 10, 10, 11, 11,
12, 12, 13, 13};
// If BMAX needs to be larger than 16, then h and x[] should be uLong.
static final int BMAX=15; // maximum bit length of any code
int[] hn = null; // hufts used in space
int[] v = null; // work area for huft_build
int[] c = null; // bit length count table
int[] r = null; // table entry for structure assignment
int[] u = null; // table stack
int[] x = null; // bit offsets, then code stack
private int huft_build(int[] b, // code lengths in bits (all assumed <= BMAX)
int bindex,
int n, // number of codes (assumed <= 288)
int s, // number of simple-valued codes (0..s-1)
int[] d, // list of base values for non-simple codes
int[] e, // list of extra bits for non-simple codes
int[] t, // result: starting table
int[] m, // maximum lookup bits, returns actual
int[] hp,// space for trees
int[] hn,// hufts used in space
int[] v // working area: values in order of bit length
){
// Given a list of code lengths and a maximum table size, make a set of
// tables to decode that set of codes. Return Z_OK on success, Z_BUF_ERROR
// if the given code set is incomplete (the tables are still built in this
// case), Z_DATA_ERROR if the input is invalid (an over-subscribed set of
// lengths), or Z_MEM_ERROR if not enough memory.
int a; // counter for codes of length k
int f; // i repeats in table every f entries
int g; // maximum code length
int h; // table level
int i; // counter, current code
int j; // counter
int k; // number of bits in current code
int l; // bits per table (returned in m)
int mask; // (1 << w) - 1, to avoid cc -O bug on HP
int p; // pointer into c[], b[], or v[]
int q; // points to current table
int w; // bits before this table == (l * h)
int xp; // pointer into x
int y; // number of dummy codes added
int z; // number of entries in current table
// Generate counts for each bit length
p = 0; i = n;
do {
c[b[bindex+p]]++; p++; i--; // assume all entries <= BMAX
}while(i!=0);
if(c[0] == n){ // null input--all zero length codes
t[0] = -1;
m[0] = 0;
return Z_OK;
}
// Find minimum and maximum length, bound *m by those
l = m[0];
for (j = 1; j <= BMAX; j++)
if(c[j]!=0) break;
k = j; // minimum code length
if(l < j){
l = j;
}
for (i = BMAX; i!=0; i--){
if(c[i]!=0) break;
}
g = i; // maximum code length
if(l > i){
l = i;
}
m[0] = l;
// Adjust last length count to fill out codes, if needed
for (y = 1 << j; j < i; j++, y <<= 1){
if ((y -= c[j]) < 0){
return Z_DATA_ERROR;
}
}
if ((y -= c[i]) < 0){
return Z_DATA_ERROR;
}
c[i] += y;
// Generate starting offsets into the value table for each length
x[1] = j = 0;
p = 1; xp = 2;
while (--i!=0) { // note that i == g from above
x[xp] = (j += c[p]);
xp++;
p++;
}
// Make a table of values in order of bit lengths
i = 0; p = 0;
do {
if ((j = b[bindex+p]) != 0){
v[x[j]++] = i;
}
p++;
}
while (++i < n);
n = x[g]; // set n to length of v
// Generate the Huffman codes and for each, make the table entries
x[0] = i = 0; // first Huffman code is zero
p = 0; // grab values in bit order
h = -1; // no tables yet--level -1
w = -l; // bits decoded == (l * h)
u[0] = 0; // just to keep compilers happy
q = 0; // ditto
z = 0; // ditto
// go through the bit lengths (k already is bits in shortest code)
for (; k <= g; k++){
a = c[k];
while (a--!=0){
// here i is the Huffman code of length k bits for value *p
// make tables up to required level
while (k > w + l){
h++;
w += l; // previous table always l bits
// compute minimum size table less than or equal to l bits
z = g - w;
z = (z > l) ? l : z; // table size upper limit
if((f=1<<(j=k-w))>a+1){ // try a k-w bit table
// too few codes for k-w bit table
f -= a + 1; // deduct codes from patterns left
xp = k;
if(j < z){
while (++j < z){ // try smaller tables up to z bits
if((f <<= 1) <= c[++xp])
break; // enough codes to use up j bits
f -= c[xp]; // else deduct codes from patterns
}
}
}
z = 1 << j; // table entries for j-bit table
// allocate new table
if (hn[0] + z > MANY){ // (note: doesn't matter for fixed)
return Z_DATA_ERROR; // overflow of MANY
}
u[h] = q = /*hp+*/ hn[0]; // DEBUG
hn[0] += z;
// connect to last table, if there is one
if(h!=0){
x[h]=i; // save pattern for backing up
r[0]=(byte)j; // bits in this table
r[1]=(byte)l; // bits to dump before this table
j=i>>>(w - l);
r[2] = (int)(q - u[h-1] - j); // offset to this table
System.arraycopy(r, 0, hp, (u[h-1]+j)*3, 3); // connect to last table
}
else{
t[0] = q; // first table is returned result
}
}
// set up table entry in r
r[1] = (byte)(k - w);
if (p >= n){
r[0] = 128 + 64; // out of values--invalid code
}
else if (v[p] < s){
r[0] = (byte)(v[p] < 256 ? 0 : 32 + 64); // 256 is end-of-block
r[2] = v[p++]; // simple code is just the value
}
else{
r[0]=(byte)(e[v[p]-s]+16+64); // non-simple--look up in lists
r[2]=d[v[p++] - s];
}
// fill code-like entries with r
f=1<<(k-w);
for (j=i>>>w;j<z;j+=f){
System.arraycopy(r, 0, hp, (q+j)*3, 3);
}
// backwards increment the k-bit code i
for (j = 1 << (k - 1); (i & j)!=0; j >>>= 1){
i ^= j;
}
i ^= j;
// backup over finished tables
mask = (1 << w) - 1; // needed on HP, cc -O bug
while ((i & mask) != x[h]){
h--; // don't need to update q
w -= l;
mask = (1 << w) - 1;
}
}
}
// Return Z_BUF_ERROR if we were given an incomplete table
return y != 0 && g != 1 ? Z_BUF_ERROR : Z_OK;
}
int inflate_trees_bits(int[] c, // 19 code lengths
int[] bb, // bits tree desired/actual depth
int[] tb, // bits tree result
int[] hp, // space for trees
ZStream z // for messages
){
int result;
initWorkArea(19);
hn[0]=0;
result = huft_build(c, 0, 19, 19, null, null, tb, bb, hp, hn, v);
if(result == Z_DATA_ERROR){
z.msg = "oversubscribed dynamic bit lengths tree";
}
else if(result == Z_BUF_ERROR || bb[0] == 0){
z.msg = "incomplete dynamic bit lengths tree";
result = Z_DATA_ERROR;
}
return result;
}
int inflate_trees_dynamic(int nl, // number of literal/length codes
int nd, // number of distance codes
int[] c, // that many (total) code lengths
int[] bl, // literal desired/actual bit depth
int[] bd, // distance desired/actual bit depth
int[] tl, // literal/length tree result
int[] td, // distance tree result
int[] hp, // space for trees
ZStream z // for messages
){
int result;
// build literal/length tree
initWorkArea(288);
hn[0]=0;
result = huft_build(c, 0, nl, 257, cplens, cplext, tl, bl, hp, hn, v);
if (result != Z_OK || bl[0] == 0){
if(result == Z_DATA_ERROR){
z.msg = "oversubscribed literal/length tree";
}
else if (result != Z_MEM_ERROR){
z.msg = "incomplete literal/length tree";
result = Z_DATA_ERROR;
}
return result;
}
// build distance tree
initWorkArea(288);
result = huft_build(c, nl, nd, 0, cpdist, cpdext, td, bd, hp, hn, v);
if (result != Z_OK || (bd[0] == 0 && nl > 257)){
if (result == Z_DATA_ERROR){
z.msg = "oversubscribed distance tree";
}
else if (result == Z_BUF_ERROR) {
z.msg = "incomplete distance tree";
result = Z_DATA_ERROR;
}
else if (result != Z_MEM_ERROR){
z.msg = "empty distance tree with lengths";
result = Z_DATA_ERROR;
}
return result;
}
return Z_OK;
}
static int inflate_trees_fixed(int[] bl, //literal desired/actual bit depth
int[] bd, //distance desired/actual bit depth
int[][] tl,//literal/length tree result
int[][] td,//distance tree result
ZStream z //for memory allocation
){
bl[0]=fixed_bl;
bd[0]=fixed_bd;
tl[0]=fixed_tl;
td[0]=fixed_td;
return Z_OK;
}
private void initWorkArea(int vsize){
if(hn==null){
hn=new int[1];
v=new int[vsize];
c=new int[BMAX+1];
r=new int[3];
u=new int[BMAX];
x=new int[BMAX+1];
}
if(v.length<vsize){ v=new int[vsize]; }
for(int i=0; i<vsize; i++){v[i]=0;}
for(int i=0; i<BMAX+1; i++){c[i]=0;}
for(int i=0; i<3; i++){r[i]=0;}
System.arraycopy(c, 0, u, 0, BMAX);
System.arraycopy(c, 0, x, 0, BMAX+1);
}
}
@@ -0,0 +1,751 @@
/* -*-mode:java; c-basic-offset:2; -*- */
/*
Copyright (c) 2000-2011 ymnk, JCraft,Inc. All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the distribution.
3. The names of the authors may not be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JCRAFT,
INC. OR ANY CONTRIBUTORS TO THIS SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/*
* This program is based on zlib-1.1.3, so all credit should go authors
* Jean-loup Gailly(jloup@gzip.org) and Mark Adler(madler@alumni.caltech.edu)
* and contributors of zlib.
*/
package com.jcraft.jzlib;
final class Inflate{
static final private int MAX_WBITS=15; // 32K LZ77 window
// preset dictionary flag in zlib header
static final private int PRESET_DICT=0x20;
static final int Z_NO_FLUSH=0;
static final int Z_PARTIAL_FLUSH=1;
static final int Z_SYNC_FLUSH=2;
static final int Z_FULL_FLUSH=3;
static final int Z_FINISH=4;
static final private int Z_DEFLATED=8;
static final private int Z_OK=0;
static final private int Z_STREAM_END=1;
static final private int Z_NEED_DICT=2;
static final private int Z_ERRNO=-1;
static final private int Z_STREAM_ERROR=-2;
static final private int Z_DATA_ERROR=-3;
static final private int Z_MEM_ERROR=-4;
static final private int Z_BUF_ERROR=-5;
static final private int Z_VERSION_ERROR=-6;
static final private int METHOD=0; // waiting for method byte
static final private int FLAG=1; // waiting for flag byte
static final private int DICT4=2; // four dictionary check bytes to go
static final private int DICT3=3; // three dictionary check bytes to go
static final private int DICT2=4; // two dictionary check bytes to go
static final private int DICT1=5; // one dictionary check byte to go
static final private int DICT0=6; // waiting for inflateSetDictionary
static final private int BLOCKS=7; // decompressing blocks
static final private int CHECK4=8; // four check bytes to go
static final private int CHECK3=9; // three check bytes to go
static final private int CHECK2=10; // two check bytes to go
static final private int CHECK1=11; // one check byte to go
static final private int DONE=12; // finished check, done
static final private int BAD=13; // got an error--stay here
static final private int HEAD=14;
static final private int LENGTH=15;
static final private int TIME=16;
static final private int OS=17;
static final private int EXLEN=18;
static final private int EXTRA=19;
static final private int NAME=20;
static final private int COMMENT=21;
static final private int HCRC=22;
static final private int FLAGS=23;
static final int INFLATE_ANY=0x40000000;
int mode; // current inflate mode
// mode dependent information
int method; // if FLAGS, method byte
// if CHECK, check values to compare
long was = -1; // computed check value
long need; // stream check value
// if BAD, inflateSync's marker bytes count
int marker;
// mode independent information
int wrap; // flag for no wrapper
// 0: no wrapper
// 1: zlib header
// 2: gzip header
// 4: auto detection
int wbits; // log2(window size) (8..15, defaults to 15)
InfBlocks blocks; // current inflate_blocks state
private final ZStream z;
private int flags;
private int need_bytes = -1;
private byte[] crcbuf=new byte[4];
GZIPHeader gheader = null;
int inflateReset(){
if(z == null) return Z_STREAM_ERROR;
z.total_in = z.total_out = 0;
z.msg = null;
this.mode = HEAD;
this.need_bytes = -1;
this.blocks.reset();
return Z_OK;
}
int inflateEnd(){
if(blocks != null){
blocks.free();
}
return Z_OK;
}
Inflate(ZStream z){
this.z=z;
}
int inflateInit(int w){
z.msg = null;
blocks = null;
// handle undocumented wrap option (no zlib header or check)
wrap = 0;
if(w < 0){
w = - w;
}
else if((w&INFLATE_ANY) != 0){
wrap = 4;
w &= ~INFLATE_ANY;
if(w < 48)
w &= 15;
}
else if((w & ~31) != 0) { // for example, DEF_WBITS + 32
wrap = 4; // zlib and gzip wrapped data should be accepted.
w &= 15;
}
else {
wrap = (w >> 4) + 1;
if(w < 48)
w &= 15;
}
if(w<8 ||w>15){
inflateEnd();
return Z_STREAM_ERROR;
}
if(blocks != null && wbits != w){
blocks.free();
blocks=null;
}
// set window size
wbits=w;
this.blocks=new InfBlocks(z, 1<<w);
// reset state
inflateReset();
return Z_OK;
}
int inflate(int f){
int hold = 0;
int r;
int b;
if(z == null || z.next_in == null){
if(f == Z_FINISH && this.mode==HEAD)
return Z_OK;
return Z_STREAM_ERROR;
}
f = f == Z_FINISH ? Z_BUF_ERROR : Z_OK;
r = Z_BUF_ERROR;
while (true){
switch (this.mode){
case HEAD:
if(wrap==0){
this.mode = BLOCKS;
break;
}
try { r=readBytes(2, r, f); }
catch(Return e){ return e.r; }
if((wrap == 4 || (wrap&2)!=0) &&
this.need == 0x8b1fL) { // gzip header
if(wrap == 4){
wrap = 2;
}
z.adler=new CRC32();
checksum(2, this.need);
if(gheader==null)
gheader=new GZIPHeader();
this.mode = FLAGS;
break;
}
if((wrap&2) != 0){
this.mode = BAD;
z.msg = "incorrect header check";
break;
}
flags = 0;
this.method = ((int)this.need)&0xff;
b=((int)(this.need>>8))&0xff;
if(((wrap&1)==0 || // check if zlib header allowed
(((this.method << 8)+b) % 31)!=0) &&
(this.method&0xf)!=Z_DEFLATED){
if(wrap == 4){
z.next_in_index -= 2;
z.avail_in += 2;
z.total_in -= 2;
wrap = 0;
this.mode = BLOCKS;
break;
}
this.mode = BAD;
z.msg = "incorrect header check";
// since zlib 1.2, it is allowted to inflateSync for this case.
/*
this.marker = 5; // can't try inflateSync
*/
break;
}
if((this.method&0xf)!=Z_DEFLATED){
this.mode = BAD;
z.msg="unknown compression method";
// since zlib 1.2, it is allowted to inflateSync for this case.
/*
this.marker = 5; // can't try inflateSync
*/
break;
}
if(wrap == 4){
wrap = 1;
}
if((this.method>>4)+8>this.wbits){
this.mode = BAD;
z.msg="invalid window size";
// since zlib 1.2, it is allowted to inflateSync for this case.
/*
this.marker = 5; // can't try inflateSync
*/
break;
}
z.adler=new Adler32();
if((b&PRESET_DICT)==0){
this.mode = BLOCKS;
break;
}
this.mode = DICT4;
case DICT4:
if(z.avail_in==0)return r;r=f;
z.avail_in--; z.total_in++;
this.need=((z.next_in[z.next_in_index++]&0xff)<<24)&0xff000000L;
this.mode=DICT3;
case DICT3:
if(z.avail_in==0)return r;r=f;
z.avail_in--; z.total_in++;
this.need+=((z.next_in[z.next_in_index++]&0xff)<<16)&0xff0000L;
this.mode=DICT2;
case DICT2:
if(z.avail_in==0)return r;r=f;
z.avail_in--; z.total_in++;
this.need+=((z.next_in[z.next_in_index++]&0xff)<<8)&0xff00L;
this.mode=DICT1;
case DICT1:
if(z.avail_in==0)return r;r=f;
z.avail_in--; z.total_in++;
this.need += (z.next_in[z.next_in_index++]&0xffL);
z.adler.reset(this.need);
this.mode = DICT0;
return Z_NEED_DICT;
case DICT0:
this.mode = BAD;
z.msg = "need dictionary";
this.marker = 0; // can try inflateSync
return Z_STREAM_ERROR;
case BLOCKS:
r = this.blocks.proc(r);
if(r == Z_DATA_ERROR){
this.mode = BAD;
this.marker = 0; // can try inflateSync
break;
}
if(r == Z_OK){
r = f;
}
if(r != Z_STREAM_END){
return r;
}
r = f;
this.was=z.adler.getValue();
this.blocks.reset();
if(this.wrap==0){
this.mode=DONE;
break;
}
this.mode=CHECK4;
case CHECK4:
if(z.avail_in==0)return r;r=f;
z.avail_in--; z.total_in++;
this.need=((z.next_in[z.next_in_index++]&0xff)<<24)&0xff000000L;
this.mode=CHECK3;
case CHECK3:
if(z.avail_in==0)return r;r=f;
z.avail_in--; z.total_in++;
this.need+=((z.next_in[z.next_in_index++]&0xff)<<16)&0xff0000L;
this.mode = CHECK2;
case CHECK2:
if(z.avail_in==0)return r;r=f;
z.avail_in--; z.total_in++;
this.need+=((z.next_in[z.next_in_index++]&0xff)<<8)&0xff00L;
this.mode = CHECK1;
case CHECK1:
if(z.avail_in==0)return r;r=f;
z.avail_in--; z.total_in++;
this.need+=(z.next_in[z.next_in_index++]&0xffL);
if(flags!=0){ // gzip
this.need = ((this.need&0xff000000)>>24 |
(this.need&0x00ff0000)>>8 |
(this.need&0x0000ff00)<<8 |
(this.need&0x0000ffff)<<24)&0xffffffffL;
}
if(((int)(this.was)) != ((int)(this.need))){
z.msg = "incorrect data check";
// chack is delayed
/*
this.mode = BAD;
this.marker = 5; // can't try inflateSync
break;
*/
}
else if(flags!=0 && gheader!=null){
gheader.crc = this.need;
}
this.mode = LENGTH;
case LENGTH:
if (wrap!=0 && flags!=0) {
try { r=readBytes(4, r, f); }
catch(Return e){ return e.r; }
if(z.msg!=null && z.msg.equals("incorrect data check")){
this.mode = BAD;
this.marker = 5; // can't try inflateSync
break;
}
if (this.need != (z.total_out & 0xffffffffL)) {
z.msg = "incorrect length check";
this.mode = BAD;
break;
}
z.msg = null;
}
else {
if(z.msg!=null && z.msg.equals("incorrect data check")){
this.mode = BAD;
this.marker = 5; // can't try inflateSync
break;
}
}
this.mode = DONE;
case DONE:
return Z_STREAM_END;
case BAD:
return Z_DATA_ERROR;
case FLAGS:
try { r=readBytes(2, r, f); }
catch(Return e){ return e.r; }
flags = ((int)this.need)&0xffff;
if ((flags & 0xff) != Z_DEFLATED) {
z.msg = "unknown compression method";
this.mode = BAD;
break;
}
if ((flags & 0xe000)!=0) {
z.msg = "unknown header flags set";
this.mode = BAD;
break;
}
if ((flags & 0x0200)!=0){
checksum(2, this.need);
}
this.mode = TIME;
case TIME:
try { r=readBytes(4, r, f); }
catch(Return e){ return e.r; }
if(gheader!=null)
gheader.time = this.need;
if ((flags & 0x0200)!=0){
checksum(4, this.need);
}
this.mode = OS;
case OS:
try { r=readBytes(2, r, f); }
catch(Return e){ return e.r; }
if(gheader!=null){
gheader.xflags = ((int)this.need)&0xff;
gheader.os = (((int)this.need)>>8)&0xff;
}
if ((flags & 0x0200)!=0){
checksum(2, this.need);
}
this.mode = EXLEN;
case EXLEN:
if ((flags & 0x0400)!=0) {
try { r=readBytes(2, r, f); }
catch(Return e){ return e.r; }
if(gheader!=null){
gheader.extra = new byte[((int)this.need)&0xffff];
}
if ((flags & 0x0200)!=0){
checksum(2, this.need);
}
}
else if(gheader!=null){
gheader.extra=null;
}
this.mode = EXTRA;
case EXTRA:
if ((flags & 0x0400)!=0) {
try {
r=readBytes(r, f);
if(gheader!=null){
byte[] foo = tmp_string.toByteArray();
tmp_string=null;
if(foo.length == gheader.extra.length){
System.arraycopy(foo, 0, gheader.extra, 0, foo.length);
}
else{
z.msg = "bad extra field length";
this.mode = BAD;
break;
}
}
}
catch(Return e){ return e.r; }
}
else if(gheader!=null){
gheader.extra=null;
}
this.mode = NAME;
case NAME:
if ((flags & 0x0800)!=0) {
try {
r=readString(r, f);
if(gheader!=null){
gheader.name=tmp_string.toByteArray();
}
tmp_string=null;
}
catch(Return e){ return e.r; }
}
else if(gheader!=null){
gheader.name=null;
}
this.mode = COMMENT;
case COMMENT:
if ((flags & 0x1000)!=0) {
try {
r=readString(r, f);
if(gheader!=null){
gheader.comment=tmp_string.toByteArray();
}
tmp_string=null;
}
catch(Return e){ return e.r; }
}
else if(gheader!=null){
gheader.comment=null;
}
this.mode = HCRC;
case HCRC:
if ((flags & 0x0200)!=0) {
try { r=readBytes(2, r, f); }
catch(Return e){ return e.r; }
if(gheader!=null){
gheader.hcrc=(int)(this.need&0xffff);
}
if(this.need != (z.adler.getValue()&0xffffL)){
this.mode = BAD;
z.msg = "header crc mismatch";
this.marker = 5; // can't try inflateSync
break;
}
}
z.adler = new CRC32();
this.mode = BLOCKS;
break;
default:
return Z_STREAM_ERROR;
}
}
}
int inflateSetDictionary(byte[] dictionary, int dictLength){
if(z==null || (this.mode != DICT0 && this.wrap != 0)){
return Z_STREAM_ERROR;
}
int index=0;
int length = dictLength;
if(this.mode==DICT0){
long adler_need=z.adler.getValue();
z.adler.reset();
z.adler.update(dictionary, 0, dictLength);
if(z.adler.getValue()!=adler_need){
return Z_DATA_ERROR;
}
}
z.adler.reset();
if(length >= (1<<this.wbits)){
length = (1<<this.wbits)-1;
index=dictLength - length;
}
this.blocks.set_dictionary(dictionary, index, length);
this.mode = BLOCKS;
return Z_OK;
}
static private byte[] mark = {(byte)0, (byte)0, (byte)0xff, (byte)0xff};
int inflateSync(){
int n; // number of bytes to look at
int p; // pointer to bytes
int m; // number of marker bytes found in a row
long r, w; // temporaries to save total_in and total_out
// set up
if(z == null)
return Z_STREAM_ERROR;
if(this.mode != BAD){
this.mode = BAD;
this.marker = 0;
}
if((n=z.avail_in)==0)
return Z_BUF_ERROR;
p=z.next_in_index;
m=this.marker;
// search
while (n!=0 && m < 4){
if(z.next_in[p] == mark[m]){
m++;
}
else if(z.next_in[p]!=0){
m = 0;
}
else{
m = 4 - m;
}
p++; n--;
}
// restore
z.total_in += p-z.next_in_index;
z.next_in_index = p;
z.avail_in = n;
this.marker = m;
// return no joy or set up to restart on a new block
if(m != 4){
return Z_DATA_ERROR;
}
r=z.total_in; w=z.total_out;
inflateReset();
z.total_in=r; z.total_out = w;
this.mode = BLOCKS;
return Z_OK;
}
// Returns true if inflate is currently at the end of a block generated
// by Z_SYNC_FLUSH or Z_FULL_FLUSH. This function is used by one PPP
// implementation to provide an additional safety check. PPP uses Z_SYNC_FLUSH
// but removes the length bytes of the resulting empty stored block. When
// decompressing, PPP checks that at the end of input packet, inflate is
// waiting for these length bytes.
int inflateSyncPoint(){
if(z == null || this.blocks == null)
return Z_STREAM_ERROR;
return this.blocks.sync_point();
}
private int readBytes(int n, int r, int f) throws Return{
if(need_bytes == -1){
need_bytes=n;
this.need=0;
}
while(need_bytes>0){
if(z.avail_in==0){ throw new Return(r); }; r=f;
z.avail_in--; z.total_in++;
this.need = this.need |
((z.next_in[z.next_in_index++]&0xff)<<((n-need_bytes)*8));
need_bytes--;
}
if(n==2){
this.need&=0xffffL;
}
else if(n==4) {
this.need&=0xffffffffL;
}
need_bytes=-1;
return r;
}
class Return extends Exception{
int r;
Return(int r){this.r=r; }
}
private java.io.ByteArrayOutputStream tmp_string = null;
private int readString(int r, int f) throws Return{
if(tmp_string == null){
tmp_string=new java.io.ByteArrayOutputStream();
}
int b=0;
do {
if(z.avail_in==0){ throw new Return(r); }; r=f;
z.avail_in--; z.total_in++;
b = z.next_in[z.next_in_index];
if(b!=0) tmp_string.write(z.next_in, z.next_in_index, 1);
z.adler.update(z.next_in, z.next_in_index, 1);
z.next_in_index++;
}while(b!=0);
return r;
}
private int readBytes(int r, int f) throws Return{
if(tmp_string == null){
tmp_string=new java.io.ByteArrayOutputStream();
}
int b=0;
while(this.need>0){
if(z.avail_in==0){ throw new Return(r); }; r=f;
z.avail_in--; z.total_in++;
b = z.next_in[z.next_in_index];
tmp_string.write(z.next_in, z.next_in_index, 1);
z.adler.update(z.next_in, z.next_in_index, 1);
z.next_in_index++;
this.need--;
}
return r;
}
private void checksum(int n, long v){
for(int i=0; i<n; i++){
crcbuf[i]=(byte)(v&0xff);
v>>=8;
}
z.adler.update(crcbuf, 0, n);
}
public GZIPHeader getGZIPHeader(){
return gheader;
}
boolean inParsingHeader(){
switch(mode){
case HEAD:
case DICT4:
case DICT3:
case DICT2:
case DICT1:
case FLAGS:
case TIME:
case OS:
case EXLEN:
case EXTRA:
case NAME:
case COMMENT:
case HCRC:
return true;
default:
return false;
}
}
}
@@ -0,0 +1,168 @@
/* -*-mode:java; c-basic-offset:2; indent-tabs-mode:nil -*- */
/*
Copyright (c) 2011 ymnk, JCraft,Inc. All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the distribution.
3. The names of the authors may not be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JCRAFT,
INC. OR ANY CONTRIBUTORS TO THIS SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/*
* This program is based on zlib-1.1.3, so all credit should go authors
* Jean-loup Gailly(jloup@gzip.org) and Mark Adler(madler@alumni.caltech.edu)
* and contributors of zlib.
*/
package com.jcraft.jzlib;
final public class Inflater extends ZStream{
static final private int MAX_WBITS=15; // 32K LZ77 window
static final private int DEF_WBITS=MAX_WBITS;
static final private int Z_NO_FLUSH=0;
static final private int Z_PARTIAL_FLUSH=1;
static final private int Z_SYNC_FLUSH=2;
static final private int Z_FULL_FLUSH=3;
static final private int Z_FINISH=4;
static final private int MAX_MEM_LEVEL=9;
static final private int Z_OK=0;
static final private int Z_STREAM_END=1;
static final private int Z_NEED_DICT=2;
static final private int Z_ERRNO=-1;
static final private int Z_STREAM_ERROR=-2;
static final private int Z_DATA_ERROR=-3;
static final private int Z_MEM_ERROR=-4;
static final private int Z_BUF_ERROR=-5;
static final private int Z_VERSION_ERROR=-6;
public Inflater() {
super();
init();
}
public Inflater(JZlib.WrapperType wrapperType) throws GZIPException {
this(DEF_WBITS, wrapperType);
}
public Inflater(int w, JZlib.WrapperType wrapperType) throws GZIPException {
super();
int ret = init(w, wrapperType);
if(ret!=Z_OK)
throw new GZIPException(ret+": "+msg);
}
public Inflater(int w) throws GZIPException {
this(w, false);
}
public Inflater(boolean nowrap) throws GZIPException {
this(DEF_WBITS, nowrap);
}
public Inflater(int w, boolean nowrap) throws GZIPException {
super();
int ret = init(w, nowrap);
if(ret!=Z_OK)
throw new GZIPException(ret+": "+msg);
}
private boolean finished = false;
public int init(){
return init(DEF_WBITS);
}
public int init(JZlib.WrapperType wrapperType){
return init(DEF_WBITS, wrapperType);
}
public int init(int w, JZlib.WrapperType wrapperType) {
boolean nowrap = false;
if(wrapperType == JZlib.W_NONE){
nowrap = true;
}
else if(wrapperType == JZlib.W_GZIP) {
w += 16;
}
else if(wrapperType == JZlib.W_ANY) {
w |= Inflate.INFLATE_ANY;
}
else if(wrapperType == JZlib.W_ZLIB) {
}
return init(w, nowrap);
}
public int init(boolean nowrap){
return init(DEF_WBITS, nowrap);
}
public int init(int w){
return init(w, false);
}
public int init(int w, boolean nowrap){
finished = false;
istate=new Inflate(this);
return istate.inflateInit(nowrap?-w:w);
}
public int inflate(int f){
if(istate==null) return Z_STREAM_ERROR;
int ret = istate.inflate(f);
if(ret == Z_STREAM_END)
finished = true;
return ret;
}
public int end(){
finished = true;
if(istate==null) return Z_STREAM_ERROR;
int ret=istate.inflateEnd();
// istate = null;
return ret;
}
public int sync(){
if(istate == null)
return Z_STREAM_ERROR;
return istate.inflateSync();
}
public int syncPoint(){
if(istate == null)
return Z_STREAM_ERROR;
return istate.inflateSyncPoint();
}
public int setDictionary(byte[] dictionary, int dictLength){
if(istate == null)
return Z_STREAM_ERROR;
return istate.inflateSetDictionary(dictionary, dictLength);
}
public boolean finished(){
return istate.mode==12 /*DONE*/;
}
}
@@ -0,0 +1,247 @@
/* -*-mode:java; c-basic-offset:2; indent-tabs-mode:nil -*- */
/*
Copyright (c) 2011 ymnk, JCraft,Inc. All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the distribution.
3. The names of the authors may not be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JCRAFT,
INC. OR ANY CONTRIBUTORS TO THIS SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.jcraft.jzlib;
import java.io.*;
public class InflaterInputStream extends FilterInputStream {
protected final Inflater inflater;
protected byte[] buf;
private boolean closed = false;
private boolean eof = false;
private boolean close_in = true;
protected static final int DEFAULT_BUFSIZE = 512;
public InflaterInputStream(InputStream in) throws IOException {
this(in, false);
}
public InflaterInputStream(InputStream in, boolean nowrap) throws IOException {
this(in, new Inflater(nowrap));
myinflater = true;
}
public InflaterInputStream(InputStream in, Inflater inflater) throws IOException {
this(in, inflater, DEFAULT_BUFSIZE);
}
public InflaterInputStream(InputStream in,
Inflater inflater, int size) throws IOException {
this(in, inflater, size, true);
}
public InflaterInputStream(InputStream in,
Inflater inflater,
int size, boolean close_in) throws IOException {
super(in);
if (in == null || inflater == null) {
throw new NullPointerException();
}
else if (size <= 0) {
throw new IllegalArgumentException("buffer size must be greater than 0");
}
this.inflater = inflater;
buf = new byte[size];
this.close_in = close_in;
}
protected boolean myinflater = false;
private byte[] byte1 = new byte[1];
public int read() throws IOException {
if (closed) { throw new IOException("Stream closed"); }
return read(byte1, 0, 1) == -1 ? -1 : byte1[0] & 0xff;
}
public int read(byte[] b, int off, int len) throws IOException {
if (closed) { throw new IOException("Stream closed"); }
if (b == null) {
throw new NullPointerException();
}
else if (off < 0 || len < 0 || len > b.length - off) {
throw new IndexOutOfBoundsException();
}
else if (len == 0) {
return 0;
}
else if (eof) {
return -1;
}
int n = 0;
inflater.setOutput(b, off, len);
while(!eof) {
if(inflater.avail_in==0)
fill();
int err = inflater.inflate(JZlib.Z_NO_FLUSH);
n += inflater.next_out_index - off;
off = inflater.next_out_index;
switch(err) {
case JZlib.Z_DATA_ERROR:
throw new IOException(inflater.msg);
case JZlib.Z_STREAM_END:
case JZlib.Z_NEED_DICT:
eof = true;
if(err == JZlib.Z_NEED_DICT)
return -1;
break;
default:
}
if(inflater.avail_out==0)
break;
}
return n;
}
public int available() throws IOException {
if (closed) { throw new IOException("Stream closed"); }
if (eof) {
return 0;
}
else {
return 1;
}
}
private byte[] b = new byte[512];
public long skip(long n) throws IOException {
if (n < 0) {
throw new IllegalArgumentException("negative skip length");
}
if (closed) { throw new IOException("Stream closed"); }
int max = (int)Math.min(n, Integer.MAX_VALUE);
int total = 0;
while (total < max) {
int len = max - total;
if (len > b.length) {
len = b.length;
}
len = read(b, 0, len);
if (len == -1) {
eof = true;
break;
}
total += len;
}
return total;
}
public void close() throws IOException {
if (!closed) {
if (myinflater)
inflater.end();
if(close_in)
in.close();
closed = true;
}
}
protected void fill() throws IOException {
if (closed) { throw new IOException("Stream closed"); }
int len = in.read(buf, 0, buf.length);
if (len == -1) {
if(inflater.istate.wrap == 0 &&
!inflater.finished()){
buf[0]=0;
len=1;
}
else if(inflater.istate.was != -1){ // in reading trailer
throw new IOException("footer is not found");
}
else{
throw new EOFException("Unexpected end of ZLIB input stream");
}
}
inflater.setInput(buf, 0, len, true);
}
public boolean markSupported() {
return false;
}
public synchronized void mark(int readlimit) {
}
public synchronized void reset() throws IOException {
throw new IOException("mark/reset not supported");
}
public long getTotalIn() {
return inflater.getTotalIn();
}
public long getTotalOut() {
return inflater.getTotalOut();
}
public byte[] getAvailIn() {
if(inflater.avail_in<=0)
return null;
byte[] tmp = new byte[inflater.avail_in];
System.arraycopy(inflater.next_in, inflater.next_in_index,
tmp, 0, inflater.avail_in);
return tmp;
}
public void readHeader() throws IOException {
byte[] empty = "".getBytes();
inflater.setInput(empty, 0, 0, false);
inflater.setOutput(empty, 0, 0);
int err = inflater.inflate(JZlib.Z_NO_FLUSH);
if(!inflater.istate.inParsingHeader()){
return;
}
byte[] b1 = new byte[1];
do{
int i = in.read(b1);
if(i<=0)
throw new IOException("no input");
inflater.setInput(b1);
err = inflater.inflate(JZlib.Z_NO_FLUSH);
if(err!=0/*Z_OK*/)
throw new IOException(inflater.msg);
}
while(inflater.istate.inParsingHeader());
}
public Inflater getInflater(){
return inflater;
}
}
@@ -0,0 +1,92 @@
/* -*-mode:java; c-basic-offset:2; -*- */
/*
Copyright (c) 2011 ymnk, JCraft,Inc. All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the distribution.
3. The names of the authors may not be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JCRAFT,
INC. OR ANY CONTRIBUTORS TO THIS SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/*
* This program is based on zlib-1.1.3, so all credit should go authors
* Jean-loup Gailly(jloup@gzip.org) and Mark Adler(madler@alumni.caltech.edu)
* and contributors of zlib.
*/
package com.jcraft.jzlib;
final public class JZlib{
private static final String version="1.1.0";
public static String version(){return version;}
static final public int MAX_WBITS=15; // 32K LZ77 window
static final public int DEF_WBITS=MAX_WBITS;
public enum WrapperType {
NONE, ZLIB, GZIP, ANY
}
public static final WrapperType W_NONE = WrapperType.NONE;
public static final WrapperType W_ZLIB = WrapperType.ZLIB;
public static final WrapperType W_GZIP = WrapperType.GZIP;
public static final WrapperType W_ANY = WrapperType.ANY;
// compression levels
static final public int Z_NO_COMPRESSION=0;
static final public int Z_BEST_SPEED=1;
static final public int Z_BEST_COMPRESSION=9;
static final public int Z_DEFAULT_COMPRESSION=(-1);
// compression strategy
static final public int Z_FILTERED=1;
static final public int Z_HUFFMAN_ONLY=2;
static final public int Z_DEFAULT_STRATEGY=0;
static final public int Z_NO_FLUSH=0;
static final public int Z_PARTIAL_FLUSH=1;
static final public int Z_SYNC_FLUSH=2;
static final public int Z_FULL_FLUSH=3;
static final public int Z_FINISH=4;
static final public int Z_OK=0;
static final public int Z_STREAM_END=1;
static final public int Z_NEED_DICT=2;
static final public int Z_ERRNO=-1;
static final public int Z_STREAM_ERROR=-2;
static final public int Z_DATA_ERROR=-3;
static final public int Z_MEM_ERROR=-4;
static final public int Z_BUF_ERROR=-5;
static final public int Z_VERSION_ERROR=-6;
// The three kinds of block type
static final public byte Z_BINARY = 0;
static final public byte Z_ASCII = 1;
static final public byte Z_UNKNOWN = 2;
public static long adler32_combine(long adler1, long adler2, long len2){
return Adler32.combine(adler1, adler2, len2);
}
public static long crc32_combine(long crc1, long crc2, long len2){
return CRC32.combine(crc1, crc2, len2);
}
}
@@ -0,0 +1,148 @@
/* -*-mode:java; c-basic-offset:2; -*- */
/*
Copyright (c) 2000,2001,2002,2003 ymnk, JCraft,Inc. All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the distribution.
3. The names of the authors may not be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JCRAFT,
INC. OR ANY CONTRIBUTORS TO THIS SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/*
* This program is based on zlib-1.1.3, so all credit should go authors
* Jean-loup Gailly(jloup@gzip.org) and Mark Adler(madler@alumni.caltech.edu)
* and contributors of zlib.
*/
package com.jcraft.jzlib;
final class StaticTree{
static final private int MAX_BITS=15;
static final private int BL_CODES=19;
static final private int D_CODES=30;
static final private int LITERALS=256;
static final private int LENGTH_CODES=29;
static final private int L_CODES=(LITERALS+1+LENGTH_CODES);
// Bit length codes must not exceed MAX_BL_BITS bits
static final int MAX_BL_BITS=7;
static final short[] static_ltree = {
12, 8, 140, 8, 76, 8, 204, 8, 44, 8,
172, 8, 108, 8, 236, 8, 28, 8, 156, 8,
92, 8, 220, 8, 60, 8, 188, 8, 124, 8,
252, 8, 2, 8, 130, 8, 66, 8, 194, 8,
34, 8, 162, 8, 98, 8, 226, 8, 18, 8,
146, 8, 82, 8, 210, 8, 50, 8, 178, 8,
114, 8, 242, 8, 10, 8, 138, 8, 74, 8,
202, 8, 42, 8, 170, 8, 106, 8, 234, 8,
26, 8, 154, 8, 90, 8, 218, 8, 58, 8,
186, 8, 122, 8, 250, 8, 6, 8, 134, 8,
70, 8, 198, 8, 38, 8, 166, 8, 102, 8,
230, 8, 22, 8, 150, 8, 86, 8, 214, 8,
54, 8, 182, 8, 118, 8, 246, 8, 14, 8,
142, 8, 78, 8, 206, 8, 46, 8, 174, 8,
110, 8, 238, 8, 30, 8, 158, 8, 94, 8,
222, 8, 62, 8, 190, 8, 126, 8, 254, 8,
1, 8, 129, 8, 65, 8, 193, 8, 33, 8,
161, 8, 97, 8, 225, 8, 17, 8, 145, 8,
81, 8, 209, 8, 49, 8, 177, 8, 113, 8,
241, 8, 9, 8, 137, 8, 73, 8, 201, 8,
41, 8, 169, 8, 105, 8, 233, 8, 25, 8,
153, 8, 89, 8, 217, 8, 57, 8, 185, 8,
121, 8, 249, 8, 5, 8, 133, 8, 69, 8,
197, 8, 37, 8, 165, 8, 101, 8, 229, 8,
21, 8, 149, 8, 85, 8, 213, 8, 53, 8,
181, 8, 117, 8, 245, 8, 13, 8, 141, 8,
77, 8, 205, 8, 45, 8, 173, 8, 109, 8,
237, 8, 29, 8, 157, 8, 93, 8, 221, 8,
61, 8, 189, 8, 125, 8, 253, 8, 19, 9,
275, 9, 147, 9, 403, 9, 83, 9, 339, 9,
211, 9, 467, 9, 51, 9, 307, 9, 179, 9,
435, 9, 115, 9, 371, 9, 243, 9, 499, 9,
11, 9, 267, 9, 139, 9, 395, 9, 75, 9,
331, 9, 203, 9, 459, 9, 43, 9, 299, 9,
171, 9, 427, 9, 107, 9, 363, 9, 235, 9,
491, 9, 27, 9, 283, 9, 155, 9, 411, 9,
91, 9, 347, 9, 219, 9, 475, 9, 59, 9,
315, 9, 187, 9, 443, 9, 123, 9, 379, 9,
251, 9, 507, 9, 7, 9, 263, 9, 135, 9,
391, 9, 71, 9, 327, 9, 199, 9, 455, 9,
39, 9, 295, 9, 167, 9, 423, 9, 103, 9,
359, 9, 231, 9, 487, 9, 23, 9, 279, 9,
151, 9, 407, 9, 87, 9, 343, 9, 215, 9,
471, 9, 55, 9, 311, 9, 183, 9, 439, 9,
119, 9, 375, 9, 247, 9, 503, 9, 15, 9,
271, 9, 143, 9, 399, 9, 79, 9, 335, 9,
207, 9, 463, 9, 47, 9, 303, 9, 175, 9,
431, 9, 111, 9, 367, 9, 239, 9, 495, 9,
31, 9, 287, 9, 159, 9, 415, 9, 95, 9,
351, 9, 223, 9, 479, 9, 63, 9, 319, 9,
191, 9, 447, 9, 127, 9, 383, 9, 255, 9,
511, 9, 0, 7, 64, 7, 32, 7, 96, 7,
16, 7, 80, 7, 48, 7, 112, 7, 8, 7,
72, 7, 40, 7, 104, 7, 24, 7, 88, 7,
56, 7, 120, 7, 4, 7, 68, 7, 36, 7,
100, 7, 20, 7, 84, 7, 52, 7, 116, 7,
3, 8, 131, 8, 67, 8, 195, 8, 35, 8,
163, 8, 99, 8, 227, 8
};
static final short[] static_dtree = {
0, 5, 16, 5, 8, 5, 24, 5, 4, 5,
20, 5, 12, 5, 28, 5, 2, 5, 18, 5,
10, 5, 26, 5, 6, 5, 22, 5, 14, 5,
30, 5, 1, 5, 17, 5, 9, 5, 25, 5,
5, 5, 21, 5, 13, 5, 29, 5, 3, 5,
19, 5, 11, 5, 27, 5, 7, 5, 23, 5
};
static StaticTree static_l_desc =
new StaticTree(static_ltree, Tree.extra_lbits,
LITERALS+1, L_CODES, MAX_BITS);
static StaticTree static_d_desc =
new StaticTree(static_dtree, Tree.extra_dbits,
0, D_CODES, MAX_BITS);
static StaticTree static_bl_desc =
new StaticTree(null, Tree.extra_blbits,
0, BL_CODES, MAX_BL_BITS);
short[] static_tree; // static tree or null
int[] extra_bits; // extra bits for each code or null
int extra_base; // base index for extra_bits
int elems; // max number of elements in the tree
int max_length; // max bit length for the codes
private StaticTree(short[] static_tree,
int[] extra_bits,
int extra_base,
int elems,
int max_length){
this.static_tree=static_tree;
this.extra_bits=extra_bits;
this.extra_base=extra_base;
this.elems=elems;
this.max_length=max_length;
}
}
@@ -0,0 +1,367 @@
/* -*-mode:java; c-basic-offset:2; -*- */
/*
Copyright (c) 2000,2001,2002,2003 ymnk, JCraft,Inc. All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the distribution.
3. The names of the authors may not be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JCRAFT,
INC. OR ANY CONTRIBUTORS TO THIS SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/*
* This program is based on zlib-1.1.3, so all credit should go authors
* Jean-loup Gailly(jloup@gzip.org) and Mark Adler(madler@alumni.caltech.edu)
* and contributors of zlib.
*/
package com.jcraft.jzlib;
final class Tree{
static final private int MAX_BITS=15;
static final private int BL_CODES=19;
static final private int D_CODES=30;
static final private int LITERALS=256;
static final private int LENGTH_CODES=29;
static final private int L_CODES=(LITERALS+1+LENGTH_CODES);
static final private int HEAP_SIZE=(2*L_CODES+1);
// Bit length codes must not exceed MAX_BL_BITS bits
static final int MAX_BL_BITS=7;
// end of block literal code
static final int END_BLOCK=256;
// repeat previous bit length 3-6 times (2 bits of repeat count)
static final int REP_3_6=16;
// repeat a zero length 3-10 times (3 bits of repeat count)
static final int REPZ_3_10=17;
// repeat a zero length 11-138 times (7 bits of repeat count)
static final int REPZ_11_138=18;
// extra bits for each length code
static final int[] extra_lbits={
0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0
};
// extra bits for each distance code
static final int[] extra_dbits={
0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13
};
// extra bits for each bit length code
static final int[] extra_blbits={
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7
};
static final byte[] bl_order={
16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15};
// The lengths of the bit length codes are sent in order of decreasing
// probability, to avoid transmitting the lengths for unused bit
// length codes.
static final int Buf_size=8*2;
// see definition of array dist_code below
static final int DIST_CODE_LEN=512;
static final byte[] _dist_code = {
0, 1, 2, 3, 4, 4, 5, 5, 6, 6, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8,
8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 10, 10, 10, 10, 10, 10, 10, 10,
10, 10, 10, 10, 10, 10, 10, 10, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11,
11, 11, 11, 11, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12,
12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 13, 13, 13, 13,
13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13,
13, 13, 13, 13, 13, 13, 13, 13, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14,
14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14,
14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14,
14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 15, 15, 15, 15, 15, 15, 15, 15,
15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 0, 0, 16, 17,
18, 18, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 22, 22, 22, 22, 22, 22, 22, 22,
23, 23, 23, 23, 23, 23, 23, 23, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
24, 24, 24, 24, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25,
26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26,
26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 27, 27, 27, 27, 27, 27, 27, 27,
27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27,
27, 27, 27, 27, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28,
28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28,
28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28,
28, 28, 28, 28, 28, 28, 28, 28, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29,
29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29,
29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29,
29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29
};
static final byte[] _length_code={
0, 1, 2, 3, 4, 5, 6, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 12, 12,
13, 13, 13, 13, 14, 14, 14, 14, 15, 15, 15, 15, 16, 16, 16, 16, 16, 16, 16, 16,
17, 17, 17, 17, 17, 17, 17, 17, 18, 18, 18, 18, 18, 18, 18, 18, 19, 19, 19, 19,
19, 19, 19, 19, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20,
21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 22, 22, 22, 22,
22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 23, 23, 23, 23, 23, 23, 23, 23,
23, 23, 23, 23, 23, 23, 23, 23, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25,
25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 26, 26, 26, 26, 26, 26, 26, 26,
26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26,
26, 26, 26, 26, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27,
27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 28
};
static final int[] base_length = {
0, 1, 2, 3, 4, 5, 6, 7, 8, 10, 12, 14, 16, 20, 24, 28, 32, 40, 48, 56,
64, 80, 96, 112, 128, 160, 192, 224, 0
};
static final int[] base_dist = {
0, 1, 2, 3, 4, 6, 8, 12, 16, 24,
32, 48, 64, 96, 128, 192, 256, 384, 512, 768,
1024, 1536, 2048, 3072, 4096, 6144, 8192, 12288, 16384, 24576
};
// Mapping from a distance to a distance code. dist is the distance - 1 and
// must not have side effects. _dist_code[256] and _dist_code[257] are never
// used.
static int d_code(int dist){
return ((dist) < 256 ? _dist_code[dist] : _dist_code[256+((dist)>>>7)]);
}
short[] dyn_tree; // the dynamic tree
int max_code; // largest code with non zero frequency
StaticTree stat_desc; // the corresponding static tree
// Compute the optimal bit lengths for a tree and update the total bit length
// for the current block.
// IN assertion: the fields freq and dad are set, heap[heap_max] and
// above are the tree nodes sorted by increasing frequency.
// OUT assertions: the field len is set to the optimal bit length, the
// array bl_count contains the frequencies for each bit length.
// The length opt_len is updated; static_len is also updated if stree is
// not null.
void gen_bitlen(Deflate s){
short[] tree = dyn_tree;
short[] stree = stat_desc.static_tree;
int[] extra = stat_desc.extra_bits;
int base = stat_desc.extra_base;
int max_length = stat_desc.max_length;
int h; // heap index
int n, m; // iterate over the tree elements
int bits; // bit length
int xbits; // extra bits
short f; // frequency
int overflow = 0; // number of elements with bit length too large
for (bits = 0; bits <= MAX_BITS; bits++) s.bl_count[bits] = 0;
// In a first pass, compute the optimal bit lengths (which may
// overflow in the case of the bit length tree).
tree[s.heap[s.heap_max]*2+1] = 0; // root of the heap
for(h=s.heap_max+1; h<HEAP_SIZE; h++){
n = s.heap[h];
bits = tree[tree[n*2+1]*2+1] + 1;
if (bits > max_length){ bits = max_length; overflow++; }
tree[n*2+1] = (short)bits;
// We overwrite tree[n*2+1] which is no longer needed
if (n > max_code) continue; // not a leaf node
s.bl_count[bits]++;
xbits = 0;
if (n >= base) xbits = extra[n-base];
f = tree[n*2];
s.opt_len += f * (bits + xbits);
if (stree!=null) s.static_len += f * (stree[n*2+1] + xbits);
}
if (overflow == 0) return;
// This happens for example on obj2 and pic of the Calgary corpus
// Find the first bit length which could increase:
do {
bits = max_length-1;
while(s.bl_count[bits]==0) bits--;
s.bl_count[bits]--; // move one leaf down the tree
s.bl_count[bits+1]+=2; // move one overflow item as its brother
s.bl_count[max_length]--;
// The brother of the overflow item also moves one step up,
// but this does not affect bl_count[max_length]
overflow -= 2;
}
while (overflow > 0);
for (bits = max_length; bits != 0; bits--) {
n = s.bl_count[bits];
while (n != 0) {
m = s.heap[--h];
if (m > max_code) continue;
if (tree[m*2+1] != bits) {
s.opt_len += ((long)bits - (long)tree[m*2+1])*(long)tree[m*2];
tree[m*2+1] = (short)bits;
}
n--;
}
}
}
// Construct one Huffman tree and assigns the code bit strings and lengths.
// Update the total bit length for the current block.
// IN assertion: the field freq is set for all tree elements.
// OUT assertions: the fields len and code are set to the optimal bit length
// and corresponding code. The length opt_len is updated; static_len is
// also updated if stree is not null. The field max_code is set.
void build_tree(Deflate s){
short[] tree=dyn_tree;
short[] stree=stat_desc.static_tree;
int elems=stat_desc.elems;
int n, m; // iterate over heap elements
int max_code=-1; // largest code with non zero frequency
int node; // new node being created
// Construct the initial heap, with least frequent element in
// heap[1]. The sons of heap[n] are heap[2*n] and heap[2*n+1].
// heap[0] is not used.
s.heap_len = 0;
s.heap_max = HEAP_SIZE;
for(n=0; n<elems; n++) {
if(tree[n*2] != 0) {
s.heap[++s.heap_len] = max_code = n;
s.depth[n] = 0;
}
else{
tree[n*2+1] = 0;
}
}
// The pkzip format requires that at least one distance code exists,
// and that at least one bit should be sent even if there is only one
// possible code. So to avoid special checks later on we force at least
// two codes of non zero frequency.
while (s.heap_len < 2) {
node = s.heap[++s.heap_len] = (max_code < 2 ? ++max_code : 0);
tree[node*2] = 1;
s.depth[node] = 0;
s.opt_len--; if (stree!=null) s.static_len -= stree[node*2+1];
// node is 0 or 1 so it does not have extra bits
}
this.max_code = max_code;
// The elements heap[heap_len/2+1 .. heap_len] are leaves of the tree,
// establish sub-heaps of increasing lengths:
for(n=s.heap_len/2;n>=1; n--)
s.pqdownheap(tree, n);
// Construct the Huffman tree by repeatedly combining the least two
// frequent nodes.
node=elems; // next internal node of the tree
do{
// n = node of least frequency
n=s.heap[1];
s.heap[1]=s.heap[s.heap_len--];
s.pqdownheap(tree, 1);
m=s.heap[1]; // m = node of next least frequency
s.heap[--s.heap_max] = n; // keep the nodes sorted by frequency
s.heap[--s.heap_max] = m;
// Create a new node father of n and m
tree[node*2] = (short)(tree[n*2] + tree[m*2]);
s.depth[node] = (byte)(Math.max(s.depth[n],s.depth[m])+1);
tree[n*2+1] = tree[m*2+1] = (short)node;
// and insert the new node in the heap
s.heap[1] = node++;
s.pqdownheap(tree, 1);
}
while(s.heap_len>=2);
s.heap[--s.heap_max] = s.heap[1];
// At this point, the fields freq and dad are set. We can now
// generate the bit lengths.
gen_bitlen(s);
// The field len is now set, we can generate the bit codes
gen_codes(tree, max_code, s.bl_count, s.next_code);
}
// Generate the codes for a given tree and bit counts (which need not be
// optimal).
// IN assertion: the array bl_count contains the bit length statistics for
// the given tree and the field len is set for all tree elements.
// OUT assertion: the field code is set for all tree elements of non
// zero code length.
private final static void gen_codes(
short[] tree, // the tree to decorate
int max_code, // largest code with non zero frequency
short[] bl_count, // number of codes at each bit length
short[] next_code){
short code = 0; // running code value
int bits; // bit index
int n; // code index
// The distribution counts are first used to generate the code values
// without bit reversal.
next_code[0]=0;
for (bits = 1; bits <= MAX_BITS; bits++) {
next_code[bits] = code = (short)((code + bl_count[bits-1]) << 1);
}
// Check that the bit counts in bl_count are consistent. The last code
// must be all ones.
//Assert (code + bl_count[MAX_BITS]-1 == (1<<MAX_BITS)-1,
// "inconsistent bit counts");
//Tracev((stderr,"\ngen_codes: max_code %d ", max_code));
for (n = 0; n <= max_code; n++) {
int len = tree[n*2+1];
if (len == 0) continue;
// Now reverse the bits
tree[n*2] = (short)(bi_reverse(next_code[len]++, len));
}
}
// Reverse the first len bits of a code, using straightforward code (a faster
// method would use a table)
// IN assertion: 1 <= len <= 15
private final static int bi_reverse(
int code, // the value to invert
int len // its bit length
){
int res = 0;
do{
res|=code&1;
code>>>=1;
res<<=1;
}
while(--len>0);
return res>>>1;
}
}
@@ -0,0 +1,126 @@
/* -*-mode:java; c-basic-offset:2; indent-tabs-mode:nil -*- */
/*
Copyright (c) 2011 ymnk, JCraft,Inc. All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the distribution.
3. The names of the authors may not be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JCRAFT,
INC. OR ANY CONTRIBUTORS TO THIS SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.jcraft.jzlib;
import java.io.*;
/**
* ZInputStream
*
* @deprecated use DeflaterOutputStream or InflaterInputStream
*/
@Deprecated
public class ZInputStream extends FilterInputStream {
protected int flush=JZlib.Z_NO_FLUSH;
protected boolean compress;
protected InputStream in=null;
protected Deflater deflater;
protected InflaterInputStream iis;
public ZInputStream(InputStream in) throws IOException {
this(in, false);
}
public ZInputStream(InputStream in, boolean nowrap) throws IOException {
super(in);
iis = new InflaterInputStream(in, nowrap);
compress=false;
}
public ZInputStream(InputStream in, int level) throws IOException {
super(in);
this.in=in;
deflater = new Deflater();
deflater.init(level);
compress=true;
}
private byte[] buf1 = new byte[1];
public int read() throws IOException {
if(read(buf1, 0, 1)==-1) return -1;
return(buf1[0]&0xFF);
}
private byte[] buf = new byte[512];
public int read(byte[] b, int off, int len) throws IOException {
if(compress){
deflater.setOutput(b, off, len);
while(true){
int datalen = in.read(buf, 0, buf.length);
if(datalen == -1) return -1;
deflater.setInput(buf, 0, datalen, true);
int err = deflater.deflate(flush);
if(deflater.next_out_index>0)
return deflater.next_out_index;
if(err == JZlib.Z_STREAM_END)
return 0;
if(err == JZlib.Z_STREAM_ERROR ||
err == JZlib.Z_DATA_ERROR){
throw new ZStreamException("deflating: "+deflater.msg);
}
}
}
else{
return iis.read(b, off, len);
}
}
public long skip(long n) throws IOException {
int len=512;
if(n<len)
len=(int)n;
byte[] tmp=new byte[len];
return((long)read(tmp));
}
public int getFlushMode() {
return flush;
}
public void setFlushMode(int flush) {
this.flush=flush;
}
public long getTotalIn() {
if(compress) return deflater.total_in;
else return iis.getTotalIn();
}
public long getTotalOut() {
if(compress) return deflater.total_out;
else return iis.getTotalOut();
}
public void close() throws IOException{
if(compress) deflater.end();
else iis.close();
}
}
@@ -0,0 +1,159 @@
/* -*-mode:java; c-basic-offset:2; indent-tabs-mode:nil -*- */
/*
Copyright (c) 2011 ymnk, JCraft,Inc. All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the distribution.
3. The names of the authors may not be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JCRAFT,
INC. OR ANY CONTRIBUTORS TO THIS SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.jcraft.jzlib;
import java.io.*;
/**
* ZOutputStream
*
* @deprecated use DeflaterOutputStream or InflaterInputStream
*/
@Deprecated
public class ZOutputStream extends FilterOutputStream {
protected int bufsize=512;
protected int flush=JZlib.Z_NO_FLUSH;
protected byte[] buf=new byte[bufsize];
protected boolean compress;
protected OutputStream out;
private boolean end=false;
private DeflaterOutputStream dos;
private Inflater inflater;
public ZOutputStream(OutputStream out) throws IOException {
super(out);
this.out=out;
inflater = new Inflater();
inflater.init();
compress=false;
}
public ZOutputStream(OutputStream out, int level) throws IOException {
this(out, level, false);
}
public ZOutputStream(OutputStream out, int level, boolean nowrap) throws IOException {
super(out);
this.out=out;
Deflater deflater = new Deflater(level, nowrap);
dos = new DeflaterOutputStream(out, deflater);
compress=true;
}
private byte[] buf1 = new byte[1];
public void write(int b) throws IOException {
buf1[0]=(byte)b;
write(buf1, 0, 1);
}
public void write(byte b[], int off, int len) throws IOException {
if(len==0) return;
if(compress){
dos.write(b, off, len);
}
else {
inflater.setInput(b, off, len, true);
int err = JZlib.Z_OK;
while(inflater.avail_in>0){
inflater.setOutput(buf, 0, buf.length);
err = inflater.inflate(flush);
if(inflater.next_out_index>0)
out.write(buf, 0, inflater.next_out_index);
if(err != JZlib.Z_OK)
break;
}
if(err != JZlib.Z_OK)
throw new ZStreamException("inflating: "+inflater.msg);
return;
}
}
public int getFlushMode() {
return flush;
}
public void setFlushMode(int flush) {
this.flush=flush;
}
public void finish() throws IOException {
int err;
if(compress){
int tmp = flush;
int flush = JZlib.Z_FINISH;
try{
write("".getBytes(), 0, 0);
}
finally { flush = tmp; }
}
else{
dos.finish();
}
flush();
}
public synchronized void end() {
if(end) return;
if(compress){
try { dos.finish(); } catch(Exception e){}
}
else{
inflater.end();
}
end=true;
}
public void close() throws IOException {
try{
try{finish();}
catch (IOException ignored) {}
}
finally{
end();
out.close();
out=null;
}
}
public long getTotalIn() {
if(compress) return dos.getTotalIn();
else return inflater.total_in;
}
public long getTotalOut() {
if(compress) return dos.getTotalOut();
else return inflater.total_out;
}
public void flush() throws IOException {
out.flush();
}
}
@@ -0,0 +1,377 @@
/* -*-mode:java; c-basic-offset:2; indent-tabs-mode:nil -*- */
/*
Copyright (c) 2000-2011 ymnk, JCraft,Inc. All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the distribution.
3. The names of the authors may not be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JCRAFT,
INC. OR ANY CONTRIBUTORS TO THIS SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/*
* This program is based on zlib-1.1.3, so all credit should go authors
* Jean-loup Gailly(jloup@gzip.org) and Mark Adler(madler@alumni.caltech.edu)
* and contributors of zlib.
*/
package com.jcraft.jzlib;
/**
* ZStream
*
* @deprecated Not for public use in the future.
*/
@Deprecated
public class ZStream{
static final private int MAX_WBITS=15; // 32K LZ77 window
static final private int DEF_WBITS=MAX_WBITS;
static final private int Z_NO_FLUSH=0;
static final private int Z_PARTIAL_FLUSH=1;
static final private int Z_SYNC_FLUSH=2;
static final private int Z_FULL_FLUSH=3;
static final private int Z_FINISH=4;
static final private int MAX_MEM_LEVEL=9;
static final private int Z_OK=0;
static final private int Z_STREAM_END=1;
static final private int Z_NEED_DICT=2;
static final private int Z_ERRNO=-1;
static final private int Z_STREAM_ERROR=-2;
static final private int Z_DATA_ERROR=-3;
static final private int Z_MEM_ERROR=-4;
static final private int Z_BUF_ERROR=-5;
static final private int Z_VERSION_ERROR=-6;
public byte[] next_in; // next input byte
public int next_in_index;
public int avail_in; // number of bytes available at next_in
public long total_in; // total nb of input bytes read so far
public byte[] next_out; // next output byte should be put there
public int next_out_index;
public int avail_out; // remaining free space at next_out
public long total_out; // total nb of bytes output so far
public String msg;
Deflate dstate;
Inflate istate;
int data_type; // best guess about the data type: ascii or binary
Checksum adler;
public ZStream(){
this(new Adler32());
}
public ZStream(Checksum adler){
this.adler=adler;
}
public int inflateInit(){
return inflateInit(DEF_WBITS);
}
public int inflateInit(boolean nowrap){
return inflateInit(DEF_WBITS, nowrap);
}
public int inflateInit(int w){
return inflateInit(w, false);
}
public int inflateInit(JZlib.WrapperType wrapperType) {
return inflateInit(DEF_WBITS, wrapperType);
}
public int inflateInit(int w, JZlib.WrapperType wrapperType) {
boolean nowrap = false;
if(wrapperType == JZlib.W_NONE){
nowrap = true;
}
else if(wrapperType == JZlib.W_GZIP) {
w += 16;
}
else if(wrapperType == JZlib.W_ANY) {
w |= Inflate.INFLATE_ANY;
}
else if(wrapperType == JZlib.W_ZLIB) {
}
return inflateInit(w, nowrap);
}
public int inflateInit(int w, boolean nowrap){
istate=new Inflate(this);
return istate.inflateInit(nowrap?-w:w);
}
public int inflate(int f){
if(istate==null) return Z_STREAM_ERROR;
return istate.inflate(f);
}
public int inflateEnd(){
if(istate==null) return Z_STREAM_ERROR;
int ret=istate.inflateEnd();
// istate = null;
return ret;
}
public int inflateSync(){
if(istate == null)
return Z_STREAM_ERROR;
return istate.inflateSync();
}
public int inflateSyncPoint(){
if(istate == null)
return Z_STREAM_ERROR;
return istate.inflateSyncPoint();
}
public int inflateSetDictionary(byte[] dictionary, int dictLength){
if(istate == null)
return Z_STREAM_ERROR;
return istate.inflateSetDictionary(dictionary, dictLength);
}
public boolean inflateFinished(){
return istate.mode==12 /*DONE*/;
}
public int deflateInit(int level){
return deflateInit(level, MAX_WBITS);
}
public int deflateInit(int level, boolean nowrap){
return deflateInit(level, MAX_WBITS, nowrap);
}
public int deflateInit(int level, int bits){
return deflateInit(level, bits, false);
}
public int deflateInit(int level, int bits, int memlevel, JZlib.WrapperType wrapperType){
if(bits < 9 || bits > 15){
return Z_STREAM_ERROR;
}
if(wrapperType == JZlib.W_NONE) {
bits *= -1;
}
else if(wrapperType == JZlib.W_GZIP) {
bits += 16;
}
else if(wrapperType == JZlib.W_ANY) {
return Z_STREAM_ERROR;
}
else if(wrapperType == JZlib.W_ZLIB) {
}
return this.deflateInit(level, bits, memlevel);
}
public int deflateInit(int level, int bits, int memlevel){
dstate=new Deflate(this);
return dstate.deflateInit(level, bits, memlevel);
}
public int deflateInit(int level, int bits, boolean nowrap){
dstate=new Deflate(this);
return dstate.deflateInit(level, nowrap?-bits:bits);
}
public int deflate(int flush){
if(dstate==null){
return Z_STREAM_ERROR;
}
return dstate.deflate(flush);
}
public int deflateEnd(){
if(dstate==null) return Z_STREAM_ERROR;
int ret=dstate.deflateEnd();
dstate=null;
return ret;
}
public int deflateParams(int level, int strategy){
if(dstate==null) return Z_STREAM_ERROR;
return dstate.deflateParams(level, strategy);
}
public int deflateSetDictionary (byte[] dictionary, int dictLength){
if(dstate == null)
return Z_STREAM_ERROR;
return dstate.deflateSetDictionary(dictionary, dictLength);
}
// Flush as much pending output as possible. All deflate() output goes
// through this function so some applications may wish to modify it
// to avoid allocating a large strm->next_out buffer and copying into it.
// (See also read_buf()).
void flush_pending(){
int len=dstate.pending;
if(len>avail_out) len=avail_out;
if(len==0) return;
if(dstate.pending_buf.length<=dstate.pending_out ||
next_out.length<=next_out_index ||
dstate.pending_buf.length<(dstate.pending_out+len) ||
next_out.length<(next_out_index+len)){
//System.out.println(dstate.pending_buf.length+", "+dstate.pending_out+
// ", "+next_out.length+", "+next_out_index+", "+len);
//System.out.println("avail_out="+avail_out);
}
System.arraycopy(dstate.pending_buf, dstate.pending_out,
next_out, next_out_index, len);
next_out_index+=len;
dstate.pending_out+=len;
total_out+=len;
avail_out-=len;
dstate.pending-=len;
if(dstate.pending==0){
dstate.pending_out=0;
}
}
// Read a new buffer from the current input stream, update the adler32
// and total number of bytes read. All deflate() input goes through
// this function so some applications may wish to modify it to avoid
// allocating a large strm->next_in buffer and copying from it.
// (See also flush_pending()).
int read_buf(byte[] buf, int start, int size) {
int len=avail_in;
if(len>size) len=size;
if(len==0) return 0;
avail_in-=len;
if(dstate.wrap!=0) {
adler.update(next_in, next_in_index, len);
}
System.arraycopy(next_in, next_in_index, buf, start, len);
next_in_index += len;
total_in += len;
return len;
}
public long getAdler(){
return adler.getValue();
}
public void free(){
next_in=null;
next_out=null;
msg=null;
}
public void setOutput(byte[] buf){
setOutput(buf, 0, buf.length);
}
public void setOutput(byte[] buf, int off, int len){
next_out = buf;
next_out_index = off;
avail_out = len;
}
public void setInput(byte[] buf){
setInput(buf, 0, buf.length, false);
}
public void setInput(byte[] buf, boolean append){
setInput(buf, 0, buf.length, append);
}
public void setInput(byte[] buf, int off, int len, boolean append){
if(len<=0 && append && next_in!=null) return;
if(avail_in>0 && append){
byte[] tmp = new byte[avail_in+len];
System.arraycopy(next_in, next_in_index, tmp, 0, avail_in);
System.arraycopy(buf, off, tmp, avail_in, len);
next_in=tmp;
next_in_index=0;
avail_in+=len;
}
else{
next_in=buf;
next_in_index=off;
avail_in=len;
}
}
public byte[] getNextIn(){
return next_in;
}
public void setNextIn(byte[] next_in){
this.next_in = next_in;
}
public int getNextInIndex(){
return next_in_index;
}
public void setNextInIndex(int next_in_index){
this.next_in_index = next_in_index;
}
public int getAvailIn(){
return avail_in;
}
public void setAvailIn(int avail_in){
this.avail_in = avail_in;
}
public byte[] getNextOut(){
return next_out;
}
public void setNextOut(byte[] next_out){
this.next_out = next_out;
}
public int getNextOutIndex(){
return next_out_index;
}
public void setNextOutIndex(int next_out_index){
this.next_out_index = next_out_index;
}
public int getAvailOut(){
return avail_out;
}
public void setAvailOut(int avail_out){
this.avail_out = avail_out;
}
public long getTotalOut(){
return total_out;
}
public long getTotalIn(){
return total_in;
}
public String getMessage(){
return msg;
}
/**
* Those methods are expected to be override by Inflater and Deflater.
* In the future, they will become abstract methods.
*/
public int end(){ return Z_OK; }
public boolean finished(){ return false; }
}
@@ -0,0 +1,44 @@
/* -*-mode:java; c-basic-offset:2; -*- */
/*
Copyright (c) 2000,2001,2002,2003 ymnk, JCraft,Inc. All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the distribution.
3. The names of the authors may not be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JCRAFT,
INC. OR ANY CONTRIBUTORS TO THIS SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/*
* This program is based on zlib-1.1.3, so all credit should go authors
* Jean-loup Gailly(jloup@gzip.org) and Mark Adler(madler@alumni.caltech.edu)
* and contributors of zlib.
*/
package com.jcraft.jzlib;
public class ZStreamException extends java.io.IOException {
public ZStreamException() {
super();
}
public ZStreamException(String s) {
super(s);
}
}
@@ -0,0 +1,61 @@
package com.trilead.ssh2;
/**
* Contains constants that can be used to specify what conditions to wait for on
* a SSH-2 channel (e.g., represented by a {@link Session}).
*
* @see Session#waitForCondition(int, long)
*
* @author Christian Plattner, plattner@trilead.com
* @version $Id: ChannelCondition.java,v 1.1 2007/10/15 12:49:56 cplattne Exp $
*/
public abstract interface ChannelCondition
{
/**
* A timeout has occurred, none of your requested conditions is fulfilled.
* However, other conditions may be true - therefore, NEVER use the "=="
* operator to test for this (or any other) condition. Always use
* something like <code>((cond &amp; ChannelCondition.CLOSED) != 0)</code>.
*/
public static final int TIMEOUT = 1;
/**
* The underlying SSH-2 channel, however not necessarily the whole connection,
* has been closed. This implies <code>EOF</code>. Note that there may still
* be unread stdout or stderr data in the local window, i.e, <code>STDOUT_DATA</code>
* or/and <code>STDERR_DATA</code> may be set at the same time.
*/
public static final int CLOSED = 2;
/**
* There is stdout data available that is ready to be consumed.
*/
public static final int STDOUT_DATA = 4;
/**
* There is stderr data available that is ready to be consumed.
*/
public static final int STDERR_DATA = 8;
/**
* EOF on has been reached, no more _new_ stdout or stderr data will arrive
* from the remote server. However, there may be unread stdout or stderr
* data, i.e, <code>STDOUT_DATA</code> or/and <code>STDERR_DATA</code>
* may be set at the same time.
*/
public static final int EOF = 16;
/**
* The exit status of the remote process is available.
* Some servers never send the exist status, or occasionally "forget" to do so.
*/
public static final int EXIT_STATUS = 32;
/**
* The exit signal of the remote process is available.
*/
public static final int EXIT_SIGNAL = 64;
}
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,52 @@
package com.trilead.ssh2;
/**
* In most cases you probably do not need the information contained in here.
*
* @author Christian Plattner, plattner@trilead.com
* @version $Id: ConnectionInfo.java,v 1.1 2007/10/15 12:49:56 cplattne Exp $
*/
public class ConnectionInfo
{
/**
* The used key exchange (KEX) algorithm in the latest key exchange.
*/
public String keyExchangeAlgorithm;
/**
* The currently used crypto algorithm for packets from to the client to the
* server.
*/
public String clientToServerCryptoAlgorithm;
/**
* The currently used crypto algorithm for packets from to the server to the
* client.
*/
public String serverToClientCryptoAlgorithm;
/**
* The currently used MAC algorithm for packets from to the client to the
* server.
*/
public String clientToServerMACAlgorithm;
/**
* The currently used MAC algorithm for packets from to the server to the
* client.
*/
public String serverToClientMACAlgorithm;
/**
* The type of the server host key
*/
public String serverHostKeyAlgorithm;
/**
* The server host key that was sent during the latest key exchange.
*/
public byte[] serverHostKey;
/**
* Number of kex exchanges performed on this connection so far.
*/
public int keyExchangeCounter = 0;
}
@@ -0,0 +1,38 @@
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
{
public static final int SERVER_BANNER = 101;
/**
* 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);
public void onReceiveInfo(int infoId, String infoMsg);
}
@@ -0,0 +1,121 @@
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, 2048, 4096)}.
* This is also the default used by the Connection class.
*
*/
public DHGexParameters()
{
this(1024, 2048, 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 &gt;= 1024 and &lt;= 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 &gt;= 1024 and &lt;= 8192. Furthermore,
* min_group_len &lt;= pref_group_len &lt;= max_group_len.
*
* @param min_group_len min_group_len
* @param pref_group_len pref_group_len
* @param max_group_len 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;
}
}
@@ -0,0 +1,25 @@
package com.trilead.ssh2;
/**
* An interface which needs to be implemented if you
* want to capture debugging messages.
*
* @see Connection#enableDebugging(boolean, DebugLogger)
*
* @author Christian Plattner, plattner@trilead.com
* @version $Id: DebugLogger.java,v 1.1 2008/03/03 07:01:36 cplattne Exp $
* @deprecated
* Logging all goes to JDK java.util.logging
*/
public interface DebugLogger
{
/**
* Log a debug message.
*
* @param level 0-99, 99 is a the most verbose level
* @param className the class that generated the message
* @param message the debug message
*/
public void log(int level, String className, String message);
}
@@ -0,0 +1,70 @@
/*
* 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;
import java.io.IOException;
import java.net.InetSocketAddress;
import com.trilead.ssh2.channel.ChannelManager;
import com.trilead.ssh2.channel.DynamicAcceptThread;
/**
* A <code>DynamicPortForwarder</code> forwards TCP/IP connections to a local
* port via the secure tunnel to another host which is selected via the SOCKS
* protocol. Checkout {@link Connection#createDynamicPortForwarder(int)} on how
* to create one.
*
* @author Kenny Root
* @version $Id: $
*/
public class DynamicPortForwarder {
ChannelManager cm;
DynamicAcceptThread dat;
DynamicPortForwarder(ChannelManager cm, InetSocketAddress addr, int maxThreads)
throws IOException {
this.cm = cm;
dat = new DynamicAcceptThread(cm, addr, maxThreads);
dat.setDaemon(true);
dat.start();
}
DynamicPortForwarder(ChannelManager cm, int local_port, int maxThreads) throws IOException {
this.cm = cm;
dat = new DynamicAcceptThread(cm, local_port, maxThreads);
dat.setDaemon(true);
dat.start();
}
/** Returns the actual loopback port. Useful when the forwarder was bound to port 0. */
public int getLocalPort() {
return dat.getLocalPort();
}
/**
* Stop TCP/IP forwarding of newly arriving connections.
*
* @throws IOException
*/
public void close() throws IOException {
dat.stopWorking();
}
}
@@ -0,0 +1,220 @@
package com.trilead.ssh2;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.Socket;
import com.dragonssh.xhttpdemo.core.tunnel.vpn.SocketProtector;
import com.trilead.ssh2.crypto.Base64;
import com.trilead.ssh2.transport.ClientServerHello;
import java.net.UnknownHostException;
import com.trilead.ssh2.transport.TransportManager;
/**
* A <code>HTTPProxyData</code> object is used to specify the needed connection data
* to connect through a HTTP proxy.
*
* @see Connection#setProxyData(ProxyData)
*
* @author Christian Plattner, plattner@trilead.com
* @version $Id: HTTPProxyData.java,v 1.1 2007/10/15 12:49:56 cplattne Exp $
*/
public class HTTPProxyData implements ProxyData
{
private final String proxyHost;
private final int proxyPort;
private final String proxyUser;
private final String proxyPass;
private final String[] requestHeaderLines;
private Socket sock;
/**
* Same as calling {@link #HTTPProxyData(String, int, String, String) HTTPProxyData(proxyHost, proxyPort, <code>null</code>, <code>null</code>)}
*
* @param proxyHost Proxy hostname.
* @param proxyPort Proxy port.
*/
public HTTPProxyData(String proxyHost, int proxyPort)
{
this(proxyHost, proxyPort, null, null);
}
/**
* Same as calling {@link #HTTPProxyData(String, int, String, String, String[]) HTTPProxyData(proxyHost, proxyPort, <code>null</code>, <code>null</code>, <code>null</code>)}
*
* @param proxyHost Proxy hostname.
* @param proxyPort Proxy port.
* @param proxyUser Username for basic authentication (<code>null</code> if no authentication is needed).
* @param proxyPass Password for basic authentication (<code>null</code> if no authentication is needed).
*/
public HTTPProxyData(String proxyHost, int proxyPort, String proxyUser, String proxyPass)
{
this(proxyHost, proxyPort, proxyUser, proxyPass, null);
}
/**
* Connection data for a HTTP proxy. It is possible to specify a username and password
* if the proxy requires basic authentication. Also, additional request header lines can
* be specified (e.g., "User-Agent: CERN-LineMode/2.15 libwww/2.17b3").
* <p>
* Please note: if you want to use basic authentication, then both <code>proxyUser</code>
* and <code>proxyPass</code> must be non-null.
* <p>
* Here is an example:
* <p>
* <code>
* new HTTPProxyData("192.168.1.1", "3128", "proxyuser", "secret", new String[] {"User-Agent: TrileadBasedClient/1.0", "X-My-Proxy-Option: something"});
* </code>
*
* @param proxyHost Proxy hostname.
* @param proxyPort Proxy port.
* @param proxyUser Username for basic authentication (<code>null</code> if no authentication is needed).
* @param proxyPass Password for basic authentication (<code>null</code> if no authentication is needed).
* @param requestHeaderLines An array with additional request header lines (without end-of-line markers)
* that have to be sent to the server. May be <code>null</code>.
*/
public HTTPProxyData(String proxyHost, int proxyPort, String proxyUser, String proxyPass,
String[] requestHeaderLines)
{
if (proxyHost == null)
throw new IllegalArgumentException("proxyHost must be non-null");
if (proxyPort < 0)
throw new IllegalArgumentException("proxyPort must be non-negative");
this.proxyHost = proxyHost;
this.proxyPort = proxyPort;
this.proxyUser = proxyUser;
this.proxyPass = proxyPass;
this.requestHeaderLines = requestHeaderLines;
}
@Override
public Socket openConnection(String hostname, int port, int connectTimeout,int readTimeout) throws IOException {
sock = new Socket();
// Ensure the proxy socket bypasses the VPN to prevent routing loops.
SocketProtector.protect(sock);
InetAddress addr = TransportManager.createInetAddress(proxyHost);
sock.connect(new InetSocketAddress(addr, proxyPort), connectTimeout);
sock.setSoTimeout(readTimeout);
/* OK, now tell the proxy where we actually want to connect to */
StringBuffer sb = new StringBuffer();
sb.append("CONNECT ");
sb.append(hostname);
sb.append(':');
sb.append(port);
sb.append(" HTTP/1.0\r\n");
if ((proxyUser != null) && (proxyPass != null))
{
String credentials = proxyUser + ":" + proxyPass;
char[] encoded;
try {
encoded = Base64.encode(credentials.getBytes("ISO-8859-1"));
} catch (UnsupportedEncodingException e) {
encoded = Base64.encode(credentials.getBytes());
}
sb.append("Proxy-Authorization: Basic ");
sb.append(encoded);
sb.append("\r\n");
}
if (requestHeaderLines != null)
{
for (int i = 0; i < requestHeaderLines.length; i++)
{
if (requestHeaderLines[i] != null)
{
sb.append(requestHeaderLines[i]);
sb.append("\r\n");
}
}
}
sb.append("\r\n");
OutputStream out = sock.getOutputStream();
try {
out.write(sb.toString().getBytes("ISO-8859-1"));
} catch (UnsupportedEncodingException e) {
out.write(sb.toString().getBytes());
}
out.flush();
/* Now parse the HTTP response */
byte[] buffer = new byte[1024];
InputStream in = sock.getInputStream();
int len = ClientServerHello.readLineRN(in, buffer);
String httpReponse;
try {
httpReponse = new String(buffer, 0, len, "ISO-8859-1");
} catch (UnsupportedEncodingException e) {
httpReponse = new String(buffer, 0, len);
}
if (!httpReponse.startsWith("HTTP/"))
throw new IOException("The proxy did not send back a valid HTTP response.");
/* "HTTP/1.X XYZ X" => 14 characters minimum */
if ((httpReponse.length() < 14) || (httpReponse.charAt(8) != ' ') || (httpReponse.charAt(12) != ' '))
throw new IOException("The proxy did not send back a valid HTTP response.");
int errorCode = 0;
try
{
errorCode = Integer.parseInt(httpReponse.substring(9, 12));
}
catch (NumberFormatException ignore)
{
throw new IOException("The proxy did not send back a valid HTTP response.");
}
if ((errorCode < 0) || (errorCode > 999))
throw new IOException("The proxy did not send back a valid HTTP response.");
if (errorCode != 200)
{
throw new HTTPProxyException(httpReponse.substring(13), errorCode);
}
/* OK, read until empty line */
while (true)
{
len = ClientServerHello.readLineRN(in, buffer);
if (len == 0)
break;
}
return sock;
}
@Override
public void close()
{
if (sock != null) {
try {
sock.close();
} catch(IOException e) {}
}
}
}
@@ -0,0 +1,29 @@
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;
}
}
@@ -0,0 +1,17 @@
package com.trilead.ssh2;
import java.io.IOException;
/**
* @author Thomas Singer
*/
public final class IOWarningException extends IOException {
private static final long serialVersionUID = 1L;
// Setup ==================================================================
public IOWarningException(String message) {
super(message);
}
}
@@ -0,0 +1,56 @@
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>.
* @throws Exception exception
*/
public String[] replyToChallenge(String name, String instruction, int numPrompts, String[] prompt, boolean[] echo)
throws Exception;
}
@@ -0,0 +1,812 @@
package com.trilead.ssh2;
import java.io.BufferedReader;
import java.io.CharArrayReader;
import java.io.CharArrayWriter;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.io.Reader;
import java.io.UnsupportedEncodingException;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.SecureRandom;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Vector;
import com.trilead.ssh2.crypto.Base64;
import com.trilead.ssh2.crypto.digest.Digest;
import com.trilead.ssh2.crypto.digest.MD5;
import com.trilead.ssh2.crypto.digest.MessageMac;
import com.trilead.ssh2.crypto.digest.SHA1;
import com.trilead.ssh2.log.Logger;
import com.trilead.ssh2.signature.KeyAlgorithm;
import com.trilead.ssh2.signature.KeyAlgorithmManager;
/**
* The KnownHosts class is a handy tool to verify received server hostkeys
* based on the information in <code>known_hosts</code> files (the ones used by OpenSSH).
* <p>
* It offers basically an in-memory database for known_hosts entries, as well as some
* helper functions. Entries from a <code>known_hosts</code> file can be loaded at construction time.
* It is also possible to add more keys later (e.g., one can parse different
* known_hosts files).
*
* <p>
* It is a thread safe implementation, therefore, you need only to instantiate one
* KnownHosts for your whole application.
*
* @author Christian Plattner, plattner@trilead.com
* @version $Id: KnownHosts.java,v 1.2 2008/04/01 12:38:09 cplattne Exp $
*/
public class KnownHosts
{
private static final Logger LOGGER = Logger.getLogger(KnownHosts.class);
public static final int HOSTKEY_IS_OK = 0;
public static final int HOSTKEY_IS_NEW = 1;
public static final int HOSTKEY_HAS_CHANGED = 2;
private static final SecureRandom SECURE_RANDOM = RandomFactory.create();
private class KnownHostsEntry
{
private final String[] patterns;
private final PublicKey key;
private final String algorithm;
private KnownHostsEntry(String[] patterns, PublicKey key, String algorithm)
{
this.patterns = patterns;
this.key = key;
this.algorithm = algorithm;
}
}
private final LinkedList<KnownHostsEntry> publicKeys = new LinkedList<>();
public KnownHosts()
{
}
public KnownHosts(char[] knownHostsData) throws IOException
{
initialize(knownHostsData);
}
public KnownHosts(File knownHosts) throws IOException
{
initialize(knownHosts);
}
/**
* Adds a single public key entry to the database. Note: this will NOT add the public key
* to any physical file (e.g., "~/.ssh/known_hosts") - use <code>addHostkeyToFile()</code> for that purpose.
* This method is designed to be used in a {@link ServerHostKeyVerifier}.
*
* @param hostnames a list of hostname patterns - at least one most be specified. Check out the
* OpenSSH sshd man page for a description of the pattern matching algorithm.
* @param serverHostKeyAlgorithm as passed to the {@link ServerHostKeyVerifier}.
* @param serverHostKey as passed to the {@link ServerHostKeyVerifier}.
* @throws IOException on failure trying to convert the host key to a saveable format
*/
public void addHostkey(String[] hostnames, String serverHostKeyAlgorithm, byte[] serverHostKey) throws IOException {
if (hostnames == null) {
throw new IllegalArgumentException("hostnames may not be null");
}
for (KeyAlgorithm<PublicKey, PrivateKey> algorithm : KeyAlgorithmManager.getSupportedAlgorithms()) {
if (serverHostKeyAlgorithm.equals(algorithm.getKeyFormat())) {
PublicKey publicKey = algorithm.decodePublicKey(serverHostKey);
synchronized (publicKeys) {
publicKeys.add(new KnownHostsEntry(hostnames, publicKey, serverHostKeyAlgorithm));
}
return;
}
}
throw new IOWarningException("Unknwon host key type (" + serverHostKeyAlgorithm + ")");
}
/**
* Parses the given known_hosts data and adds entries to the database.
*
* @param knownHostsData the known hosts data to parse
* @throws IOException on failure reading the parsing the known hosts data
*/
public void addHostkeys(char[] knownHostsData) throws IOException
{
initialize(knownHostsData);
}
/**
* Parses the given known_hosts file and adds entries to the database.
*
* @param knownHosts the file to read the existing known hosts entries feom, add to add any new entries to
* @throws IOException on failure reading the existing known hosts file
*/
public void addHostkeys(File knownHosts) throws IOException
{
initialize(knownHosts);
}
/**
* Generate the hashed representation of the given hostname. Useful for adding entries
* with hashed hostnames to a known_hosts file. (see -H option of OpenSSH key-gen).
*
* @param hostname the hostname to hash
* @return the hashed representation, e.g., "|1|cDhrv7zwEUV3k71CEPHnhHZezhA=|Xo+2y6rUXo2OIWRAYhBOIijbJMA="
*/
public static String createHashedHostname(String hostname)
{
SHA1 sha1 = new SHA1();
byte[] salt = new byte[sha1.getDigestLength()];
SECURE_RANDOM.nextBytes(salt);
byte[] hash = hmacSha1Hash(salt, hostname);
String base64_salt = new String(Base64.encode(salt));
String base64_hash = new String(Base64.encode(hash));
return "|1|" + base64_salt + "|" + base64_hash;
}
private static byte[] hmacSha1Hash(byte[] salt, String hostname)
{
if (salt.length != 20) {
throw new IllegalArgumentException("Salt has wrong length (" + salt.length + ")");
}
MessageMac messageMac = new MessageMac("hmac-sha1", salt);
try {
byte[] message = hostname.getBytes("ISO-8859-1");
messageMac.update(message, 0, message.length);
} catch (UnsupportedEncodingException ignore) {
/* Actually, ISO-8859-1 is supported by all correct
* Java implementations. But... you never know. */
byte[] message = hostname.getBytes();
messageMac.update(message, 0, message.length);
}
byte[] dig = new byte[20];
messageMac.getMac(dig, 0);
return dig;
}
private boolean checkHashed(String entry, String hostname)
{
if (!entry.startsWith("|1|"))
return false;
int delim_idx = entry.indexOf('|', 3);
if (delim_idx == -1)
return false;
String salt_base64 = entry.substring(3, delim_idx);
String hash_base64 = entry.substring(delim_idx + 1);
byte[] salt = null;
byte[] hash = null;
try
{
salt = Base64.decode(salt_base64.toCharArray());
hash = Base64.decode(hash_base64.toCharArray());
}
catch (IOException e)
{
return false;
}
SHA1 sha1 = new SHA1();
if (salt.length != sha1.getDigestLength())
return false;
byte[] dig = hmacSha1Hash(salt, hostname);
for (int i = 0; i < dig.length; i++)
if (dig[i] != hash[i])
return false;
return true;
}
private int checkKey(String remoteHostname, PublicKey remoteKey)
{
int result = HOSTKEY_IS_NEW;
synchronized (publicKeys)
{
for (KnownHostsEntry ke : publicKeys) {
if (!hostnameMatches(ke.patterns, remoteHostname))
continue;
boolean res = matchKeys(ke.key, remoteKey);
if (res)
return HOSTKEY_IS_OK;
result = HOSTKEY_HAS_CHANGED;
}
}
return result;
}
private Vector<KnownHostsEntry> getAllKnownHostEntries(String hostname)
{
Vector<KnownHostsEntry> knownHostsEntries = new Vector<>();
synchronized (publicKeys)
{
for (KnownHostsEntry ke : publicKeys) {
if (hostnameMatches(ke.patterns, hostname)) {
knownHostsEntries.addElement(ke);
}
}
}
return knownHostsEntries;
}
/**
* Try to find the preferred order of hostkey algorithms for the given hostname.
* Based on the type of hostkey that is present in the internal database.
* an ordered list of hostkey algorithms is returned which can be passed
* to <code>Connection.setServerHostKeyAlgorithms</code>.
*
* @param hostname the hostname (or hostname pattern) to search for
* @return <code>null</code> if no key for the given hostname is present or
* there are keys of multiple types present for the given hostname. Otherwise,
* an array with hostkey algorithms is returned.
*/
public String[] getPreferredServerHostkeyAlgorithmOrder(String hostname)
{
String[] algos = recommendHostkeyAlgorithms(hostname);
if (algos != null)
return algos;
InetAddress[] ipAddresses;
try
{
ipAddresses = InetAddress.getAllByName(hostname);
}
catch (UnknownHostException e)
{
return null;
}
for (InetAddress ipAddress : ipAddresses) {
algos = recommendHostkeyAlgorithms(ipAddress.getHostAddress());
if (algos != null)
return algos;
}
return null;
}
private boolean hostnameMatches(String[] hostpatterns, String hostname)
{
boolean isMatch = false;
boolean negate = false;
hostname = hostname.toLowerCase();
for (String hostpattern : hostpatterns) {
if (hostpattern == null)
continue;
String pattern = null;
/* In contrast to OpenSSH we also allow negated hash entries (as well as hashed
* entries in lines with multiple entries).
*/
if ((hostpattern.length() > 0) && (hostpattern.charAt(0) == '!')) {
pattern = hostpattern.substring(1);
negate = true;
} else {
pattern = hostpattern;
negate = false;
}
/* Optimize, no need to check this entry */
if (isMatch && !negate)
continue;
/* Now compare */
if (pattern.charAt(0) == '|') {
if (checkHashed(pattern, hostname)) {
if (negate)
return false;
isMatch = true;
}
} else {
pattern = pattern.toLowerCase();
if ((pattern.indexOf('?') != -1) || (pattern.indexOf('*') != -1)) {
if (pseudoRegex(pattern.toCharArray(), 0, hostname.toCharArray(), 0)) {
if (negate)
return false;
isMatch = true;
}
} else if (pattern.compareTo(hostname) == 0) {
if (negate)
return false;
isMatch = true;
} else {
final int indexColon = pattern.indexOf(':');
final int indexLastColon = pattern.indexOf(':');
if (indexColon > 0 && indexColon < pattern.length() - 2 && indexColon == indexLastColon) {
final String bracketizedHost = '[' + hostname + ']';
if (pattern.startsWith(bracketizedHost)) {
if (negate)
return false;
isMatch = true;
}
}
}
}
}
return isMatch;
}
private void initialize(char[] knownHostsData) throws IOException {
final BufferedReader br = new BufferedReader(new CharArrayReader(knownHostsData));
for (String line = br.readLine(); line != null; line = br.readLine()) {
line = line.trim();
if (line.startsWith("#")) {
continue;
}
final String[] arr = line.split(" ");
if (arr.length < 3) {
continue;
}
final String serverHostKeyAlgorithm = arr[1];
boolean supportedKeyType = false;
for (KeyAlgorithm<PublicKey, PrivateKey> algorithm : KeyAlgorithmManager.getSupportedAlgorithms()) {
if (algorithm.getKeyFormat().equals(serverHostKeyAlgorithm)) {
supportedKeyType = true;
break;
}
}
if (!supportedKeyType) {
LOGGER.log(1, "Unsupported key type: " + serverHostKeyAlgorithm);
continue;
}
final String[] hostnames = arr[0].split(",");
final byte[] msg = Base64.decode(arr[2].toCharArray());
try {
addHostkey(hostnames, serverHostKeyAlgorithm, msg);
}
catch (IOWarningException ex) {
LOGGER.log(30, "Ignored invalid line '" + line + "'",ex);
}
}
}
private void initialize(File knownHosts) throws IOException {
final char[] buffer = new char[512];
final CharArrayWriter charWriter = new CharArrayWriter();
if (!knownHosts.createNewFile()) {
LOGGER.log(10, "Could not create known hosts file");
}
try (Reader reader = new FileReader(knownHosts)) {
while (true) {
final int readCharCount = reader.read(buffer);
if (readCharCount < 0) {
break;
}
charWriter.write(buffer, 0, readCharCount);
}
}
initialize(charWriter.toCharArray());
}
private boolean matchKeys(PublicKey key1, PublicKey key2)
{
if (null == key1) {
return null == key2;
}
return key1.equals(key2);
}
private boolean pseudoRegex(char[] pattern, int i, char[] match, int j)
{
/* This matching logic is equivalent to the one present in OpenSSH 4.1 */
while (true)
{
/* Are we at the end of the pattern? */
if (pattern.length == i)
return (match.length == j);
if (pattern[i] == '*')
{
i++;
if (pattern.length == i)
return true;
if ((pattern[i] != '*') && (pattern[i] != '?'))
{
while (true)
{
if ((pattern[i] == match[j]) && pseudoRegex(pattern, i + 1, match, j + 1))
return true;
j++;
if (match.length == j)
return false;
}
}
while (true)
{
if (pseudoRegex(pattern, i, match, j))
return true;
j++;
if (match.length == j)
return false;
}
}
if (match.length == j)
return false;
if ((pattern[i] != '?') && (pattern[i] != match[j]))
return false;
i++;
j++;
}
}
private String[] recommendHostkeyAlgorithms(String hostname)
{
String preferredAlgo = null;
Vector<KnownHostsEntry> keys = getAllKnownHostEntries(hostname);
for (KnownHostsEntry key : keys) {
String thisAlgo = key.algorithm;
if (preferredAlgo != null) {
/* If we find different key types, then return null */
if (!preferredAlgo.equals(thisAlgo)) {
return null;
}
} else {
preferredAlgo = thisAlgo;
}
}
/* If we did not find anything that we know of, return null */
if (preferredAlgo == null)
return null;
/* Now put the preferred algo to the start of the array.
* You may ask yourself why we do it that way - basically, we could just
* return only the preferred algorithm: since we have a saved key of that
* type (sent earlier from the remote host), then that should work out.
* However, imagine that the server is (for whatever reasons) not offering
* that type of hostkey anymore (e.g., "algorithm-a" was disabled and
* now "algorithm-b" is being used). If we then do not let the server send us
* a fresh key of the new type, then we shoot ourself into the foot:
* the connection cannot be established and hence the user cannot decide
* if he/she wants to accept the new key.
*/
List<String> supportedAlgorithms = new ArrayList<>();
for (KeyAlgorithm<?, ?> algorithm : KeyAlgorithmManager.getSupportedAlgorithms()) {
supportedAlgorithms.add(supportedAlgorithms.size(), algorithm.getKeyFormat());
}
if (supportedAlgorithms.contains(preferredAlgo)) {
supportedAlgorithms.remove(preferredAlgo);
supportedAlgorithms.add(0, preferredAlgo);
}
return supportedAlgorithms.toArray(new String[supportedAlgorithms.size()]);
}
/**
* Checks the internal hostkey database for the given hostkey.
* If no matching key can be found, then the hostname is resolved to an IP address
* and the search is repeated using that IP address.
*
* @param hostname the server's hostname, will be matched with all hostname patterns
* @param serverHostKeyAlgorithm type of hostkey being verified
* @param serverHostKey the key blob
* @return <ul>
* <li><code>HOSTKEY_IS_OK</code>: the given hostkey matches an entry for the given hostname</li>
* <li><code>HOSTKEY_IS_NEW</code>: no entries found for this hostname and this type of hostkey</li>
* <li><code>HOSTKEY_HAS_CHANGED</code>: hostname is known, but with another key of the same type
* (man-in-the-middle attack?)</li>
* </ul>
* @throws IOException if the supplied key blob cannot be parsed or does not match the given hostkey type.
*/
public int verifyHostkey(String hostname, String serverHostKeyAlgorithm, byte[] serverHostKey) throws IOException
{
PublicKey remoteKey = decodeHostKey(serverHostKeyAlgorithm, serverHostKey);
int result = checkKey(hostname, remoteKey);
if (result == HOSTKEY_IS_OK)
return result;
InetAddress[] ipAdresses;
try
{
ipAdresses = InetAddress.getAllByName(hostname);
}
catch (UnknownHostException e)
{
return result;
}
for (InetAddress ipAdress : ipAdresses) {
int newresult = checkKey(ipAdress.getHostAddress(), remoteKey);
if (newresult == HOSTKEY_IS_OK)
return newresult;
if (newresult == HOSTKEY_HAS_CHANGED)
result = HOSTKEY_HAS_CHANGED;
}
return result;
}
private PublicKey decodeHostKey(String hostKeyAlgorithm, byte[] encodedHostKey) throws IOException {
for (KeyAlgorithm<PublicKey, PrivateKey> algorithm : KeyAlgorithmManager.getSupportedAlgorithms()) {
if (algorithm.getKeyFormat().equals(hostKeyAlgorithm)) {
return algorithm.decodePublicKey(encodedHostKey);
}
}
throw new IllegalArgumentException("Unknown hostkey type " + hostKeyAlgorithm);
}
/**
* Adds a single public key entry to the a known_hosts file.
* This method is designed to be used in a {@link ServerHostKeyVerifier}.
*
* @param knownHosts the file where the publickey entry will be appended.
* @param hostnames a list of hostname patterns - at least one most be specified. Check out the
* OpenSSH sshd man page for a description of the pattern matching algorithm.
* @param serverHostKeyAlgorithm as passed to the {@link ServerHostKeyVerifier}.
* @param serverHostKey as passed to the {@link ServerHostKeyVerifier}.
* @throws IOException on failure parsing the key or writing to file
*/
public static void addHostkeyToFile(File knownHosts, String[] hostnames, String serverHostKeyAlgorithm,
byte[] serverHostKey) throws IOException
{
if ((hostnames == null) || (hostnames.length == 0))
throw new IllegalArgumentException("Need at least one hostname specification");
if ((serverHostKeyAlgorithm == null) || (serverHostKey == null))
throw new IllegalArgumentException();
CharArrayWriter writer = new CharArrayWriter();
for (int i = 0; i < hostnames.length; i++)
{
if (i != 0)
writer.write(',');
writer.write(hostnames[i]);
}
writer.write(' ');
writer.write(serverHostKeyAlgorithm);
writer.write(' ');
writer.write(Base64.encode(serverHostKey));
writer.write("\n");
char[] entry = writer.toCharArray();
RandomAccessFile raf = new RandomAccessFile(knownHosts, "rw");
long len = raf.length();
if (len > 0)
{
raf.seek(len - 1);
int last = raf.read();
if (last != '\n')
raf.write('\n');
}
raf.write(new String(entry).getBytes("ISO-8859-1"));
raf.close();
}
/**
* Generates a "raw" fingerprint of a hostkey.
*
* @param type either "md5" or "sha1"
* @param keyType the type of key being fingerprinted
* @param hostkey the hostkey
* @return the raw fingerprint
*/
private static byte[] rawFingerPrint(String type, String keyType, byte[] hostkey)
{
Digest dig;
if ("md5".equals(type))
{
dig = new MD5();
}
else if ("sha1".equals(type))
{
dig = new SHA1();
}
else
throw new IllegalArgumentException("Unknown hash type " + type);
boolean supportedKeyType = false;
for (KeyAlgorithm<PublicKey, PrivateKey> algorithm : KeyAlgorithmManager.getSupportedAlgorithms()) {
if (algorithm.getKeyFormat().equals(keyType)) {
supportedKeyType = true;
break;
}
}
if (!supportedKeyType) {
throw new IllegalArgumentException("Unknown key type " + keyType);
}
if (hostkey == null)
throw new IllegalArgumentException("hostkey is null");
dig.update(hostkey);
byte[] res = new byte[dig.getDigestLength()];
dig.digest(res);
return res;
}
/**
* Convert a raw fingerprint to hex representation (XX:YY:ZZ...).
* @param fingerprint raw fingerprint
* @return the hex representation
*/
private static String rawToHexFingerprint(byte[] fingerprint)
{
final char[] alpha = "0123456789abcdef".toCharArray();
StringBuilder sb = new StringBuilder();
for (int i = 0; i < fingerprint.length; i++)
{
if (i != 0)
sb.append(':');
int b = fingerprint[i] & 0xff;
sb.append(alpha[b >> 4]);
sb.append(alpha[b & 15]);
}
return sb.toString();
}
/**
* Convert a raw fingerprint to bubblebabble representation.
* @param raw raw fingerprint
* @return the bubblebabble representation
*/
private static String rawToBubblebabbleFingerprint(byte[] raw)
{
final char[] v = "aeiouy".toCharArray();
final char[] c = "bcdfghklmnprstvzx".toCharArray();
StringBuilder sb = new StringBuilder();
int seed = 1;
int rounds = (raw.length / 2) + 1;
sb.append('x');
for (int i = 0; i < rounds; i++)
{
if (((i + 1) < rounds) || ((raw.length) % 2 != 0))
{
sb.append(v[(((raw[2 * i] >> 6) & 3) + seed) % 6]);
sb.append(c[(raw[2 * i] >> 2) & 15]);
sb.append(v[((raw[2 * i] & 3) + (seed / 6)) % 6]);
if ((i + 1) < rounds)
{
sb.append(c[(((raw[(2 * i) + 1])) >> 4) & 15]);
sb.append('-');
sb.append(c[(((raw[(2 * i) + 1]))) & 15]);
// As long as seed >= 0, seed will be >= 0 afterwards
seed = ((seed * 5) + (((raw[2 * i] & 0xff) * 7) + (raw[(2 * i) + 1] & 0xff))) % 36;
}
}
else
{
sb.append(v[seed % 6]); // seed >= 0, therefore index positive
sb.append('x');
sb.append(v[seed / 6]);
}
}
sb.append('x');
return sb.toString();
}
/**
* Convert a ssh2 key-blob into a human readable hex fingerprint.
* Generated fingerprints are identical to those generated by OpenSSH.
* <p>
* Example fingerprint: d0:cb:76:19:99:5a:03:fc:73:10:70:93:f2:44:63:47.
* @param keytype the type of key being fingerprinted
* @param publickey key blob
* @return Hex fingerprint
*/
public static String createHexFingerprint(String keytype, byte[] publickey)
{
byte[] raw = rawFingerPrint("md5", keytype, publickey);
return rawToHexFingerprint(raw);
}
/**
* Convert a ssh2 key-blob into a human readable bubblebabble fingerprint.
* The used bubblebabble algorithm (taken from OpenSSH) generates fingerprints
* that are easier to remember for humans.
* <p>
* Example fingerprint: xofoc-bubuz-cazin-zufyl-pivuk-biduk-tacib-pybur-gonar-hotat-lyxux.
*
* @param keytype the type of key being fingerprinted
* @param publickey key data
* @return Bubblebabble fingerprint
*/
public static String createBubblebabbleFingerprint(String keytype, byte[] publickey)
{
byte[] raw = rawFingerPrint("sha1", keytype, publickey);
return rawToBubblebabbleFingerprint(raw);
}
}
@@ -0,0 +1,63 @@
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 the io exception
*/
public void close() throws IOException
{
lat.stopWorking();
}
}
@@ -0,0 +1,78 @@
package com.trilead.ssh2;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import com.trilead.ssh2.channel.Channel;
import com.trilead.ssh2.channel.ChannelManager;
import com.trilead.ssh2.channel.LocalAcceptThread;
/**
* A <code>LocalStreamForwarder</code> forwards an Input- and Outputstream
* pair via the secure tunnel to another host (which may or may not be identical
* to the remote SSH-2 server).
*
* @author Christian Plattner, plattner@trilead.com
* @version $Id: LocalStreamForwarder.java,v 1.1 2007/10/15 12:49:56 cplattne Exp $
*/
public class LocalStreamForwarder
{
ChannelManager cm;
String host_to_connect;
int port_to_connect;
LocalAcceptThread lat;
Channel cn;
LocalStreamForwarder(ChannelManager cm, 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;
cn = cm.openDirectTCPIPChannel(host_to_connect, port_to_connect, "127.0.0.1", 0);
}
/**
* @return An <code>InputStream</code> object.
* @throws IOException the io exception
*/
public InputStream getInputStream() throws IOException
{
return cn.getStdoutStream();
}
/**
* Get the OutputStream. Please be aware that the implementation MAY use an
* internal buffer. To make sure that the buffered data is sent over the
* tunnel, you have to call the <code>flush</code> method of the
* <code>OutputStream</code>. To signal EOF, please use the
* <code>close</code> method of the <code>OutputStream</code>.
*
* @return An <code>OutputStream</code> object.
* @throws IOException the io exception
*/
public OutputStream getOutputStream() throws IOException
{
return cn.getStdinStream();
}
/**
* Close the underlying SSH forwarding channel and free up resources.
* You can also use this method to force the shutdown of the underlying
* forwarding channel. Pending output (OutputStream not flushed) will NOT
* be sent. Pending input (InputStream) can still be read. If the shutdown
* operation is already in progress (initiated from either side), then this
* call is a no-op.
*
* @throws IOException the io exception
*/
public void close() throws IOException
{
cm.closeChannel(cn, "Closed due to user request.", true);
}
}
@@ -0,0 +1,28 @@
package com.trilead.ssh2;
import java.io.IOException;
import java.net.Socket;
/**
* An abstract 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 interface ProxyData
{
/**
* Connects the socket to the given destination using the proxy method that this instance
* represents.
*/
Socket openConnection(String hostname, int port, int connectTimeout, int readTimeout) throws IOException;
/**
* Fecha conexão do proxy
*/
void close();
}
@@ -0,0 +1,31 @@
package com.trilead.ssh2;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
/**
* Creates {@link SecureRandom}
*
* @author Kohsuke Kawaguchi
*/
class RandomFactory {
static SecureRandom create() {
try {
// JENKINS-20108
// on Unix, "new SecureRandom()" uses NativePRNG that uses a VM-wide lock, which results in
// SecureRandom.nextInt() contention when there are lots of concurrent connections.
// SHA1PRNG avoids this problem. This PRNG still gets seeded from (blocking) /dev/random,
// which assures security.
//
// note that SHA1PRNG is not a standard. See http://security.stackexchange.com/questions/47871/
//
// there's also http://coding.tocea.com/scertify-code/dont-use-the-sha1-prng-randomness-generator/
// which claims SHA1PRNG has "statistical defects" without details. I discount the credibility of
// this claim based on the lack of details, and that this is not reported as a vulnerability upstream.
return SecureRandom.getInstance("SHA1PRNG");
} catch (NoSuchAlgorithmException e) {
// fall back
return new SecureRandom();
}
}
}
@@ -0,0 +1,724 @@
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) {
String err = receiveLine(is);
throw new IOException("Remote scp terminated with error (" + err + ").");
}
throw new IOException("Remote scp terminated with error code " + c);
}
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 the io exception
*/
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 the io exception
*/
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 the io exception
*/
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 the io exception
*/
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 the io exception
*/
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 the io exception
*/
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 the io exception
*/
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 the io exception
*/
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 the io exception
*/
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 the io exception
*/
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();
}
}
}
@@ -0,0 +1,91 @@
package com.trilead.ssh2;
import java.io.IOException;
import com.trilead.ssh2.sftp.ErrorCodes;
/**
* Used in combination with the SFTPv3Client. This exception wraps
* error messages sent by the SFTP server.
*
* @author Christian Plattner, plattner@trilead.com
* @version $Id: SFTPException.java,v 1.1 2007/10/15 12:49:56 cplattne Exp $
*/
public class SFTPException extends IOException
{
private static final long serialVersionUID = 578654644222421811L;
private final String sftpErrorMessage;
private final int sftpErrorCode;
private static String constructMessage(String s, int errorCode)
{
String[] detail = ErrorCodes.getDescription(errorCode);
if (detail == null)
return s + " (UNKNOW SFTP ERROR CODE)";
return s + " (" + detail[0] + ": " + detail[1] + ")";
}
SFTPException(String msg, int errorCode)
{
super(constructMessage(msg, errorCode));
sftpErrorMessage = msg;
sftpErrorCode = errorCode;
}
/**
* Get the error message sent by the server. Often, this
* message does not help a lot (e.g., "failure").
*
* @return the plain string as sent by the server.
*/
public String getServerErrorMessage()
{
return sftpErrorMessage;
}
/**
* Get the error code sent by the server.
*
* @return an error code as defined in the SFTP specs.
*/
public int getServerErrorCode()
{
return sftpErrorCode;
}
/**
* Get the symbolic name of the error code as given in the SFTP specs.
*
* @return e.g., "SSH_FX_INVALID_FILENAME".
*/
public String getServerErrorCodeSymbol()
{
String[] detail = ErrorCodes.getDescription(sftpErrorCode);
if (detail == null)
return "UNKNOW SFTP ERROR CODE " + sftpErrorCode;
return detail[0];
}
/**
* Get the description of the error code as given in the SFTP specs.
*
* @return e.g., "The filename is not valid."
*/
public String getServerErrorCodeVerbose()
{
String[] detail = ErrorCodes.getDescription(sftpErrorCode);
if (detail == null)
return "The error code " + sftpErrorCode + " is unknown.";
return detail[1];
}
}
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,38 @@
package com.trilead.ssh2;
/**
* A <code>SFTPv3DirectoryEntry</code> as returned by {@link SFTPv3Client#ls(String)}.
*
* @author Christian Plattner, plattner@trilead.com
* @version $Id: SFTPv3DirectoryEntry.java,v 1.1 2007/10/15 12:49:56 cplattne Exp $
*/
public class SFTPv3DirectoryEntry
{
/**
* A relative name within the directory, without any path components.
*/
public String filename;
/**
* An expanded format for the file name, similar to what is returned by
* "ls -l" on Un*x systems.
* <p>
* The format of this field is unspecified by the SFTP v3 protocol.
* It MUST be suitable for use in the output of a directory listing
* command (in fact, the recommended operation for a directory listing
* command is to simply display this data). However, clients SHOULD NOT
* attempt to parse the longname field for file attributes; they SHOULD
* use the attrs field instead.
* <p>
* The recommended format for the longname field is as follows:<br>
* <code>-rwxr-xr-x 1 mjos staff 348911 Mar 25 14:29 t-filexfer</code>
*/
public String longEntry;
/**
* The attributes of this entry.
*/
public SFTPv3FileAttributes attributes;
}
@@ -0,0 +1,145 @@
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:
*
* <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();
}
}
@@ -0,0 +1,45 @@
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;
}
}
@@ -0,0 +1,31 @@
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
* @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;
}
@@ -0,0 +1,604 @@
package com.trilead.ssh2;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.security.SecureRandom;
import com.trilead.ssh2.channel.Channel;
import com.trilead.ssh2.channel.ChannelManager;
import com.trilead.ssh2.channel.X11ServerData;
import com.trilead.ssh2.packets.PacketSignal;
/**
* A Session is a remote execution of a program. "Program" means
* in this context either a shell, an application or a system command. The
* program may or may not have a tty. Only one single program can be started on
* a session. However, multiple sessions can be active simultaneously.
*
* @author Christian Plattner, plattner@trilead.com
* @version $Id: Session.java,v 1.2 2008/03/03 07:01:36 cplattne Exp $
*/
public class Session
{
ChannelManager cm;
Channel cn;
boolean flag_pty_requested = false;
boolean flag_x11_requested = false;
boolean flag_execution_started = false;
boolean flag_closed = false;
String x11FakeCookie = null;
final SecureRandom rnd;
Session(ChannelManager cm, SecureRandom rnd) throws IOException
{
this.cm = cm;
this.cn = cm.openSessionChannel();
this.rnd = rnd;
}
/**
* Basically just a wrapper for lazy people - identical to calling
* requestPTY("dumb", 0, 0, 0, 0, null).
*
* @throws IOException the io exception
*/
public void requestDumbPTY() throws IOException
{
requestPTY("dumb", 0, 0, 0, 0, null);
}
/**
* Basically just another wrapper for lazy people - identical to calling
* requestPTY(term, 0, 0, 0, 0, null).
*
* @param term the term
* @throws IOException the io exception
*/
public void requestPTY(String term) throws IOException
{
requestPTY(term, 0, 0, 0, 0, null);
}
/**
* Allocate a pseudo-terminal for this session.
* <p>
* This method may only be called before a program or shell is started in
* this session.
* <p>
* Different aspects can be specified:
*
* <ul>
* <li>The TERM environment variable value (e.g., vt100)</li>
* <li>The terminal's dimensions.</li>
* <li>The encoded terminal modes.</li>
* </ul>
* Zero dimension parameters are ignored. The character/row dimensions
* override the pixel dimensions (when nonzero). Pixel dimensions refer to
* the drawable area of the window. The dimension parameters are only
* informational. The encoding of terminal modes (parameter
* terminal_modes) is described in RFC4254.
*
* @param term
* The TERM environment variable value (e.g., vt100)
* @param term_width_characters
* terminal width, characters (e.g., 80)
* @param term_height_characters
* terminal height, rows (e.g., 24)
* @param term_width_pixels
* terminal width, pixels (e.g., 640)
* @param term_height_pixels
* terminal height, pixels (e.g., 480)
* @param terminal_modes
* encoded terminal modes (may be null)
* @throws IOException the io exception
*/
public void requestPTY(String term, int term_width_characters, int term_height_characters, int term_width_pixels,
int term_height_pixels, byte[] terminal_modes) throws IOException
{
if (term == null)
throw new IllegalArgumentException("TERM cannot be null.");
if ((terminal_modes != null) && (terminal_modes.length > 0))
{
if (terminal_modes[terminal_modes.length - 1] != 0)
throw new IOException("Illegal terminal modes description, does not end in zero byte");
}
else
terminal_modes = new byte[] { 0 };
synchronized (this)
{
/* The following is just a nicer error, we would catch it anyway later in the channel code */
if (flag_closed)
throw new IOException("This session is closed.");
if (flag_pty_requested)
throw new IOException("A PTY was already requested.");
if (flag_execution_started)
throw new IOException(
"Cannot request PTY at this stage anymore, a remote execution has already started.");
flag_pty_requested = true;
}
cm.requestPTY(cn, term, term_width_characters, term_height_characters, term_width_pixels, term_height_pixels,
terminal_modes);
}
/**
* Tells the server that the size of the terminal has changed.
*
* See {@link #requestPTY(String, int, int, int, int, byte[])} for more details about how parameters are interpreted.
*
* @param term_width_characters
* terminal width, characters (e.g., 80)
* @param term_height_characters
* terminal height, rows (e.g., 24)
* @param term_width_pixels
* terminal width, pixels (e.g., 640)
* @param term_height_pixels
* terminal height, pixels (e.g., 480)
* @throws IOException the io exception
*/
public void requestWindowChange(int term_width_characters, int term_height_characters, int term_width_pixels,
int term_height_pixels) throws IOException
{
synchronized (this)
{
/* The following is just a nicer error, we would catch it anyway later in the channel code */
if (flag_closed)
throw new IOException("This session is closed.");
if (!flag_pty_requested)
throw new IOException("A PTY was not requested.");
}
cn.requestWindowChange(term_width_characters, term_height_characters, term_width_pixels, term_height_pixels);
}
/**
* Sends a signal to the remote process.
*
* @param name the name
* @throws IOException the io exception
*/
public void signal(String name) throws IOException {
synchronized (this) {
/* The following is just a nicer error, we would catch it anyway later in the channel code */
if (flag_closed)
throw new IOException("This session is closed.");
}
cn.signal(name);
}
/**
* Sends a signal to the remote process.
* <p>
* For better portability, specify signal by name, not by its number.
*
* @param code the code
* @throws IOException the io exception
*/
public void signal(int code) throws IOException {
String sig = PacketSignal.strsignal(code);
if (sig==null) throw new IllegalArgumentException("Unrecognized signal code: "+code);
signal(sig);
}
/**
* Request X11 forwarding for the current session.
* <p>
* You have to supply the name and port of your X-server.
* <p>
* This method may only be called before a program or shell is started in
* this session.
*
* @param hostname the hostname of the real (target) X11 server (e.g., 127.0.0.1)
* @param port the port of the real (target) X11 server (e.g., 6010)
* @param cookie if non-null, then present this cookie to the real X11 server
* @param singleConnection if true, then the server is instructed to only forward one single
* connection, no more connections shall be forwarded after first, or after the session
* channel has been closed
* @throws IOException the io exception
*/
public void requestX11Forwarding(String hostname, int port, byte[] cookie, boolean singleConnection)
throws IOException
{
if (hostname == null)
throw new IllegalArgumentException("hostname argument may not be null");
synchronized (this)
{
/* The following is just a nicer error, we would catch it anyway later in the channel code */
if (flag_closed)
throw new IOException("This session is closed.");
if (flag_x11_requested)
throw new IOException("X11 forwarding was already requested.");
if (flag_execution_started)
throw new IOException(
"Cannot request X11 forwarding at this stage anymore, a remote execution has already started.");
flag_x11_requested = true;
}
/* X11ServerData - used to store data about the target X11 server */
X11ServerData x11data = new X11ServerData();
x11data.hostname = hostname;
x11data.port = port;
x11data.x11_magic_cookie = cookie; /* if non-null, then present this cookie to the real X11 server */
/* Generate fake cookie - this one is used between remote clients and our proxy */
byte[] fakeCookie = new byte[16];
String hexEncodedFakeCookie;
/* Make sure that this fake cookie is unique for this connection */
while (true)
{
rnd.nextBytes(fakeCookie);
/* Generate also hex representation of fake cookie */
StringBuffer tmp = new StringBuffer(32);
for (int i = 0; i < fakeCookie.length; i++)
{
String digit2 = Integer.toHexString(fakeCookie[i] & 0xff);
tmp.append((digit2.length() == 2) ? digit2 : "0" + digit2);
}
hexEncodedFakeCookie = tmp.toString();
/* Well, yes, chances are low, but we want to be on the safe side */
if (cm.checkX11Cookie(hexEncodedFakeCookie) == null)
break;
}
/* Ask for X11 forwarding */
cm.requestX11(cn, singleConnection, "MIT-MAGIC-COOKIE-1", hexEncodedFakeCookie, 0);
/* OK, that went fine, get ready to accept X11 connections... */
/* ... but only if the user has not called close() in the meantime =) */
synchronized (this)
{
if (flag_closed == false)
{
this.x11FakeCookie = hexEncodedFakeCookie;
cm.registerX11Cookie(hexEncodedFakeCookie, x11data);
}
}
/* Now it is safe to start remote X11 programs */
}
/**
* Execute a command on the remote machine.
*
* @param cmd
* The command to execute on the remote host.
* @throws IOException the io exception
*/
public void execCommand(String cmd) throws IOException
{
if (cmd == null)
throw new IllegalArgumentException("cmd argument may not be null");
synchronized (this)
{
/* The following is just a nicer error, we would catch it anyway later in the channel code */
if (flag_closed)
throw new IOException("This session is closed.");
if (flag_execution_started)
throw new IOException("A remote execution has already started.");
flag_execution_started = true;
}
cm.requestExecCommand(cn, cmd);
}
/**
* Start a shell on the remote machine.
*
* @throws IOException the io exception
*/
public void startShell() throws IOException
{
synchronized (this)
{
/* The following is just a nicer error, we would catch it anyway later in the channel code */
if (flag_closed)
throw new IOException("This session is closed.");
if (flag_execution_started)
throw new IOException("A remote execution has already started.");
flag_execution_started = true;
}
cm.requestShell(cn);
}
/**
* Start a subsystem on the remote machine.
* Unless you know what you are doing, you will never need this.
*
* @param name the name of the subsystem.
* @throws IOException the io exception
*/
public void startSubSystem(String name) throws IOException
{
if (name == null)
throw new IllegalArgumentException("name argument may not be null");
synchronized (this)
{
/* The following is just a nicer error, we would catch it anyway later in the channel code */
if (flag_closed)
throw new IOException("This session is closed.");
if (flag_execution_started)
throw new IOException("A remote execution has already started.");
flag_execution_started = true;
}
cm.requestSubSystem(cn, name);
}
/**
* This method can be used to perform end-to-end session (i.e., SSH channel)
* testing. It sends a 'ping' message to the server and waits for the 'pong'
* from the server.
* <p>
* Implementation details: this method sends a SSH_MSG_CHANNEL_REQUEST request
* ('trilead-ping') to the server and waits for the SSH_MSG_CHANNEL_FAILURE reply
* packet.
*
* @throws IOException in case of any problem or when the session is closed
*/
public void ping() throws IOException
{
synchronized (this)
{
/*
* The following is just a nicer error, we would catch it anyway
* later in the channel code
*/
if (flag_closed)
throw new IOException("This session is closed.");
}
cm.requestChannelTrileadPing(cn);
}
public InputStream getStdout()
{
return cn.getStdoutStream();
}
public InputStream getStderr()
{
return cn.getStderrStream();
}
public OutputStream getStdin()
{
return cn.getStdinStream();
}
/**
* Write stdout received from the other side to the specified {@link OutputStream}.
*
* <p>
* By default, when data arrives from the other side, trilead buffers them and lets
* you read it at your convenience from {@link #getStdout()}. This is normally convenient,
* but if all you are doing is to send the data to another {@link OutputStream} by
* copying a stream, then you'll be end up wasting a thread just for this.
* In such a situation, you can call this method and let the I/O handling thread of trilead
* directly pass the received data to the output stream. This also eliminates the internal
* buffer used for spooling.
*
* <p>
* When you do this, beware of a blocking write! If a write blocks, it'll affect
* all the other channels and sessions that are sharing the same SSH connection,
* as there's only one I/O thread. For example, this can happen if you are writing to
* {@link Socket}.
*
* <p>
* If any data has already been received and spooled before calling this method,
* the data will be sent to the given stream immediately.
*
* <p>
* To signal the end of the stream, when the other side notifies us of EOF or when
* the channel closes, the output stream gets closed. If this is not desirable,
* you must wrap the output stream and ignore the {@link OutputStream#close()} call.
*
* @param os the os
* @throws IOException the io exception
*/
public void pipeStdout(OutputStream os) throws IOException {
cn.pipeStdoutStream(os);
}
/**
* The same as {@link #pipeStdout(OutputStream)} except for stderr, not for stdout.
*
* @param os the os
* @throws IOException the io exception
*/
public void pipeStderr(OutputStream os) throws IOException {
cn.pipeStderrStream(os);
}
/**
* This method blocks until there is more data available on either the
* stdout or stderr InputStream of this Session. Very useful
* if you do not want to use two parallel threads for reading from the two
* InputStreams. One can also specify a timeout. NOTE: do NOT call this
* method if you use concurrent threads that operate on either of the two
* InputStreams of this Session (otherwise this method may
* block, even though more data is available).
*
* @param timeout
* The (non-negative) timeout in ms. 0 means no
* timeout, the call may block forever.
* @return
* <ul>
* <li>0 if no more data will arrive.</li>
* <li>1 if more data is available.</li>
* <li>-1 if a timeout occurred.</li>
* </ul>
*
* @throws IOException the io exception
* @throws InterruptedException the interrupted exception
* @deprecated This method has been replaced with a much more powerful wait-for-condition
* interface and therefore acts only as a wrapper.
*
*/
public int waitUntilDataAvailable(long timeout) throws IOException, InterruptedException {
if (timeout < 0)
throw new IllegalArgumentException("timeout must not be negative!");
int conditions = cm.waitForCondition(cn, timeout, ChannelCondition.STDOUT_DATA | ChannelCondition.STDERR_DATA
| ChannelCondition.EOF);
if ((conditions & ChannelCondition.TIMEOUT) != 0)
return -1;
if ((conditions & (ChannelCondition.STDOUT_DATA | ChannelCondition.STDERR_DATA)) != 0)
return 1;
/* Here we do not need to check separately for CLOSED, since CLOSED implies EOF */
if ((conditions & ChannelCondition.EOF) != 0)
return 0;
throw new IllegalStateException("Unexpected condition result (" + conditions + ")");
}
/**
* This method blocks until certain conditions hold true on the underlying SSH-2 channel.
* <p>
* This method returns as soon as one of the following happens:
* <ul>
* <li>at least of the specified conditions (see {@link ChannelCondition}) holds true</li>
* <li>timeout &gt; 0 and a timeout occured (TIMEOUT will be set in result conditions)</li>
* <li>the underlying channel was closed (CLOSED will be set in result conditions)</li>
* </ul>
* <p>
* In any case, the result value contains ALL current conditions, which may be more
* than the specified condition set (i.e., never use the "==" operator to test for conditions
* in the bitmask, see also comments in {@link ChannelCondition}).
* <p>
* Note: do NOT call this method if you want to wait for STDOUT_DATA or STDERR_DATA and
* there are concurrent threads (e.g., StreamGobblers) that operate on either of the two
* InputStreams of this Session (otherwise this method may
* block, even though more data is available in the StreamGobblers).
*
* @param condition_set a bitmask based on {@link ChannelCondition} values
* @param timeout non-negative timeout in ms, 0 means no timeout
* @return all bitmask specifying all current conditions that are true
* @throws InterruptedException the interrupted exception
*/
public int waitForCondition(int condition_set, long timeout) throws InterruptedException {
if (timeout < 0)
throw new IllegalArgumentException("timeout must be non-negative!");
return cm.waitForCondition(cn, timeout, condition_set);
}
/**
* Get the exit code/status from the remote command - if available. Be
* careful - not all server implementations return this value. It is
* generally a good idea to call this method only when all data from the
* remote side has been consumed (see also the WaitForCondition method).
*
* @return An Integer holding the exit code, or
* null if no exit code is (yet) available.
*/
public Integer getExitStatus()
{
return cn.getExitStatus();
}
/**
* Get the name of the signal by which the process on the remote side was
* stopped - if available and applicable. Be careful - not all server
* implementations return this value.
*
* @return An String holding the name of the signal, or
* null if the process exited normally or is still
* running (or if the server forgot to send this information).
*/
public String getExitSignal()
{
return cn.getExitSignal();
}
/**
* Close this session. NEVER forget to call this method to free up resources -
* even if you got an exception from one of the other methods (or when
* getting an Exception on the Input- or OutputStreams). 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 close()
* method, you may be wasting (local) resources.
*
*/
public void close()
{
synchronized (this)
{
if (flag_closed)
return;
flag_closed = true;
if (x11FakeCookie != null)
cm.unRegisterX11Cookie(x11FakeCookie, true);
try
{
cm.closeChannel(cn, "Closed due to user request", true);
}
catch (IOException ignored)
{
}
}
}
/**
* Sets the receive window size.
* <p>
* The receive window is a maximum number of bytes that the remote side can send to this channel without
* waiting for us to consume them (AKA "in-flight bytes").
* <p>
* When your connection is over a large-latency/high-bandiwdth network, specifying a bigger value
* allows the network to be efficiently utilized. OTOH, if you don't drain this channel quickly enough
* all those bytes in flight can end up getting buffered.
* <p>
* This value can be adjusted at runtime.
*
* @param newSize the new size
*/
public synchronized void setWindowSize(int newSize) {
cn.setWindowSize(newSize);
}
}
@@ -0,0 +1,232 @@
package com.trilead.ssh2;
import java.io.IOException;
import java.io.InputStream;
import java.io.InterruptedIOException;
/**
* A <code>StreamGobbler</code> is an InputStream that uses an internal worker
* thread to constantly consume input from another InputStream. It uses a buffer
* to store the consumed data. The buffer size is automatically adjusted, if needed.
* <p>
* This class is sometimes very convenient - if you wrap a session's STDOUT and STDERR
* InputStreams with instances of this class, then you don't have to bother about
* the shared window of STDOUT and STDERR in the low level SSH-2 protocol,
* since all arriving data will be immediatelly consumed by the worker threads.
* Also, as a side effect, the streams will be buffered (e.g., single byte
* read() operations are faster).
* <p>
* Other SSH for Java libraries include this functionality by default in
* their STDOUT and STDERR InputStream implementations, however, please be aware
* that this approach has also a downside:
* <p>
* If you do not call the StreamGobbler's <code>read()</code> method often enough
* and the peer is constantly sending huge amounts of data, then you will sooner or later
* encounter a low memory situation due to the aggregated data (well, it also depends on the Java heap size).
* Joe Average will like this class anyway - a paranoid programmer would never use such an approach.
* <p>
* The term "StreamGobbler" was taken from an article called "When Runtime.exec() won't",
* see http://www.javaworld.com/javaworld/jw-12-2000/jw-1229-traps.html.
*
* @author Christian Plattner, plattner@trilead.com
* @version $Id: StreamGobbler.java,v 1.1 2007/10/15 12:49:56 cplattne Exp $
*/
public class StreamGobbler extends InputStream
{
class GobblerThread extends Thread
{
public void run()
{
byte[] buff = new byte[8192];
while (true)
{
try
{
int avail = is.read(buff);
synchronized (synchronizer)
{
if (avail <= 0)
{
isEOF = true;
synchronizer.notifyAll();
break;
}
int space_available = buffer.length - write_pos;
if (space_available < avail)
{
/* compact/resize buffer */
int unread_size = write_pos - read_pos;
int need_space = unread_size + avail;
byte[] new_buffer = buffer;
if (need_space > buffer.length)
{
int inc = need_space / 3;
inc = (inc < 256) ? 256 : inc;
inc = (inc > 8192) ? 8192 : inc;
new_buffer = new byte[need_space + inc];
}
if (unread_size > 0)
System.arraycopy(buffer, read_pos, new_buffer, 0, unread_size);
buffer = new_buffer;
read_pos = 0;
write_pos = unread_size;
}
System.arraycopy(buff, 0, buffer, write_pos, avail);
write_pos += avail;
synchronizer.notifyAll();
}
}
catch (IOException e)
{
synchronized (synchronizer)
{
exception = e;
synchronizer.notifyAll();
break;
}
}
}
}
}
private InputStream is;
private final GobblerThread t;
private final Object synchronizer = new Object();
private boolean isEOF = false;
private boolean isClosed = false;
private IOException exception = null;
private byte[] buffer = new byte[2048];
private int read_pos = 0;
private int write_pos = 0;
public StreamGobbler(InputStream is)
{
this.is = is;
t = new GobblerThread();
t.setDaemon(true);
t.start();
}
public int read() throws IOException
{
synchronized (synchronizer)
{
if (isClosed)
throw new IOException("This StreamGobbler is closed.");
while (read_pos == write_pos)
{
if (exception != null)
throw exception;
if (isEOF)
return -1;
try
{
synchronizer.wait();
}
catch (InterruptedException e)
{
throw new InterruptedIOException();
}
}
int b = buffer[read_pos++] & 0xff;
return b;
}
}
public int available() throws IOException
{
synchronized (synchronizer)
{
if (isClosed)
throw new IOException("This StreamGobbler is closed.");
return write_pos - read_pos;
}
}
public int read(byte[] b) throws IOException
{
return read(b, 0, b.length);
}
public void close() throws IOException
{
synchronized (synchronizer)
{
if (isClosed)
return;
isClosed = true;
isEOF = true;
synchronizer.notifyAll();
is.close();
}
}
public int read(byte[] b, int off, int len) throws IOException
{
if (b == null)
throw new NullPointerException();
if ((off < 0) || (len < 0) || ((off + len) > b.length) || ((off + len) < 0) || (off > b.length))
throw new IndexOutOfBoundsException();
if (len == 0)
return 0;
synchronized (synchronizer)
{
if (isClosed)
throw new IOException("This StreamGobbler is closed.");
while (read_pos == write_pos)
{
if (exception != null)
throw exception;
if (isEOF)
return -1;
try
{
synchronizer.wait();
}
catch (InterruptedException e)
{
throw new InterruptedIOException();
}
}
int avail = write_pos - read_pos;
avail = (avail > len) ? len : avail;
System.arraycopy(buffer, read_pos, b, off, avail);
read_pos += avail;
return avail;
}
}
}
@@ -0,0 +1,7 @@
package com.trilead.ssh2.auth;
public interface AgentIdentity {
public String getAlgName();
public byte[] getPublicKeyBlob();
public byte[] sign(byte[] data);
}
@@ -0,0 +1,7 @@
package com.trilead.ssh2.auth;
import java.util.Collection;
public interface AgentProxy {
public Collection/*<AgentIdentity>*/ getIdentities();
}
@@ -0,0 +1,470 @@
package com.trilead.ssh2.auth;
import com.trilead.ssh2.InteractiveCallback;
import com.trilead.ssh2.crypto.PEMDecoder;
import com.trilead.ssh2.packets.*;
import com.trilead.ssh2.signature.KeyAlgorithm;
import com.trilead.ssh2.signature.KeyAlgorithmManager;
import com.trilead.ssh2.transport.MessageHandler;
import com.trilead.ssh2.transport.TransportManager;
import java.io.IOException;
import java.io.InterruptedIOException;
import java.security.KeyPair;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.SecureRandom;
import java.util.Collection;
import java.util.Vector;
import java.util.concurrent.TimeUnit;
import com.trilead.ssh2.ConnectionMonitor;
/**
* AuthenticationManager.
*
* @author Christian Plattner, plattner@trilead.com
* @version $Id: AuthenticationManager.java,v 1.1 2007/10/15 12:49:57 cplattne Exp $
*/
public class AuthenticationManager implements MessageHandler
{
public static final String PROPERTY_TIMEOUT = AuthenticationManager.class.getName() + ".timeout";
public static final long TIMEOUT = Long.valueOf(System.getProperty(PROPERTY_TIMEOUT,"120000"));
TransportManager tm;
Vector packets = new Vector();
Vector<ConnectionMonitor> connMonitors = new Vector<>();
boolean connectionClosed = false;
String[] remainingMethods = new String[0];
boolean isPartialSuccess = false;
boolean authenticated = false;
boolean initDone = false;
public AuthenticationManager(TransportManager tm)
{
this.tm = tm;
}
public void setConnectionMonitors(Vector<ConnectionMonitor> connMonitors) {
this.connMonitors = (Vector<ConnectionMonitor>) connMonitors.clone();
}
boolean methodPossible(String methName)
{
if (remainingMethods == null)
return false;
for (String remainingMethod : remainingMethods) {
if (remainingMethod.compareTo(methName) == 0)
return true;
}
return false;
}
byte[] deQueue() throws IOException
{
synchronized (packets)
{
long waitUntil = System.currentTimeMillis() + TIMEOUT;
long now = System.currentTimeMillis();
while (packets.size() == 0 && now < waitUntil)
{
if (connectionClosed)
throw new IOException("The connection is closed.", tm.getReasonClosedCause());
try
{
packets.wait(TIMEOUT);
}
catch (InterruptedException ign)
{
throw new InterruptedIOException(ign.getMessage());
}
now = System.currentTimeMillis();
}
if(packets.size()==0){
throw new IOException("No valid packets after " + TIMEOUT + " milliseconds, " +
"you can increase the timeout by setting the property -D" + PROPERTY_TIMEOUT + "=<MILLISECONDS>");
}
/* This sequence works with J2ME */
byte[] res = (byte[]) packets.firstElement();
packets.removeElementAt(0);
return res;
}
}
byte[] getNextMessage() throws IOException
{
while (true)
{
byte[] msg = deQueue();
if (msg[0] != Packets.SSH_MSG_USERAUTH_BANNER)
return msg;
PacketUserauthBanner sb = new PacketUserauthBanner(msg, 0, msg.length);
String banner = sb.getBanner();
if (banner != null) {
for (ConnectionMonitor listener : connMonitors) {
listener.onReceiveInfo(ConnectionMonitor.SERVER_BANNER, banner);
}
}
}
}
public String[] getRemainingMethods(String user) throws IOException
{
initialize(user);
return remainingMethods;
}
public boolean getPartialSuccess()
{
return isPartialSuccess;
}
private boolean initialize(String user) throws IOException
{
if (!initDone)
{
tm.registerMessageHandler(this, 0, 255);
PacketServiceRequest sr = new PacketServiceRequest("ssh-userauth");
tm.sendMessage(sr.getPayload());
PacketUserauthRequestNone urn = new PacketUserauthRequestNone("ssh-connection", user);
tm.sendMessage(urn.getPayload());
byte[] msg = getNextMessage();
new PacketServiceAccept(msg, 0, msg.length);
msg = getNextMessage();
initDone = true;
if (msg[0] == Packets.SSH_MSG_USERAUTH_SUCCESS)
{
authenticated = true;
tm.removeMessageHandler(this, 0, 255);
return true;
}
if (msg[0] == Packets.SSH_MSG_USERAUTH_FAILURE)
{
PacketUserauthFailure puf = new PacketUserauthFailure(msg, 0, msg.length);
remainingMethods = puf.getAuthThatCanContinue();
isPartialSuccess = puf.isPartialSuccess();
return false;
}
throw new IOException("Unexpected SSH message (type " + msg[0] + ")");
}
return authenticated;
}
public boolean authenticatePublicKey(String user, AgentProxy proxy) throws IOException {
initialize(user);
boolean success;
for (AgentIdentity identity : (Collection<AgentIdentity>) proxy.getIdentities()) {
success = authenticatePublicKey(user, proxy, identity);
if (success) {
return true;
}
}
return false;
}
boolean authenticatePublicKey(String user, AgentProxy proxy, AgentIdentity identity) throws IOException {
if (!methodPossible("publickey"))
throw new IOException("Authentication method publickey not supported by the server at this stage.");
byte[] pubKeyBlob = identity.getPublicKeyBlob();
if(pubKeyBlob == null) {
return false;
}
TypesWriter tw = new TypesWriter();
byte[] H = tm.getSessionIdentifier();
tw.writeString(H, 0, H.length);
tw.writeByte(Packets.SSH_MSG_USERAUTH_REQUEST);
tw.writeString(user);
tw.writeString("ssh-connection");
tw.writeString("publickey");
tw.writeBoolean(true);
tw.writeString(identity.getAlgName());
tw.writeString(pubKeyBlob, 0, pubKeyBlob.length);
byte[] msg = tw.getBytes();
byte[] response = identity.sign(msg);
PacketUserauthRequestPublicKey ua = new PacketUserauthRequestPublicKey(
"ssh-connection", user, identity.getAlgName(), pubKeyBlob, response);
tm.sendMessage(ua.getPayload());
byte[] ar = getNextMessage();
if (ar[0] == Packets.SSH_MSG_USERAUTH_SUCCESS)
{
authenticated = true;
tm.removeMessageHandler(this, 0, 255);
return true;
}
if (ar[0] == Packets.SSH_MSG_USERAUTH_FAILURE)
{
PacketUserauthFailure puf = new PacketUserauthFailure(ar, 0, ar.length);
remainingMethods = puf.getAuthThatCanContinue();
isPartialSuccess = puf.isPartialSuccess();
return false;
}
throw new IOException("Unexpected SSH message (type " + ar[0] + ")");
}
public boolean authenticatePublicKey(String user, char[] PEMPrivateKey, String password, SecureRandom rnd)
throws IOException
{
try
{
initialize(user);
if (!methodPossible("publickey"))
throw new IOException("Authentication method publickey not supported by the server at this stage.");
KeyPair keyPair = PEMDecoder.decodeKeyPair(PEMPrivateKey, password);
PrivateKey key = keyPair.getPrivate();
boolean supportedKey = false;
for (KeyAlgorithm<PublicKey, PrivateKey> algorithm : KeyAlgorithmManager.getSupportedAlgorithms()) {
if (algorithm.supportsKey(key)) {
byte[] encodedKey = algorithm.encodePublicKey(keyPair.getPublic());
TypesWriter tw = new TypesWriter();
byte[] H = tm.getSessionIdentifier();
tw.writeString(H, 0, H.length);
tw.writeByte(Packets.SSH_MSG_USERAUTH_REQUEST);
tw.writeString(user);
tw.writeString("ssh-connection");
tw.writeString("publickey");
tw.writeBoolean(true);
tw.writeString(algorithm.getKeyFormat());
tw.writeString(encodedKey, 0, encodedKey.length);
byte[] msg = tw.getBytes();
byte[] ds = algorithm.generateSignature(msg, keyPair.getPrivate(), rnd);
byte[] ds_enc = algorithm.encodeSignature(ds);
PacketUserauthRequestPublicKey ua = new PacketUserauthRequestPublicKey("ssh-connection", user,
algorithm.getKeyFormat(), encodedKey, ds_enc);
tm.sendMessage(ua.getPayload());
supportedKey = true;
break;
}
}
if (!supportedKey) {
throw new IOException("Unknown private key type returned by the PEM decoder.");
}
byte[] ar = getNextMessage();
if (ar[0] == Packets.SSH_MSG_USERAUTH_SUCCESS)
{
authenticated = true;
tm.removeMessageHandler(this, 0, 255);
return true;
}
if (ar[0] == Packets.SSH_MSG_USERAUTH_FAILURE)
{
PacketUserauthFailure puf = new PacketUserauthFailure(ar, 0, ar.length);
remainingMethods = puf.getAuthThatCanContinue();
isPartialSuccess = puf.isPartialSuccess();
return false;
}
throw new IOException("Unexpected SSH message (type " + ar[0] + ")");
}
catch (IOException e)
{
tm.close(e, false);
throw new IOException("Publickey authentication failed.", e);
}
}
public boolean authenticateNone(String user) throws IOException
{
try
{
initialize(user);
return authenticated;
}
catch (IOException e)
{
tm.close(e, false);
throw new IOException("None authentication failed.", e);
}
}
public boolean authenticatePassword(String user, String pass) throws IOException
{
try
{
initialize(user);
if (!methodPossible("password"))
throw new IOException("Authentication method password not supported by the server at this stage.");
PacketUserauthRequestPassword ua = new PacketUserauthRequestPassword("ssh-connection", user, pass);
tm.sendMessage(ua.getPayload());
byte[] ar = getNextMessage();
if (ar[0] == Packets.SSH_MSG_USERAUTH_SUCCESS)
{
authenticated = true;
tm.removeMessageHandler(this, 0, 255);
return true;
}
if (ar[0] == Packets.SSH_MSG_USERAUTH_FAILURE)
{
PacketUserauthFailure puf = new PacketUserauthFailure(ar, 0, ar.length);
remainingMethods = puf.getAuthThatCanContinue();
isPartialSuccess = puf.isPartialSuccess();
return false;
}
throw new IOException("Unexpected SSH message (type " + ar[0] + ")");
}
catch (IOException e)
{
tm.close(e, false);
throw new IOException("Password authentication failed.", e);
}
}
public boolean authenticateInteractive(String user, String[] submethods, InteractiveCallback cb) throws IOException
{
try
{
initialize(user);
if (!methodPossible("keyboard-interactive"))
throw new IOException(
"Authentication method keyboard-interactive not supported by the server at this stage.");
if (submethods == null)
submethods = new String[0];
PacketUserauthRequestInteractive ua = new PacketUserauthRequestInteractive("ssh-connection", user,
submethods);
tm.sendMessage(ua.getPayload());
while (true)
{
byte[] ar = getNextMessage();
if (ar[0] == Packets.SSH_MSG_USERAUTH_SUCCESS)
{
authenticated = true;
tm.removeMessageHandler(this, 0, 255);
return true;
}
if (ar[0] == Packets.SSH_MSG_USERAUTH_FAILURE)
{
PacketUserauthFailure puf = new PacketUserauthFailure(ar, 0, ar.length);
remainingMethods = puf.getAuthThatCanContinue();
isPartialSuccess = puf.isPartialSuccess();
return false;
}
if (ar[0] == Packets.SSH_MSG_USERAUTH_INFO_REQUEST)
{
PacketUserauthInfoRequest pui = new PacketUserauthInfoRequest(ar, 0, ar.length);
String[] responses;
try
{
responses = cb.replyToChallenge(pui.getName(), pui.getInstruction(), pui.getNumPrompts(), pui
.getPrompt(), pui.getEcho());
}
catch (Exception e)
{
throw new IOException("Exception in callback.", e);
}
if (responses == null)
throw new IOException("Your callback may not return NULL!");
PacketUserauthInfoResponse puir = new PacketUserauthInfoResponse(responses);
tm.sendMessage(puir.getPayload());
continue;
}
throw new IOException("Unexpected SSH message (type " + ar[0] + ")");
}
}
catch (IOException e)
{
tm.close(e, false);
throw new IOException("Keyboard-interactive authentication failed.", e);
}
}
public void handleMessage(byte[] msg, int msglen) throws IOException
{
synchronized (packets)
{
byte[] tmp = new byte[msglen];
System.arraycopy(msg, 0, tmp, 0, msglen);
packets.addElement(tmp);
packets.notifyAll();
if (packets.size() > 5)
{
connectionClosed = true;
throw new IOException("Error, peer is flooding us with authentication packets.");
}
}
}
public void handleEndMessage(Throwable cause) throws IOException {
synchronized (packets) {
connectionClosed = true;
packets.notifyAll();
}
}
}
@@ -0,0 +1,453 @@
package com.trilead.ssh2.channel;
import com.trilead.ssh2.log.Logger;
import com.trilead.ssh2.packets.PacketSignal;
import com.trilead.ssh2.packets.PacketWindowChange;
import com.trilead.ssh2.packets.Packets;
import com.trilead.ssh2.transport.TransportManager;
import java.io.IOException;
import java.io.InputStream;
import java.io.InterruptedIOException;
import java.io.OutputStream;
import static com.trilead.ssh2.util.IOUtils.closeQuietly;
/**
* Channel.
*
* @author Christian Plattner, plattner@trilead.com
* @version $Id: Channel.java,v 1.1 2007/10/15 12:49:56 cplattne Exp $
*/
public class Channel
{
/*
* OK. Here is an important part of the JVM Specification:
* (http://java.sun.com/docs/books/vmspec/2nd-edition/html/Threads.doc.html#22214)
*
* Any association between locks and variables is purely conventional.
* Locking any lock conceptually flushes all variables from a thread's
* working memory, and unlocking any lock forces the writing out to main
* memory of all variables that the thread has assigned. That a lock may be
* associated with a particular object or a class is purely a convention.
* (...)
*
* If a thread uses a particular shared variable only after locking a
* particular lock and before the corresponding unlocking of that same lock,
* then the thread will read the shared value of that variable from main
* memory after the lock operation, if necessary, and will copy back to main
* memory the value most recently assigned to that variable before the
* unlock operation.
*
* This, in conjunction with the mutual exclusion rules for locks, suffices
* to guarantee that values are correctly transmitted from one thread to
* another through shared variables.
*
* ====> Always keep that in mind when modifying the Channel/ChannelManger
* code.
*
*/
static final int STATE_OPENING = 1;
static final int STATE_OPEN = 2;
static final int STATE_CLOSED = 4;
private static final int CHANNEL_BUFFER_SIZE = Integer.getInteger(
Channel.class.getName()+".bufferSize",
1024*1024 + 16*1024).intValue();
/**
* This channel's session size.
*/
// @GuarydedBy("this")
int channelBufferSize = CHANNEL_BUFFER_SIZE;
/*
* To achieve correctness, the following rules have to be respected when
* accessing this object:
*/
// These fields can always be read
final ChannelManager cm;
final ChannelOutputStream stdinStream;
/**
* One stream.
*
* Either {@link #stream} and {@link #buffer} is set, or the {@link #sink} is set, but those
* are mutually exclusive. The former is used when we are buffering data and let the application
* read it via {@link InputStream}, and the latter is used when we are passing through the data
* to another {@link OutputStream}.
*
* The synchronization is done by {@link Channel}
*/
class Output {
ChannelInputStream stream;
FifoBuffer buffer = new FifoBuffer(Channel.this, 2048, channelBufferSize);
OutputStream sink;
public void write(byte[] buf, int start, int len) throws IOException {
if (buffer!=null) {
try {
buffer.write(buf,start,len);
} catch (InterruptedException e) {
throw new InterruptedIOException();
}
} else {
sink.write(buf,start,len);
freeupWindow(len, true);
}
}
/**
* How many bytes can be read from the buffer?
*/
public int readable() {
if (buffer!=null) return buffer.readable();
else return 0;
}
/**
* See {@link InputStream#available()}
*/
public int available() {
if (buffer==null)
throw new IllegalStateException("Output is being piped to "+sink);
int sz = buffer.readable();
if (sz>0) return sz;
return isEOF() ? -1 : 0;
}
/**
* Read from the buffer.
*/
public int read(byte[] buf, int start, int len) throws InterruptedException {
return buffer.read(buf,start,len);
}
/**
* Called when there will be no more data arriving to this output any more.
* Not that buffer might still have some more data that needs to be drained.
*/
public void eof() {
if (buffer!=null)
buffer.close();
else
closeQuietly(sink);
}
/**
* Instead of spooling data, let our I/O thread write to the given {@link OutputStream}.
*/
public void pipeTo(OutputStream os) throws IOException {
sink = os;
if (buffer.readable()!=0) {
freeupWindow(buffer.writeTo(os));
}
buffer = null;
stream = null;
}
}
final Output stdout = new Output();
final Output stderr = new Output();
// These two fields will only be written while the Channel is in state
// STATE_OPENING.
// The code makes sure that the two fields are written out when the state is
// changing to STATE_OPEN.
// Therefore, if you know that the Channel is in state STATE_OPEN, then you
// can read these two fields without synchronizing on the Channel. However, make
// sure that you get the latest values (e.g., flush caches by synchronizing on any
// object). However, to be on the safe side, you can lock the channel.
int localID = -1;
int remoteID = -1;
/*
* Make sure that we never send a data/EOF/WindowChange msg after a CLOSE
* msg.
*
* This is a little bit complicated, but we have to do it in that way, since
* we cannot keep a lock on the Channel during the send operation (this
* would block sometimes the receiver thread, and, in extreme cases, can
* lead to a deadlock on both sides of the connection (senders are blocked
* since the receive buffers on the other side are full, and receiver
* threads wait for the senders to finish). It all depends on the
* implementation on the other side. But we cannot make any assumptions, we
* have to assume the worst case. Confused? Just believe me.
*/
/*
* If you send a message on a channel, then you have to aquire the
* "channelSendLock" and check the "closeMessageSent" flag (this variable
* may only be accessed while holding the "channelSendLock" !!!
*
* BTW: NEVER EVER SEND MESSAGES FROM THE RECEIVE THREAD - see explanation
* above.
*/
final Object channelSendLock = new Object();
boolean closeMessageSent = false;
/*
* Stop memory fragmentation by allocating this often used buffer.
* May only be used while holding the channelSendLock
*/
final byte[] msgWindowAdjust = new byte[9];
// If you access (read or write) any of the following fields, then you have
// to synchronize on the channel.
int state = STATE_OPENING;
boolean closeMessageRecv = false;
/* This is a stupid implementation. At the moment we can only wait
* for one pending request per channel.
*/
int successCounter = 0;
int failedCounter = 0;
int localWindow = 0; /* locally, we use a small window, < 2^31 */
long remoteWindow = 0; /* long for readable 2^32 - 1 window support */
int localMaxPacketSize = -1;
int remoteMaxPacketSize = -1;
private boolean eof = false;
synchronized void eof() {
stdout.eof();
stderr.eof();
eof = true;
}
boolean isEOF() {
return eof;
}
Integer exit_status;
String exit_signal;
// we keep the x11 cookie so that this channel can be closed when this
// specific x11 forwarding gets stopped
String hexX11FakeCookie;
// reasonClosed is special, since we sometimes need to access it
// while holding the channelSendLock.
// We protect it with a private short term lock.
private final Object reasonClosedLock = new Object();
private Throwable reasonClosed = null;
public Channel(ChannelManager cm)
{
this.cm = cm;
this.localWindow = channelBufferSize;
this.localMaxPacketSize = TransportManager.MAX_PACKET_SIZE - 1024; // leave enough slack
this.stdinStream = new ChannelOutputStream(this);
this.stdout.stream = new ChannelInputStream(this, false);
this.stderr.stream = new ChannelInputStream(this, true);
}
/* Methods to allow access from classes outside of this package */
public synchronized void setWindowSize(int newSize) {
if (newSize<=0) throw new IllegalArgumentException("Invalid value: "+newSize);
this.channelBufferSize = newSize;
// next time when the other side sends us something, we'll issue SSH_MSG_CHANNEL_WINDOW_ADJUST
}
public ChannelInputStream getStderrStream()
{
return stderr.stream;
}
public ChannelOutputStream getStdinStream()
{
return stdinStream;
}
public ChannelInputStream getStdoutStream()
{
return stdout.stream;
}
public synchronized void pipeStdoutStream(OutputStream os) throws IOException {
stdout.pipeTo(os);
}
public synchronized void pipeStderrStream(OutputStream os) throws IOException {
stderr.pipeTo(os);
}
public String getExitSignal()
{
synchronized (this)
{
return exit_signal;
}
}
public Integer getExitStatus()
{
synchronized (this)
{
return exit_status;
}
}
/**
* Gets reason closed.
*
* @return the reason closed
* @deprecated Use {@link #getReasonClosedCause()}
*/
public String getReasonClosed()
{
synchronized (reasonClosedLock)
{
return reasonClosed!=null ? reasonClosed.getMessage() : null;
}
}
public Throwable getReasonClosedCause()
{
synchronized (reasonClosedLock)
{
return reasonClosed;
}
}
public void setReasonClosed(String reasonClosed)
{
setReasonClosed(new IOException(reasonClosed));
}
public void setReasonClosed(Throwable reasonClosed) {
synchronized (reasonClosedLock)
{
if (this.reasonClosed == null)
this.reasonClosed = reasonClosed;
}
}
/**
* Update the flow control couner and if necessary, sends ACK to the other end to
* let it send more data.
*/
void freeupWindow(int copylen) throws IOException {
freeupWindow(copylen, false);
}
/**
* Update the flow control couner and if necessary, sends ACK to the other end to
* let it send more data.
*/
void freeupWindow(int copylen, boolean sendAsync) throws IOException {
if (copylen <= 0) return;
int increment = 0;
int remoteID;
int localID;
synchronized (this) {
if (localWindow <= ((channelBufferSize * 3) / 4)) {
// have enough local window been consumed? if so, we'll send Ack
// the window control is on the combined bytes of stdout & stderr
int space = channelBufferSize - stdout.readable() - stderr.readable();
increment = space - localWindow;
if (increment > 0) // increment<0 can't happen, but be defensive
localWindow += increment;
}
remoteID = this.remoteID; /* read while holding the lock */
localID = this.localID; /* read while holding the lock */
}
/*
* If a consumer reads stdout and stdin in parallel, we may end up with
* sending two msgWindowAdjust messages. Luckily, it
* does not matter in which order they arrive at the server.
*/
if (increment > 0)
{
if (log.isEnabled())
log.log(80, "Sending SSH_MSG_CHANNEL_WINDOW_ADJUST (channel " + localID + ", " + increment + ")");
synchronized (channelSendLock)
{
byte[] msg = msgWindowAdjust;
msg[0] = Packets.SSH_MSG_CHANNEL_WINDOW_ADJUST;
msg[1] = (byte) (remoteID >> 24);
msg[2] = (byte) (remoteID >> 16);
msg[3] = (byte) (remoteID >> 8);
msg[4] = (byte) (remoteID);
msg[5] = (byte) (increment >> 24);
msg[6] = (byte) (increment >> 16);
msg[7] = (byte) (increment >> 8);
msg[8] = (byte) (increment);
if (closeMessageSent == false) {
if (sendAsync) {
cm.tm.sendAsynchronousMessage(msg);
} else {
cm.tm.sendMessage(msg);
}
}
}
}
}
public void requestWindowChange(int term_width_characters, int term_height_characters,
int term_width_pixels, int term_height_pixels) throws IOException {
PacketWindowChange pwc;
synchronized (this) {
if (state != Channel.STATE_OPEN)
throw (IOException)new IOException("Cannot request window-change on this channel").initCause(getReasonClosedCause());
pwc = new PacketWindowChange(remoteID, term_width_characters, term_height_characters,
term_width_pixels, term_height_pixels);
}
synchronized (channelSendLock) {
if (closeMessageSent)
throw (IOException)new IOException("Cannot request window-change on this channel").initCause(getReasonClosedCause());
cm.tm.sendMessage(pwc.getPayload());
}
}
public void signal(String name) throws IOException {
PacketSignal p;
synchronized (this) {
if (state != Channel.STATE_OPEN)
throw (IOException)new IOException("Cannot send signal on this channel").initCause(getReasonClosedCause());
p = new PacketSignal(remoteID, name);
}
synchronized (channelSendLock) {
if (closeMessageSent)
throw (IOException)new IOException("Cannot request window-change on this channel").initCause(getReasonClosedCause());
cm.tm.sendMessage(p.getPayload());
}
}
private static final Logger log = Logger.getLogger(Channel.class);
}
@@ -0,0 +1,86 @@
package com.trilead.ssh2.channel;
import java.io.IOException;
import java.io.InputStream;
/**
* ChannelInputStream.
*
* @author Christian Plattner, plattner@trilead.com
* @version $Id: ChannelInputStream.java,v 1.1 2007/10/15 12:49:56 cplattne Exp $
*/
public final class ChannelInputStream extends InputStream
{
Channel c;
boolean isClosed = false;
boolean isEOF = false;
boolean extendedFlag = false;
ChannelInputStream(Channel c, boolean isExtended)
{
this.c = c;
this.extendedFlag = isExtended;
}
public int available() throws IOException
{
if (isEOF)
return 0;
int avail = c.cm.getAvailable(c, extendedFlag);
/* We must not return -1 on EOF */
return (avail > 0) ? avail : 0;
}
public void close() throws IOException
{
isClosed = true;
}
public int read(byte[] b, int off, int len) throws IOException
{
if (b == null)
throw new NullPointerException();
if ((off < 0) || (len < 0) || ((off + len) > b.length) || ((off + len) < 0) || (off > b.length))
throw new IndexOutOfBoundsException();
if (len == 0)
return 0;
if (isEOF)
return -1;
int ret = c.cm.getChannelData(c, extendedFlag, b, off, len);
if (ret == -1)
{
isEOF = true;
}
return ret;
}
public int read(byte[] b) throws IOException
{
return read(b, 0, b.length);
}
public int read() throws IOException
{
/* Yes, this stream is pure and unbuffered, a single byte read() is slow */
final byte b[] = new byte[1];
int ret = read(b, 0, 1);
if (ret != 1)
return -1;
return b[0] & 0xff;
}
}
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,70 @@
package com.trilead.ssh2.channel;
import java.io.IOException;
import java.io.OutputStream;
/**
* ChannelOutputStream.
*
* @author Christian Plattner, plattner@trilead.com
* @version $Id: ChannelOutputStream.java,v 1.1 2007/10/15 12:49:56 cplattne Exp $
*/
public final class ChannelOutputStream extends OutputStream
{
Channel c;
boolean isClosed = false;
ChannelOutputStream(Channel c)
{
this.c = c;
}
public void write(int b) throws IOException
{
byte[] buff = new byte[1];
buff[0] = (byte) b;
write(buff, 0, 1);
}
public void close() throws IOException
{
if (isClosed == false)
{
isClosed = true;
c.cm.sendEOF(c);
}
}
public void flush() throws IOException
{
if (isClosed)
throw new IOException("This OutputStream is closed.");
/* This is a no-op, since this stream is unbuffered */
}
public void write(byte[] b, int off, int len) throws IOException
{
if (isClosed)
throw new IOException("This OutputStream is closed.");
if (b == null)
throw new NullPointerException();
if ((off < 0) || (len < 0) || ((off + len) > b.length) || ((off + len) < 0) || (off > b.length))
throw new IndexOutOfBoundsException();
if (len == 0)
return;
c.cm.sendData(c, b, off, len);
}
public void write(byte[] b) throws IOException
{
write(b, 0, b.length);
}
}
@@ -0,0 +1,345 @@
/*
* 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.channel;
import java.io.IOException;
import java.io.InputStream;
import java.io.InterruptedIOException;
import java.io.OutputStream;
import java.io.PushbackInputStream;
import java.net.ConnectException;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.NoRouteToHostException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.Semaphore;
import net.sourceforge.jsocks.Proxy;
import net.sourceforge.jsocks.ProxyMessage;
import net.sourceforge.jsocks.Socks5Message;
import net.sourceforge.jsocks.SocksException;
import net.sourceforge.jsocks.server.ServerAuthenticator;
import net.sourceforge.jsocks.server.ServerAuthenticatorNone;
import android.util.Log;
import com.trilead.ssh2.log.Logger;
/**
* DynamicAcceptThread.
*
* @author Kenny Root
* @version $Id$
*/
public class DynamicAcceptThread extends Thread
implements IChannelWorkerThread {
private static final Logger log = Logger.getLogger(DynamicAcceptThread.class);
private ChannelManager cm;
private final static int MAX_THREAD_COUNT = 25;
private Semaphore threadBound;
private ServerSocket ss;
public DynamicAcceptThread(ChannelManager cm, InetSocketAddress localAddress, int maxThreads)
throws IOException {
this.cm = cm;
setName("DynamicAcceptThread");
ss = new ServerSocket();
ss.bind(localAddress);
if (maxThreads < 2) {
maxThreads = MAX_THREAD_COUNT;
}
threadBound = new Semaphore(maxThreads);
}
public DynamicAcceptThread(ChannelManager cm, int local_port, int maxThreads)
throws IOException {
this.cm = cm;
setName("DynamicAcceptThread");
ss = new ServerSocket(local_port);
if (maxThreads < 2) {
maxThreads = MAX_THREAD_COUNT;
}
threadBound = new Semaphore(maxThreads);
}
public int getLocalPort() {
return ss.getLocalPort();
}
@Override
public void run() {
try {
cm.registerThread(this);
} catch (IOException e) {
stopWorking();
return;
}
while (true) {
Socket sock = null;
try {
sock = ss.accept();
} catch (IOException e) {
stopWorking();
return;
}
threadBound.acquireUninterruptibly();
DynamicAcceptRunnable dar = new DynamicAcceptRunnable(
new ServerAuthenticatorNone(), sock);
Thread t = new Thread(dar);
t.setDaemon(true);
t.start();
}
}
/*
* (non-Javadoc)
*
* @see com.trilead.ssh2.channel.IChannelWorkerThread#stopWorking()
*/
@Override
public void stopWorking() {
try {
/* This will lead to an IOException in the ss.accept() call */
ss.close();
} catch (IOException e) {
}
}
class DynamicAcceptRunnable implements Runnable {
private boolean exceptionChainContains(Throwable t, String needle) {
while (t != null) {
String m = t.getMessage();
if (m != null && m.contains(needle))
return true;
t = t.getCause();
}
return false;
}
private static final int idleTimeout = 60*1000*6; // 6 minutes
private ServerAuthenticator auth;
private Socket sock;
private InputStream in;
private OutputStream out;
private ProxyMessage msg;
public DynamicAcceptRunnable(ServerAuthenticator auth, Socket sock) {
this.auth = auth;
this.sock = sock;
setName("DynamicAcceptRunnable");
}
@Override
public void run() {
try {
startSession();
} catch (IOException ioe) {
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);
} catch (Error e) {
// Force to GC here
System.gc();
} finally {
if (auth != null)
auth.endSession();
threadBound.release();
}
}
private void handleRequest(ProxyMessage msg) throws IOException {
if (!auth.checkRequest(msg))
throw new SocksException(Proxy.SOCKS_FAILURE);
switch (msg.command) {
case Proxy.SOCKS_CMD_CONNECT:
onConnect(msg);
break;
default:
throw new SocksException(Proxy.SOCKS_CMD_NOT_SUPPORTED);
}
}
private void onConnect(ProxyMessage msg) throws IOException {
ProxyMessage response = null;
Channel cn = null;
StreamForwarder r2l = null;
StreamForwarder l2r = null;
response = new Socks5Message(Proxy.SOCKS_SUCCESS,
(InetAddress) null, 0);
response.write(out);
String destHost = msg.host;
if (msg.ip != null)
destHost = msg.ip.getHostAddress();
try {
/*
* This may fail, e.g., if the remote port is closed (in
* optimistic terms: not open yet)
*/
cn = cm.openDirectTCPIPChannel(destHost, msg.port, "127.0.0.1",
0);
} catch (IOException e) {
/*
* Some SSH server implementations (commonly Go-based) incorrectly build
* "host:port" for IPv6 literals without brackets, which results in
* "too many colons in address". Retry once with a bracketed IPv6 host.
*/
if (destHost != null && destHost.indexOf(':') >= 0 && destHost.charAt(0) != '['
&& (exceptionChainContains(e, "too many colons in address")
|| (exceptionChainContains(e, "dial tcp") && exceptionChainContains(e, "too many colons")))) {
try {
String bracketedHost = "[" + destHost + "]";
if (log.isEnabled())
log.log(50, "Retrying DirectTCPIP with bracketed IPv6 host: " + bracketedHost + ":" + msg.port);
cn = cm.openDirectTCPIPChannel(bracketedHost, msg.port, "127.0.0.1", 0);
} catch (IOException retry) {
e = retry;
}
}
if (cn == null) {
/*
* Simply close the local socket and wait for the next incoming
* connection
*/
try {
sock.close();
} catch (IOException ignore) {
}
return;
}
}
try {
r2l = new StreamForwarder(cn, null, null, cn.getStdoutStream(), out,
"RemoteToLocal");
l2r = new StreamForwarder(cn, r2l, sock, in, cn.stdinStream,
"LocalToRemote");
} catch (IOException e) {
try {
/*
* This message is only visible during debugging, since we
* discard the channel immediatelly
*/
cn.cm.closeChannel(cn,
"Weird error during creation of StreamForwarder ("
+ e.getMessage() + ")", true);
} catch (IOException ignore) {
}
return;
}
r2l.setDaemon(true);
l2r.setDaemon(true);
r2l.start();
l2r.start();
}
private 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 {
throw new SocksException(Proxy.SOCKS_FAILURE);
}
return msg;
}
private void sendErrorMessage(int error_code) {
ProxyMessage err_msg = new Socks5Message(error_code);
try {
err_msg.write(out);
} catch (IOException ioe) {
}
}
private void startSession() throws IOException {
sock.setSoTimeout(idleTimeout);
try {
auth = auth.startSession(sock);
} catch (IOException ioe) {
log.log(50, "Could not start SOCKS session");
ioe.printStackTrace();
auth = null;
return;
}
if (auth == null) { // Authentication failed
log.log(50, "SOCKS auth failed");
return;
}
in = auth.getInputStream();
out = auth.getOutputStream();
msg = readMsg(in);
handleRequest(msg);
}
}
}
@@ -0,0 +1,244 @@
package com.trilead.ssh2.channel;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
/**
* FIFO buffer for a reader thread and a writer thread to collaborate.
*
* Unlike a ring buffer, which uses a fixed memory regardless of the number of bytes currently in the buffer,
* this implementation uses a single linked list to reduce the memory footprint when the reader
* closely follows the writer, regardless of the capacity limit set in the constructor.
*
* In trilead, the writer puts the data we receive from the network, and the user code acts as a reader.
* A user code normally drains the buffer more quickly than what the network delivers, so this implementation
* saves memory while simultaneously allowing us to advertise a bigger window size for a large latency network.
*
* @author Kohsuke Kawaguchi
*/
class FifoBuffer {
/**
* Unit of buffer, singly linked and lazy created as needed.
*/
static final class Page {
final byte[] buf;
Page next;
Page(int sz) {
this.buf = new byte[sz];
}
}
/**
* Points to a specific byte in a {@link Page}.
*/
class Pointer {
Page p;
/**
* [0,p.buf.size)
*/
int off;
Pointer(Page p, int off) {
this.p = p;
this.off = off;
}
/**
* Figure out the number of bytes that can be read/written in one array copy.
*/
private int chunk() {
int sz = pageSize-off;
assert sz>=0;
if (sz>0) return sz;
Page q = p.next;
if (q==null)
q = p.next = newPage();
p = q;
off = 0;
return pageSize;
}
public void write(byte[] buf, int start, int len) {
while (len>0) {
int chunk = Math.min(len,chunk());
System.arraycopy(buf,start,p.buf,off,chunk);
off+=chunk;
len-=chunk;
start+=chunk;
}
}
public void read(byte[] buf, int start, int len) {
while (len>0) {
int chunk = Math.min(len,chunk());
System.arraycopy(p.buf,off,buf,start,chunk);
off+=chunk;
len-=chunk;
start+=chunk;
}
}
}
private final Object lock;
/**
* Number of bytes currently in this ring buffer
*/
private int sz;
/**
* Cap to the # of bytes that we can hold.
*/
private int limit;
private final int pageSize;
/**
* The position at which the next read/write will happen.
*/
private Pointer r,w;
/**
* Set to true when the writer closes the write end.
*/
private boolean closed;
FifoBuffer(int pageSize, int limit) {
this(null,pageSize,limit);
}
FifoBuffer(Object lock, int pageSize, int limit) {
this.lock = lock==null ? this : lock;
this.limit = limit;
this.pageSize = pageSize;
Page p = newPage();
r = new Pointer(p,0);
w = new Pointer(p,0);
}
public void setLimit(int newLimit) {
synchronized (lock) {
limit = newLimit;
}
}
private Page newPage() {
return new Page(pageSize);
}
/**
* Number of bytes readable
*/
int readable() {
synchronized (lock) {
return sz;
}
}
/**
* Number of bytes writable
*/
int writable() {
return Math.max(0,limit-readable());
}
public void write(byte[] buf, int start, int len) throws InterruptedException {
while (len>0) {
int chunk;
synchronized (lock) {
while ((chunk = Math.min(len,writable()))==0)
lock.wait();
w.write(buf, start, chunk);
start += chunk;
len -= chunk;
sz += chunk;
lock.notifyAll();
}
}
}
public void close() {
synchronized (lock) {
if (!closed) {
closed = true;
releaseRing();
lock.notifyAll();
}
}
}
/**
* If the ring is no longer needed, release the buffer.
*/
private void releaseRing() {
if (closed && readable()==0)
r = w = null;
}
/**
*
* @see InputStream#read(byte[],int,int)
*/
public int read(byte[] buf, int start, int len) throws InterruptedException {
if (len==0) return 0;
int read = 0; // total # of bytes read
while (true) {
int chunk;
synchronized (lock) {
while (true) {
chunk = Math.min(len,readable());
if (chunk>0) break;
// there's nothing we can immediately read
if (read>0) return read; // we've already read some
if (closed) {
releaseRing();
return -1; // no more data
}
lock.wait(); // wait until the writer gives us something
}
r.read(buf,start,chunk);
start += chunk;
len -= chunk;
read += chunk;
sz -= chunk;
lock.notifyAll();
}
}
}
/**
* Write whatever readable to the specified OutputStream, then return.
*/
public int writeTo(OutputStream out) throws IOException {
try {
int total = 0;
while (readable()>0) {
byte[] buf = new byte[1024]; // most often this method gets called before we have any data, so this is a win
int read = read(buf, 0, buf.length);
out.write(buf,0,read);
total += read;
}
return total;
} catch (InterruptedException e) {
throw new AssertionError(e); // we carefully read only what we can read without blocking
}
}
}
@@ -0,0 +1,13 @@
package com.trilead.ssh2.channel;
/**
* IChannelWorkerThread.
*
* @author Christian Plattner, plattner@trilead.com
* @version $Id: IChannelWorkerThread.java,v 1.1 2007/10/15 12:49:56 cplattne Exp $
*/
interface IChannelWorkerThread
{
public void stopWorking();
}
@@ -0,0 +1,135 @@
package com.trilead.ssh2.channel;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;
/**
* LocalAcceptThread.
*
* @author Christian Plattner, plattner@trilead.com
* @version $Id: LocalAcceptThread.java,v 1.1 2007/10/15 12:49:56 cplattne Exp $
*/
public class LocalAcceptThread extends Thread implements IChannelWorkerThread
{
ChannelManager cm;
String host_to_connect;
int port_to_connect;
final ServerSocket ss;
public LocalAcceptThread(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;
ss = new ServerSocket(local_port);
}
public LocalAcceptThread(ChannelManager cm, InetSocketAddress localAddress, 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;
ss = new ServerSocket();
ss.bind(localAddress);
}
public void run()
{
try
{
cm.registerThread(this);
}
catch (IOException e)
{
stopWorking();
return;
}
while (true)
{
Socket s = null;
try
{
s = ss.accept();
}
catch (IOException e)
{
stopWorking();
return;
}
Channel cn = null;
StreamForwarder r2l = null;
StreamForwarder l2r = null;
try
{
/* This may fail, e.g., if the remote port is closed (in optimistic terms: not open yet) */
cn = cm.openDirectTCPIPChannel(host_to_connect, port_to_connect, s.getInetAddress().getHostAddress(), s
.getPort());
}
catch (IOException e)
{
/* Simply close the local socket and wait for the next incoming connection */
try
{
s.close();
}
catch (IOException ignore)
{
}
continue;
}
try
{
r2l = new StreamForwarder(cn, null, null, cn.getStdoutStream(), s.getOutputStream(), "RemoteToLocal");
l2r = new StreamForwarder(cn, r2l, s, s.getInputStream(), cn.stdinStream, "LocalToRemote");
}
catch (IOException e)
{
try
{
/* This message is only visible during debugging, since we discard the channel immediatelly */
cn.cm.closeChannel(cn, "Weird error during creation of StreamForwarder (" + e.getMessage() + ")",
true);
}
catch (IOException ignore)
{
}
continue;
}
r2l.setDaemon(true);
l2r.setDaemon(true);
r2l.start();
l2r.start();
}
}
public void stopWorking()
{
try
{
/* This will lead to an IOException in the ss.accept() call */
ss.close();
}
catch (IOException e)
{
}
}
}
@@ -0,0 +1,105 @@
package com.trilead.ssh2.channel;
import java.io.IOException;
import java.io.InterruptedIOException;
import java.net.Socket;
import com.trilead.ssh2.log.Logger;
/**
* RemoteAcceptThread.
*
* @author Christian Plattner, plattner@trilead.com
* @version $Id: RemoteAcceptThread.java,v 1.1 2007/10/15 12:49:56 cplattne Exp $
*/
public class RemoteAcceptThread extends Thread
{
private static final Logger log = Logger.getLogger(RemoteAcceptThread.class);
Channel c;
String remoteConnectedAddress;
int remoteConnectedPort;
String remoteOriginatorAddress;
int remoteOriginatorPort;
String targetAddress;
int targetPort;
Socket s;
public RemoteAcceptThread(Channel c, String remoteConnectedAddress, int remoteConnectedPort,
String remoteOriginatorAddress, int remoteOriginatorPort, String targetAddress, int targetPort)
{
this.c = c;
this.remoteConnectedAddress = remoteConnectedAddress;
this.remoteConnectedPort = remoteConnectedPort;
this.remoteOriginatorAddress = remoteOriginatorAddress;
this.remoteOriginatorPort = remoteOriginatorPort;
this.targetAddress = targetAddress;
this.targetPort = targetPort;
if (log.isEnabled())
log.log(30, "RemoteAcceptThread: " + remoteConnectedAddress + "/" + remoteConnectedPort + ", R: "
+ remoteOriginatorAddress + "/" + remoteOriginatorPort);
}
public void run()
{
try
{
c.cm.sendOpenConfirmation(c);
s = new Socket(targetAddress, targetPort);
StreamForwarder r2l = new StreamForwarder(c, null, null, c.getStdoutStream(), s.getOutputStream(),
"RemoteToLocal");
StreamForwarder l2r = new StreamForwarder(c, null, null, s.getInputStream(), c.getStdinStream(),
"LocalToRemote");
/* No need to start two threads, one can be executed in the current thread */
r2l.setDaemon(true);
r2l.start();
l2r.run();
while (r2l.isAlive())
{
try
{
r2l.join();
}
catch (InterruptedException e)
{
throw new InterruptedIOException();
}
}
/* If the channel is already closed, then this is a no-op */
c.cm.closeChannel(c, "EOF on both streams reached.", true);
s.close();
}
catch (IOException e)
{
log.log(50, "IOException in proxy code",e);
try
{
c.cm.closeChannel(c, "IOException in proxy code (" + e.getMessage() + ")", true);
}
catch (IOException e1)
{
}
try
{
if (s != null)
s.close();
}
catch (IOException e1)
{
}
}
}
}
@@ -0,0 +1,17 @@
package com.trilead.ssh2.channel;
/**
* RemoteForwardingData. Data about a requested remote forwarding.
*
* @author Christian Plattner, plattner@trilead.com
* @version $Id: RemoteForwardingData.java,v 1.1 2007/10/15 12:49:56 cplattne Exp $
*/
public class RemoteForwardingData
{
public String bindAddress;
public int bindPort;
String targetAddress;
int targetPort;
}
@@ -0,0 +1,241 @@
package com.trilead.ssh2.channel;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.InterruptedIOException;
import java.net.Socket;
import com.trilead.ssh2.log.Logger;
/**
* RemoteX11AcceptThread.
*
* @author Christian Plattner, plattner@trilead.com
* @version $Id: RemoteX11AcceptThread.java,v 1.2 2008/04/01 12:38:09 cplattne Exp $
*/
public class RemoteX11AcceptThread extends Thread
{
private static final Logger log = Logger.getLogger(RemoteX11AcceptThread.class);
Channel c;
String remoteOriginatorAddress;
int remoteOriginatorPort;
Socket s;
public RemoteX11AcceptThread(Channel c, String remoteOriginatorAddress, int remoteOriginatorPort)
{
this.c = c;
this.remoteOriginatorAddress = remoteOriginatorAddress;
this.remoteOriginatorPort = remoteOriginatorPort;
}
public void run()
{
try
{
/* Send Open Confirmation */
c.cm.sendOpenConfirmation(c);
/* Read startup packet from client */
OutputStream remote_os = c.getStdinStream();
InputStream remote_is = c.getStdoutStream();
/* The following code is based on the protocol description given in:
* Scheifler/Gettys,
* X Windows System: Core and Extension Protocols:
* X Version 11, Releases 6 and 6.1 ISBN 1-55558-148-X
*/
/*
* Client startup:
*
* 1 0X42 MSB first/0x6c lSB first - byteorder
* 1 - unused
* 2 card16 - protocol-major-version
* 2 card16 - protocol-minor-version
* 2 n - lenght of authorization-protocol-name
* 2 d - lenght of authorization-protocol-data
* 2 - unused
* string8 - authorization-protocol-name
* p - unused, p=pad(n)
* string8 - authorization-protocol-data
* q - unused, q=pad(d)
*
* pad(X) = (4 - (X mod 4)) mod 4
*
* Server response:
*
* 1 (0 failed, 2 authenticate, 1 success)
* ...
*
*/
/* Later on we will simply forward the first 6 header bytes to the "real" X11 server */
byte[] header = new byte[6];
if (remote_is.read(header) != 6)
throw new IOException("Unexpected EOF on X11 startup!");
if ((header[0] != 0x42) && (header[0] != 0x6c)) // 0x42 MSB first, 0x6C LSB first
throw new IOException("Unknown endian format in X11 message!");
/* Yes, I came up with this myself - shall I file an application for a patent? =) */
int idxMSB = (header[0] == 0x42) ? 0 : 1;
/* Read authorization data header */
byte[] auth_buff = new byte[6];
if (remote_is.read(auth_buff) != 6)
throw new IOException("Unexpected EOF on X11 startup!");
int authProtocolNameLength = ((auth_buff[idxMSB] & 0xff) << 8) | (auth_buff[1 - idxMSB] & 0xff);
int authProtocolDataLength = ((auth_buff[2 + idxMSB] & 0xff) << 8) | (auth_buff[3 - idxMSB] & 0xff);
if ((authProtocolNameLength > 256) || (authProtocolDataLength > 256))
throw new IOException("Buggy X11 authorization data");
int authProtocolNamePadding = ((4 - (authProtocolNameLength % 4)) % 4);
int authProtocolDataPadding = ((4 - (authProtocolDataLength % 4)) % 4);
byte[] authProtocolName = new byte[authProtocolNameLength];
byte[] authProtocolData = new byte[authProtocolDataLength];
byte[] paddingBuffer = new byte[4];
if (remote_is.read(authProtocolName) != authProtocolNameLength)
throw new IOException("Unexpected EOF on X11 startup! (authProtocolName)");
if (remote_is.read(paddingBuffer, 0, authProtocolNamePadding) != authProtocolNamePadding)
throw new IOException("Unexpected EOF on X11 startup! (authProtocolNamePadding)");
if (remote_is.read(authProtocolData) != authProtocolDataLength)
throw new IOException("Unexpected EOF on X11 startup! (authProtocolData)");
if (remote_is.read(paddingBuffer, 0, authProtocolDataPadding) != authProtocolDataPadding)
throw new IOException("Unexpected EOF on X11 startup! (authProtocolDataPadding)");
if ("MIT-MAGIC-COOKIE-1".equals(new String(authProtocolName, "ISO-8859-1")) == false)
throw new IOException("Unknown X11 authorization protocol!");
if (authProtocolDataLength != 16)
throw new IOException("Wrong data length for X11 authorization data!");
StringBuffer tmp = new StringBuffer(32);
for (int i = 0; i < authProtocolData.length; i++)
{
String digit2 = Integer.toHexString(authProtocolData[i] & 0xff);
tmp.append((digit2.length() == 2) ? digit2 : "0" + digit2);
}
String hexEncodedFakeCookie = tmp.toString();
/* Order is very important here - it may be that a certain x11 forwarding
* gets disabled right in the moment when we check and register our connection
* */
synchronized (c)
{
/* Please read the comment in Channel.java */
c.hexX11FakeCookie = hexEncodedFakeCookie;
}
/* Now check our fake cookie directory to see if we produced this cookie */
X11ServerData sd = c.cm.checkX11Cookie(hexEncodedFakeCookie);
if (sd == null)
throw new IOException("Invalid X11 cookie received.");
/* If the session which corresponds to this cookie is closed then we will
* detect this: the session's close code will close all channels
* with the session's assigned x11 fake cookie.
*/
s = new Socket(sd.hostname, sd.port);
OutputStream x11_os = s.getOutputStream();
InputStream x11_is = s.getInputStream();
/* Now we are sending the startup packet to the real X11 server */
x11_os.write(header);
if (sd.x11_magic_cookie == null)
{
byte[] emptyAuthData = new byte[6];
/* empty auth data, hopefully you are connecting to localhost =) */
x11_os.write(emptyAuthData);
}
else
{
if (sd.x11_magic_cookie.length != 16)
throw new IOException("The real X11 cookie has an invalid length!");
/* send X11 cookie specified by client */
x11_os.write(auth_buff);
x11_os.write(authProtocolName); /* re-use */
x11_os.write(paddingBuffer, 0, authProtocolNamePadding);
x11_os.write(sd.x11_magic_cookie);
x11_os.write(paddingBuffer, 0, authProtocolDataPadding);
}
x11_os.flush();
/* Start forwarding traffic */
StreamForwarder r2l = new StreamForwarder(c, null, null, remote_is, x11_os, "RemoteToX11");
StreamForwarder l2r = new StreamForwarder(c, null, null, x11_is, remote_os, "X11ToRemote");
/* No need to start two threads, one can be executed in the current thread */
r2l.setDaemon(true);
r2l.start();
l2r.run();
while (r2l.isAlive())
{
try
{
r2l.join();
}
catch (InterruptedException e)
{
throw new InterruptedIOException();
}
}
/* If the channel is already closed, then this is a no-op */
c.cm.closeChannel(c, "EOF on both X11 streams reached.", true);
s.close();
}
catch (IOException e)
{
log.log(50, "IOException in X11 proxy code",e);
try
{
c.cm.closeChannel(c, "IOException in X11 proxy code (" + e.getMessage() + ")", true);
}
catch (IOException e1)
{
}
try
{
if (s != null)
s.close();
}
catch (IOException e1)
{
}
}
}
}
@@ -0,0 +1,114 @@
package com.trilead.ssh2.channel;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
/**
* A StreamForwarder forwards data between two given streams.
* If two StreamForwarder threads are used (one for each direction)
* then one can be configured to shutdown the underlying channel/socket
* if both threads have finished forwarding (EOF).
*
* @author Christian Plattner, plattner@trilead.com
* @version $Id: StreamForwarder.java,v 1.1 2007/10/15 12:49:56 cplattne Exp $
*/
public class StreamForwarder extends Thread
{
OutputStream os;
InputStream is;
byte[] buffer;
Channel c;
StreamForwarder sibling;
Socket s;
String mode;
StreamForwarder(Channel c, StreamForwarder sibling, Socket s, InputStream is, OutputStream os, String mode)
throws IOException
{
this.is = is;
this.os = os;
this.mode = mode;
this.c = c;
this.sibling = sibling;
this.s = s;
// window size is for the other side of the network with some latency.
// we don't need such a big buffer for a copy stream tight loop
this.buffer = new byte[8192/*c.channelBufferSize*/];
}
public void run()
{
try
{
while (true)
{
int len = is.read(buffer);
if (len <= 0)
break;
os.write(buffer, 0, len);
os.flush();
}
}
catch (IOException ignore)
{
try
{
c.cm.closeChannel(c, "Closed due to exception in StreamForwarder (" + mode + "): "
+ ignore.getMessage(), true);
}
catch (IOException e)
{
}
}
finally
{
try
{
os.close();
}
catch (IOException e1)
{
}
try
{
is.close();
}
catch (IOException e2)
{
}
if (sibling != null)
{
while (sibling.isAlive())
{
try
{
sibling.join();
}
catch (InterruptedException e)
{
}
}
try
{
c.cm.closeChannel(c, "StreamForwarder (" + mode + ") is cleaning up the connection", true);
}
catch (IOException e3)
{
}
try
{
if (s != null)
s.close();
}
catch (IOException e1)
{
}
}
}
}
}
@@ -0,0 +1,16 @@
package com.trilead.ssh2.channel;
/**
* X11ServerData. Data regarding an x11 forwarding target.
*
* @author Christian Plattner, plattner@trilead.com
* @version $Id: X11ServerData.java,v 1.1 2007/10/15 12:49:56 cplattne Exp $
*
*/
public class X11ServerData
{
public String hostname;
public int port;
public byte[] x11_magic_cookie; /* not the remote (fake) one, the local (real) one */
}
@@ -0,0 +1,86 @@
/*
* 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 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);
}
}
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;
}
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);
}
}
@@ -0,0 +1,32 @@
/*
* 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 {
boolean canCompressPreauth();
int compress(byte[] buf, int start, int len, byte[] output);
int getBufferSize();
byte[] uncompress(byte[] buf, int start, int[] len);
}

Some files were not shown because too many files have changed in this diff Show More