code stringlengths 1 2.01M | repo_name stringlengths 3 62 | path stringlengths 1 267 | language stringclasses 231 values | license stringclasses 13 values | size int64 1 2.01M |
|---|---|---|---|---|---|
package com.trilead.ssh2.packets;
import java.io.IOException;
import java.security.SecureRandom;
import com.trilead.ssh2.crypto.CryptoWishList;
import com.trilead.ssh2.transport.KexParameters;
/**
* PacketKexInit.
*
* @author Christian Plattner, plattner@trilead.com
* @version $Id: PacketKexInit.java,v 1.1 2007/10/15 12:49:55 cplattne Exp $
*/
public class PacketKexInit {
byte[] payload;
KexParameters kp = new KexParameters();
public PacketKexInit(byte payload[], int off, int len) throws IOException {
this.payload = new byte[len];
System.arraycopy(payload, off, this.payload, 0, len);
TypesReader tr = new TypesReader(payload, off, len);
int packet_type = tr.readByte();
if (packet_type != Packets.SSH_MSG_KEXINIT)
throw new IOException("This is not a KexInitPacket! ("
+ packet_type + ")");
kp.cookie = tr.readBytes(16);
kp.kex_algorithms = tr.readNameList();
kp.server_host_key_algorithms = tr.readNameList();
kp.encryption_algorithms_client_to_server = tr.readNameList();
kp.encryption_algorithms_server_to_client = tr.readNameList();
kp.mac_algorithms_client_to_server = tr.readNameList();
kp.mac_algorithms_server_to_client = tr.readNameList();
kp.compression_algorithms_client_to_server = tr.readNameList();
kp.compression_algorithms_server_to_client = tr.readNameList();
kp.languages_client_to_server = tr.readNameList();
kp.languages_server_to_client = tr.readNameList();
kp.first_kex_packet_follows = tr.readBoolean();
kp.reserved_field1 = tr.readUINT32();
if (tr.remain() != 0)
throw new IOException("Padding in KexInitPacket!");
}
public PacketKexInit(CryptoWishList cwl, SecureRandom rnd) {
kp.cookie = new byte[16];
rnd.nextBytes(kp.cookie);
kp.kex_algorithms = cwl.kexAlgorithms;
kp.server_host_key_algorithms = cwl.serverHostKeyAlgorithms;
kp.encryption_algorithms_client_to_server = cwl.c2s_enc_algos;
kp.encryption_algorithms_server_to_client = cwl.s2c_enc_algos;
kp.mac_algorithms_client_to_server = cwl.c2s_mac_algos;
kp.mac_algorithms_server_to_client = cwl.s2c_mac_algos;
kp.compression_algorithms_client_to_server = cwl.c2s_comp_algos;
kp.compression_algorithms_server_to_client = cwl.s2c_comp_algos;
kp.languages_client_to_server = new String[] {};
kp.languages_server_to_client = new String[] {};
kp.first_kex_packet_follows = false;
kp.reserved_field1 = 0;
}
public String[] getCompression_algorithms_client_to_server() {
return kp.compression_algorithms_client_to_server;
}
public String[] getCompression_algorithms_server_to_client() {
return kp.compression_algorithms_server_to_client;
}
public byte[] getCookie() {
return kp.cookie;
}
public String[] getEncryption_algorithms_client_to_server() {
return kp.encryption_algorithms_client_to_server;
}
public String[] getEncryption_algorithms_server_to_client() {
return kp.encryption_algorithms_server_to_client;
}
public String[] getKex_algorithms() {
return kp.kex_algorithms;
}
public KexParameters getKexParameters() {
return kp;
}
public String[] getLanguages_client_to_server() {
return kp.languages_client_to_server;
}
public String[] getLanguages_server_to_client() {
return kp.languages_server_to_client;
}
public String[] getMac_algorithms_client_to_server() {
return kp.mac_algorithms_client_to_server;
}
public String[] getMac_algorithms_server_to_client() {
return kp.mac_algorithms_server_to_client;
}
public byte[] getPayload() {
if (payload == null) {
TypesWriter tw = new TypesWriter();
tw.writeByte(Packets.SSH_MSG_KEXINIT);
tw.writeBytes(kp.cookie, 0, 16);
tw.writeNameList(kp.kex_algorithms);
tw.writeNameList(kp.server_host_key_algorithms);
tw.writeNameList(kp.encryption_algorithms_client_to_server);
tw.writeNameList(kp.encryption_algorithms_server_to_client);
tw.writeNameList(kp.mac_algorithms_client_to_server);
tw.writeNameList(kp.mac_algorithms_server_to_client);
tw.writeNameList(kp.compression_algorithms_client_to_server);
tw.writeNameList(kp.compression_algorithms_server_to_client);
tw.writeNameList(kp.languages_client_to_server);
tw.writeNameList(kp.languages_server_to_client);
tw.writeBoolean(kp.first_kex_packet_follows);
tw.writeUINT32(kp.reserved_field1);
payload = tw.getBytes();
}
return payload;
}
public int getReserved_field1() {
return kp.reserved_field1;
}
public String[] getServer_host_key_algorithms() {
return kp.server_host_key_algorithms;
}
public boolean isFirst_kex_packet_follows() {
return kp.first_kex_packet_follows;
}
}
| 07pratik-myssh | src/com/trilead/ssh2/packets/PacketKexInit.java | Java | gpl3 | 4,736 |
package com.trilead.ssh2.packets;
import java.io.IOException;
import java.math.BigInteger;
/**
* PacketKexDhGexGroup.
*
* @author Christian Plattner, plattner@trilead.com
* @version $Id: PacketKexDhGexGroup.java,v 1.1 2007/10/15 12:49:55 cplattne Exp
* $
*/
public class PacketKexDhGexGroup {
byte[] payload;
BigInteger p;
BigInteger g;
public PacketKexDhGexGroup(byte payload[], int off, int len)
throws IOException {
this.payload = new byte[len];
System.arraycopy(payload, off, this.payload, 0, len);
TypesReader tr = new TypesReader(payload, off, len);
int packet_type = tr.readByte();
if (packet_type != Packets.SSH_MSG_KEX_DH_GEX_GROUP)
throw new IllegalArgumentException(
"This is not a SSH_MSG_KEX_DH_GEX_GROUP! (" + packet_type
+ ")");
p = tr.readMPINT();
g = tr.readMPINT();
if (tr.remain() != 0)
throw new IOException("PADDING IN SSH_MSG_KEX_DH_GEX_GROUP!");
}
public BigInteger getG() {
return g;
}
public BigInteger getP() {
return p;
}
}
| 07pratik-myssh | src/com/trilead/ssh2/packets/PacketKexDhGexGroup.java | Java | gpl3 | 1,075 |
package com.trilead.ssh2.packets;
/**
* PacketSessionStartShell.
*
* @author Christian Plattner, plattner@trilead.com
* @version $Id: PacketSessionStartShell.java,v 1.1 2007/10/15 12:49:55 cplattne
* Exp $
*/
public class PacketSessionStartShell {
byte[] payload;
public int recipientChannelID;
public boolean wantReply;
public PacketSessionStartShell(int recipientChannelID, boolean wantReply) {
this.recipientChannelID = recipientChannelID;
this.wantReply = wantReply;
}
public byte[] getPayload() {
if (payload == null) {
TypesWriter tw = new TypesWriter();
tw.writeByte(Packets.SSH_MSG_CHANNEL_REQUEST);
tw.writeUINT32(recipientChannelID);
tw.writeString("shell");
tw.writeBoolean(wantReply);
payload = tw.getBytes();
}
return payload;
}
}
| 07pratik-myssh | src/com/trilead/ssh2/packets/PacketSessionStartShell.java | Java | gpl3 | 831 |
package com.trilead.ssh2.packets;
import com.trilead.ssh2.DHGexParameters;
/**
* PacketKexDhGexRequest.
*
* @author Christian Plattner, plattner@trilead.com
* @version $Id: PacketKexDhGexRequest.java,v 1.1 2007/10/15 12:49:55 cplattne
* Exp $
*/
public class PacketKexDhGexRequest {
byte[] payload;
int min;
int n;
int max;
public PacketKexDhGexRequest(DHGexParameters para) {
this.min = para.getMin_group_len();
this.n = para.getPref_group_len();
this.max = para.getMax_group_len();
}
public byte[] getPayload() {
if (payload == null) {
TypesWriter tw = new TypesWriter();
tw.writeByte(Packets.SSH_MSG_KEX_DH_GEX_REQUEST);
tw.writeUINT32(min);
tw.writeUINT32(n);
tw.writeUINT32(max);
payload = tw.getBytes();
}
return payload;
}
}
| 07pratik-myssh | src/com/trilead/ssh2/packets/PacketKexDhGexRequest.java | Java | gpl3 | 827 |
package com.trilead.ssh2.packets;
import java.math.BigInteger;
/**
* PacketKexDHInit.
*
* @author Christian Plattner, plattner@trilead.com
* @version $Id: PacketKexDHInit.java,v 1.1 2007/10/15 12:49:55 cplattne Exp $
*/
public class PacketKexDHInit {
byte[] payload;
BigInteger e;
public PacketKexDHInit(BigInteger e) {
this.e = e;
}
public byte[] getPayload() {
if (payload == null) {
TypesWriter tw = new TypesWriter();
tw.writeByte(Packets.SSH_MSG_KEXDH_INIT);
tw.writeMPInt(e);
payload = tw.getBytes();
}
return payload;
}
}
| 07pratik-myssh | src/com/trilead/ssh2/packets/PacketKexDHInit.java | Java | gpl3 | 595 |
package com.trilead.ssh2.packets;
import java.io.IOException;
import java.math.BigInteger;
/**
* PacketKexDhGexReply.
*
* @author Christian Plattner, plattner@trilead.com
* @version $Id: PacketKexDhGexReply.java,v 1.1 2007/10/15 12:49:55 cplattne Exp
* $
*/
public class PacketKexDhGexReply {
byte[] payload;
byte[] hostKey;
BigInteger f;
byte[] signature;
public PacketKexDhGexReply(byte payload[], int off, int len)
throws IOException {
this.payload = new byte[len];
System.arraycopy(payload, off, this.payload, 0, len);
TypesReader tr = new TypesReader(payload, off, len);
int packet_type = tr.readByte();
if (packet_type != Packets.SSH_MSG_KEX_DH_GEX_REPLY)
throw new IOException("This is not a SSH_MSG_KEX_DH_GEX_REPLY! ("
+ packet_type + ")");
hostKey = tr.readByteString();
f = tr.readMPINT();
signature = tr.readByteString();
if (tr.remain() != 0)
throw new IOException("PADDING IN SSH_MSG_KEX_DH_GEX_REPLY!");
}
public BigInteger getF() {
return f;
}
public byte[] getHostKey() {
return hostKey;
}
public byte[] getSignature() {
return signature;
}
}
| 07pratik-myssh | src/com/trilead/ssh2/packets/PacketKexDhGexReply.java | Java | gpl3 | 1,190 |
package com.trilead.ssh2.packets;
/**
* Packets.
*
* @author Christian Plattner, plattner@trilead.com
* @version $Id: Packets.java,v 1.1 2007/10/15 12:49:55 cplattne Exp $
*/
public class Packets {
public static final int SSH_MSG_DISCONNECT = 1;
public static final int SSH_MSG_IGNORE = 2;
public static final int SSH_MSG_UNIMPLEMENTED = 3;
public static final int SSH_MSG_DEBUG = 4;
public static final int SSH_MSG_SERVICE_REQUEST = 5;
public static final int SSH_MSG_SERVICE_ACCEPT = 6;
public static final int SSH_MSG_KEXINIT = 20;
public static final int SSH_MSG_NEWKEYS = 21;
public static final int SSH_MSG_KEXDH_INIT = 30;
public static final int SSH_MSG_KEXDH_REPLY = 31;
public static final int SSH_MSG_KEX_DH_GEX_REQUEST_OLD = 30;
public static final int SSH_MSG_KEX_DH_GEX_REQUEST = 34;
public static final int SSH_MSG_KEX_DH_GEX_GROUP = 31;
public static final int SSH_MSG_KEX_DH_GEX_INIT = 32;
public static final int SSH_MSG_KEX_DH_GEX_REPLY = 33;
public static final int SSH_MSG_USERAUTH_REQUEST = 50;
public static final int SSH_MSG_USERAUTH_FAILURE = 51;
public static final int SSH_MSG_USERAUTH_SUCCESS = 52;
public static final int SSH_MSG_USERAUTH_BANNER = 53;
public static final int SSH_MSG_USERAUTH_INFO_REQUEST = 60;
public static final int SSH_MSG_USERAUTH_INFO_RESPONSE = 61;
public static final int SSH_MSG_GLOBAL_REQUEST = 80;
public static final int SSH_MSG_REQUEST_SUCCESS = 81;
public static final int SSH_MSG_REQUEST_FAILURE = 82;
public static final int SSH_MSG_CHANNEL_OPEN = 90;
public static final int SSH_MSG_CHANNEL_OPEN_CONFIRMATION = 91;
public static final int SSH_MSG_CHANNEL_OPEN_FAILURE = 92;
public static final int SSH_MSG_CHANNEL_WINDOW_ADJUST = 93;
public static final int SSH_MSG_CHANNEL_DATA = 94;
public static final int SSH_MSG_CHANNEL_EXTENDED_DATA = 95;
public static final int SSH_MSG_CHANNEL_EOF = 96;
public static final int SSH_MSG_CHANNEL_CLOSE = 97;
public static final int SSH_MSG_CHANNEL_REQUEST = 98;
public static final int SSH_MSG_CHANNEL_SUCCESS = 99;
public static final int SSH_MSG_CHANNEL_FAILURE = 100;
public static final int SSH_EXTENDED_DATA_STDERR = 1;
public static final int SSH_DISCONNECT_HOST_NOT_ALLOWED_TO_CONNECT = 1;
public static final int SSH_DISCONNECT_PROTOCOL_ERROR = 2;
public static final int SSH_DISCONNECT_KEY_EXCHANGE_FAILED = 3;
public static final int SSH_DISCONNECT_RESERVED = 4;
public static final int SSH_DISCONNECT_MAC_ERROR = 5;
public static final int SSH_DISCONNECT_COMPRESSION_ERROR = 6;
public static final int SSH_DISCONNECT_SERVICE_NOT_AVAILABLE = 7;
public static final int SSH_DISCONNECT_PROTOCOL_VERSION_NOT_SUPPORTED = 8;
public static final int SSH_DISCONNECT_HOST_KEY_NOT_VERIFIABLE = 9;
public static final int SSH_DISCONNECT_CONNECTION_LOST = 10;
public static final int SSH_DISCONNECT_BY_APPLICATION = 11;
public static final int SSH_DISCONNECT_TOO_MANY_CONNECTIONS = 12;
public static final int SSH_DISCONNECT_AUTH_CANCELLED_BY_USER = 13;
public static final int SSH_DISCONNECT_NO_MORE_AUTH_METHODS_AVAILABLE = 14;
public static final int SSH_DISCONNECT_ILLEGAL_USER_NAME = 15;
public static final int SSH_OPEN_ADMINISTRATIVELY_PROHIBITED = 1;
public static final int SSH_OPEN_CONNECT_FAILED = 2;
public static final int SSH_OPEN_UNKNOWN_CHANNEL_TYPE = 3;
public static final int SSH_OPEN_RESOURCE_SHORTAGE = 4;
private static final String[] reverseNames = new String[101];
static {
reverseNames[1] = "SSH_MSG_DISCONNECT";
reverseNames[2] = "SSH_MSG_IGNORE";
reverseNames[3] = "SSH_MSG_UNIMPLEMENTED";
reverseNames[4] = "SSH_MSG_DEBUG";
reverseNames[5] = "SSH_MSG_SERVICE_REQUEST";
reverseNames[6] = "SSH_MSG_SERVICE_ACCEPT";
reverseNames[20] = "SSH_MSG_KEXINIT";
reverseNames[21] = "SSH_MSG_NEWKEYS";
reverseNames[30] = "SSH_MSG_KEXDH_INIT";
reverseNames[31] = "SSH_MSG_KEXDH_REPLY/SSH_MSG_KEX_DH_GEX_GROUP";
reverseNames[32] = "SSH_MSG_KEX_DH_GEX_INIT";
reverseNames[33] = "SSH_MSG_KEX_DH_GEX_REPLY";
reverseNames[34] = "SSH_MSG_KEX_DH_GEX_REQUEST";
reverseNames[50] = "SSH_MSG_USERAUTH_REQUEST";
reverseNames[51] = "SSH_MSG_USERAUTH_FAILURE";
reverseNames[52] = "SSH_MSG_USERAUTH_SUCCESS";
reverseNames[53] = "SSH_MSG_USERAUTH_BANNER";
reverseNames[60] = "SSH_MSG_USERAUTH_INFO_REQUEST";
reverseNames[61] = "SSH_MSG_USERAUTH_INFO_RESPONSE";
reverseNames[80] = "SSH_MSG_GLOBAL_REQUEST";
reverseNames[81] = "SSH_MSG_REQUEST_SUCCESS";
reverseNames[82] = "SSH_MSG_REQUEST_FAILURE";
reverseNames[90] = "SSH_MSG_CHANNEL_OPEN";
reverseNames[91] = "SSH_MSG_CHANNEL_OPEN_CONFIRMATION";
reverseNames[92] = "SSH_MSG_CHANNEL_OPEN_FAILURE";
reverseNames[93] = "SSH_MSG_CHANNEL_WINDOW_ADJUST";
reverseNames[94] = "SSH_MSG_CHANNEL_DATA";
reverseNames[95] = "SSH_MSG_CHANNEL_EXTENDED_DATA";
reverseNames[96] = "SSH_MSG_CHANNEL_EOF";
reverseNames[97] = "SSH_MSG_CHANNEL_CLOSE";
reverseNames[98] = "SSH_MSG_CHANNEL_REQUEST";
reverseNames[99] = "SSH_MSG_CHANNEL_SUCCESS";
reverseNames[100] = "SSH_MSG_CHANNEL_FAILURE";
}
public static final String getMessageName(int type) {
String res = null;
if ((type >= 0) && (type < reverseNames.length)) {
res = reverseNames[type];
}
return (res == null) ? ("UNKNOWN MSG " + type) : res;
}
// public static final void debug(String tag, byte[] msg)
// {
// System.err.println(tag + " Type: " + msg[0] + ", LEN: " + msg.length);
//
// for (int i = 0; i < msg.length; i++)
// {
// if (((msg[i] >= 'a') && (msg[i] <= 'z')) || ((msg[i] >= 'A') && (msg[i]
// <= 'Z'))
// || ((msg[i] >= '0') && (msg[i] <= '9')) || (msg[i] == ' '))
// System.err.print((char) msg[i]);
// else
// System.err.print(".");
// }
// System.err.println();
// System.err.flush();
// }
}
| 07pratik-myssh | src/com/trilead/ssh2/packets/Packets.java | Java | gpl3 | 5,920 |
package com.trilead.ssh2.packets;
/**
* PacketChannelTrileadPing.
*
* @author Christian Plattner, plattner@trilead.com
* @version $Id: PacketChannelTrileadPing.java,v 1.1 2008/03/03 07:01:36
* cplattne Exp $
*/
public class PacketChannelTrileadPing {
byte[] payload;
public int recipientChannelID;
public PacketChannelTrileadPing(int recipientChannelID) {
this.recipientChannelID = recipientChannelID;
}
public byte[] getPayload() {
if (payload == null) {
TypesWriter tw = new TypesWriter();
tw.writeByte(Packets.SSH_MSG_CHANNEL_REQUEST);
tw.writeUINT32(recipientChannelID);
tw.writeString("trilead-ping");
tw.writeBoolean(true);
payload = tw.getBytes();
}
return payload;
}
}
| 07pratik-myssh | src/com/trilead/ssh2/packets/PacketChannelTrileadPing.java | Java | gpl3 | 759 |
package com.trilead.ssh2.packets;
/**
* PacketSessionExecCommand.
*
* @author Christian Plattner, plattner@trilead.com
* @version $Id: PacketSessionExecCommand.java,v 1.1 2007/10/15 12:49:55
* cplattne Exp $
*/
public class PacketSessionExecCommand {
byte[] payload;
public int recipientChannelID;
public boolean wantReply;
public String command;
public PacketSessionExecCommand(int recipientChannelID, boolean wantReply,
String command) {
this.recipientChannelID = recipientChannelID;
this.wantReply = wantReply;
this.command = command;
}
public byte[] getPayload() {
if (payload == null) {
TypesWriter tw = new TypesWriter();
tw.writeByte(Packets.SSH_MSG_CHANNEL_REQUEST);
tw.writeUINT32(recipientChannelID);
tw.writeString("exec");
tw.writeBoolean(wantReply);
tw.writeString(command);
payload = tw.getBytes();
}
return payload;
}
}
| 07pratik-myssh | src/com/trilead/ssh2/packets/PacketSessionExecCommand.java | Java | gpl3 | 935 |
package com.trilead.ssh2.packets;
/**
* PacketUserauthInfoResponse.
*
* @author Christian Plattner, plattner@trilead.com
* @version $Id: PacketUserauthInfoResponse.java,v 1.1 2007/10/15 12:49:55
* cplattne Exp $
*/
public class PacketUserauthInfoResponse {
byte[] payload;
String[] responses;
public PacketUserauthInfoResponse(String[] responses) {
this.responses = responses;
}
public byte[] getPayload() {
if (payload == null) {
TypesWriter tw = new TypesWriter();
tw.writeByte(Packets.SSH_MSG_USERAUTH_INFO_RESPONSE);
tw.writeUINT32(responses.length);
for (int i = 0; i < responses.length; i++)
tw.writeString(responses[i]);
payload = tw.getBytes();
}
return payload;
}
}
| 07pratik-myssh | src/com/trilead/ssh2/packets/PacketUserauthInfoResponse.java | Java | gpl3 | 760 |
package com.trilead.ssh2.packets;
/**
* PacketGlobalCancelForwardRequest.
*
* @author Christian Plattner, plattner@trilead.com
* @version $Id: PacketGlobalCancelForwardRequest.java,v 1.1 2007/10/15 12:49:55
* cplattne Exp $
*/
public class PacketGlobalCancelForwardRequest {
byte[] payload;
public boolean wantReply;
public String bindAddress;
public int bindPort;
public PacketGlobalCancelForwardRequest(boolean wantReply,
String bindAddress, int bindPort) {
this.wantReply = wantReply;
this.bindAddress = bindAddress;
this.bindPort = bindPort;
}
public byte[] getPayload() {
if (payload == null) {
TypesWriter tw = new TypesWriter();
tw.writeByte(Packets.SSH_MSG_GLOBAL_REQUEST);
tw.writeString("cancel-tcpip-forward");
tw.writeBoolean(wantReply);
tw.writeString(bindAddress);
tw.writeUINT32(bindPort);
payload = tw.getBytes();
}
return payload;
}
}
| 07pratik-myssh | src/com/trilead/ssh2/packets/PacketGlobalCancelForwardRequest.java | Java | gpl3 | 956 |
package com.trilead.ssh2.packets;
import java.io.IOException;
/**
* PacketChannelWindowAdjust.
*
* @author Christian Plattner, plattner@trilead.com
* @version $Id: PacketChannelWindowAdjust.java,v 1.1 2007/10/15 12:49:55
* cplattne Exp $
*/
public class PacketChannelWindowAdjust {
byte[] payload;
public int recipientChannelID;
public int windowChange;
public PacketChannelWindowAdjust(byte payload[], int off, int len)
throws IOException {
this.payload = new byte[len];
System.arraycopy(payload, off, this.payload, 0, len);
TypesReader tr = new TypesReader(payload, off, len);
int packet_type = tr.readByte();
if (packet_type != Packets.SSH_MSG_CHANNEL_WINDOW_ADJUST)
throw new IOException(
"This is not a SSH_MSG_CHANNEL_WINDOW_ADJUST! ("
+ packet_type + ")");
recipientChannelID = tr.readUINT32();
windowChange = tr.readUINT32();
if (tr.remain() != 0)
throw new IOException(
"Padding in SSH_MSG_CHANNEL_WINDOW_ADJUST packet!");
}
public PacketChannelWindowAdjust(int recipientChannelID, int windowChange) {
this.recipientChannelID = recipientChannelID;
this.windowChange = windowChange;
}
public byte[] getPayload() {
if (payload == null) {
TypesWriter tw = new TypesWriter();
tw.writeByte(Packets.SSH_MSG_CHANNEL_WINDOW_ADJUST);
tw.writeUINT32(recipientChannelID);
tw.writeUINT32(windowChange);
payload = tw.getBytes();
}
return payload;
}
}
| 07pratik-myssh | src/com/trilead/ssh2/packets/PacketChannelWindowAdjust.java | Java | gpl3 | 1,505 |
package com.trilead.ssh2.packets;
import java.io.IOException;
/**
* PacketServiceRequest.
*
* @author Christian Plattner, plattner@trilead.com
* @version $Id: PacketServiceRequest.java,v 1.1 2007/10/15 12:49:55 cplattne
* Exp $
*/
public class PacketServiceRequest {
byte[] payload;
String serviceName;
public PacketServiceRequest(byte payload[], int off, int len)
throws IOException {
this.payload = new byte[len];
System.arraycopy(payload, off, this.payload, 0, len);
TypesReader tr = new TypesReader(payload, off, len);
int packet_type = tr.readByte();
if (packet_type != Packets.SSH_MSG_SERVICE_REQUEST)
throw new IOException("This is not a SSH_MSG_SERVICE_REQUEST! ("
+ packet_type + ")");
serviceName = tr.readString();
if (tr.remain() != 0)
throw new IOException("Padding in SSH_MSG_SERVICE_REQUEST packet!");
}
public PacketServiceRequest(String serviceName) {
this.serviceName = serviceName;
}
public byte[] getPayload() {
if (payload == null) {
TypesWriter tw = new TypesWriter();
tw.writeByte(Packets.SSH_MSG_SERVICE_REQUEST);
tw.writeString(serviceName);
payload = tw.getBytes();
}
return payload;
}
}
| 07pratik-myssh | src/com/trilead/ssh2/packets/PacketServiceRequest.java | Java | gpl3 | 1,246 |
package com.trilead.ssh2.packets;
/**
* PacketSessionX11Request.
*
* @author Christian Plattner, plattner@trilead.com
* @version $Id: PacketSessionX11Request.java,v 1.1 2007/10/15 12:49:55 cplattne
* Exp $
*/
public class PacketSessionX11Request {
byte[] payload;
public int recipientChannelID;
public boolean wantReply;
public boolean singleConnection;
String x11AuthenticationProtocol;
String x11AuthenticationCookie;
int x11ScreenNumber;
public PacketSessionX11Request(int recipientChannelID, boolean wantReply,
boolean singleConnection, String x11AuthenticationProtocol,
String x11AuthenticationCookie, int x11ScreenNumber) {
this.recipientChannelID = recipientChannelID;
this.wantReply = wantReply;
this.singleConnection = singleConnection;
this.x11AuthenticationProtocol = x11AuthenticationProtocol;
this.x11AuthenticationCookie = x11AuthenticationCookie;
this.x11ScreenNumber = x11ScreenNumber;
}
public byte[] getPayload() {
if (payload == null) {
TypesWriter tw = new TypesWriter();
tw.writeByte(Packets.SSH_MSG_CHANNEL_REQUEST);
tw.writeUINT32(recipientChannelID);
tw.writeString("x11-req");
tw.writeBoolean(wantReply);
tw.writeBoolean(singleConnection);
tw.writeString(x11AuthenticationProtocol);
tw.writeString(x11AuthenticationCookie);
tw.writeUINT32(x11ScreenNumber);
payload = tw.getBytes();
}
return payload;
}
}
| 07pratik-myssh | src/com/trilead/ssh2/packets/PacketSessionX11Request.java | Java | gpl3 | 1,468 |
package com.trilead.ssh2.packets;
/**
* PacketOpenDirectTCPIPChannel.
*
* @author Christian Plattner, plattner@trilead.com
* @version $Id: PacketOpenDirectTCPIPChannel.java,v 1.1 2007/10/15 12:49:55
* cplattne Exp $
*/
public class PacketOpenDirectTCPIPChannel {
byte[] payload;
int channelID;
int initialWindowSize;
int maxPacketSize;
String host_to_connect;
int port_to_connect;
String originator_IP_address;
int originator_port;
public PacketOpenDirectTCPIPChannel(int channelID, int initialWindowSize,
int maxPacketSize, String host_to_connect, int port_to_connect,
String originator_IP_address, int originator_port) {
this.channelID = channelID;
this.initialWindowSize = initialWindowSize;
this.maxPacketSize = maxPacketSize;
this.host_to_connect = host_to_connect;
this.port_to_connect = port_to_connect;
this.originator_IP_address = originator_IP_address;
this.originator_port = originator_port;
}
public byte[] getPayload() {
if (payload == null) {
TypesWriter tw = new TypesWriter();
tw.writeByte(Packets.SSH_MSG_CHANNEL_OPEN);
tw.writeString("direct-tcpip");
tw.writeUINT32(channelID);
tw.writeUINT32(initialWindowSize);
tw.writeUINT32(maxPacketSize);
tw.writeString(host_to_connect);
tw.writeUINT32(port_to_connect);
tw.writeString(originator_IP_address);
tw.writeUINT32(originator_port);
payload = tw.getBytes();
}
return payload;
}
}
| 07pratik-myssh | src/com/trilead/ssh2/packets/PacketOpenDirectTCPIPChannel.java | Java | gpl3 | 1,493 |
package com.trilead.ssh2.packets;
/**
* PacketGlobalForwardRequest.
*
* @author Christian Plattner, plattner@trilead.com
* @version $Id: PacketGlobalForwardRequest.java,v 1.1 2007/10/15 12:49:55
* cplattne Exp $
*/
public class PacketGlobalForwardRequest {
byte[] payload;
public boolean wantReply;
public String bindAddress;
public int bindPort;
public PacketGlobalForwardRequest(boolean wantReply, String bindAddress,
int bindPort) {
this.wantReply = wantReply;
this.bindAddress = bindAddress;
this.bindPort = bindPort;
}
public byte[] getPayload() {
if (payload == null) {
TypesWriter tw = new TypesWriter();
tw.writeByte(Packets.SSH_MSG_GLOBAL_REQUEST);
tw.writeString("tcpip-forward");
tw.writeBoolean(wantReply);
tw.writeString(bindAddress);
tw.writeUINT32(bindPort);
payload = tw.getBytes();
}
return payload;
}
}
| 07pratik-myssh | src/com/trilead/ssh2/packets/PacketGlobalForwardRequest.java | Java | gpl3 | 925 |
package com.trilead.ssh2.packets;
import java.math.BigInteger;
/**
* PacketKexDhGexInit.
*
* @author Christian Plattner, plattner@trilead.com
* @version $Id: PacketKexDhGexInit.java,v 1.1 2007/10/15 12:49:55 cplattne Exp
* $
*/
public class PacketKexDhGexInit {
byte[] payload;
BigInteger e;
public PacketKexDhGexInit(BigInteger e) {
this.e = e;
}
public byte[] getPayload() {
if (payload == null) {
TypesWriter tw = new TypesWriter();
tw.writeByte(Packets.SSH_MSG_KEX_DH_GEX_INIT);
tw.writeMPInt(e);
payload = tw.getBytes();
}
return payload;
}
}
| 07pratik-myssh | src/com/trilead/ssh2/packets/PacketKexDhGexInit.java | Java | gpl3 | 625 |
package com.trilead.ssh2.packets;
public class PacketSessionPtyResize {
byte[] payload;
public int recipientChannelID;
public int width;
public int height;
public int pixelWidth;
public int pixelHeight;
public PacketSessionPtyResize(int recipientChannelID, int width,
int height, int pixelWidth, int pixelHeight) {
this.recipientChannelID = recipientChannelID;
this.width = width;
this.height = height;
this.pixelWidth = pixelWidth;
this.pixelHeight = pixelHeight;
}
public byte[] getPayload() {
if (payload == null) {
TypesWriter tw = new TypesWriter();
tw.writeByte(Packets.SSH_MSG_CHANNEL_REQUEST);
tw.writeUINT32(recipientChannelID);
tw.writeString("window-change");
tw.writeBoolean(false);
tw.writeUINT32(width);
tw.writeUINT32(height);
tw.writeUINT32(pixelWidth);
tw.writeUINT32(pixelHeight);
payload = tw.getBytes();
}
return payload;
}
}
| 07pratik-myssh | src/com/trilead/ssh2/packets/PacketSessionPtyResize.java | Java | gpl3 | 910 |
package com.trilead.ssh2.packets;
import java.io.IOException;
/**
* PacketDisconnect.
*
* @author Christian Plattner, plattner@trilead.com
* @version $Id: PacketDisconnect.java,v 1.2 2008/04/01 12:38:09 cplattne Exp $
*/
public class PacketDisconnect {
byte[] payload;
int reason;
String desc;
String lang;
public PacketDisconnect(byte payload[], int off, int len)
throws IOException {
this.payload = new byte[len];
System.arraycopy(payload, off, this.payload, 0, len);
TypesReader tr = new TypesReader(payload, off, len);
int packet_type = tr.readByte();
if (packet_type != Packets.SSH_MSG_DISCONNECT)
throw new IOException("This is not a Disconnect Packet! ("
+ packet_type + ")");
reason = tr.readUINT32();
desc = tr.readString();
lang = tr.readString();
}
public PacketDisconnect(int reason, String desc, String lang) {
this.reason = reason;
this.desc = desc;
this.lang = lang;
}
public byte[] getPayload() {
if (payload == null) {
TypesWriter tw = new TypesWriter();
tw.writeByte(Packets.SSH_MSG_DISCONNECT);
tw.writeUINT32(reason);
tw.writeString(desc);
tw.writeString(lang);
payload = tw.getBytes();
}
return payload;
}
}
| 07pratik-myssh | src/com/trilead/ssh2/packets/PacketDisconnect.java | Java | gpl3 | 1,265 |
package com.trilead.ssh2.packets;
/**
* PacketSessionSubsystemRequest.
*
* @author Christian Plattner, plattner@trilead.com
* @version $Id: PacketSessionSubsystemRequest.java,v 1.1 2007/10/15 12:49:55
* cplattne Exp $
*/
public class PacketSessionSubsystemRequest {
byte[] payload;
public int recipientChannelID;
public boolean wantReply;
public String subsystem;
public PacketSessionSubsystemRequest(int recipientChannelID,
boolean wantReply, String subsystem) {
this.recipientChannelID = recipientChannelID;
this.wantReply = wantReply;
this.subsystem = subsystem;
}
public byte[] getPayload() {
if (payload == null) {
TypesWriter tw = new TypesWriter();
tw.writeByte(Packets.SSH_MSG_CHANNEL_REQUEST);
tw.writeUINT32(recipientChannelID);
tw.writeString("subsystem");
tw.writeBoolean(wantReply);
tw.writeString(subsystem);
payload = tw.getBytes();
tw.getBytes(payload);
}
return payload;
}
}
| 07pratik-myssh | src/com/trilead/ssh2/packets/PacketSessionSubsystemRequest.java | Java | gpl3 | 996 |
package com.trilead.ssh2.packets;
import java.io.IOException;
/**
* PacketServiceAccept.
*
* @author Christian Plattner, plattner@trilead.com
* @version $Id: PacketServiceAccept.java,v 1.2 2008/04/01 12:38:09 cplattne Exp
* $
*/
public class PacketServiceAccept {
byte[] payload;
String serviceName;
public PacketServiceAccept(byte payload[], int off, int len)
throws IOException {
this.payload = new byte[len];
System.arraycopy(payload, off, this.payload, 0, len);
TypesReader tr = new TypesReader(payload, off, len);
int packet_type = tr.readByte();
if (packet_type != Packets.SSH_MSG_SERVICE_ACCEPT)
throw new IOException("This is not a SSH_MSG_SERVICE_ACCEPT! ("
+ packet_type + ")");
/*
* Be clever in case the server is not. Some servers seem to violate
* RFC4253
*/
if (tr.remain() > 0) {
serviceName = tr.readString();
} else {
serviceName = "";
}
if (tr.remain() != 0)
throw new IOException("Padding in SSH_MSG_SERVICE_ACCEPT packet!");
}
public PacketServiceAccept(String serviceName) {
this.serviceName = serviceName;
}
public byte[] getPayload() {
if (payload == null) {
TypesWriter tw = new TypesWriter();
tw.writeByte(Packets.SSH_MSG_SERVICE_ACCEPT);
tw.writeString(serviceName);
payload = tw.getBytes();
}
return payload;
}
}
| 07pratik-myssh | src/com/trilead/ssh2/packets/PacketServiceAccept.java | Java | gpl3 | 1,404 |
package com.trilead.ssh2.packets;
import java.io.IOException;
/**
* PacketUserauthBanner.
*
* @author Christian Plattner, plattner@trilead.com
* @version $Id: PacketUserauthBanner.java,v 1.1 2007/10/15 12:49:55 cplattne
* Exp $
*/
public class PacketUserauthBanner {
byte[] payload;
String message;
String language;
public PacketUserauthBanner(byte payload[], int off, int len)
throws IOException {
this.payload = new byte[len];
System.arraycopy(payload, off, this.payload, 0, len);
TypesReader tr = new TypesReader(payload, off, len);
int packet_type = tr.readByte();
if (packet_type != Packets.SSH_MSG_USERAUTH_BANNER)
throw new IOException("This is not a SSH_MSG_USERAUTH_BANNER! ("
+ packet_type + ")");
message = tr.readString("UTF-8");
language = tr.readString();
if (tr.remain() != 0)
throw new IOException("Padding in SSH_MSG_USERAUTH_REQUEST packet!");
}
public PacketUserauthBanner(String message, String language) {
this.message = message;
this.language = language;
}
public String getBanner() {
return message;
}
public byte[] getPayload() {
if (payload == null) {
TypesWriter tw = new TypesWriter();
tw.writeByte(Packets.SSH_MSG_USERAUTH_BANNER);
tw.writeString(message);
tw.writeString(language);
payload = tw.getBytes();
}
return payload;
}
}
| 07pratik-myssh | src/com/trilead/ssh2/packets/PacketUserauthBanner.java | Java | gpl3 | 1,411 |
package com.trilead.ssh2.packets;
import java.io.IOException;
/**
* PacketNewKeys.
*
* @author Christian Plattner, plattner@trilead.com
* @version $Id: PacketNewKeys.java,v 1.1 2007/10/15 12:49:55 cplattne Exp $
*/
public class PacketNewKeys {
byte[] payload;
public PacketNewKeys() {
}
public PacketNewKeys(byte payload[], int off, int len) throws IOException {
this.payload = new byte[len];
System.arraycopy(payload, off, this.payload, 0, len);
TypesReader tr = new TypesReader(payload, off, len);
int packet_type = tr.readByte();
if (packet_type != Packets.SSH_MSG_NEWKEYS)
throw new IOException("This is not a SSH_MSG_NEWKEYS! ("
+ packet_type + ")");
if (tr.remain() != 0)
throw new IOException("Padding in SSH_MSG_NEWKEYS packet!");
}
public byte[] getPayload() {
if (payload == null) {
TypesWriter tw = new TypesWriter();
tw.writeByte(Packets.SSH_MSG_NEWKEYS);
payload = tw.getBytes();
}
return payload;
}
}
| 07pratik-myssh | src/com/trilead/ssh2/packets/PacketNewKeys.java | Java | gpl3 | 1,016 |
package com.trilead.ssh2.packets;
/**
* PacketSessionPtyRequest.
*
* @author Christian Plattner, plattner@trilead.com
* @version $Id: PacketSessionPtyRequest.java,v 1.1 2007/10/15 12:49:55 cplattne
* Exp $
*/
public class PacketSessionPtyRequest {
byte[] payload;
public int recipientChannelID;
public boolean wantReply;
public String term;
public int character_width;
public int character_height;
public int pixel_width;
public int pixel_height;
public byte[] terminal_modes;
public PacketSessionPtyRequest(int recipientChannelID, boolean wantReply,
String term, int character_width, int character_height,
int pixel_width, int pixel_height, byte[] terminal_modes) {
this.recipientChannelID = recipientChannelID;
this.wantReply = wantReply;
this.term = term;
this.character_width = character_width;
this.character_height = character_height;
this.pixel_width = pixel_width;
this.pixel_height = pixel_height;
this.terminal_modes = terminal_modes;
}
public byte[] getPayload() {
if (payload == null) {
TypesWriter tw = new TypesWriter();
tw.writeByte(Packets.SSH_MSG_CHANNEL_REQUEST);
tw.writeUINT32(recipientChannelID);
tw.writeString("pty-req");
tw.writeBoolean(wantReply);
tw.writeString(term);
tw.writeUINT32(character_width);
tw.writeUINT32(character_height);
tw.writeUINT32(pixel_width);
tw.writeUINT32(pixel_height);
tw.writeString(terminal_modes, 0, terminal_modes.length);
payload = tw.getBytes();
}
return payload;
}
}
| 07pratik-myssh | src/com/trilead/ssh2/packets/PacketSessionPtyRequest.java | Java | gpl3 | 1,577 |
package com.trilead.ssh2.packets;
import java.io.IOException;
import java.math.BigInteger;
/**
* PacketKexDHReply.
*
* @author Christian Plattner, plattner@trilead.com
* @version $Id: PacketKexDHReply.java,v 1.1 2007/10/15 12:49:55 cplattne Exp $
*/
public class PacketKexDHReply {
byte[] payload;
byte[] hostKey;
BigInteger f;
byte[] signature;
public PacketKexDHReply(byte payload[], int off, int len)
throws IOException {
this.payload = new byte[len];
System.arraycopy(payload, off, this.payload, 0, len);
TypesReader tr = new TypesReader(payload, off, len);
int packet_type = tr.readByte();
if (packet_type != Packets.SSH_MSG_KEXDH_REPLY)
throw new IOException("This is not a SSH_MSG_KEXDH_REPLY! ("
+ packet_type + ")");
hostKey = tr.readByteString();
f = tr.readMPINT();
signature = tr.readByteString();
if (tr.remain() != 0)
throw new IOException("PADDING IN SSH_MSG_KEXDH_REPLY!");
}
public BigInteger getF() {
return f;
}
public byte[] getHostKey() {
return hostKey;
}
public byte[] getSignature() {
return signature;
}
}
| 07pratik-myssh | src/com/trilead/ssh2/packets/PacketKexDHReply.java | Java | gpl3 | 1,150 |
package com.trilead.ssh2;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.security.SecureRandom;
import com.trilead.ssh2.channel.Channel;
import com.trilead.ssh2.channel.ChannelManager;
import com.trilead.ssh2.channel.X11ServerData;
/**
* A <code>Session</code> 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;
}
/**
* 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
* <code>close()</code> 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) {
}
}
}
/**
* Execute a command on the remote machine.
*
* @param cmd
* The command to execute on the remote host.
* @throws IOException
*/
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);
}
/**
* 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 <code>String</code> holding the name of the signal, or
* <code>null</code> if the process exited normally or is still
* running (or if the server forgot to send this information).
*/
public String getExitSignal() {
return cn.getExitSignal();
}
/**
* 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 <code<WaitForCondition</code>
* method).
*
* @return An <code>Integer</code> holding the exit code, or
* <code>null</code> if no exit code is (yet) available.
*/
public Integer getExitStatus() {
return cn.getExitStatus();
}
public InputStream getStderr() {
return cn.getStderrStream();
}
public OutputStream getStdin() {
return cn.getStdinStream();
}
public InputStream getStdout() {
return cn.getStdoutStream();
}
/**
* 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);
}
/**
* Request authentication agent forwarding.
*
* @param agent
* object that implements the callbacks
*
* @throws IOException
* in case of any problem or when the session is closed
*/
public synchronized boolean requestAuthAgentForwarding(
AuthAgentCallback agent) 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.");
}
return cm.requestChannelAgentForwarding(cn, agent);
}
/**
* Basically just a wrapper for lazy people - identical to calling
* <code>requestPTY("dumb", 0, 0, 0, 0, null)</code>.
*
* @throws IOException
*/
public void requestDumbPTY() throws IOException {
requestPTY("dumb", 0, 0, 0, 0, null);
}
/**
* Basically just another wrapper for lazy people - identical to calling
* <code>requestPTY(term, 0, 0, 0, 0, null)</code>.
*
* @throws IOException
*/
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:
* <p>
* <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
* <code>terminal_modes</code>) 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 <code>null</code>)
* @throws IOException
*/
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);
}
/**
* 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
*/
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 */
}
/**
* Inform other side of connection that our PTY has resized.
* <p>
* 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.
*
* @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
*/
public void resizePTY(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.");
}
cm.resizePTY(cn, term_width_characters, term_height_characters,
term_width_pixels, term_height_pixels);
}
/**
* Start a shell on the remote machine.
*
* @throws IOException
*/
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
*/
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 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 > 0 and a timeout occured (TIMEOUT will be set in result
* conditions)</a>
* <li>the underlying channel was closed (CLOSED will be set in result
* conditions)</a>
* </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 <code>Session</code>
* (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, <code>0</code> means no timeout
* @return all bitmask specifying all current conditions that are true
*/
public int waitForCondition(int condition_set, long timeout) {
if (timeout < 0)
throw new IllegalArgumentException("timeout must be non-negative!");
return cm.waitForCondition(cn, timeout, condition_set);
}
/**
* This method blocks until there is more data available on either the
* stdout or stderr InputStream of this <code>Session</code>. 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 <code>Session</code> (otherwise this method may
* block, even though more data is available).
*
* @param timeout
* The (non-negative) timeout in <code>ms</code>. <code>0</code>
* means no timeout, the call may block forever.
* @return <ul>
* <li><code>0</code> if no more data will arrive.</li>
* <li><code>1</code> if more data is available.</li>
* <li><code>-1</code> if a timeout occurred.</li>
* </ul>
*
* @throws IOException
* @deprecated This method has been replaced with a much more powerful
* wait-for-condition interface and therefore acts only as a
* wrapper.
*
*/
@Deprecated
public int waitUntilDataAvailable(long timeout) throws IOException {
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 + ")");
}
}
| 07pratik-myssh | src/com/trilead/ssh2/Session.java | Java | gpl3 | 17,597 |
package com.trilead.ssh2.transport;
/**
* NegotiatedParameters.
*
* @author Christian Plattner, plattner@trilead.com
* @version $Id: NegotiatedParameters.java,v 1.1 2007/10/15 12:49:57 cplattne
* Exp $
*/
public class NegotiatedParameters {
public boolean guessOK;
public String kex_algo;
public String server_host_key_algo;
public String enc_algo_client_to_server;
public String enc_algo_server_to_client;
public String mac_algo_client_to_server;
public String mac_algo_server_to_client;
public String comp_algo_client_to_server;
public String comp_algo_server_to_client;
public String lang_client_to_server;
public String lang_server_to_client;
}
| 07pratik-myssh | src/com/trilead/ssh2/transport/NegotiatedParameters.java | Java | gpl3 | 699 |
package com.trilead.ssh2.transport;
/**
* NegotiateException.
*
* @author Christian Plattner, plattner@trilead.com
* @version $Id: NegotiateException.java,v 1.1 2007/10/15 12:49:56 cplattne Exp
* $
*/
public class NegotiateException extends Exception {
private static final long serialVersionUID = 3689910669428143157L;
}
| 07pratik-myssh | src/com/trilead/ssh2/transport/NegotiateException.java | Java | gpl3 | 352 |
package com.trilead.ssh2.transport;
import java.io.IOException;
/**
* MessageHandler.
*
* @author Christian Plattner, plattner@trilead.com
* @version $Id: MessageHandler.java,v 1.1 2007/10/15 12:49:56 cplattne Exp $
*/
public interface MessageHandler {
public void handleMessage(byte[] msg, int msglen) throws IOException;
}
| 07pratik-myssh | src/com/trilead/ssh2/transport/MessageHandler.java | Java | gpl3 | 347 |
package com.trilead.ssh2.transport;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import com.trilead.ssh2.Connection;
/**
* ClientServerHello.
*
* @author Christian Plattner, plattner@trilead.com
* @version $Id: ClientServerHello.java,v 1.2 2008/04/01 12:38:09 cplattne Exp $
*/
public class ClientServerHello {
public final static int readLineRN(InputStream is, byte[] buffer)
throws IOException {
int pos = 0;
boolean need10 = false;
int len = 0;
while (true) {
int c = is.read();
if (c == -1)
throw new IOException("Premature connection close");
buffer[pos++] = (byte) c;
if (c == 13) {
need10 = true;
continue;
}
if (c == 10)
break;
if (need10 == true)
throw new IOException(
"Malformed line sent by the server, the line does not end correctly.");
len++;
if (pos >= buffer.length)
throw new IOException("The server sent a too long line.");
}
return len;
}
String server_line;
String client_line;
String server_versioncomment;
public ClientServerHello(InputStream bi, OutputStream bo)
throws IOException {
client_line = "SSH-2.0-" + Connection.identification;
bo.write((client_line + "\r\n").getBytes("ISO-8859-1"));
bo.flush();
byte[] serverVersion = new byte[512];
for (int i = 0; i < 50; i++) {
int len = readLineRN(bi, serverVersion);
server_line = new String(serverVersion, 0, len, "ISO-8859-1");
if (server_line.startsWith("SSH-"))
break;
}
if (server_line.startsWith("SSH-") == false)
throw new IOException(
"Malformed server identification string. There was no line starting with 'SSH-' amongst the first 50 lines.");
if (server_line.startsWith("SSH-1.99-"))
server_versioncomment = server_line.substring(9);
else if (server_line.startsWith("SSH-2.0-"))
server_versioncomment = server_line.substring(8);
else
throw new IOException(
"Server uses incompatible protocol, it is not SSH-2 compatible.");
}
/**
* @return Returns the client_versioncomment.
*/
public byte[] getClientString() {
byte[] result;
try {
result = client_line.getBytes("ISO-8859-1");
} catch (UnsupportedEncodingException ign) {
result = client_line.getBytes();
}
return result;
}
/**
* @return Returns the server_versioncomment.
*/
public byte[] getServerString() {
byte[] result;
try {
result = server_line.getBytes("ISO-8859-1");
} catch (UnsupportedEncodingException ign) {
result = server_line.getBytes();
}
return result;
}
}
| 07pratik-myssh | src/com/trilead/ssh2/transport/ClientServerHello.java | Java | gpl3 | 2,724 |
package com.trilead.ssh2.transport;
/**
* KexParameters.
*
* @author Christian Plattner, plattner@trilead.com
* @version $Id: KexParameters.java,v 1.1 2007/10/15 12:49:56 cplattne Exp $
*/
public class KexParameters {
public byte[] cookie;
public String[] kex_algorithms;
public String[] server_host_key_algorithms;
public String[] encryption_algorithms_client_to_server;
public String[] encryption_algorithms_server_to_client;
public String[] mac_algorithms_client_to_server;
public String[] mac_algorithms_server_to_client;
public String[] compression_algorithms_client_to_server;
public String[] compression_algorithms_server_to_client;
public String[] languages_client_to_server;
public String[] languages_server_to_client;
public boolean first_kex_packet_follows;
public int reserved_field1;
}
| 07pratik-myssh | src/com/trilead/ssh2/transport/KexParameters.java | Java | gpl3 | 842 |
package com.trilead.ssh2.transport;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.UnknownHostException;
import java.security.SecureRandom;
import java.util.Vector;
import com.trilead.ssh2.ConnectionInfo;
import com.trilead.ssh2.ConnectionMonitor;
import com.trilead.ssh2.DHGexParameters;
import com.trilead.ssh2.HTTPProxyData;
import com.trilead.ssh2.HTTPProxyException;
import com.trilead.ssh2.ProxyData;
import com.trilead.ssh2.ServerHostKeyVerifier;
import com.trilead.ssh2.compression.ICompressor;
import com.trilead.ssh2.crypto.Base64;
import com.trilead.ssh2.crypto.CryptoWishList;
import com.trilead.ssh2.crypto.cipher.BlockCipher;
import com.trilead.ssh2.crypto.digest.MAC;
import com.trilead.ssh2.log.Logger;
import com.trilead.ssh2.packets.PacketDisconnect;
import com.trilead.ssh2.packets.Packets;
import com.trilead.ssh2.packets.TypesReader;
import com.trilead.ssh2.util.Tokenizer;
/*
* Yes, the "standard" is a big mess. On one side, the say that arbitary channel
* packets are allowed during kex exchange, on the other side we need to blindly
* ignore the next _packet_ if the KEX guess was wrong. Where do we know from that
* the next packet is not a channel data packet? Yes, we could check if it is in
* the KEX range. But the standard says nothing about this. The OpenSSH guys
* block local "normal" traffic during KEX. That's fine - however, they assume
* that the other side is doing the same. During re-key, if they receive traffic
* other than KEX, they become horribly irritated and kill the connection. Since
* we are very likely going to communicate with OpenSSH servers, we have to play
* the same game - even though we could do better.
*
* btw: having stdout and stderr on the same channel, with a shared window, is
* also a VERY good idea... =(
*/
/**
* TransportManager.
*
* @author Christian Plattner, plattner@trilead.com
* @version $Id: TransportManager.java,v 1.2 2008/04/01 12:38:09 cplattne Exp $
*/
public class TransportManager {
class AsynchronousWorker extends Thread {
@Override
public void run() {
while (true) {
byte[] msg = null;
synchronized (asynchronousQueue) {
if (asynchronousQueue.size() == 0) {
/*
* After the queue is empty for about 2 seconds, stop
* this thread
*/
try {
asynchronousQueue.wait(2000);
} catch (InterruptedException e) {
/*
* OKOK, if somebody interrupts us, then we may die
* earlier.
*/
}
if (asynchronousQueue.size() == 0) {
asynchronousThread = null;
return;
}
}
msg = asynchronousQueue.remove(0);
}
/*
* The following invocation may throw an IOException. There is
* no point in handling it - it simply means that the connection
* has a problem and we should stop sending asynchronously
* messages. We do not need to signal that we have exited
* (asynchronousThread = null): further messages in the queue
* cannot be sent by this or any other thread. Other threads
* will sooner or later (when receiving or sending the next
* message) get the same IOException and get to the same
* conclusion.
*/
try {
sendMessage(msg);
} catch (IOException e) {
return;
}
}
}
}
class HandlerEntry {
MessageHandler mh;
int low;
int high;
}
private static final Logger log = Logger.getLogger(TransportManager.class);
private final Vector<byte[]> asynchronousQueue = new Vector<byte[]>();
private Thread asynchronousThread = null;
String hostname;
int port;
final Socket sock = new Socket();
Object connectionSemaphore = new Object();
boolean flagKexOngoing = false;
boolean connectionClosed = false;
Throwable reasonClosedCause = null;
TransportConnection tc;
KexManager km;
Vector<HandlerEntry> messageHandlers = new Vector<HandlerEntry>();
Thread receiveThread;
Vector connectionMonitors = new Vector();
boolean monitorsWereInformed = false;
public TransportManager(String host, int port) throws IOException {
this.hostname = host;
this.port = port;
}
public void changeRecvCipher(BlockCipher bc, MAC mac) {
tc.changeRecvCipher(bc, mac);
}
/**
* @param comp
*/
public void changeRecvCompression(ICompressor comp) {
tc.changeRecvCompression(comp);
}
public void changeSendCipher(BlockCipher bc, MAC mac) {
tc.changeSendCipher(bc, mac);
}
/**
* @param comp
*/
public void changeSendCompression(ICompressor comp) {
tc.changeSendCompression(comp);
}
public void close(Throwable cause, boolean useDisconnectPacket) {
if (useDisconnectPacket == false) {
/*
* OK, hard shutdown - do not aquire the semaphore, perhaps somebody
* is inside (and waits until the remote side is ready to accept new
* data).
*/
try {
sock.close();
} catch (IOException ignore) {
}
/*
* OK, whoever tried to send data, should now agree that there is no
* point in further waiting =) It is safe now to aquire the
* semaphore.
*/
}
synchronized (connectionSemaphore) {
if (connectionClosed == false) {
if (useDisconnectPacket == true) {
try {
byte[] msg = new PacketDisconnect(
Packets.SSH_DISCONNECT_BY_APPLICATION,
cause.getMessage(), "").getPayload();
if (tc != null)
tc.sendMessage(msg);
} catch (IOException ignore) {
}
try {
sock.close();
} catch (IOException ignore) {
}
}
connectionClosed = true;
reasonClosedCause = cause; /* may be null */
}
connectionSemaphore.notifyAll();
}
/* No check if we need to inform the monitors */
Vector monitors = null;
synchronized (this) {
/*
* Short term lock to protect "connectionMonitors" and
* "monitorsWereInformed" (they may be modified concurrently)
*/
if (monitorsWereInformed == false) {
monitorsWereInformed = true;
monitors = (Vector) connectionMonitors.clone();
}
}
if (monitors != null) {
for (int i = 0; i < monitors.size(); i++) {
try {
ConnectionMonitor cmon = (ConnectionMonitor) monitors
.elementAt(i);
cmon.connectionLost(reasonClosedCause);
} catch (Exception ignore) {
}
}
}
}
/**
* There were reports that there are JDKs which use the resolver even though
* one supplies a dotted IP address in the Socket constructor. That is why
* we try to generate the InetAdress "by hand".
*
* @param host
* @return the InetAddress
* @throws UnknownHostException
*/
private InetAddress createInetAddress(String host)
throws UnknownHostException {
/* Check if it is a dotted IP4 address */
InetAddress addr = parseIPv4Address(host);
if (addr != null)
return addr;
return InetAddress.getByName(host);
}
private void establishConnection(ProxyData proxyData, int connectTimeout)
throws IOException {
/* See the comment for createInetAddress() */
if (proxyData == null) {
InetAddress addr = createInetAddress(hostname);
sock.connect(new InetSocketAddress(addr, port), connectTimeout);
sock.setSoTimeout(0);
return;
}
if (proxyData instanceof HTTPProxyData) {
HTTPProxyData pd = (HTTPProxyData) proxyData;
/* At the moment, we only support HTTP proxies */
InetAddress addr = createInetAddress(pd.proxyHost);
sock.connect(new InetSocketAddress(addr, pd.proxyPort),
connectTimeout);
sock.setSoTimeout(0);
/* 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 ((pd.proxyUser != null) && (pd.proxyPass != null)) {
String credentials = pd.proxyUser + ":" + pd.proxyPass;
char[] encoded = Base64.encode(credentials
.getBytes("ISO-8859-1"));
sb.append("Proxy-Authorization: Basic ");
sb.append(encoded);
sb.append("\r\n");
}
if (pd.requestHeaderLines != null) {
for (int i = 0; i < pd.requestHeaderLines.length; i++) {
if (pd.requestHeaderLines[i] != null) {
sb.append(pd.requestHeaderLines[i]);
sb.append("\r\n");
}
}
}
sb.append("\r\n");
OutputStream out = sock.getOutputStream();
out.write(sb.toString().getBytes("ISO-8859-1"));
out.flush();
/* Now parse the HTTP response */
byte[] buffer = new byte[1024];
InputStream in = sock.getInputStream();
int len = ClientServerHello.readLineRN(in, buffer);
String httpReponse = new String(buffer, 0, len, "ISO-8859-1");
if (httpReponse.startsWith("HTTP/") == false)
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;
}
throw new IOException("Unsupported ProxyData");
}
public void forceKeyExchange(CryptoWishList cwl, DHGexParameters dhgex)
throws IOException {
km.initiateKEX(cwl, dhgex);
}
public ConnectionInfo getConnectionInfo(int kexNumber) throws IOException {
return km.getOrWaitForConnectionInfo(kexNumber);
}
public int getPacketOverheadEstimate() {
return tc.getPacketOverheadEstimate();
}
public Throwable getReasonClosedCause() {
synchronized (connectionSemaphore) {
return reasonClosedCause;
}
}
public byte[] getSessionIdentifier() {
return km.sessionId;
}
public void initialize(CryptoWishList cwl, ServerHostKeyVerifier verifier,
DHGexParameters dhgex, int connectTimeout, SecureRandom rnd,
ProxyData proxyData) throws IOException {
/* First, establish the TCP connection to the SSH-2 server */
establishConnection(proxyData, connectTimeout);
/*
* Parse the server line and say hello - important: this information is
* later needed for the key exchange (to stop man-in-the-middle attacks)
* - that is why we wrap it into an object for later use.
*/
ClientServerHello csh = new ClientServerHello(sock.getInputStream(),
sock.getOutputStream());
tc = new TransportConnection(sock.getInputStream(),
sock.getOutputStream(), rnd);
km = new KexManager(this, csh, cwl, hostname, port, verifier, rnd);
km.initiateKEX(cwl, dhgex);
receiveThread = new Thread(new Runnable() {
@Override
public void run() {
try {
receiveLoop();
} catch (IOException e) {
close(e, false);
if (log.isEnabled())
log.log(10, "Receive thread: error in receiveLoop: "
+ e.getMessage());
}
if (log.isEnabled())
log.log(50, "Receive thread: back from receiveLoop");
/* Tell all handlers that it is time to say goodbye */
if (km != null) {
try {
km.handleMessage(null, 0);
} catch (IOException e) {
}
}
for (int i = 0; i < messageHandlers.size(); i++) {
HandlerEntry he = messageHandlers.elementAt(i);
try {
he.mh.handleMessage(null, 0);
} catch (Exception ignore) {
}
}
}
});
receiveThread.setDaemon(true);
receiveThread.start();
}
public void kexFinished() throws IOException {
synchronized (connectionSemaphore) {
flagKexOngoing = false;
connectionSemaphore.notifyAll();
}
}
private InetAddress parseIPv4Address(String host)
throws UnknownHostException {
if (host == null)
return null;
String[] quad = Tokenizer.parseTokens(host, '.');
if ((quad == null) || (quad.length != 4))
return null;
byte[] addr = new byte[4];
for (int i = 0; i < 4; i++) {
int part = 0;
if ((quad[i].length() == 0) || (quad[i].length() > 3))
return null;
for (int k = 0; k < quad[i].length(); k++) {
char c = quad[i].charAt(k);
/* No, Character.isDigit is not the same */
if ((c < '0') || (c > '9'))
return null;
part = part * 10 + (c - '0');
}
if (part > 255) /* 300.1.2.3 is invalid =) */
return null;
addr[i] = (byte) part;
}
return InetAddress.getByAddress(host, addr);
}
public void receiveLoop() throws IOException {
byte[] msg = new byte[35000];
while (true) {
int msglen = tc.receiveMessage(msg, 0, msg.length);
int type = msg[0] & 0xff;
if (type == Packets.SSH_MSG_IGNORE)
continue;
if (type == Packets.SSH_MSG_DEBUG) {
if (log.isEnabled()) {
TypesReader tr = new TypesReader(msg, 0, msglen);
tr.readByte();
tr.readBoolean();
StringBuffer debugMessageBuffer = new StringBuffer();
debugMessageBuffer.append(tr.readString("UTF-8"));
for (int i = 0; i < debugMessageBuffer.length(); i++) {
char c = debugMessageBuffer.charAt(i);
if ((c >= 32) && (c <= 126))
continue;
debugMessageBuffer.setCharAt(i, '\uFFFD');
}
log.log(50, "DEBUG Message from remote: '"
+ debugMessageBuffer.toString() + "'");
}
continue;
}
if (type == Packets.SSH_MSG_UNIMPLEMENTED) {
throw new IOException(
"Peer sent UNIMPLEMENTED message, that should not happen.");
}
if (type == Packets.SSH_MSG_DISCONNECT) {
TypesReader tr = new TypesReader(msg, 0, msglen);
tr.readByte();
int reason_code = tr.readUINT32();
StringBuffer reasonBuffer = new StringBuffer();
reasonBuffer.append(tr.readString("UTF-8"));
/*
* Do not get fooled by servers that send abnormal long error
* messages
*/
if (reasonBuffer.length() > 255) {
reasonBuffer.setLength(255);
reasonBuffer.setCharAt(254, '.');
reasonBuffer.setCharAt(253, '.');
reasonBuffer.setCharAt(252, '.');
}
/*
* Also, check that the server did not send charcaters that may
* screw up the receiver -> restrict to reasonable US-ASCII
* subset -> "printable characters" (ASCII 32 - 126). Replace
* all others with 0xFFFD (UNICODE replacement character).
*/
for (int i = 0; i < reasonBuffer.length(); i++) {
char c = reasonBuffer.charAt(i);
if ((c >= 32) && (c <= 126))
continue;
reasonBuffer.setCharAt(i, '\uFFFD');
}
throw new IOException(
"Peer sent DISCONNECT message (reason code "
+ reason_code + "): " + reasonBuffer.toString());
}
/*
* Is it a KEX Packet?
*/
if ((type == Packets.SSH_MSG_KEXINIT)
|| (type == Packets.SSH_MSG_NEWKEYS)
|| ((type >= 30) && (type <= 49))) {
km.handleMessage(msg, msglen);
continue;
}
if (type == Packets.SSH_MSG_USERAUTH_SUCCESS) {
tc.startCompression();
}
MessageHandler mh = null;
for (int i = 0; i < messageHandlers.size(); i++) {
HandlerEntry he = messageHandlers.elementAt(i);
if ((he.low <= type) && (type <= he.high)) {
mh = he.mh;
break;
}
}
if (mh == null)
throw new IOException("Unexpected SSH message (type " + type
+ ")");
mh.handleMessage(msg, msglen);
}
}
public void registerMessageHandler(MessageHandler mh, int low, int high) {
HandlerEntry he = new HandlerEntry();
he.mh = mh;
he.low = low;
he.high = high;
synchronized (messageHandlers) {
messageHandlers.addElement(he);
}
}
public void removeMessageHandler(MessageHandler mh, int low, int high) {
synchronized (messageHandlers) {
for (int i = 0; i < messageHandlers.size(); i++) {
HandlerEntry he = messageHandlers.elementAt(i);
if ((he.mh == mh) && (he.low == low) && (he.high == high)) {
messageHandlers.removeElementAt(i);
break;
}
}
}
}
public void sendAsynchronousMessage(byte[] msg) throws IOException {
synchronized (asynchronousQueue) {
asynchronousQueue.addElement(msg);
/*
* This limit should be flexible enough. We need this, otherwise the
* peer can flood us with global requests (and other stuff where we
* have to reply with an asynchronous message) and (if the server
* just sends data and does not read what we send) this will
* probably put us in a low memory situation (our send queue would
* grow and grow and...)
*/
if (asynchronousQueue.size() > 100)
throw new IOException(
"Error: the peer is not consuming our asynchronous replies.");
/* Check if we have an asynchronous sending thread */
if (asynchronousThread == null) {
asynchronousThread = new AsynchronousWorker();
asynchronousThread.setDaemon(true);
asynchronousThread.start();
/*
* The thread will stop after 2 seconds of inactivity (i.e.,
* empty queue)
*/
}
}
}
public void sendKexMessage(byte[] msg) throws IOException {
synchronized (connectionSemaphore) {
if (connectionClosed) {
throw (IOException) new IOException(
"Sorry, this connection is closed.")
.initCause(reasonClosedCause);
}
flagKexOngoing = true;
try {
tc.sendMessage(msg);
} catch (IOException e) {
close(e, false);
throw e;
}
}
}
public void sendMessage(byte[] msg) throws IOException {
if (Thread.currentThread() == receiveThread)
throw new IOException(
"Assertion error: sendMessage may never be invoked by the receiver thread!");
synchronized (connectionSemaphore) {
while (true) {
if (connectionClosed) {
throw (IOException) new IOException(
"Sorry, this connection is closed.")
.initCause(reasonClosedCause);
}
if (flagKexOngoing == false)
break;
try {
connectionSemaphore.wait();
} catch (InterruptedException e) {
}
}
try {
tc.sendMessage(msg);
} catch (IOException e) {
close(e, false);
throw e;
}
}
}
public void setConnectionMonitors(Vector monitors) {
synchronized (this) {
connectionMonitors = (Vector) monitors.clone();
}
}
public void setSoTimeout(int timeout) throws IOException {
sock.setSoTimeout(timeout);
}
public void setTcpNoDelay(boolean state) throws IOException {
sock.setTcpNoDelay(state);
}
/**
*
*/
public void startCompression() {
tc.startCompression();
}
}
| 07pratik-myssh | src/com/trilead/ssh2/transport/TransportManager.java | Java | gpl3 | 19,525 |
package com.trilead.ssh2.transport;
import java.math.BigInteger;
import com.trilead.ssh2.DHGexParameters;
import com.trilead.ssh2.crypto.dh.DhExchange;
import com.trilead.ssh2.crypto.dh.DhGroupExchange;
import com.trilead.ssh2.packets.PacketKexInit;
/**
* KexState.
*
* @author Christian Plattner, plattner@trilead.com
* @version $Id: KexState.java,v 1.1 2007/10/15 12:49:57 cplattne Exp $
*/
public class KexState {
public PacketKexInit localKEX;
public PacketKexInit remoteKEX;
public NegotiatedParameters np;
public int state = 0;
public BigInteger K;
public byte[] H;
public byte[] hostkey;
public DhExchange dhx;
public DhGroupExchange dhgx;
public DHGexParameters dhgexParameters;
}
| 07pratik-myssh | src/com/trilead/ssh2/transport/KexState.java | Java | gpl3 | 741 |
package com.trilead.ssh2.transport;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.security.SecureRandom;
import com.trilead.ssh2.compression.ICompressor;
import com.trilead.ssh2.crypto.cipher.BlockCipher;
import com.trilead.ssh2.crypto.cipher.CipherInputStream;
import com.trilead.ssh2.crypto.cipher.CipherOutputStream;
import com.trilead.ssh2.crypto.cipher.NullCipher;
import com.trilead.ssh2.crypto.digest.MAC;
import com.trilead.ssh2.log.Logger;
import com.trilead.ssh2.packets.Packets;
/**
* TransportConnection.
*
* @author Christian Plattner, plattner@trilead.com
* @version $Id: TransportConnection.java,v 1.1 2007/10/15 12:49:56 cplattne Exp
* $
*/
public class TransportConnection {
private static final Logger log = Logger
.getLogger(TransportConnection.class);
int send_seq_number = 0;
int recv_seq_number = 0;
CipherInputStream cis;
CipherOutputStream cos;
boolean useRandomPadding = false;
/* Depends on current MAC and CIPHER */
MAC send_mac;
byte[] send_mac_buffer;
int send_padd_blocksize = 8;
MAC recv_mac;
byte[] recv_mac_buffer;
byte[] recv_mac_buffer_cmp;
int recv_padd_blocksize = 8;
ICompressor recv_comp = null;
ICompressor send_comp = null;
boolean can_recv_compress = false;
boolean can_send_compress = false;
byte[] recv_comp_buffer;
byte[] send_comp_buffer;
/* won't change */
final byte[] send_padding_buffer = new byte[256];
final byte[] send_packet_header_buffer = new byte[5];
final byte[] recv_padding_buffer = new byte[256];
final byte[] recv_packet_header_buffer = new byte[5];
boolean recv_packet_header_present = false;
ClientServerHello csh;
final SecureRandom rnd;
public TransportConnection(InputStream is, OutputStream os, SecureRandom rnd) {
this.cis = new CipherInputStream(new NullCipher(), is);
this.cos = new CipherOutputStream(new NullCipher(), os);
this.rnd = rnd;
}
public void changeRecvCipher(BlockCipher bc, MAC mac) {
cis.changeCipher(bc);
recv_mac = mac;
recv_mac_buffer = (mac != null) ? new byte[mac.size()] : null;
recv_mac_buffer_cmp = (mac != null) ? new byte[mac.size()] : null;
recv_padd_blocksize = bc.getBlockSize();
if (recv_padd_blocksize < 8)
recv_padd_blocksize = 8;
}
public void changeRecvCompression(ICompressor comp) {
recv_comp = comp;
if (comp != null) {
recv_comp_buffer = new byte[comp.getBufferSize()];
can_recv_compress |= recv_comp.canCompressPreauth();
}
}
public void changeSendCipher(BlockCipher bc, MAC mac) {
if ((bc instanceof NullCipher) == false) {
/* Only use zero byte padding for the first few packets */
useRandomPadding = true;
/* Once we start encrypting, there is no way back */
}
cos.changeCipher(bc);
send_mac = mac;
send_mac_buffer = (mac != null) ? new byte[mac.size()] : null;
send_padd_blocksize = bc.getBlockSize();
if (send_padd_blocksize < 8)
send_padd_blocksize = 8;
}
public void changeSendCompression(ICompressor comp) {
send_comp = comp;
if (comp != null) {
send_comp_buffer = new byte[comp.getBufferSize()];
can_send_compress |= send_comp.canCompressPreauth();
}
}
public int getPacketOverheadEstimate() {
// return an estimate for the paket overhead (for send operations)
return 5 + 4 + (send_padd_blocksize - 1) + send_mac_buffer.length;
}
public int peekNextMessageLength() throws IOException {
if (recv_packet_header_present == false) {
cis.read(recv_packet_header_buffer, 0, 5);
recv_packet_header_present = true;
}
int packet_length = ((recv_packet_header_buffer[0] & 0xff) << 24)
| ((recv_packet_header_buffer[1] & 0xff) << 16)
| ((recv_packet_header_buffer[2] & 0xff) << 8)
| ((recv_packet_header_buffer[3] & 0xff));
int padding_length = recv_packet_header_buffer[4] & 0xff;
if (packet_length > 35000 || packet_length < 12)
throw new IOException("Illegal packet size! (" + packet_length
+ ")");
int payload_length = packet_length - padding_length - 1;
if (payload_length < 0)
throw new IOException(
"Illegal padding_length in packet from remote ("
+ padding_length + ")");
return payload_length;
}
public int receiveMessage(byte buffer[], int off, int len)
throws IOException {
if (recv_packet_header_present == false) {
cis.read(recv_packet_header_buffer, 0, 5);
} else
recv_packet_header_present = false;
int packet_length = ((recv_packet_header_buffer[0] & 0xff) << 24)
| ((recv_packet_header_buffer[1] & 0xff) << 16)
| ((recv_packet_header_buffer[2] & 0xff) << 8)
| ((recv_packet_header_buffer[3] & 0xff));
int padding_length = recv_packet_header_buffer[4] & 0xff;
if (packet_length > 35000 || packet_length < 12)
throw new IOException("Illegal packet size! (" + packet_length
+ ")");
int payload_length = packet_length - padding_length - 1;
if (payload_length < 0)
throw new IOException(
"Illegal padding_length in packet from remote ("
+ padding_length + ")");
if (payload_length >= len)
throw new IOException("Receive buffer too small (" + len
+ ", need " + payload_length + ")");
cis.read(buffer, off, payload_length);
cis.read(recv_padding_buffer, 0, padding_length);
if (recv_mac != null) {
cis.readPlain(recv_mac_buffer, 0, recv_mac_buffer.length);
recv_mac.initMac(recv_seq_number);
recv_mac.update(recv_packet_header_buffer, 0, 5);
recv_mac.update(buffer, off, payload_length);
recv_mac.update(recv_padding_buffer, 0, padding_length);
recv_mac.getMac(recv_mac_buffer_cmp, 0);
for (int i = 0; i < recv_mac_buffer.length; i++) {
if (recv_mac_buffer[i] != recv_mac_buffer_cmp[i])
throw new IOException("Remote sent corrupt MAC.");
}
}
recv_seq_number++;
if (log.isEnabled()) {
log.log(90,
"Received " + Packets.getMessageName(buffer[off] & 0xff)
+ " " + payload_length + " bytes payload");
}
if (recv_comp != null && can_recv_compress) {
int[] uncomp_len = new int[] { payload_length };
buffer = recv_comp.uncompress(buffer, off, uncomp_len);
if (buffer == null) {
throw new IOException("Error while inflating remote data");
} else {
return uncomp_len[0];
}
} else {
return payload_length;
}
}
public void sendMessage(byte[] message) throws IOException {
sendMessage(message, 0, message.length, 0);
}
public void sendMessage(byte[] message, int off, int len)
throws IOException {
sendMessage(message, off, len, 0);
}
public void sendMessage(byte[] message, int off, int len, int padd)
throws IOException {
if (padd < 4)
padd = 4;
else if (padd > 64)
padd = 64;
if (send_comp != null && can_send_compress) {
if (send_comp_buffer.length < message.length + 1024)
send_comp_buffer = new byte[message.length + 1024];
len = send_comp.compress(message, off, len, send_comp_buffer);
message = send_comp_buffer;
}
int packet_len = 5 + len + padd; /* Minimum allowed padding is 4 */
int slack = packet_len % send_padd_blocksize;
if (slack != 0) {
packet_len += (send_padd_blocksize - slack);
}
if (packet_len < 16)
packet_len = 16;
int padd_len = packet_len - (5 + len);
if (useRandomPadding) {
for (int i = 0; i < padd_len; i = i + 4) {
/*
* don't waste calls to rnd.nextInt() (by using only 8bit of the
* output). just believe me: even though we may write here up to
* 3 bytes which won't be used, there is no "buffer overflow"
* (i.e., arrayindexoutofbounds). the padding buffer is big
* enough =) (256 bytes, and that is bigger than any current
* cipher block size + 64).
*/
int r = rnd.nextInt();
send_padding_buffer[i] = (byte) r;
send_padding_buffer[i + 1] = (byte) (r >> 8);
send_padding_buffer[i + 2] = (byte) (r >> 16);
send_padding_buffer[i + 3] = (byte) (r >> 24);
}
} else {
/* use zero padding for unencrypted traffic */
for (int i = 0; i < padd_len; i++)
send_padding_buffer[i] = 0;
/*
* Actually this code is paranoid: we never filled any bytes into
* the padding buffer so far, therefore it should consist of zeros
* only.
*/
}
send_packet_header_buffer[0] = (byte) ((packet_len - 4) >> 24);
send_packet_header_buffer[1] = (byte) ((packet_len - 4) >> 16);
send_packet_header_buffer[2] = (byte) ((packet_len - 4) >> 8);
send_packet_header_buffer[3] = (byte) ((packet_len - 4));
send_packet_header_buffer[4] = (byte) padd_len;
cos.write(send_packet_header_buffer, 0, 5);
cos.write(message, off, len);
cos.write(send_padding_buffer, 0, padd_len);
if (send_mac != null) {
send_mac.initMac(send_seq_number);
send_mac.update(send_packet_header_buffer, 0, 5);
send_mac.update(message, off, len);
send_mac.update(send_padding_buffer, 0, padd_len);
send_mac.getMac(send_mac_buffer, 0);
cos.writePlain(send_mac_buffer, 0, send_mac_buffer.length);
}
cos.flush();
if (log.isEnabled()) {
log.log(90, "Sent " + Packets.getMessageName(message[off] & 0xff)
+ " " + len + " bytes payload");
}
send_seq_number++;
}
/**
*
*/
public void startCompression() {
can_recv_compress = true;
can_send_compress = true;
}
}
| 07pratik-myssh | src/com/trilead/ssh2/transport/TransportConnection.java | Java | gpl3 | 9,574 |
package com.trilead.ssh2.transport;
import java.io.IOException;
import java.security.SecureRandom;
import com.trilead.ssh2.ConnectionInfo;
import com.trilead.ssh2.DHGexParameters;
import com.trilead.ssh2.ServerHostKeyVerifier;
import com.trilead.ssh2.compression.CompressionFactory;
import com.trilead.ssh2.compression.ICompressor;
import com.trilead.ssh2.crypto.CryptoWishList;
import com.trilead.ssh2.crypto.KeyMaterial;
import com.trilead.ssh2.crypto.cipher.BlockCipher;
import com.trilead.ssh2.crypto.cipher.BlockCipherFactory;
import com.trilead.ssh2.crypto.dh.DhExchange;
import com.trilead.ssh2.crypto.dh.DhGroupExchange;
import com.trilead.ssh2.crypto.digest.MAC;
import com.trilead.ssh2.log.Logger;
import com.trilead.ssh2.packets.PacketKexDHInit;
import com.trilead.ssh2.packets.PacketKexDHReply;
import com.trilead.ssh2.packets.PacketKexDhGexGroup;
import com.trilead.ssh2.packets.PacketKexDhGexInit;
import com.trilead.ssh2.packets.PacketKexDhGexReply;
import com.trilead.ssh2.packets.PacketKexDhGexRequest;
import com.trilead.ssh2.packets.PacketKexDhGexRequestOld;
import com.trilead.ssh2.packets.PacketKexInit;
import com.trilead.ssh2.packets.PacketNewKeys;
import com.trilead.ssh2.packets.Packets;
import com.trilead.ssh2.signature.DSAPublicKey;
import com.trilead.ssh2.signature.DSASHA1Verify;
import com.trilead.ssh2.signature.DSASignature;
import com.trilead.ssh2.signature.RSAPublicKey;
import com.trilead.ssh2.signature.RSASHA1Verify;
import com.trilead.ssh2.signature.RSASignature;
/**
* KexManager.
*
* @author Christian Plattner, plattner@trilead.com
* @version $Id: KexManager.java,v 1.1 2007/10/15 12:49:56 cplattne Exp $
*/
public class KexManager {
private static final Logger log = Logger.getLogger(KexManager.class);
public static final void checkKexAlgorithmList(String[] algos) {
for (int i = 0; i < algos.length; i++) {
if ("diffie-hellman-group-exchange-sha1".equals(algos[i]))
continue;
if ("diffie-hellman-group14-sha1".equals(algos[i]))
continue;
if ("diffie-hellman-group1-sha1".equals(algos[i]))
continue;
throw new IllegalArgumentException("Unknown kex algorithm '"
+ algos[i] + "'");
}
}
public static final void checkServerHostkeyAlgorithmsList(String[] algos) {
for (int i = 0; i < algos.length; i++) {
if (("ssh-rsa".equals(algos[i]) == false)
&& ("ssh-dss".equals(algos[i]) == false))
throw new IllegalArgumentException(
"Unknown server host key algorithm '" + algos[i] + "'");
}
}
public static final String[] getDefaultKexAlgorithmList() {
return new String[] { "diffie-hellman-group-exchange-sha1",
"diffie-hellman-group14-sha1", "diffie-hellman-group1-sha1" };
}
public static final String[] getDefaultServerHostkeyAlgorithmList() {
return new String[] { "ssh-rsa", "ssh-dss" };
}
KexState kxs;
int kexCount = 0;
KeyMaterial km;
byte[] sessionId;
ClientServerHello csh;
final Object accessLock = new Object();
ConnectionInfo lastConnInfo = null;
boolean connectionClosed = false;
boolean ignore_next_kex_packet = false;
final TransportManager tm;
CryptoWishList nextKEXcryptoWishList;
DHGexParameters nextKEXdhgexParameters;
ServerHostKeyVerifier verifier;
final String hostname;
final int port;
final SecureRandom rnd;
public KexManager(TransportManager tm, ClientServerHello csh,
CryptoWishList initialCwl, String hostname, int port,
ServerHostKeyVerifier keyVerifier, SecureRandom rnd) {
this.tm = tm;
this.csh = csh;
this.nextKEXcryptoWishList = initialCwl;
this.nextKEXdhgexParameters = new DHGexParameters();
this.hostname = hostname;
this.port = port;
this.verifier = keyVerifier;
this.rnd = rnd;
}
private boolean compareFirstOfNameList(String[] a, String[] b) {
if (a == null || b == null)
throw new IllegalArgumentException();
if ((a.length == 0) && (b.length == 0))
return true;
if ((a.length == 0) || (b.length == 0))
return false;
return (a[0].equals(b[0]));
}
private boolean establishKeyMaterial() {
try {
int mac_cs_key_len = MAC
.getKeyLen(kxs.np.mac_algo_client_to_server);
int enc_cs_key_len = BlockCipherFactory
.getKeySize(kxs.np.enc_algo_client_to_server);
int enc_cs_block_len = BlockCipherFactory
.getBlockSize(kxs.np.enc_algo_client_to_server);
int mac_sc_key_len = MAC
.getKeyLen(kxs.np.mac_algo_server_to_client);
int enc_sc_key_len = BlockCipherFactory
.getKeySize(kxs.np.enc_algo_server_to_client);
int enc_sc_block_len = BlockCipherFactory
.getBlockSize(kxs.np.enc_algo_server_to_client);
km = KeyMaterial.create("SHA1", kxs.H, kxs.K, sessionId,
enc_cs_key_len, enc_cs_block_len, mac_cs_key_len,
enc_sc_key_len, enc_sc_block_len, mac_sc_key_len);
} catch (IllegalArgumentException e) {
return false;
}
return true;
}
private void finishKex() throws IOException {
if (sessionId == null)
sessionId = kxs.H;
establishKeyMaterial();
/* Tell the other side that we start using the new material */
PacketNewKeys ign = new PacketNewKeys();
tm.sendKexMessage(ign.getPayload());
BlockCipher cbc;
MAC mac;
ICompressor comp;
try {
cbc = BlockCipherFactory
.createCipher(kxs.np.enc_algo_client_to_server, true,
km.enc_key_client_to_server,
km.initial_iv_client_to_server);
mac = new MAC(kxs.np.mac_algo_client_to_server,
km.integrity_key_client_to_server);
comp = CompressionFactory
.createCompressor(kxs.np.comp_algo_client_to_server);
} catch (IllegalArgumentException e1) {
throw new IOException("Fatal error during MAC startup!");
}
tm.changeSendCipher(cbc, mac);
tm.changeSendCompression(comp);
tm.kexFinished();
}
private String getFirstMatch(String[] client, String[] server)
throws NegotiateException {
if (client == null || server == null)
throw new IllegalArgumentException();
if (client.length == 0)
return null;
for (int i = 0; i < client.length; i++) {
for (int j = 0; j < server.length; j++) {
if (client[i].equals(server[j]))
return client[i];
}
}
throw new NegotiateException();
}
public ConnectionInfo getOrWaitForConnectionInfo(int minKexCount)
throws IOException {
synchronized (accessLock) {
while (true) {
if ((lastConnInfo != null)
&& (lastConnInfo.keyExchangeCounter >= minKexCount))
return lastConnInfo;
if (connectionClosed)
throw (IOException) new IOException(
"Key exchange was not finished, connection is closed.")
.initCause(tm.getReasonClosedCause());
try {
accessLock.wait();
} catch (InterruptedException e) {
}
}
}
}
public synchronized void handleMessage(byte[] msg, int msglen)
throws IOException {
PacketKexInit kip;
if (msg == null) {
synchronized (accessLock) {
connectionClosed = true;
accessLock.notifyAll();
return;
}
}
if ((kxs == null) && (msg[0] != Packets.SSH_MSG_KEXINIT))
throw new IOException("Unexpected KEX message (type " + msg[0]
+ ")");
if (ignore_next_kex_packet) {
ignore_next_kex_packet = false;
return;
}
if (msg[0] == Packets.SSH_MSG_KEXINIT) {
if ((kxs != null) && (kxs.state != 0))
throw new IOException(
"Unexpected SSH_MSG_KEXINIT message during on-going kex exchange!");
if (kxs == null) {
/*
* Ah, OK, peer wants to do KEX. Let's be nice and play
* together.
*/
kxs = new KexState();
kxs.dhgexParameters = nextKEXdhgexParameters;
kip = new PacketKexInit(nextKEXcryptoWishList, rnd);
kxs.localKEX = kip;
tm.sendKexMessage(kip.getPayload());
}
kip = new PacketKexInit(msg, 0, msglen);
kxs.remoteKEX = kip;
kxs.np = mergeKexParameters(kxs.localKEX.getKexParameters(),
kxs.remoteKEX.getKexParameters());
if (kxs.np == null)
throw new IOException(
"Cannot negotiate, proposals do not match.");
if (kxs.remoteKEX.isFirst_kex_packet_follows()
&& (kxs.np.guessOK == false)) {
/*
* Guess was wrong, we need to ignore the next kex packet.
*/
ignore_next_kex_packet = true;
}
if (kxs.np.kex_algo.equals("diffie-hellman-group-exchange-sha1")) {
if (kxs.dhgexParameters.getMin_group_len() == 0
|| csh.server_versioncomment
.matches("OpenSSH_2\\.([0-4]\\.|5\\.[0-2]).*")) {
PacketKexDhGexRequestOld dhgexreq = new PacketKexDhGexRequestOld(
kxs.dhgexParameters);
tm.sendKexMessage(dhgexreq.getPayload());
} else {
PacketKexDhGexRequest dhgexreq = new PacketKexDhGexRequest(
kxs.dhgexParameters);
tm.sendKexMessage(dhgexreq.getPayload());
}
kxs.state = 1;
return;
}
if (kxs.np.kex_algo.equals("diffie-hellman-group1-sha1")
|| kxs.np.kex_algo.equals("diffie-hellman-group14-sha1")) {
kxs.dhx = new DhExchange();
if (kxs.np.kex_algo.equals("diffie-hellman-group1-sha1"))
kxs.dhx.init(1, rnd);
else
kxs.dhx.init(14, rnd);
PacketKexDHInit kp = new PacketKexDHInit(kxs.dhx.getE());
tm.sendKexMessage(kp.getPayload());
kxs.state = 1;
return;
}
throw new IllegalStateException("Unkown KEX method!");
}
if (msg[0] == Packets.SSH_MSG_NEWKEYS) {
if (km == null)
throw new IOException(
"Peer sent SSH_MSG_NEWKEYS, but I have no key material ready!");
BlockCipher cbc;
MAC mac;
ICompressor comp;
try {
cbc = BlockCipherFactory.createCipher(
kxs.np.enc_algo_server_to_client, false,
km.enc_key_server_to_client,
km.initial_iv_server_to_client);
mac = new MAC(kxs.np.mac_algo_server_to_client,
km.integrity_key_server_to_client);
comp = CompressionFactory
.createCompressor(kxs.np.comp_algo_server_to_client);
} catch (IllegalArgumentException e1) {
throw new IOException("Fatal error during MAC startup!");
}
tm.changeRecvCipher(cbc, mac);
tm.changeRecvCompression(comp);
ConnectionInfo sci = new ConnectionInfo();
kexCount++;
sci.keyExchangeAlgorithm = kxs.np.kex_algo;
sci.keyExchangeCounter = kexCount;
sci.clientToServerCryptoAlgorithm = kxs.np.enc_algo_client_to_server;
sci.serverToClientCryptoAlgorithm = kxs.np.enc_algo_server_to_client;
sci.clientToServerMACAlgorithm = kxs.np.mac_algo_client_to_server;
sci.serverToClientMACAlgorithm = kxs.np.mac_algo_server_to_client;
sci.serverHostKeyAlgorithm = kxs.np.server_host_key_algo;
sci.serverHostKey = kxs.hostkey;
synchronized (accessLock) {
lastConnInfo = sci;
accessLock.notifyAll();
}
kxs = null;
return;
}
if ((kxs == null) || (kxs.state == 0))
throw new IOException("Unexpected Kex submessage!");
if (kxs.np.kex_algo.equals("diffie-hellman-group-exchange-sha1")) {
if (kxs.state == 1) {
PacketKexDhGexGroup dhgexgrp = new PacketKexDhGexGroup(msg, 0,
msglen);
kxs.dhgx = new DhGroupExchange(dhgexgrp.getP(), dhgexgrp.getG());
kxs.dhgx.init(rnd);
PacketKexDhGexInit dhgexinit = new PacketKexDhGexInit(
kxs.dhgx.getE());
tm.sendKexMessage(dhgexinit.getPayload());
kxs.state = 2;
return;
}
if (kxs.state == 2) {
PacketKexDhGexReply dhgexrpl = new PacketKexDhGexReply(msg, 0,
msglen);
kxs.hostkey = dhgexrpl.getHostKey();
if (verifier != null) {
boolean vres = false;
try {
vres = verifier.verifyServerHostKey(hostname, port,
kxs.np.server_host_key_algo, kxs.hostkey);
} catch (Exception e) {
throw (IOException) new IOException(
"The server hostkey was not accepted by the verifier callback.")
.initCause(e);
}
if (vres == false)
throw new IOException(
"The server hostkey was not accepted by the verifier callback");
}
kxs.dhgx.setF(dhgexrpl.getF());
try {
kxs.H = kxs.dhgx.calculateH(csh.getClientString(),
csh.getServerString(), kxs.localKEX.getPayload(),
kxs.remoteKEX.getPayload(), dhgexrpl.getHostKey(),
kxs.dhgexParameters);
} catch (IllegalArgumentException e) {
throw (IOException) new IOException("KEX error.")
.initCause(e);
}
boolean res = verifySignature(dhgexrpl.getSignature(),
kxs.hostkey);
if (res == false)
throw new IOException(
"Hostkey signature sent by remote is wrong!");
kxs.K = kxs.dhgx.getK();
finishKex();
kxs.state = -1;
return;
}
throw new IllegalStateException("Illegal State in KEX Exchange!");
}
if (kxs.np.kex_algo.equals("diffie-hellman-group1-sha1")
|| kxs.np.kex_algo.equals("diffie-hellman-group14-sha1")) {
if (kxs.state == 1) {
PacketKexDHReply dhr = new PacketKexDHReply(msg, 0, msglen);
kxs.hostkey = dhr.getHostKey();
if (verifier != null) {
boolean vres = false;
try {
vres = verifier.verifyServerHostKey(hostname, port,
kxs.np.server_host_key_algo, kxs.hostkey);
} catch (Exception e) {
throw (IOException) new IOException(
"The server hostkey was not accepted by the verifier callback.")
.initCause(e);
}
if (vres == false)
throw new IOException(
"The server hostkey was not accepted by the verifier callback");
}
kxs.dhx.setF(dhr.getF());
try {
kxs.H = kxs.dhx.calculateH(csh.getClientString(),
csh.getServerString(), kxs.localKEX.getPayload(),
kxs.remoteKEX.getPayload(), dhr.getHostKey());
} catch (IllegalArgumentException e) {
throw (IOException) new IOException("KEX error.")
.initCause(e);
}
boolean res = verifySignature(dhr.getSignature(), kxs.hostkey);
if (res == false)
throw new IOException(
"Hostkey signature sent by remote is wrong!");
kxs.K = kxs.dhx.getK();
finishKex();
kxs.state = -1;
return;
}
}
throw new IllegalStateException("Unkown KEX method! ("
+ kxs.np.kex_algo + ")");
}
public synchronized void initiateKEX(CryptoWishList cwl,
DHGexParameters dhgex) throws IOException {
nextKEXcryptoWishList = cwl;
nextKEXdhgexParameters = dhgex;
if (kxs == null) {
kxs = new KexState();
kxs.dhgexParameters = nextKEXdhgexParameters;
PacketKexInit kp = new PacketKexInit(nextKEXcryptoWishList, rnd);
kxs.localKEX = kp;
tm.sendKexMessage(kp.getPayload());
}
}
private boolean isGuessOK(KexParameters cpar, KexParameters spar) {
if (cpar == null || spar == null)
throw new IllegalArgumentException();
if (compareFirstOfNameList(cpar.kex_algorithms, spar.kex_algorithms) == false) {
return false;
}
if (compareFirstOfNameList(cpar.server_host_key_algorithms,
spar.server_host_key_algorithms) == false) {
return false;
}
/*
* We do NOT check here if the other algorithms can be agreed on, this
* is just a check if kex_algorithms and server_host_key_algorithms were
* guessed right!
*/
return true;
}
private NegotiatedParameters mergeKexParameters(KexParameters client,
KexParameters server) {
NegotiatedParameters np = new NegotiatedParameters();
try {
np.kex_algo = getFirstMatch(client.kex_algorithms,
server.kex_algorithms);
log.log(20, "kex_algo=" + np.kex_algo);
np.server_host_key_algo = getFirstMatch(
client.server_host_key_algorithms,
server.server_host_key_algorithms);
log.log(20, "server_host_key_algo=" + np.server_host_key_algo);
np.enc_algo_client_to_server = getFirstMatch(
client.encryption_algorithms_client_to_server,
server.encryption_algorithms_client_to_server);
np.enc_algo_server_to_client = getFirstMatch(
client.encryption_algorithms_server_to_client,
server.encryption_algorithms_server_to_client);
log.log(20, "enc_algo_client_to_server="
+ np.enc_algo_client_to_server);
log.log(20, "enc_algo_server_to_client="
+ np.enc_algo_server_to_client);
np.mac_algo_client_to_server = getFirstMatch(
client.mac_algorithms_client_to_server,
server.mac_algorithms_client_to_server);
np.mac_algo_server_to_client = getFirstMatch(
client.mac_algorithms_server_to_client,
server.mac_algorithms_server_to_client);
log.log(20, "mac_algo_client_to_server="
+ np.mac_algo_client_to_server);
log.log(20, "mac_algo_server_to_client="
+ np.mac_algo_server_to_client);
np.comp_algo_client_to_server = getFirstMatch(
client.compression_algorithms_client_to_server,
server.compression_algorithms_client_to_server);
np.comp_algo_server_to_client = getFirstMatch(
client.compression_algorithms_server_to_client,
server.compression_algorithms_server_to_client);
log.log(20, "comp_algo_client_to_server="
+ np.comp_algo_client_to_server);
log.log(20, "comp_algo_server_to_client="
+ np.comp_algo_server_to_client);
} catch (NegotiateException e) {
return null;
}
try {
np.lang_client_to_server = getFirstMatch(
client.languages_client_to_server,
server.languages_client_to_server);
} catch (NegotiateException e1) {
np.lang_client_to_server = null;
}
try {
np.lang_server_to_client = getFirstMatch(
client.languages_server_to_client,
server.languages_server_to_client);
} catch (NegotiateException e2) {
np.lang_server_to_client = null;
}
if (isGuessOK(client, server))
np.guessOK = true;
return np;
}
private boolean verifySignature(byte[] sig, byte[] hostkey)
throws IOException {
if (kxs.np.server_host_key_algo.equals("ssh-rsa")) {
RSASignature rs = RSASHA1Verify.decodeSSHRSASignature(sig);
RSAPublicKey rpk = RSASHA1Verify.decodeSSHRSAPublicKey(hostkey);
log.log(50, "Verifying ssh-rsa signature");
return RSASHA1Verify.verifySignature(kxs.H, rs, rpk);
}
if (kxs.np.server_host_key_algo.equals("ssh-dss")) {
DSASignature ds = DSASHA1Verify.decodeSSHDSASignature(sig);
DSAPublicKey dpk = DSASHA1Verify.decodeSSHDSAPublicKey(hostkey);
log.log(50, "Verifying ssh-dss signature");
return DSASHA1Verify.verifySignature(kxs.H, ds, dpk);
}
throw new IOException("Unknown server host key algorithm '"
+ kxs.np.server_host_key_algo + "'");
}
}
| 07pratik-myssh | src/com/trilead/ssh2/transport/KexManager.java | Java | gpl3 | 18,717 |
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 {
class LenNamePair {
long length;
String filename;
}
Connection conn;
public SCPClient(Connection conn) {
if (conn == null)
throw new IllegalArgumentException("Cannot accept null argument!");
this.conn = conn;
}
/**
* Download a file from the remote server and pipe its contents into an
* <code>OutputStream</code>. Please note that, to enable flexible usage of
* this method, the <code>OutputStream</code> will not be closed nor
* flushed.
*
* @param remoteFile
* Path and name of the remote file.
* @param target
* OutputStream where the contents of the file will be sent to.
* @throws IOException
*/
public void get(String remoteFile, OutputStream target) throws IOException {
get(new String[] { remoteFile }, new OutputStream[] { target });
}
private void get(String remoteFiles[], OutputStream[] targets)
throws IOException {
Session sess = null;
if ((remoteFiles == null) || (targets == null))
throw new IllegalArgumentException("Null argument.");
if (remoteFiles.length != targets.length)
throw new IllegalArgumentException(
"Length of arguments does not match.");
if (remoteFiles.length == 0)
return;
String cmd = "scp -f";
for (int i = 0; i < remoteFiles.length; i++) {
if (remoteFiles[i] == null)
throw new IllegalArgumentException(
"Cannot accept null filename.");
String tmp = remoteFiles[i].trim();
if (tmp.length() == 0)
throw new IllegalArgumentException(
"Cannot accept empty filename.");
cmd += (" " + tmp);
}
try {
sess = conn.openSession();
sess.execCommand(cmd);
receiveFiles(sess, targets);
} catch (IOException e) {
throw (IOException) new IOException("Error during SCP transfer.")
.initCause(e);
} finally {
if (sess != null)
sess.close();
}
}
/**
* Download a file from the remote server to a local directory.
*
* @param remoteFile
* Path and name of the remote file.
* @param localTargetDirectory
* Local directory to put the downloaded file.
*
* @throws IOException
*/
public void get(String remoteFile, String localTargetDirectory)
throws IOException {
get(new String[] { remoteFile }, localTargetDirectory);
}
/**
* Download a set of files from the remote server to a local directory.
*
* @param remoteFiles
* Paths and names of the remote files.
* @param localTargetDirectory
* Local directory to put the downloaded files.
*
* @throws IOException
*/
public void get(String remoteFiles[], String localTargetDirectory)
throws IOException {
Session sess = null;
if ((remoteFiles == null) || (localTargetDirectory == null))
throw new IllegalArgumentException("Null argument.");
if (remoteFiles.length == 0)
return;
String cmd = "scp -f";
for (int i = 0; i < remoteFiles.length; i++) {
if (remoteFiles[i] == null)
throw new IllegalArgumentException(
"Cannot accept null filename.");
String tmp = remoteFiles[i].trim();
if (tmp.length() == 0)
throw new IllegalArgumentException(
"Cannot accept empty filename.");
cmd += (" " + tmp);
}
try {
sess = conn.openSession();
sess.execCommand(cmd);
receiveFiles(sess, remoteFiles, localTargetDirectory);
} catch (IOException e) {
throw (IOException) new IOException("Error during SCP transfer.")
.initCause(e);
} finally {
if (sess != null)
sess.close();
}
}
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;
}
/**
* Create a remote file and copy the contents of the passed byte array into
* it. Uses mode 0600 for creating the remote file.
*
* @param data
* the data to be copied into the remote file.
* @param remoteFileName
* The name of the file which will be created in the remote
* target directory.
* @param remoteTargetDirectory
* Remote target directory. Use an empty string to specify the
* default directory.
* @throws IOException
*/
public void put(byte[] data, String remoteFileName,
String remoteTargetDirectory) throws IOException {
put(data, remoteFileName, remoteTargetDirectory, "0600");
}
/**
* Create a remote file and copy the contents of the passed byte array into
* it. The method use the specified mode when creating the file on the
* remote side.
*
* @param data
* the data to be copied into the remote file.
* @param remoteFileName
* The name of the file which will be created in the remote
* target directory.
* @param remoteTargetDirectory
* Remote target directory. Use an empty string to specify the
* default directory.
* @param mode
* a four digit string (e.g., 0644, see "man chmod", "man open")
* @throws IOException
*/
public void put(byte[] data, String remoteFileName,
String remoteTargetDirectory, String mode) throws IOException {
Session sess = null;
if ((remoteFileName == null) || (remoteTargetDirectory == null)
|| (mode == null))
throw new IllegalArgumentException("Null argument.");
if (mode.length() != 4)
throw new IllegalArgumentException("Invalid mode.");
for (int i = 0; i < mode.length(); i++)
if (Character.isDigit(mode.charAt(i)) == false)
throw new IllegalArgumentException("Invalid mode.");
remoteTargetDirectory = remoteTargetDirectory.trim();
remoteTargetDirectory = (remoteTargetDirectory.length() > 0) ? remoteTargetDirectory
: ".";
String cmd = "scp -t -d " + remoteTargetDirectory;
try {
sess = conn.openSession();
sess.execCommand(cmd);
sendBytes(sess, data, remoteFileName, mode);
} catch (IOException e) {
throw (IOException) new IOException("Error during SCP transfer.")
.initCause(e);
} finally {
if (sess != null)
sess.close();
}
}
/**
* Copy a local file to a remote directory, uses mode 0600 when creating the
* file on the remote side.
*
* @param localFile
* Path and name of local file.
* @param remoteTargetDirectory
* Remote target directory. Use an empty string to specify the
* default directory.
*
* @throws IOException
*/
public void put(String localFile, String remoteTargetDirectory)
throws IOException {
put(new String[] { localFile }, remoteTargetDirectory, "0600");
}
/**
* Copy a local file to a remote directory, uses the specified mode when
* creating the file on the remote side.
*
* @param localFile
* Path and name of local file.
* @param remoteTargetDirectory
* Remote target directory. Use an empty string to specify the
* default directory.
* @param mode
* a four digit string (e.g., 0644, see "man chmod", "man open")
* @throws IOException
*/
public void put(String localFile, String remoteTargetDirectory, String mode)
throws IOException {
put(new String[] { localFile }, remoteTargetDirectory, mode);
}
/**
* Copy a local file to a remote directory, uses the specified mode and
* remote filename when creating the file on the remote side.
*
* @param localFile
* Path and name of local file.
* @param remoteFileName
* The name of the file which will be created in the remote
* target directory.
* @param remoteTargetDirectory
* Remote target directory. Use an empty string to specify the
* default directory.
* @param mode
* a four digit string (e.g., 0644, see "man chmod", "man open")
* @throws IOException
*/
public void put(String localFile, String remoteFileName,
String remoteTargetDirectory, String mode) throws IOException {
put(new String[] { localFile }, new String[] { remoteFileName },
remoteTargetDirectory, mode);
}
/**
* Copy a set of local files to a remote directory, uses mode 0600 when
* creating files on the remote side.
*
* @param localFiles
* Paths and names of local file names.
* @param remoteTargetDirectory
* Remote target directory. Use an empty string to specify the
* default directory.
*
* @throws IOException
*/
public void put(String[] localFiles, String remoteTargetDirectory)
throws IOException {
put(localFiles, remoteTargetDirectory, "0600");
}
/**
* Copy a set of local files to a remote directory, uses the specified mode
* when creating the files on the remote side.
*
* @param localFiles
* Paths and names of the local files.
* @param remoteTargetDirectory
* Remote target directory. Use an empty string to specify the
* default directory.
* @param mode
* a four digit string (e.g., 0644, see "man chmod", "man open")
* @throws IOException
*/
public void put(String[] localFiles, String remoteTargetDirectory,
String mode) throws IOException {
put(localFiles, null, remoteTargetDirectory, mode);
}
public void put(String[] localFiles, String[] remoteFiles,
String remoteTargetDirectory, String mode) throws IOException {
Session sess = null;
/*
* remoteFiles may be null, indicating that the local filenames shall be
* used
*/
if ((localFiles == null) || (remoteTargetDirectory == null)
|| (mode == null))
throw new IllegalArgumentException("Null argument.");
if (mode.length() != 4)
throw new IllegalArgumentException("Invalid mode.");
for (int i = 0; i < mode.length(); i++)
if (Character.isDigit(mode.charAt(i)) == false)
throw new IllegalArgumentException("Invalid mode.");
if (localFiles.length == 0)
return;
remoteTargetDirectory = remoteTargetDirectory.trim();
remoteTargetDirectory = (remoteTargetDirectory.length() > 0) ? remoteTargetDirectory
: ".";
String cmd = "scp -t -d " + remoteTargetDirectory;
for (int i = 0; i < localFiles.length; i++) {
if (localFiles[i] == null)
throw new IllegalArgumentException(
"Cannot accept null filename.");
}
try {
sess = conn.openSession();
sess.execCommand(cmd);
sendFiles(sess, localFiles, remoteFiles, mode);
} catch (IOException e) {
throw (IOException) new IOException("Error during SCP transfer.")
.initCause(e);
} finally {
if (sess != null)
sess.close();
}
}
private void readResponse(InputStream is) throws IOException {
int c = is.read();
if (c == 0)
return;
if (c == -1)
throw new IOException("Remote scp terminated unexpectedly.");
if ((c != 1) && (c != 2))
throw new IOException("Remote scp sent illegal error code.");
if (c == 2)
throw new IOException("Remote scp terminated with error.");
String err = receiveLine(is);
throw new IOException("Remote scp terminated with error (" + err + ").");
}
private 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();
}
}
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 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();
}
}
| 07pratik-myssh | src/com/trilead/ssh2/SCPClient.java | Java | gpl3 | 19,058 |
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, 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 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);
}
@Override
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.stdoutStream,
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();
}
}
@Override
public void stopWorking() {
try {
/* This will lead to an IOException in the ss.accept() call */
ss.close();
} catch (IOException e) {
}
}
}
| 07pratik-myssh | src/com/trilead/ssh2/channel/LocalAcceptThread.java | Java | gpl3 | 2,834 |
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;
}
| 07pratik-myssh | src/com/trilead/ssh2/channel/RemoteForwardingData.java | Java | gpl3 | 407 |
package com.trilead.ssh2.channel;
import java.io.IOException;
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(20, "RemoteAcceptThread: " + remoteConnectedAddress + "/"
+ remoteConnectedPort + ", R: " + remoteOriginatorAddress
+ "/" + remoteOriginatorPort);
}
@Override
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) {
}
}
/* 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.getMessage());
try {
c.cm.closeChannel(c,
"IOException in proxy code (" + e.getMessage() + ")",
true);
} catch (IOException e1) {
}
try {
if (s != null)
s.close();
} catch (IOException e1) {
}
}
}
}
| 07pratik-myssh | src/com/trilead/ssh2/channel/RemoteAcceptThread.java | Java | gpl3 | 2,505 |
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;
private byte[] writeBuffer;
boolean isClosed = false;
ChannelOutputStream(Channel c) {
this.c = c;
writeBuffer = new byte[1];
}
@Override
public void close() throws IOException {
if (isClosed == false) {
isClosed = true;
c.cm.sendEOF(c);
}
}
@Override
public void flush() throws IOException {
if (isClosed)
throw new IOException("This OutputStream is closed.");
/* This is a no-op, since this stream is unbuffered */
}
@Override
public void write(byte[] b) throws IOException {
write(b, 0, b.length);
}
@Override
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);
}
@Override
public void write(int b) throws IOException {
writeBuffer[0] = (byte) b;
write(writeBuffer, 0, 1);
}
}
| 07pratik-myssh | src/com/trilead/ssh2/channel/ChannelOutputStream.java | Java | gpl3 | 1,508 |
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;
}
@Override
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;
}
@Override
public void close() throws IOException {
isClosed = true;
}
@Override
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;
}
@Override
public int read(byte[] b) throws IOException {
return read(b, 0, b.length);
}
@Override
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;
}
}
| 07pratik-myssh | src/com/trilead/ssh2/channel/ChannelInputStream.java | Java | gpl3 | 1,706 |
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 = new byte[Channel.CHANNEL_BUFFER_SIZE];
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;
}
@Override
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) {
}
}
}
}
} | 07pratik-myssh | src/com/trilead/ssh2/channel/StreamForwarder.java | Java | gpl3 | 1,975 |
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
*/
}
| 07pratik-myssh | src/com/trilead/ssh2/channel/X11ServerData.java | Java | gpl3 | 451 |
package com.trilead.ssh2.channel;
/**
* 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;
static final int CHANNEL_BUFFER_SIZE = 30000;
/*
* 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;
final ChannelInputStream stdoutStream;
final ChannelInputStream stderrStream;
// 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;
final byte[] stdoutBuffer = new byte[CHANNEL_BUFFER_SIZE];
final byte[] stderrBuffer = new byte[CHANNEL_BUFFER_SIZE];
int stdoutReadpos = 0;
int stdoutWritepos = 0;
int stderrReadpos = 0;
int stderrWritepos = 0;
boolean EOF = false;
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 String reasonClosed = null;
public Channel(ChannelManager cm) {
this.cm = cm;
this.localWindow = CHANNEL_BUFFER_SIZE;
this.localMaxPacketSize = 35000 - 1024; // leave enough slack
this.stdinStream = new ChannelOutputStream(this);
this.stdoutStream = new ChannelInputStream(this, false);
this.stderrStream = new ChannelInputStream(this, true);
}
/* Methods to allow access from classes outside of this package */
public String getExitSignal() {
synchronized (this) {
return exit_signal;
}
}
public Integer getExitStatus() {
synchronized (this) {
return exit_status;
}
}
public String getReasonClosed() {
synchronized (reasonClosedLock) {
return reasonClosed;
}
}
public ChannelInputStream getStderrStream() {
return stderrStream;
}
public ChannelOutputStream getStdinStream() {
return stdinStream;
}
public ChannelInputStream getStdoutStream() {
return stdoutStream;
}
public void setReasonClosed(String reasonClosed) {
synchronized (reasonClosedLock) {
if (this.reasonClosed == null)
this.reasonClosed = reasonClosed;
}
}
}
| 07pratik-myssh | src/com/trilead/ssh2/channel/Channel.java | Java | gpl3 | 6,188 |
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();
}
| 07pratik-myssh | src/com/trilead/ssh2/channel/IChannelWorkerThread.java | Java | gpl3 | 295 |
/*
* 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 net.sourceforge.jsocks.Proxy;
import net.sourceforge.jsocks.ProxyMessage;
import net.sourceforge.jsocks.Socks4Message;
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;
/**
* DynamicAcceptThread.
*
* @author Kenny Root
* @version $Id$
*/
public class DynamicAcceptThread extends Thread implements IChannelWorkerThread {
class DynamicAcceptRunnable implements Runnable {
private static final int idleTimeout = 60000; // 3 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");
}
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;
if (msg instanceof Socks5Message) {
response = new Socks5Message(Proxy.SOCKS_SUCCESS,
(InetAddress) null, 0);
} else {
response = new Socks4Message(Socks4Message.REPLY_OK,
(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) {
/*
* 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.stdoutStream, 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 if (version == 4) {
msg = new Socks4Message(push_in, false);
} else {
throw new SocksException(Proxy.SOCKS_FAILURE);
}
return msg;
}
@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();
thread_num--;
}
}
private void sendErrorMessage(int error_code) {
ProxyMessage err_msg;
if (msg instanceof Socks4Message)
err_msg = new Socks4Message(Socks4Message.REPLY_REJECTED);
else
err_msg = new Socks5Message(error_code);
try {
err_msg.write(out);
} catch (IOException ioe) {
}
}
private void startSession() throws IOException {
sock.setSoTimeout(idleTimeout);
try {
auth = auth.startSession(sock);
} catch (IOException ioe) {
System.out.println("Could not start SOCKS session");
ioe.printStackTrace();
auth = null;
return;
}
if (auth == null) { // Authentication failed
System.out.println("SOCKS auth failed");
return;
}
in = auth.getInputStream();
out = auth.getOutputStream();
msg = readMsg(in);
handleRequest(msg);
}
}
private volatile int thread_num = 0;
private ChannelManager cm;
private final static int MAX_THREAD_COUNT = 2;
private ServerSocket ss;
public DynamicAcceptThread(ChannelManager cm, InetSocketAddress localAddress)
throws IOException {
this.cm = cm;
ss = new ServerSocket();
ss.bind(localAddress);
}
public DynamicAcceptThread(ChannelManager cm, int local_port)
throws IOException {
this.cm = cm;
setName("DynamicAcceptThread");
ss = new ServerSocket(local_port);
}
@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;
}
DynamicAcceptRunnable dar = new DynamicAcceptRunnable(
new ServerAuthenticatorNone(), sock);
Thread t = new Thread(dar);
t.setDaemon(true);
t.start();
thread_num++;
while (thread_num > MAX_THREAD_COUNT) {
Log.d("SOCKSProxy", "Max thread number exceeded");
System.gc();
try {
Thread.sleep(2000);
} catch (InterruptedException ignore) {
// Nothing
}
}
}
}
/*
* (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) {
}
}
}
| 07pratik-myssh | src/com/trilead/ssh2/channel/DynamicAcceptThread.java | Java | gpl3 | 7,544 |
/*
* 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.OutputStream;
import java.math.BigInteger;
import java.security.SecureRandom;
import java.util.Map;
import java.util.Map.Entry;
import com.trilead.ssh2.AuthAgentCallback;
import com.trilead.ssh2.log.Logger;
import com.trilead.ssh2.packets.TypesReader;
import com.trilead.ssh2.packets.TypesWriter;
import com.trilead.ssh2.signature.DSAPrivateKey;
import com.trilead.ssh2.signature.DSASHA1Verify;
import com.trilead.ssh2.signature.DSASignature;
import com.trilead.ssh2.signature.RSAPrivateKey;
import com.trilead.ssh2.signature.RSASHA1Verify;
import com.trilead.ssh2.signature.RSASignature;
/**
* AuthAgentForwardThread.
*
* @author Kenny Root
* @version $Id$
*/
public class AuthAgentForwardThread extends Thread implements
IChannelWorkerThread {
private static final byte[] SSH_AGENT_FAILURE = { 0, 0, 0, 1, 5 }; // 5
private static final byte[] SSH_AGENT_SUCCESS = { 0, 0, 0, 1, 6 }; // 6
private static final int SSH2_AGENTC_REQUEST_IDENTITIES = 11;
private static final int SSH2_AGENT_IDENTITIES_ANSWER = 12;
private static final int SSH2_AGENTC_SIGN_REQUEST = 13;
private static final int SSH2_AGENT_SIGN_RESPONSE = 14;
private static final int SSH2_AGENTC_ADD_IDENTITY = 17;
private static final int SSH2_AGENTC_REMOVE_IDENTITY = 18;
private static final int SSH2_AGENTC_REMOVE_ALL_IDENTITIES = 19;
// private static final int SSH_AGENTC_ADD_SMARTCARD_KEY = 20;
// private static final int SSH_AGENTC_REMOVE_SMARTCARD_KEY = 21;
private static final int SSH_AGENTC_LOCK = 22;
private static final int SSH_AGENTC_UNLOCK = 23;
private static final int SSH2_AGENTC_ADD_ID_CONSTRAINED = 25;
// private static final int SSH_AGENTC_ADD_SMARTCARD_KEY_CONSTRAINED = 26;
// Constraints for adding keys
private static final int SSH_AGENT_CONSTRAIN_LIFETIME = 1;
private static final int SSH_AGENT_CONSTRAIN_CONFIRM = 2;
// Flags for signature requests
// private static final int SSH_AGENT_OLD_SIGNATURE = 1;
private static final Logger log = Logger
.getLogger(RemoteAcceptThread.class);
AuthAgentCallback authAgent;
OutputStream os;
InputStream is;
Channel c;
byte[] buffer = new byte[Channel.CHANNEL_BUFFER_SIZE];
public AuthAgentForwardThread(Channel c, AuthAgentCallback authAgent) {
this.c = c;
this.authAgent = authAgent;
if (log.isEnabled())
log.log(20, "AuthAgentForwardThread started");
}
/**
* @param tr
*/
private void addIdentity(TypesReader tr, boolean checkConstraints) {
try {
if (failWhenLocked())
return;
String type = tr.readString();
Object key;
String comment;
if (type.equals("ssh-rsa")) {
BigInteger n = tr.readMPINT();
BigInteger e = tr.readMPINT();
BigInteger d = tr.readMPINT();
tr.readMPINT(); // iqmp
tr.readMPINT(); // p
tr.readMPINT(); // q
comment = tr.readString();
key = new RSAPrivateKey(d, e, n);
} else if (type.equals("ssh-dss")) {
BigInteger p = tr.readMPINT();
BigInteger q = tr.readMPINT();
BigInteger g = tr.readMPINT();
BigInteger y = tr.readMPINT();
BigInteger x = tr.readMPINT();
comment = tr.readString();
key = new DSAPrivateKey(p, q, g, y, x);
} else {
os.write(SSH_AGENT_FAILURE);
return;
}
boolean confirmUse = false;
int lifetime = 0;
if (checkConstraints) {
while (tr.remain() > 0) {
int constraint = tr.readByte();
if (constraint == SSH_AGENT_CONSTRAIN_CONFIRM)
confirmUse = true;
else if (constraint == SSH_AGENT_CONSTRAIN_LIFETIME)
lifetime = tr.readUINT32();
else {
// Unknown constraint. Bail.
os.write(SSH_AGENT_FAILURE);
return;
}
}
}
if (authAgent.addIdentity(key, comment, confirmUse, lifetime))
os.write(SSH_AGENT_SUCCESS);
else
os.write(SSH_AGENT_FAILURE);
} catch (IOException e) {
try {
os.write(SSH_AGENT_FAILURE);
} catch (IOException e1) {
}
}
}
/**
* @return whether the agent is locked
*/
private boolean failWhenLocked() throws IOException {
if (authAgent.isAgentLocked()) {
os.write(SSH_AGENT_FAILURE);
return true;
} else
return false;
}
/**
* @param tr
*/
private void processLockRequest(TypesReader tr) {
try {
if (failWhenLocked())
return;
String lockPassphrase = tr.readString();
if (!authAgent.setAgentLock(lockPassphrase)) {
os.write(SSH_AGENT_FAILURE);
return;
} else
os.write(SSH_AGENT_SUCCESS);
} catch (IOException e) {
try {
os.write(SSH_AGENT_FAILURE);
} catch (IOException e1) {
}
}
}
private void processSignRequest(TypesReader tr) {
try {
if (failWhenLocked())
return;
byte[] publicKey = tr.readByteString();
byte[] challenge = tr.readByteString();
int flags = tr.readUINT32();
if (flags != 0) {
// We don't understand any flags; abort!
os.write(SSH_AGENT_FAILURE);
return;
}
Object trileadKey = authAgent.getPrivateKey(publicKey);
if (trileadKey == null) {
os.write(SSH_AGENT_FAILURE);
return;
}
byte[] response;
if (trileadKey instanceof RSAPrivateKey) {
RSASignature signature = RSASHA1Verify.generateSignature(
challenge, (RSAPrivateKey) trileadKey);
response = RSASHA1Verify.encodeSSHRSASignature(signature);
} else if (trileadKey instanceof DSAPrivateKey) {
DSASignature signature = DSASHA1Verify.generateSignature(
challenge, (DSAPrivateKey) trileadKey,
new SecureRandom());
response = DSASHA1Verify.encodeSSHDSASignature(signature);
} else {
os.write(SSH_AGENT_FAILURE);
return;
}
TypesWriter tw = new TypesWriter();
tw.writeByte(SSH2_AGENT_SIGN_RESPONSE);
tw.writeString(response, 0, response.length);
sendPacket(tw.getBytes());
} catch (IOException e) {
try {
os.write(SSH_AGENT_FAILURE);
} catch (IOException e1) {
}
}
}
/**
* @param tr
*/
private void processUnlockRequest(TypesReader tr) {
try {
String unlockPassphrase = tr.readString();
if (authAgent.requestAgentUnlock(unlockPassphrase))
os.write(SSH_AGENT_SUCCESS);
else
os.write(SSH_AGENT_FAILURE);
} catch (IOException e) {
try {
os.write(SSH_AGENT_FAILURE);
} catch (IOException e1) {
}
}
}
/**
* @param tr
*/
private void removeAllIdentities(TypesReader tr) {
try {
if (failWhenLocked())
return;
if (authAgent.removeAllIdentities())
os.write(SSH_AGENT_SUCCESS);
else
os.write(SSH_AGENT_FAILURE);
} catch (IOException e) {
try {
os.write(SSH_AGENT_FAILURE);
} catch (IOException e1) {
}
}
}
/**
* @param tr
*/
private void removeIdentity(TypesReader tr) {
try {
if (failWhenLocked())
return;
byte[] publicKey = tr.readByteString();
if (authAgent.removeIdentity(publicKey))
os.write(SSH_AGENT_SUCCESS);
else
os.write(SSH_AGENT_FAILURE);
} catch (IOException e) {
try {
os.write(SSH_AGENT_FAILURE);
} catch (IOException e1) {
}
}
}
@Override
public void run() {
try {
c.cm.registerThread(this);
} catch (IOException e) {
stopWorking();
return;
}
try {
c.cm.sendOpenConfirmation(c);
is = c.getStdoutStream();
os = c.getStdinStream();
int totalSize = 4;
int readSoFar = 0;
while (true) {
int len;
try {
len = is.read(buffer, readSoFar, buffer.length - readSoFar);
} catch (IOException e) {
stopWorking();
return;
}
if (len <= 0)
break;
readSoFar += len;
if (readSoFar >= 4) {
TypesReader tr = new TypesReader(buffer, 0, 4);
totalSize = tr.readUINT32() + 4;
}
if (totalSize == readSoFar) {
TypesReader tr = new TypesReader(buffer, 4, readSoFar - 4);
int messageType = tr.readByte();
switch (messageType) {
case SSH2_AGENTC_REQUEST_IDENTITIES:
sendIdentities();
break;
case SSH2_AGENTC_ADD_IDENTITY:
addIdentity(tr, false);
break;
case SSH2_AGENTC_ADD_ID_CONSTRAINED:
addIdentity(tr, true);
break;
case SSH2_AGENTC_REMOVE_IDENTITY:
removeIdentity(tr);
break;
case SSH2_AGENTC_REMOVE_ALL_IDENTITIES:
removeAllIdentities(tr);
break;
case SSH2_AGENTC_SIGN_REQUEST:
processSignRequest(tr);
break;
case SSH_AGENTC_LOCK:
processLockRequest(tr);
break;
case SSH_AGENTC_UNLOCK:
processUnlockRequest(tr);
break;
default:
os.write(SSH_AGENT_FAILURE);
break;
}
readSoFar = 0;
}
}
c.cm.closeChannel(c, "EOF on both streams reached.", true);
} catch (IOException e) {
log.log(50, "IOException in agent forwarder: " + e.getMessage());
try {
is.close();
} catch (IOException e1) {
}
try {
os.close();
} catch (IOException e2) {
}
try {
c.cm.closeChannel(c,
"IOException in agent forwarder (" + e.getMessage()
+ ")", true);
} catch (IOException e3) {
}
}
}
private void sendIdentities() throws IOException {
Map<String, byte[]> keys = null;
TypesWriter tw = new TypesWriter();
tw.writeByte(SSH2_AGENT_IDENTITIES_ANSWER);
int numKeys = 0;
if (!authAgent.isAgentLocked())
keys = authAgent.retrieveIdentities();
if (keys != null)
numKeys = keys.size();
tw.writeUINT32(numKeys);
if (keys != null) {
for (Entry<String, byte[]> entry : keys.entrySet()) {
byte[] keyBytes = entry.getValue();
tw.writeString(keyBytes, 0, keyBytes.length);
tw.writeString(entry.getKey());
}
}
sendPacket(tw.getBytes());
}
/**
* @param tw
* @throws IOException
*/
private void sendPacket(byte[] message) throws IOException {
TypesWriter packet = new TypesWriter();
packet.writeUINT32(message.length);
packet.writeBytes(message);
os.write(packet.getBytes());
}
@Override
public void stopWorking() {
try {
/* This will lead to an IOException in the is.read() call */
is.close();
} catch (IOException e) {
}
}
}
| 07pratik-myssh | src/com/trilead/ssh2/channel/AuthAgentForwardThread.java | Java | gpl3 | 10,708 |
package com.trilead.ssh2.channel;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
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;
}
@Override
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) {
}
}
/* 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.getMessage());
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) {
}
}
}
}
| 07pratik-myssh | src/com/trilead/ssh2/channel/RemoteX11AcceptThread.java | Java | gpl3 | 7,337 |
package com.trilead.ssh2.channel;
import java.io.IOException;
import java.util.HashMap;
import java.util.Vector;
import com.trilead.ssh2.AuthAgentCallback;
import com.trilead.ssh2.ChannelCondition;
import com.trilead.ssh2.log.Logger;
import com.trilead.ssh2.packets.PacketChannelAuthAgentReq;
import com.trilead.ssh2.packets.PacketChannelOpenConfirmation;
import com.trilead.ssh2.packets.PacketChannelOpenFailure;
import com.trilead.ssh2.packets.PacketChannelTrileadPing;
import com.trilead.ssh2.packets.PacketGlobalCancelForwardRequest;
import com.trilead.ssh2.packets.PacketGlobalForwardRequest;
import com.trilead.ssh2.packets.PacketGlobalTrileadPing;
import com.trilead.ssh2.packets.PacketOpenDirectTCPIPChannel;
import com.trilead.ssh2.packets.PacketOpenSessionChannel;
import com.trilead.ssh2.packets.PacketSessionExecCommand;
import com.trilead.ssh2.packets.PacketSessionPtyRequest;
import com.trilead.ssh2.packets.PacketSessionPtyResize;
import com.trilead.ssh2.packets.PacketSessionStartShell;
import com.trilead.ssh2.packets.PacketSessionSubsystemRequest;
import com.trilead.ssh2.packets.PacketSessionX11Request;
import com.trilead.ssh2.packets.Packets;
import com.trilead.ssh2.packets.TypesReader;
import com.trilead.ssh2.transport.MessageHandler;
import com.trilead.ssh2.transport.TransportManager;
/**
* ChannelManager. Please read the comments in Channel.java.
* <p>
* Besides the crypto part, this is the core of the library.
*
* @author Christian Plattner, plattner@trilead.com
* @version $Id: ChannelManager.java,v 1.2 2008/03/03 07:01:36 cplattne Exp $
*/
public class ChannelManager implements MessageHandler {
private static final Logger log = Logger.getLogger(ChannelManager.class);
private HashMap x11_magic_cookies = new HashMap();
private TransportManager tm;
private Vector channels = new Vector();
private int nextLocalChannel = 100;
private boolean shutdown = false;
private int globalSuccessCounter = 0;
private int globalFailedCounter = 0;
private HashMap remoteForwardings = new HashMap();
private AuthAgentCallback authAgent;
private Vector listenerThreads = new Vector();
private boolean listenerThreadsAllowed = true;
public ChannelManager(TransportManager tm) {
this.tm = tm;
tm.registerMessageHandler(this, 80, 100);
}
private int addChannel(Channel c) {
synchronized (channels) {
channels.addElement(c);
return nextLocalChannel++;
}
}
public X11ServerData checkX11Cookie(String hexFakeCookie) {
synchronized (x11_magic_cookies) {
if (hexFakeCookie != null)
return (X11ServerData) x11_magic_cookies.get(hexFakeCookie);
}
return null;
}
public void closeAllChannels() {
if (log.isEnabled())
log.log(50, "Closing all channels");
Vector channel_copy;
synchronized (channels) {
channel_copy = (Vector) channels.clone();
}
for (int i = 0; i < channel_copy.size(); i++) {
Channel c = (Channel) channel_copy.elementAt(i);
try {
closeChannel(c, "Closing all channels", true);
} catch (IOException e) {
}
}
}
public void closeChannel(Channel c, String reason, boolean force)
throws IOException {
byte msg[] = new byte[5];
synchronized (c) {
if (force) {
c.state = Channel.STATE_CLOSED;
c.EOF = true;
}
c.setReasonClosed(reason);
msg[0] = Packets.SSH_MSG_CHANNEL_CLOSE;
msg[1] = (byte) (c.remoteID >> 24);
msg[2] = (byte) (c.remoteID >> 16);
msg[3] = (byte) (c.remoteID >> 8);
msg[4] = (byte) (c.remoteID);
c.notifyAll();
}
synchronized (c.channelSendLock) {
if (c.closeMessageSent == true)
return;
tm.sendMessage(msg);
c.closeMessageSent = true;
}
if (log.isEnabled())
log.log(50, "Sent SSH_MSG_CHANNEL_CLOSE (channel " + c.localID
+ ")");
}
public int getAvailable(Channel c, boolean extended) throws IOException {
synchronized (c) {
int avail;
if (extended)
avail = c.stderrWritepos - c.stderrReadpos;
else
avail = c.stdoutWritepos - c.stdoutReadpos;
return ((avail > 0) ? avail : (c.EOF ? -1 : 0));
}
}
private Channel getChannel(int id) {
synchronized (channels) {
for (int i = 0; i < channels.size(); i++) {
Channel c = (Channel) channels.elementAt(i);
if (c.localID == id)
return c;
}
}
return null;
}
public int getChannelData(Channel c, boolean extended, byte[] target,
int off, int len) throws IOException {
int copylen = 0;
int increment = 0;
int remoteID = 0;
int localID = 0;
synchronized (c) {
int stdoutAvail = 0;
int stderrAvail = 0;
while (true) {
/*
* Data available? We have to return remaining data even if the
* channel is already closed.
*/
stdoutAvail = c.stdoutWritepos - c.stdoutReadpos;
stderrAvail = c.stderrWritepos - c.stderrReadpos;
if ((!extended) && (stdoutAvail != 0))
break;
if ((extended) && (stderrAvail != 0))
break;
/* Do not wait if more data will never arrive (EOF or CLOSED) */
if ((c.EOF) || (c.state != Channel.STATE_OPEN))
return -1;
try {
c.wait();
} catch (InterruptedException ignore) {
}
}
/* OK, there is some data. Return it. */
if (!extended) {
copylen = (stdoutAvail > len) ? len : stdoutAvail;
System.arraycopy(c.stdoutBuffer, c.stdoutReadpos, target, off,
copylen);
c.stdoutReadpos += copylen;
if (c.stdoutReadpos != c.stdoutWritepos)
System.arraycopy(c.stdoutBuffer, c.stdoutReadpos,
c.stdoutBuffer, 0, c.stdoutWritepos
- c.stdoutReadpos);
c.stdoutWritepos -= c.stdoutReadpos;
c.stdoutReadpos = 0;
} else {
copylen = (stderrAvail > len) ? len : stderrAvail;
System.arraycopy(c.stderrBuffer, c.stderrReadpos, target, off,
copylen);
c.stderrReadpos += copylen;
if (c.stderrReadpos != c.stderrWritepos)
System.arraycopy(c.stderrBuffer, c.stderrReadpos,
c.stderrBuffer, 0, c.stderrWritepos
- c.stderrReadpos);
c.stderrWritepos -= c.stderrReadpos;
c.stderrReadpos = 0;
}
if (c.state != Channel.STATE_OPEN)
return copylen;
if (c.localWindow < ((Channel.CHANNEL_BUFFER_SIZE + 1) / 2)) {
int minFreeSpace = Math.min(Channel.CHANNEL_BUFFER_SIZE
- c.stdoutWritepos, Channel.CHANNEL_BUFFER_SIZE
- c.stderrWritepos);
increment = minFreeSpace - c.localWindow;
c.localWindow = minFreeSpace;
}
remoteID = c.remoteID; /* read while holding the lock */
localID = c.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 (c.channelSendLock) {
byte[] msg = c.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 (c.closeMessageSent == false)
tm.sendMessage(msg);
}
}
return copylen;
}
@Override
public void handleMessage(byte[] msg, int msglen) throws IOException {
if (msg == null) {
if (log.isEnabled())
log.log(50, "HandleMessage: got shutdown");
synchronized (listenerThreads) {
for (int i = 0; i < listenerThreads.size(); i++) {
IChannelWorkerThread lat = (IChannelWorkerThread) listenerThreads
.elementAt(i);
lat.stopWorking();
}
listenerThreadsAllowed = false;
}
synchronized (channels) {
shutdown = true;
for (int i = 0; i < channels.size(); i++) {
Channel c = (Channel) channels.elementAt(i);
synchronized (c) {
c.EOF = true;
c.state = Channel.STATE_CLOSED;
c.setReasonClosed("The connection is being shutdown");
c.closeMessageRecv = true; /*
* You never know, perhaps
* we are waiting for a
* pending close message
* from the server...
*/
c.notifyAll();
}
}
/* Works with J2ME */
channels.setSize(0);
channels.trimToSize();
channels.notifyAll(); /* Notify global response waiters */
return;
}
}
switch (msg[0]) {
case Packets.SSH_MSG_CHANNEL_OPEN_CONFIRMATION:
msgChannelOpenConfirmation(msg, msglen);
break;
case Packets.SSH_MSG_CHANNEL_WINDOW_ADJUST:
msgChannelWindowAdjust(msg, msglen);
break;
case Packets.SSH_MSG_CHANNEL_DATA:
msgChannelData(msg, msglen);
break;
case Packets.SSH_MSG_CHANNEL_EXTENDED_DATA:
msgChannelExtendedData(msg, msglen);
break;
case Packets.SSH_MSG_CHANNEL_REQUEST:
msgChannelRequest(msg, msglen);
break;
case Packets.SSH_MSG_CHANNEL_EOF:
msgChannelEOF(msg, msglen);
break;
case Packets.SSH_MSG_CHANNEL_OPEN:
msgChannelOpen(msg, msglen);
break;
case Packets.SSH_MSG_CHANNEL_CLOSE:
msgChannelClose(msg, msglen);
break;
case Packets.SSH_MSG_CHANNEL_SUCCESS:
msgChannelSuccess(msg, msglen);
break;
case Packets.SSH_MSG_CHANNEL_FAILURE:
msgChannelFailure(msg, msglen);
break;
case Packets.SSH_MSG_CHANNEL_OPEN_FAILURE:
msgChannelOpenFailure(msg, msglen);
break;
case Packets.SSH_MSG_GLOBAL_REQUEST:
msgGlobalRequest(msg, msglen);
break;
case Packets.SSH_MSG_REQUEST_SUCCESS:
msgGlobalSuccess();
break;
case Packets.SSH_MSG_REQUEST_FAILURE:
msgGlobalFailure();
break;
default:
throw new IOException("Cannot handle unknown channel message "
+ (msg[0] & 0xff));
}
}
public void msgChannelClose(byte[] msg, int msglen) throws IOException {
if (msglen != 5)
throw new IOException(
"SSH_MSG_CHANNEL_CLOSE message has wrong size (" + msglen
+ ")");
int id = ((msg[1] & 0xff) << 24) | ((msg[2] & 0xff) << 16)
| ((msg[3] & 0xff) << 8) | (msg[4] & 0xff);
Channel c = getChannel(id);
if (c == null)
throw new IOException(
"Unexpected SSH_MSG_CHANNEL_CLOSE message for non-existent channel "
+ id);
synchronized (c) {
c.EOF = true;
c.state = Channel.STATE_CLOSED;
c.setReasonClosed("Close requested by remote");
c.closeMessageRecv = true;
removeChannel(c.localID);
c.notifyAll();
}
if (log.isEnabled())
log.log(50, "Got SSH_MSG_CHANNEL_CLOSE (channel " + id + ")");
}
public void msgChannelData(byte[] msg, int msglen) throws IOException {
if (msglen <= 9)
throw new IOException(
"SSH_MSG_CHANNEL_DATA message has wrong size (" + msglen
+ ")");
int id = ((msg[1] & 0xff) << 24) | ((msg[2] & 0xff) << 16)
| ((msg[3] & 0xff) << 8) | (msg[4] & 0xff);
int len = ((msg[5] & 0xff) << 24) | ((msg[6] & 0xff) << 16)
| ((msg[7] & 0xff) << 8) | (msg[8] & 0xff);
Channel c = getChannel(id);
if (c == null)
throw new IOException(
"Unexpected SSH_MSG_CHANNEL_DATA message for non-existent channel "
+ id);
if (len != (msglen - 9))
throw new IOException(
"SSH_MSG_CHANNEL_DATA message has wrong len (calculated "
+ (msglen - 9) + ", got " + len + ")");
if (log.isEnabled())
log.log(80, "Got SSH_MSG_CHANNEL_DATA (channel " + id + ", " + len
+ ")");
synchronized (c) {
if (c.state == Channel.STATE_CLOSED)
return; // ignore
if (c.state != Channel.STATE_OPEN)
throw new IOException(
"Got SSH_MSG_CHANNEL_DATA, but channel is not in correct state ("
+ c.state + ")");
if (c.localWindow < len)
throw new IOException(
"Remote sent too much data, does not fit into window.");
c.localWindow -= len;
System.arraycopy(msg, 9, c.stdoutBuffer, c.stdoutWritepos, len);
c.stdoutWritepos += len;
c.notifyAll();
}
}
public void msgChannelEOF(byte[] msg, int msglen) throws IOException {
if (msglen != 5)
throw new IOException(
"SSH_MSG_CHANNEL_EOF message has wrong size (" + msglen
+ ")");
int id = ((msg[1] & 0xff) << 24) | ((msg[2] & 0xff) << 16)
| ((msg[3] & 0xff) << 8) | (msg[4] & 0xff);
Channel c = getChannel(id);
if (c == null)
throw new IOException(
"Unexpected SSH_MSG_CHANNEL_EOF message for non-existent channel "
+ id);
synchronized (c) {
c.EOF = true;
c.notifyAll();
}
if (log.isEnabled())
log.log(50, "Got SSH_MSG_CHANNEL_EOF (channel " + id + ")");
}
public void msgChannelExtendedData(byte[] msg, int msglen)
throws IOException {
if (msglen <= 13)
throw new IOException(
"SSH_MSG_CHANNEL_EXTENDED_DATA message has wrong size ("
+ msglen + ")");
int id = ((msg[1] & 0xff) << 24) | ((msg[2] & 0xff) << 16)
| ((msg[3] & 0xff) << 8) | (msg[4] & 0xff);
int dataType = ((msg[5] & 0xff) << 24) | ((msg[6] & 0xff) << 16)
| ((msg[7] & 0xff) << 8) | (msg[8] & 0xff);
int len = ((msg[9] & 0xff) << 24) | ((msg[10] & 0xff) << 16)
| ((msg[11] & 0xff) << 8) | (msg[12] & 0xff);
Channel c = getChannel(id);
if (c == null)
throw new IOException(
"Unexpected SSH_MSG_CHANNEL_EXTENDED_DATA message for non-existent channel "
+ id);
if (dataType != Packets.SSH_EXTENDED_DATA_STDERR)
throw new IOException(
"SSH_MSG_CHANNEL_EXTENDED_DATA message has unknown type ("
+ dataType + ")");
if (len != (msglen - 13))
throw new IOException(
"SSH_MSG_CHANNEL_EXTENDED_DATA message has wrong len (calculated "
+ (msglen - 13) + ", got " + len + ")");
if (log.isEnabled())
log.log(80, "Got SSH_MSG_CHANNEL_EXTENDED_DATA (channel " + id
+ ", " + len + ")");
synchronized (c) {
if (c.state == Channel.STATE_CLOSED)
return; // ignore
if (c.state != Channel.STATE_OPEN)
throw new IOException(
"Got SSH_MSG_CHANNEL_EXTENDED_DATA, but channel is not in correct state ("
+ c.state + ")");
if (c.localWindow < len)
throw new IOException(
"Remote sent too much data, does not fit into window.");
c.localWindow -= len;
System.arraycopy(msg, 13, c.stderrBuffer, c.stderrWritepos, len);
c.stderrWritepos += len;
c.notifyAll();
}
}
public void msgChannelFailure(byte[] msg, int msglen) throws IOException {
if (msglen != 5)
throw new IOException(
"SSH_MSG_CHANNEL_FAILURE message has wrong size (" + msglen
+ ")");
int id = ((msg[1] & 0xff) << 24) | ((msg[2] & 0xff) << 16)
| ((msg[3] & 0xff) << 8) | (msg[4] & 0xff);
Channel c = getChannel(id);
if (c == null)
throw new IOException(
"Unexpected SSH_MSG_CHANNEL_FAILURE message for non-existent channel "
+ id);
synchronized (c) {
c.failedCounter++;
c.notifyAll();
}
if (log.isEnabled())
log.log(50, "Got SSH_MSG_CHANNEL_FAILURE (channel " + id + ")");
}
public void msgChannelOpen(byte[] msg, int msglen) throws IOException {
TypesReader tr = new TypesReader(msg, 0, msglen);
tr.readByte(); // skip packet type
String channelType = tr.readString();
int remoteID = tr.readUINT32(); /* sender channel */
int remoteWindow = tr.readUINT32(); /* initial window size */
int remoteMaxPacketSize = tr.readUINT32(); /* maximum packet size */
if ("x11".equals(channelType)) {
synchronized (x11_magic_cookies) {
/*
* If we did not request X11 forwarding, then simply ignore this
* bogus request.
*/
if (x11_magic_cookies.size() == 0) {
PacketChannelOpenFailure pcof = new PacketChannelOpenFailure(
remoteID,
Packets.SSH_OPEN_ADMINISTRATIVELY_PROHIBITED,
"X11 forwarding not activated", "");
tm.sendAsynchronousMessage(pcof.getPayload());
if (log.isEnabled())
log.log(20, "Unexpected X11 request, denying it!");
return;
}
}
String remoteOriginatorAddress = tr.readString();
int remoteOriginatorPort = tr.readUINT32();
Channel c = new Channel(this);
synchronized (c) {
c.remoteID = remoteID;
c.remoteWindow = remoteWindow & 0xFFFFffffL; /*
* properly convert
* UINT32 to long
*/
c.remoteMaxPacketSize = remoteMaxPacketSize;
c.localID = addChannel(c);
}
/*
* The open confirmation message will be sent from another thread
*/
RemoteX11AcceptThread rxat = new RemoteX11AcceptThread(c,
remoteOriginatorAddress, remoteOriginatorPort);
rxat.setDaemon(true);
rxat.start();
return;
}
if ("forwarded-tcpip".equals(channelType)) {
String remoteConnectedAddress = tr.readString(); /*
* address that was
* connected
*/
int remoteConnectedPort = tr.readUINT32(); /*
* port that was
* connected
*/
String remoteOriginatorAddress = tr.readString(); /*
* originator IP
* address
*/
int remoteOriginatorPort = tr.readUINT32(); /* originator port */
RemoteForwardingData rfd = null;
synchronized (remoteForwardings) {
rfd = (RemoteForwardingData) remoteForwardings.get(new Integer(
remoteConnectedPort));
}
if (rfd == null) {
PacketChannelOpenFailure pcof = new PacketChannelOpenFailure(
remoteID, Packets.SSH_OPEN_ADMINISTRATIVELY_PROHIBITED,
"No thanks, unknown port in forwarded-tcpip request",
"");
/* Always try to be polite. */
tm.sendAsynchronousMessage(pcof.getPayload());
if (log.isEnabled())
log.log(20,
"Unexpected forwarded-tcpip request, denying it!");
return;
}
Channel c = new Channel(this);
synchronized (c) {
c.remoteID = remoteID;
c.remoteWindow = remoteWindow & 0xFFFFffffL; /*
* convert UINT32 to
* long
*/
c.remoteMaxPacketSize = remoteMaxPacketSize;
c.localID = addChannel(c);
}
/*
* The open confirmation message will be sent from another thread.
*/
RemoteAcceptThread rat = new RemoteAcceptThread(c,
remoteConnectedAddress, remoteConnectedPort,
remoteOriginatorAddress, remoteOriginatorPort,
rfd.targetAddress, rfd.targetPort);
rat.setDaemon(true);
rat.start();
return;
}
if ("auth-agent@openssh.com".equals(channelType)) {
Channel c = new Channel(this);
synchronized (c) {
c.remoteID = remoteID;
c.remoteWindow = remoteWindow & 0xFFFFffffL; /*
* properly convert
* UINT32 to long
*/
c.remoteMaxPacketSize = remoteMaxPacketSize;
c.localID = addChannel(c);
}
AuthAgentForwardThread aat = new AuthAgentForwardThread(c,
authAgent);
aat.setDaemon(true);
aat.start();
return;
}
/* Tell the server that we have no idea what it is talking about */
PacketChannelOpenFailure pcof = new PacketChannelOpenFailure(remoteID,
Packets.SSH_OPEN_UNKNOWN_CHANNEL_TYPE, "Unknown channel type",
"");
tm.sendAsynchronousMessage(pcof.getPayload());
if (log.isEnabled())
log.log(20, "The peer tried to open an unsupported channel type ("
+ channelType + ")");
}
public void msgChannelOpenConfirmation(byte[] msg, int msglen)
throws IOException {
PacketChannelOpenConfirmation sm = new PacketChannelOpenConfirmation(
msg, 0, msglen);
Channel c = getChannel(sm.recipientChannelID);
if (c == null)
throw new IOException(
"Unexpected SSH_MSG_CHANNEL_OPEN_CONFIRMATION message for non-existent channel "
+ sm.recipientChannelID);
synchronized (c) {
if (c.state != Channel.STATE_OPENING)
throw new IOException(
"Unexpected SSH_MSG_CHANNEL_OPEN_CONFIRMATION message for channel "
+ sm.recipientChannelID);
c.remoteID = sm.senderChannelID;
c.remoteWindow = sm.initialWindowSize & 0xFFFFffffL; /*
* convert
* UINT32 to
* long
*/
c.remoteMaxPacketSize = sm.maxPacketSize;
c.state = Channel.STATE_OPEN;
c.notifyAll();
}
if (log.isEnabled())
log.log(50, "Got SSH_MSG_CHANNEL_OPEN_CONFIRMATION (channel "
+ sm.recipientChannelID + " / remote: "
+ sm.senderChannelID + ")");
}
public void msgChannelOpenFailure(byte[] msg, int msglen)
throws IOException {
if (msglen < 5)
throw new IOException(
"SSH_MSG_CHANNEL_OPEN_FAILURE message has wrong size ("
+ msglen + ")");
TypesReader tr = new TypesReader(msg, 0, msglen);
tr.readByte(); // skip packet type
int id = tr.readUINT32(); /* sender channel */
Channel c = getChannel(id);
if (c == null)
throw new IOException(
"Unexpected SSH_MSG_CHANNEL_OPEN_FAILURE message for non-existent channel "
+ id);
int reasonCode = tr.readUINT32();
String description = tr.readString("UTF-8");
String reasonCodeSymbolicName = null;
switch (reasonCode) {
case 1:
reasonCodeSymbolicName = "SSH_OPEN_ADMINISTRATIVELY_PROHIBITED";
break;
case 2:
reasonCodeSymbolicName = "SSH_OPEN_CONNECT_FAILED";
break;
case 3:
reasonCodeSymbolicName = "SSH_OPEN_UNKNOWN_CHANNEL_TYPE";
break;
case 4:
reasonCodeSymbolicName = "SSH_OPEN_RESOURCE_SHORTAGE";
break;
default:
reasonCodeSymbolicName = "UNKNOWN REASON CODE (" + reasonCode + ")";
}
StringBuffer descriptionBuffer = new StringBuffer();
descriptionBuffer.append(description);
for (int i = 0; i < descriptionBuffer.length(); i++) {
char cc = descriptionBuffer.charAt(i);
if ((cc >= 32) && (cc <= 126))
continue;
descriptionBuffer.setCharAt(i, '\uFFFD');
}
synchronized (c) {
c.EOF = true;
c.state = Channel.STATE_CLOSED;
c.setReasonClosed("The server refused to open the channel ("
+ reasonCodeSymbolicName + ", '"
+ descriptionBuffer.toString() + "')");
c.notifyAll();
}
if (log.isEnabled())
log.log(50, "Got SSH_MSG_CHANNEL_OPEN_FAILURE (channel " + id + ")");
}
public void msgChannelRequest(byte[] msg, int msglen) throws IOException {
TypesReader tr = new TypesReader(msg, 0, msglen);
tr.readByte(); // skip packet type
int id = tr.readUINT32();
Channel c = getChannel(id);
if (c == null)
throw new IOException(
"Unexpected SSH_MSG_CHANNEL_REQUEST message for non-existent channel "
+ id);
String type = tr.readString("US-ASCII");
boolean wantReply = tr.readBoolean();
if (log.isEnabled())
log.log(80, "Got SSH_MSG_CHANNEL_REQUEST (channel " + id + ", '"
+ type + "')");
if (type.equals("exit-status")) {
if (wantReply != false)
throw new IOException(
"Badly formatted SSH_MSG_CHANNEL_REQUEST message, 'want reply' is true");
int exit_status = tr.readUINT32();
if (tr.remain() != 0)
throw new IOException(
"Badly formatted SSH_MSG_CHANNEL_REQUEST message");
synchronized (c) {
c.exit_status = new Integer(exit_status);
c.notifyAll();
}
if (log.isEnabled())
log.log(50, "Got EXIT STATUS (channel " + id + ", status "
+ exit_status + ")");
return;
}
if (type.equals("exit-signal")) {
if (wantReply != false)
throw new IOException(
"Badly formatted SSH_MSG_CHANNEL_REQUEST message, 'want reply' is true");
String signame = tr.readString("US-ASCII");
tr.readBoolean();
tr.readString();
tr.readString();
if (tr.remain() != 0)
throw new IOException(
"Badly formatted SSH_MSG_CHANNEL_REQUEST message");
synchronized (c) {
c.exit_signal = signame;
c.notifyAll();
}
if (log.isEnabled())
log.log(50, "Got EXIT SIGNAL (channel " + id + ", signal "
+ signame + ")");
return;
}
/*
* We simply ignore unknown channel requests, however, if the server
* wants a reply, then we signal that we have no idea what it is about.
*/
if (wantReply) {
byte[] reply = new byte[5];
reply[0] = Packets.SSH_MSG_CHANNEL_FAILURE;
reply[1] = (byte) (c.remoteID >> 24);
reply[2] = (byte) (c.remoteID >> 16);
reply[3] = (byte) (c.remoteID >> 8);
reply[4] = (byte) (c.remoteID);
tm.sendAsynchronousMessage(reply);
}
if (log.isEnabled())
log.log(50, "Channel request '" + type
+ "' is not known, ignoring it");
}
public void msgChannelSuccess(byte[] msg, int msglen) throws IOException {
if (msglen != 5)
throw new IOException(
"SSH_MSG_CHANNEL_SUCCESS message has wrong size (" + msglen
+ ")");
int id = ((msg[1] & 0xff) << 24) | ((msg[2] & 0xff) << 16)
| ((msg[3] & 0xff) << 8) | (msg[4] & 0xff);
Channel c = getChannel(id);
if (c == null)
throw new IOException(
"Unexpected SSH_MSG_CHANNEL_SUCCESS message for non-existent channel "
+ id);
synchronized (c) {
c.successCounter++;
c.notifyAll();
}
if (log.isEnabled())
log.log(80, "Got SSH_MSG_CHANNEL_SUCCESS (channel " + id + ")");
}
public void msgChannelWindowAdjust(byte[] msg, int msglen)
throws IOException {
if (msglen != 9)
throw new IOException(
"SSH_MSG_CHANNEL_WINDOW_ADJUST message has wrong size ("
+ msglen + ")");
int id = ((msg[1] & 0xff) << 24) | ((msg[2] & 0xff) << 16)
| ((msg[3] & 0xff) << 8) | (msg[4] & 0xff);
int windowChange = ((msg[5] & 0xff) << 24) | ((msg[6] & 0xff) << 16)
| ((msg[7] & 0xff) << 8) | (msg[8] & 0xff);
Channel c = getChannel(id);
if (c == null)
throw new IOException(
"Unexpected SSH_MSG_CHANNEL_WINDOW_ADJUST message for non-existent channel "
+ id);
synchronized (c) {
final long huge = 0xFFFFffffL; /* 2^32 - 1 */
c.remoteWindow += (windowChange & huge); /* avoid sign extension */
/* TODO - is this a good heuristic? */
if ((c.remoteWindow > huge))
c.remoteWindow = huge;
c.notifyAll();
}
if (log.isEnabled())
log.log(80, "Got SSH_MSG_CHANNEL_WINDOW_ADJUST (channel " + id
+ ", " + windowChange + ")");
}
public void msgGlobalFailure() throws IOException {
synchronized (channels) {
globalFailedCounter++;
channels.notifyAll();
}
if (log.isEnabled())
log.log(80, "Got SSH_MSG_REQUEST_FAILURE");
}
public void msgGlobalRequest(byte[] msg, int msglen) throws IOException {
/* Currently we do not support any kind of global request */
TypesReader tr = new TypesReader(msg, 0, msglen);
tr.readByte(); // skip packet type
String requestName = tr.readString();
boolean wantReply = tr.readBoolean();
if (wantReply) {
byte[] reply_failure = new byte[1];
reply_failure[0] = Packets.SSH_MSG_REQUEST_FAILURE;
tm.sendAsynchronousMessage(reply_failure);
}
/* We do not clean up the requestName String - that is OK for debug */
if (log.isEnabled())
log.log(80, "Got SSH_MSG_GLOBAL_REQUEST (" + requestName + ")");
}
public void msgGlobalSuccess() throws IOException {
synchronized (channels) {
globalSuccessCounter++;
channels.notifyAll();
}
if (log.isEnabled())
log.log(80, "Got SSH_MSG_REQUEST_SUCCESS");
}
public Channel openDirectTCPIPChannel(String host_to_connect,
int port_to_connect, String originator_IP_address,
int originator_port) throws IOException {
Channel c = new Channel(this);
synchronized (c) {
c.localID = addChannel(c);
// end of synchronized block forces writing out to main memory
}
PacketOpenDirectTCPIPChannel dtc = new PacketOpenDirectTCPIPChannel(
c.localID, c.localWindow, c.localMaxPacketSize,
host_to_connect, port_to_connect, originator_IP_address,
originator_port);
tm.sendMessage(dtc.getPayload());
waitUntilChannelOpen(c);
return c;
}
public Channel openSessionChannel() throws IOException {
Channel c = new Channel(this);
synchronized (c) {
c.localID = addChannel(c);
// end of synchronized block forces the writing out to main memory
}
if (log.isEnabled())
log.log(50, "Sending SSH_MSG_CHANNEL_OPEN (Channel " + c.localID
+ ")");
PacketOpenSessionChannel smo = new PacketOpenSessionChannel(c.localID,
c.localWindow, c.localMaxPacketSize);
tm.sendMessage(smo.getPayload());
waitUntilChannelOpen(c);
return c;
}
public void registerThread(IChannelWorkerThread thr) throws IOException {
synchronized (listenerThreads) {
if (listenerThreadsAllowed == false)
throw new IOException("Too late, this connection is closed.");
listenerThreads.addElement(thr);
}
}
public void registerX11Cookie(String hexFakeCookie, X11ServerData data) {
synchronized (x11_magic_cookies) {
x11_magic_cookies.put(hexFakeCookie, data);
}
}
private void removeChannel(int id) {
synchronized (channels) {
for (int i = 0; i < channels.size(); i++) {
Channel c = (Channel) channels.elementAt(i);
if (c.localID == id) {
channels.removeElementAt(i);
break;
}
}
}
}
public void requestCancelGlobalForward(int bindPort) throws IOException {
RemoteForwardingData rfd = null;
synchronized (remoteForwardings) {
rfd = (RemoteForwardingData) remoteForwardings.get(new Integer(
bindPort));
if (rfd == null)
throw new IOException(
"Sorry, there is no known remote forwarding for remote port "
+ bindPort);
}
synchronized (channels) {
globalSuccessCounter = globalFailedCounter = 0;
}
PacketGlobalCancelForwardRequest pgcf = new PacketGlobalCancelForwardRequest(
true, rfd.bindAddress, rfd.bindPort);
tm.sendMessage(pgcf.getPayload());
if (log.isEnabled())
log.log(50, "Requesting cancelation of remote forward ('"
+ rfd.bindAddress + "', " + rfd.bindPort + ")");
try {
if (waitForGlobalRequestResult() == false)
throw new IOException("The server denied the request.");
} finally {
synchronized (remoteForwardings) {
/*
* Only now we are sure that no more forwarded connections will
* arrive
*/
remoteForwardings.remove(rfd);
}
}
}
/**
* @param agent
* @throws IOException
*/
public boolean requestChannelAgentForwarding(Channel c,
AuthAgentCallback authAgent) throws IOException {
synchronized (this) {
if (this.authAgent != null)
throw new IllegalStateException("Auth agent already exists");
this.authAgent = authAgent;
}
synchronized (channels) {
globalSuccessCounter = globalFailedCounter = 0;
}
if (log.isEnabled())
log.log(50, "Requesting agent forwarding");
PacketChannelAuthAgentReq aar = new PacketChannelAuthAgentReq(
c.remoteID);
tm.sendMessage(aar.getPayload());
if (waitForChannelRequestResult(c) == false) {
authAgent = null;
return false;
}
return true;
}
public void requestChannelTrileadPing(Channel c) throws IOException {
PacketChannelTrileadPing pctp;
synchronized (c) {
if (c.state != Channel.STATE_OPEN)
throw new IOException("Cannot ping this channel ("
+ c.getReasonClosed() + ")");
pctp = new PacketChannelTrileadPing(c.remoteID);
c.successCounter = c.failedCounter = 0;
}
synchronized (c.channelSendLock) {
if (c.closeMessageSent)
throw new IOException("Cannot ping this channel ("
+ c.getReasonClosed() + ")");
tm.sendMessage(pctp.getPayload());
}
try {
if (waitForChannelRequestResult(c) == true)
throw new IOException(
"Your server is alive - but buggy. "
+ "It replied with SSH_MSG_SESSION_SUCCESS when it actually should not.");
} catch (IOException e) {
throw (IOException) new IOException("The ping request failed.")
.initCause(e);
}
}
public void requestExecCommand(Channel c, String cmd) throws IOException {
PacketSessionExecCommand sm;
synchronized (c) {
if (c.state != Channel.STATE_OPEN)
throw new IOException(
"Cannot execute command on this channel ("
+ c.getReasonClosed() + ")");
sm = new PacketSessionExecCommand(c.remoteID, true, cmd);
c.successCounter = c.failedCounter = 0;
}
synchronized (c.channelSendLock) {
if (c.closeMessageSent)
throw new IOException(
"Cannot execute command on this channel ("
+ c.getReasonClosed() + ")");
tm.sendMessage(sm.getPayload());
}
if (log.isEnabled())
log.log(50, "Executing command (channel " + c.localID + ", '" + cmd
+ "')");
try {
if (waitForChannelRequestResult(c) == false)
throw new IOException("The server denied the request.");
} catch (IOException e) {
throw (IOException) new IOException("The execute request failed.")
.initCause(e);
}
}
public int requestGlobalForward(String bindAddress, int bindPort,
String targetAddress, int targetPort) throws IOException {
RemoteForwardingData rfd = new RemoteForwardingData();
rfd.bindAddress = bindAddress;
rfd.bindPort = bindPort;
rfd.targetAddress = targetAddress;
rfd.targetPort = targetPort;
synchronized (remoteForwardings) {
Integer key = new Integer(bindPort);
if (remoteForwardings.get(key) != null) {
throw new IOException(
"There is already a forwarding for remote port "
+ bindPort);
}
remoteForwardings.put(key, rfd);
}
synchronized (channels) {
globalSuccessCounter = globalFailedCounter = 0;
}
PacketGlobalForwardRequest pgf = new PacketGlobalForwardRequest(true,
bindAddress, bindPort);
tm.sendMessage(pgf.getPayload());
if (log.isEnabled())
log.log(50, "Requesting a remote forwarding ('" + bindAddress
+ "', " + bindPort + ")");
try {
if (waitForGlobalRequestResult() == false)
throw new IOException(
"The server denied the request (did you enable port forwarding?)");
} catch (IOException e) {
synchronized (remoteForwardings) {
remoteForwardings.remove(rfd);
}
throw e;
}
return bindPort;
}
public void requestGlobalTrileadPing() throws IOException {
synchronized (channels) {
globalSuccessCounter = globalFailedCounter = 0;
}
PacketGlobalTrileadPing pgtp = new PacketGlobalTrileadPing();
tm.sendMessage(pgtp.getPayload());
if (log.isEnabled())
log.log(50, "Sending SSH_MSG_GLOBAL_REQUEST 'trilead-ping'.");
try {
if (waitForGlobalRequestResult() == true)
throw new IOException(
"Your server is alive - but buggy. "
+ "It replied with SSH_MSG_REQUEST_SUCCESS when it actually should not.");
} catch (IOException e) {
throw (IOException) new IOException("The ping request failed.")
.initCause(e);
}
}
public void requestPTY(Channel c, String term, int term_width_characters,
int term_height_characters, int term_width_pixels,
int term_height_pixels, byte[] terminal_modes) throws IOException {
PacketSessionPtyRequest spr;
synchronized (c) {
if (c.state != Channel.STATE_OPEN)
throw new IOException("Cannot request PTY on this channel ("
+ c.getReasonClosed() + ")");
spr = new PacketSessionPtyRequest(c.remoteID, true, term,
term_width_characters, term_height_characters,
term_width_pixels, term_height_pixels, terminal_modes);
c.successCounter = c.failedCounter = 0;
}
synchronized (c.channelSendLock) {
if (c.closeMessageSent)
throw new IOException("Cannot request PTY on this channel ("
+ c.getReasonClosed() + ")");
tm.sendMessage(spr.getPayload());
}
try {
if (waitForChannelRequestResult(c) == false)
throw new IOException("The server denied the request.");
} catch (IOException e) {
throw (IOException) new IOException("PTY request failed")
.initCause(e);
}
}
public void requestShell(Channel c) throws IOException {
PacketSessionStartShell sm;
synchronized (c) {
if (c.state != Channel.STATE_OPEN)
throw new IOException("Cannot start shell on this channel ("
+ c.getReasonClosed() + ")");
sm = new PacketSessionStartShell(c.remoteID, true);
c.successCounter = c.failedCounter = 0;
}
synchronized (c.channelSendLock) {
if (c.closeMessageSent)
throw new IOException("Cannot start shell on this channel ("
+ c.getReasonClosed() + ")");
tm.sendMessage(sm.getPayload());
}
try {
if (waitForChannelRequestResult(c) == false)
throw new IOException("The server denied the request.");
} catch (IOException e) {
throw (IOException) new IOException("The shell request failed.")
.initCause(e);
}
}
public void requestSubSystem(Channel c, String subSystemName)
throws IOException {
PacketSessionSubsystemRequest ssr;
synchronized (c) {
if (c.state != Channel.STATE_OPEN)
throw new IOException(
"Cannot request subsystem on this channel ("
+ c.getReasonClosed() + ")");
ssr = new PacketSessionSubsystemRequest(c.remoteID, true,
subSystemName);
c.successCounter = c.failedCounter = 0;
}
synchronized (c.channelSendLock) {
if (c.closeMessageSent)
throw new IOException(
"Cannot request subsystem on this channel ("
+ c.getReasonClosed() + ")");
tm.sendMessage(ssr.getPayload());
}
try {
if (waitForChannelRequestResult(c) == false)
throw new IOException("The server denied the request.");
} catch (IOException e) {
throw (IOException) new IOException("The subsystem request failed.")
.initCause(e);
}
}
public void requestX11(Channel c, boolean singleConnection,
String x11AuthenticationProtocol, String x11AuthenticationCookie,
int x11ScreenNumber) throws IOException {
PacketSessionX11Request psr;
synchronized (c) {
if (c.state != Channel.STATE_OPEN)
throw new IOException("Cannot request X11 on this channel ("
+ c.getReasonClosed() + ")");
psr = new PacketSessionX11Request(c.remoteID, true,
singleConnection, x11AuthenticationProtocol,
x11AuthenticationCookie, x11ScreenNumber);
c.successCounter = c.failedCounter = 0;
}
synchronized (c.channelSendLock) {
if (c.closeMessageSent)
throw new IOException("Cannot request X11 on this channel ("
+ c.getReasonClosed() + ")");
tm.sendMessage(psr.getPayload());
}
if (log.isEnabled())
log.log(50, "Requesting X11 forwarding (Channel " + c.localID + "/"
+ c.remoteID + ")");
try {
if (waitForChannelRequestResult(c) == false)
throw new IOException("The server denied the request.");
} catch (IOException e) {
throw (IOException) new IOException("The X11 request failed.")
.initCause(e);
}
}
public void resizePTY(Channel c, int term_width_characters,
int term_height_characters, int term_width_pixels,
int term_height_pixels) throws IOException {
PacketSessionPtyResize spr;
synchronized (c) {
if (c.state != Channel.STATE_OPEN)
throw new IOException("Cannot request PTY on this channel ("
+ c.getReasonClosed() + ")");
spr = new PacketSessionPtyResize(c.remoteID, term_width_characters,
term_height_characters, term_width_pixels,
term_height_pixels);
c.successCounter = c.failedCounter = 0;
}
synchronized (c.channelSendLock) {
if (c.closeMessageSent)
throw new IOException("Cannot request PTY on this channel ("
+ c.getReasonClosed() + ")");
tm.sendMessage(spr.getPayload());
}
}
public void sendData(Channel c, byte[] buffer, int pos, int len)
throws IOException {
while (len > 0) {
int thislen = 0;
byte[] msg;
synchronized (c) {
while (true) {
if (c.state == Channel.STATE_CLOSED)
throw new IOException("SSH channel is closed. ("
+ c.getReasonClosed() + ")");
if (c.state != Channel.STATE_OPEN)
throw new IOException("SSH channel in strange state. ("
+ c.state + ")");
if (c.remoteWindow != 0)
break;
try {
c.wait();
} catch (InterruptedException ignore) {
}
}
/* len > 0, no sign extension can happen when comparing */
thislen = (c.remoteWindow >= len) ? len : (int) c.remoteWindow;
int estimatedMaxDataLen = c.remoteMaxPacketSize
- (tm.getPacketOverheadEstimate() + 9);
/* The worst case scenario =) a true bottleneck */
if (estimatedMaxDataLen <= 0) {
estimatedMaxDataLen = 1;
}
if (thislen > estimatedMaxDataLen)
thislen = estimatedMaxDataLen;
c.remoteWindow -= thislen;
msg = new byte[1 + 8 + thislen];
msg[0] = Packets.SSH_MSG_CHANNEL_DATA;
msg[1] = (byte) (c.remoteID >> 24);
msg[2] = (byte) (c.remoteID >> 16);
msg[3] = (byte) (c.remoteID >> 8);
msg[4] = (byte) (c.remoteID);
msg[5] = (byte) (thislen >> 24);
msg[6] = (byte) (thislen >> 16);
msg[7] = (byte) (thislen >> 8);
msg[8] = (byte) (thislen);
System.arraycopy(buffer, pos, msg, 9, thislen);
}
synchronized (c.channelSendLock) {
if (c.closeMessageSent == true)
throw new IOException("SSH channel is closed. ("
+ c.getReasonClosed() + ")");
tm.sendMessage(msg);
}
pos += thislen;
len -= thislen;
}
}
public void sendEOF(Channel c) throws IOException {
byte[] msg = new byte[5];
synchronized (c) {
if (c.state != Channel.STATE_OPEN)
return;
msg[0] = Packets.SSH_MSG_CHANNEL_EOF;
msg[1] = (byte) (c.remoteID >> 24);
msg[2] = (byte) (c.remoteID >> 16);
msg[3] = (byte) (c.remoteID >> 8);
msg[4] = (byte) (c.remoteID);
}
synchronized (c.channelSendLock) {
if (c.closeMessageSent == true)
return;
tm.sendMessage(msg);
}
if (log.isEnabled())
log.log(50, "Sent EOF (Channel " + c.localID + "/" + c.remoteID
+ ")");
}
public void sendOpenConfirmation(Channel c) throws IOException {
PacketChannelOpenConfirmation pcoc = null;
synchronized (c) {
if (c.state != Channel.STATE_OPENING)
return;
c.state = Channel.STATE_OPEN;
pcoc = new PacketChannelOpenConfirmation(c.remoteID, c.localID,
c.localWindow, c.localMaxPacketSize);
}
synchronized (c.channelSendLock) {
if (c.closeMessageSent == true)
return;
tm.sendMessage(pcoc.getPayload());
}
}
public void unRegisterX11Cookie(String hexFakeCookie, boolean killChannels) {
if (hexFakeCookie == null)
throw new IllegalStateException("hexFakeCookie may not be null");
synchronized (x11_magic_cookies) {
x11_magic_cookies.remove(hexFakeCookie);
}
if (killChannels == false)
return;
if (log.isEnabled())
log.log(50, "Closing all X11 channels for the given fake cookie");
Vector channel_copy;
synchronized (channels) {
channel_copy = (Vector) channels.clone();
}
for (int i = 0; i < channel_copy.size(); i++) {
Channel c = (Channel) channel_copy.elementAt(i);
synchronized (c) {
if (hexFakeCookie.equals(c.hexX11FakeCookie) == false)
continue;
}
try {
closeChannel(
c,
"Closing X11 channel since the corresponding session is closing",
true);
} catch (IOException e) {
}
}
}
private final boolean waitForChannelRequestResult(Channel c)
throws IOException {
synchronized (c) {
while ((c.successCounter == 0) && (c.failedCounter == 0)) {
if (c.state != Channel.STATE_OPEN) {
String detail = c.getReasonClosed();
if (detail == null)
detail = "state: " + c.state;
throw new IOException("This SSH2 channel is not open ("
+ detail + ")");
}
try {
c.wait();
} catch (InterruptedException ignore) {
}
}
if ((c.failedCounter == 0) && (c.successCounter == 1))
return true;
if ((c.failedCounter == 1) && (c.successCounter == 0))
return false;
throw new IOException("Illegal state. The server sent "
+ c.successCounter + " SSH_MSG_CHANNEL_SUCCESS and "
+ c.failedCounter + " SSH_MSG_CHANNEL_FAILURE messages.");
}
}
/**
* Wait until for a condition.
*
* @param c
* Channel
* @param timeout
* in ms, 0 means no timeout.
* @param condition_mask
* minimum event mask
* @return all current events
*
*/
public int waitForCondition(Channel c, long timeout, int condition_mask) {
long end_time = 0;
boolean end_time_set = false;
synchronized (c) {
while (true) {
int current_cond = 0;
int stdoutAvail = c.stdoutWritepos - c.stdoutReadpos;
int stderrAvail = c.stderrWritepos - c.stderrReadpos;
if (stdoutAvail > 0)
current_cond = current_cond | ChannelCondition.STDOUT_DATA;
if (stderrAvail > 0)
current_cond = current_cond | ChannelCondition.STDERR_DATA;
if (c.EOF)
current_cond = current_cond | ChannelCondition.EOF;
if (c.getExitStatus() != null)
current_cond = current_cond | ChannelCondition.EXIT_STATUS;
if (c.getExitSignal() != null)
current_cond = current_cond | ChannelCondition.EXIT_SIGNAL;
if (c.state == Channel.STATE_CLOSED)
return current_cond | ChannelCondition.CLOSED
| ChannelCondition.EOF;
if ((current_cond & condition_mask) != 0)
return current_cond;
if (timeout > 0) {
if (!end_time_set) {
end_time = System.currentTimeMillis() + timeout;
end_time_set = true;
} else {
timeout = end_time - System.currentTimeMillis();
if (timeout <= 0)
return current_cond | ChannelCondition.TIMEOUT;
}
}
try {
if (timeout > 0)
c.wait(timeout);
else
c.wait();
} catch (InterruptedException e) {
}
}
}
}
private final boolean waitForGlobalRequestResult() throws IOException {
synchronized (channels) {
while ((globalSuccessCounter == 0) && (globalFailedCounter == 0)) {
if (shutdown) {
throw new IOException("The connection is being shutdown");
}
try {
channels.wait();
} catch (InterruptedException ignore) {
}
}
if ((globalFailedCounter == 0) && (globalSuccessCounter == 1))
return true;
if ((globalFailedCounter == 1) && (globalSuccessCounter == 0))
return false;
throw new IOException("Illegal state. The server sent "
+ globalSuccessCounter + " SSH_MSG_REQUEST_SUCCESS and "
+ globalFailedCounter
+ " SSH_MSG_REQUEST_FAILURE messages.");
}
}
private void waitUntilChannelOpen(Channel c) throws IOException {
synchronized (c) {
while (c.state == Channel.STATE_OPENING) {
try {
c.wait();
} catch (InterruptedException ignore) {
}
}
if (c.state != Channel.STATE_OPEN) {
removeChannel(c.localID);
String detail = c.getReasonClosed();
if (detail == null)
detail = "state: " + c.state;
throw new IOException("Could not open channel (" + detail + ")");
}
}
}
}
| 07pratik-myssh | src/com/trilead/ssh2/channel/ChannelManager.java | Java | gpl3 | 47,985 |
package com.trilead.ssh2.sftp;
/**
*
* SFTP Attribute Bits for the "attrib-bits" and "attrib-bits-valid" fields of
* the SFTP ATTR data type.
* <p>
* Yes, these are the "attrib-bits", even though they have "_FLAGS_" in their
* name. Don't ask - I did not invent it.
* <p>
* "<i>These fields, taken together, reflect various attributes of the file or
* directory, on the server. Bits not set in 'attrib-bits-valid' MUST be ignored
* in the 'attrib-bits' field. This allows both the server and the client to
* communicate only the bits it knows about without inadvertently twiddling bits
* they don't understand.</i>"
*
* @author Christian Plattner, plattner@trilead.com
* @version $Id: AttribBits.java,v 1.1 2007/10/15 12:49:55 cplattne Exp $
*
*/
public class AttribBits {
/**
* Advisory, read-only bit. This bit is not part of the access control
* information on the file, but is rather an advisory field indicating that
* the file should not be written.
*/
public static final int SSH_FILEXFER_ATTR_FLAGS_READONLY = 0x00000001;
/**
* The file is part of the operating system.
*/
public static final int SSH_FILEXFER_ATTR_FLAGS_SYSTEM = 0x00000002;
/**
* File SHOULD NOT be shown to user unless specifically requested. For
* example, most UNIX systems SHOULD set this bit if the filename begins
* with a 'period'. This bit may be read-only (see section 5.4 of the SFTP
* standard draft). Most UNIX systems will not allow this to be changed.
*/
public static final int SSH_FILEXFER_ATTR_FLAGS_HIDDEN = 0x00000004;
/**
* This attribute applies only to directories. This attribute is always
* read-only, and cannot be modified. This attribute means that files and
* directory names in this directory should be compared without regard to
* case.
* <p>
* It is recommended that where possible, the server's filesystem be allowed
* to do comparisons. For example, if a client wished to prompt a user
* before overwriting a file, it should not compare the new name with the
* previously retrieved list of names in the directory. Rather, it should
* first try to create the new file by specifying SSH_FXF_CREATE_NEW flag.
* Then, if this fails and returns SSH_FX_FILE_ALREADY_EXISTS, it should
* prompt the user and then retry the create specifying
* SSH_FXF_CREATE_TRUNCATE.
* <p>
* Unless otherwise specified, filenames are assumed to be case sensitive.
*/
public static final int SSH_FILEXFER_ATTR_FLAGS_CASE_INSENSITIVE = 0x00000008;
/**
* The file should be included in backup / archive operations.
*/
public static final int SSH_FILEXFER_ATTR_FLAGS_ARCHIVE = 0x00000010;
/**
* The file is stored on disk using file-system level transparent
* encryption. This flag does not affect the file data on the wire (for
* either READ or WRITE requests.)
*/
public static final int SSH_FILEXFER_ATTR_FLAGS_ENCRYPTED = 0x00000020;
/**
* The file is stored on disk using file-system level transparent
* compression. This flag does not affect the file data on the wire.
*/
public static final int SSH_FILEXFER_ATTR_FLAGS_COMPRESSED = 0x00000040;
/**
* The file is a sparse file; this means that file blocks that have not been
* explicitly written are not stored on disk. For example, if a client
* writes a buffer at 10 M from the beginning of the file, the blocks
* between the previous EOF marker and the 10 M offset would not consume
* physical disk space.
* <p>
* Some servers may store all files as sparse files, in which case this bit
* will be unconditionally set. Other servers may not have a mechanism for
* determining if the file is sparse, and so the file MAY be stored sparse
* even if this flag is not set.
*/
public static final int SSH_FILEXFER_ATTR_FLAGS_SPARSE = 0x00000080;
/**
* Opening the file without either the SSH_FXF_ACCESS_APPEND_DATA or the
* SSH_FXF_ACCESS_APPEND_DATA_ATOMIC flag (see section 8.1.1.3 of the SFTP
* standard draft) MUST result in an SSH_FX_INVALID_PARAMETER error.
*/
public static final int SSH_FILEXFER_ATTR_FLAGS_APPEND_ONLY = 0x00000100;
/**
* The file cannot be deleted or renamed, no hard link can be created to
* this file, and no data can be written to the file.
* <p>
* This bit implies a stronger level of protection than
* SSH_FILEXFER_ATTR_FLAGS_READONLY, the file permission mask or ACLs.
* Typically even the superuser cannot write to immutable files, and only
* the superuser can set or remove the bit.
*/
public static final int SSH_FILEXFER_ATTR_FLAGS_IMMUTABLE = 0x00000200;
/**
* When the file is modified, the changes are written synchronously to the
* disk.
*/
public static final int SSH_FILEXFER_ATTR_FLAGS_SYNC = 0x00000400;
/**
* The server MAY include this bit in a directory listing or realpath
* response. It indicates there was a failure in the translation to UTF-8.
* If this flag is included, the server SHOULD also include the
* UNTRANSLATED_NAME attribute.
*/
public static final int SSH_FILEXFER_ATTR_FLAGS_TRANSLATION_ERR = 0x00000800;
}
| 07pratik-myssh | src/com/trilead/ssh2/sftp/AttribBits.java | Java | gpl3 | 5,221 |
package com.trilead.ssh2.sftp;
/**
*
* Permissions for the 'permissions' field in the SFTP ATTRS data type.
* <p>
* "<i>The 'permissions' field contains a bit mask specifying file permissions.
* These permissions correspond to the st_mode field of the stat structure
* defined by POSIX [IEEE.1003-1.1996].</i>"
*
* @author Christian Plattner, plattner@trilead.com
* @version $Id: AttribPermissions.java,v 1.1 2007/10/15 12:49:55 cplattne Exp $
*
*/
public class AttribPermissions {
/* Octal values! */
public static final int S_IRUSR = 0400;
public static final int S_IWUSR = 0200;
public static final int S_IXUSR = 0100;
public static final int S_IRGRP = 0040;
public static final int S_IWGRP = 0020;
public static final int S_IXGRP = 0010;
public static final int S_IROTH = 0004;
public static final int S_IWOTH = 0002;
public static final int S_IXOTH = 0001;
public static final int S_ISUID = 04000;
public static final int S_ISGID = 02000;
public static final int S_ISVTX = 01000;
}
| 07pratik-myssh | src/com/trilead/ssh2/sftp/AttribPermissions.java | Java | gpl3 | 1,046 |
package com.trilead.ssh2.sftp;
/**
*
* Attribute Flags. The 'valid-attribute-flags' field in the SFTP ATTRS data
* type specifies which of the fields are actually present.
*
* @author Christian Plattner, plattner@trilead.com
* @version $Id: AttribFlags.java,v 1.1 2007/10/15 12:49:55 cplattne Exp $
*
*/
public class AttribFlags {
/**
* Indicates that the 'allocation-size' field is present.
*/
public static final int SSH_FILEXFER_ATTR_SIZE = 0x00000001;
/**
* Protocol version 6: 0x00000002 was used in a previous version of this
* protocol. It is now a reserved value and MUST NOT appear in the mask.
* Some future version of this protocol may reuse this value.
*/
public static final int SSH_FILEXFER_ATTR_V3_UIDGID = 0x00000002;
/**
* Indicates that the 'permissions' field is present.
*/
public static final int SSH_FILEXFER_ATTR_PERMISSIONS = 0x00000004;
/**
* Indicates that the 'atime' and 'mtime' field are present (protocol v3).
*/
public static final int SSH_FILEXFER_ATTR_V3_ACMODTIME = 0x00000008;
/**
* Indicates that the 'atime' field is present.
*/
public static final int SSH_FILEXFER_ATTR_ACCESSTIME = 0x00000008;
/**
* Indicates that the 'createtime' field is present.
*/
public static final int SSH_FILEXFER_ATTR_CREATETIME = 0x00000010;
/**
* Indicates that the 'mtime' field is present.
*/
public static final int SSH_FILEXFER_ATTR_MODIFYTIME = 0x00000020;
/**
* Indicates that the 'acl' field is present.
*/
public static final int SSH_FILEXFER_ATTR_ACL = 0x00000040;
/**
* Indicates that the 'owner' and 'group' fields are present.
*/
public static final int SSH_FILEXFER_ATTR_OWNERGROUP = 0x00000080;
/**
* Indicates that additionally to the 'atime', 'createtime', 'mtime' and
* 'ctime' fields (if present), there is also 'atime-nseconds',
* 'createtime-nseconds', 'mtime-nseconds' and 'ctime-nseconds'.
*/
public static final int SSH_FILEXFER_ATTR_SUBSECOND_TIMES = 0x00000100;
/**
* Indicates that the 'attrib-bits' and 'attrib-bits-valid' fields are
* present.
*/
public static final int SSH_FILEXFER_ATTR_BITS = 0x00000200;
/**
* Indicates that the 'allocation-size' field is present.
*/
public static final int SSH_FILEXFER_ATTR_ALLOCATION_SIZE = 0x00000400;
/**
* Indicates that the 'text-hint' field is present.
*/
public static final int SSH_FILEXFER_ATTR_TEXT_HINT = 0x00000800;
/**
* Indicates that the 'mime-type' field is present.
*/
public static final int SSH_FILEXFER_ATTR_MIME_TYPE = 0x00001000;
/**
* Indicates that the 'link-count' field is present.
*/
public static final int SSH_FILEXFER_ATTR_LINK_COUNT = 0x00002000;
/**
* Indicates that the 'untranslated-name' field is present.
*/
public static final int SSH_FILEXFER_ATTR_UNTRANSLATED_NAME = 0x00004000;
/**
* Indicates that the 'ctime' field is present.
*/
public static final int SSH_FILEXFER_ATTR_CTIME = 0x00008000;
/**
* Indicates that the 'extended-count' field (and probablby some
* 'extensions') is present.
*/
public static final int SSH_FILEXFER_ATTR_EXTENDED = 0x80000000;
}
| 07pratik-myssh | src/com/trilead/ssh2/sftp/AttribFlags.java | Java | gpl3 | 3,243 |
package com.trilead.ssh2.sftp;
/**
*
* Types for the 'type' field in the SFTP ATTRS data type.
* <p>
* "<i>On a POSIX system, these values would be derived from the mode field of
* the stat structure. SPECIAL should be used for files that are of a known type
* which cannot be expressed in the protocol. UNKNOWN should be used if the type
* is not known.</i>"
*
* @author Christian Plattner, plattner@trilead.com
* @version $Id: AttribTypes.java,v 1.1 2007/10/15 12:49:55 cplattne Exp $
*
*/
public class AttribTypes {
public static final int SSH_FILEXFER_TYPE_REGULAR = 1;
public static final int SSH_FILEXFER_TYPE_DIRECTORY = 2;
public static final int SSH_FILEXFER_TYPE_SYMLINK = 3;
public static final int SSH_FILEXFER_TYPE_SPECIAL = 4;
public static final int SSH_FILEXFER_TYPE_UNKNOWN = 5;
public static final int SSH_FILEXFER_TYPE_SOCKET = 6;
public static final int SSH_FILEXFER_TYPE_CHAR_DEVICE = 7;
public static final int SSH_FILEXFER_TYPE_BLOCK_DEVICE = 8;
public static final int SSH_FILEXFER_TYPE_FIFO = 9;
}
| 07pratik-myssh | src/com/trilead/ssh2/sftp/AttribTypes.java | Java | gpl3 | 1,074 |
package com.trilead.ssh2.sftp;
/**
*
* SFTP Error Codes
*
* @author Christian Plattner, plattner@trilead.com
* @version $Id: ErrorCodes.java,v 1.1 2007/10/15 12:49:55 cplattne Exp $
*
*/
public class ErrorCodes {
public static final int SSH_FX_OK = 0;
public static final int SSH_FX_EOF = 1;
public static final int SSH_FX_NO_SUCH_FILE = 2;
public static final int SSH_FX_PERMISSION_DENIED = 3;
public static final int SSH_FX_FAILURE = 4;
public static final int SSH_FX_BAD_MESSAGE = 5;
public static final int SSH_FX_NO_CONNECTION = 6;
public static final int SSH_FX_CONNECTION_LOST = 7;
public static final int SSH_FX_OP_UNSUPPORTED = 8;
public static final int SSH_FX_INVALID_HANDLE = 9;
public static final int SSH_FX_NO_SUCH_PATH = 10;
public static final int SSH_FX_FILE_ALREADY_EXISTS = 11;
public static final int SSH_FX_WRITE_PROTECT = 12;
public static final int SSH_FX_NO_MEDIA = 13;
public static final int SSH_FX_NO_SPACE_ON_FILESYSTEM = 14;
public static final int SSH_FX_QUOTA_EXCEEDED = 15;
public static final int SSH_FX_UNKNOWN_PRINCIPAL = 16;
public static final int SSH_FX_LOCK_CONFLICT = 17;
public static final int SSH_FX_DIR_NOT_EMPTY = 18;
public static final int SSH_FX_NOT_A_DIRECTORY = 19;
public static final int SSH_FX_INVALID_FILENAME = 20;
public static final int SSH_FX_LINK_LOOP = 21;
public static final int SSH_FX_CANNOT_DELETE = 22;
public static final int SSH_FX_INVALID_PARAMETER = 23;
public static final int SSH_FX_FILE_IS_A_DIRECTORY = 24;
public static final int SSH_FX_BYTE_RANGE_LOCK_CONFLICT = 25;
public static final int SSH_FX_BYTE_RANGE_LOCK_REFUSED = 26;
public static final int SSH_FX_DELETE_PENDING = 27;
public static final int SSH_FX_FILE_CORRUPT = 28;
public static final int SSH_FX_OWNER_INVALID = 29;
public static final int SSH_FX_GROUP_INVALID = 30;
public static final int SSH_FX_NO_MATCHING_BYTE_RANGE_LOCK = 31;
private static final String[][] messages = {
{ "SSH_FX_OK", "Indicates successful completion of the operation." },
{
"SSH_FX_EOF",
"An attempt to read past the end-of-file was made; or, there are no more directory entries to return." },
{ "SSH_FX_NO_SUCH_FILE",
"A reference was made to a file which does not exist." },
{ "SSH_FX_PERMISSION_DENIED",
"The user does not have sufficient permissions to perform the operation." },
{ "SSH_FX_FAILURE",
"An error occurred, but no specific error code exists to describe the failure." },
{ "SSH_FX_BAD_MESSAGE",
"A badly formatted packet or other SFTP protocol incompatibility was detected." },
{ "SSH_FX_NO_CONNECTION", "There is no connection to the server." },
{ "SSH_FX_CONNECTION_LOST",
"The connection to the server was lost." },
{
"SSH_FX_OP_UNSUPPORTED",
"An attempted operation could not be completed by the server because the server does not support the operation." },
{ "SSH_FX_INVALID_HANDLE", "The handle value was invalid." },
{ "SSH_FX_NO_SUCH_PATH",
"The file path does not exist or is invalid." },
{ "SSH_FX_FILE_ALREADY_EXISTS", "The file already exists." },
{ "SSH_FX_WRITE_PROTECT",
"The file is on read-only media, or the media is write protected." },
{
"SSH_FX_NO_MEDIA",
"The requested operation cannot be completed because there is no media available in the drive." },
{
"SSH_FX_NO_SPACE_ON_FILESYSTEM",
"The requested operation cannot be completed because there is insufficient free space on the filesystem." },
{
"SSH_FX_QUOTA_EXCEEDED",
"The operation cannot be completed because it would exceed the user's storage quota." },
{
"SSH_FX_UNKNOWN_PRINCIPAL",
"A principal referenced by the request (either the 'owner', 'group', or 'who' field of an ACL), was unknown. The error specific data contains the problematic names." },
{ "SSH_FX_LOCK_CONFLICT",
"The file could not be opened because it is locked by another process." },
{ "SSH_FX_DIR_NOT_EMPTY", "The directory is not empty." },
{ "SSH_FX_NOT_A_DIRECTORY",
"The specified file is not a directory." },
{ "SSH_FX_INVALID_FILENAME", "The filename is not valid." },
{
"SSH_FX_LINK_LOOP",
"Too many symbolic links encountered or, an SSH_FXF_NOFOLLOW open encountered a symbolic link as the final component." },
{
"SSH_FX_CANNOT_DELETE",
"The file cannot be deleted. One possible reason is that the advisory READONLY attribute-bit is set." },
{
"SSH_FX_INVALID_PARAMETER",
"One of the parameters was out of range, or the parameters specified cannot be used together." },
{
"SSH_FX_FILE_IS_A_DIRECTORY",
"The specified file was a directory in a context where a directory cannot be used." },
{
"SSH_FX_BYTE_RANGE_LOCK_CONFLICT",
" A read or write operation failed because another process's mandatory byte-range lock overlaps with the request." },
{ "SSH_FX_BYTE_RANGE_LOCK_REFUSED",
"A request for a byte range lock was refused." },
{ "SSH_FX_DELETE_PENDING",
"An operation was attempted on a file for which a delete operation is pending." },
{ "SSH_FX_FILE_CORRUPT",
"The file is corrupt; an filesystem integrity check should be run." },
{ "SSH_FX_OWNER_INVALID",
"The principal specified can not be assigned as an owner of a file." },
{ "SSH_FX_GROUP_INVALID",
"The principal specified can not be assigned as the primary group of a file." },
{
"SSH_FX_NO_MATCHING_BYTE_RANGE_LOCK",
"The requested operation could not be completed because the specifed byte range lock has not been granted." },
};
public static final String[] getDescription(int errorCode) {
if ((errorCode < 0) || (errorCode >= messages.length))
return null;
return messages[errorCode];
}
}
| 07pratik-myssh | src/com/trilead/ssh2/sftp/ErrorCodes.java | Java | gpl3 | 5,920 |
package com.trilead.ssh2.sftp;
/**
*
* SFTP Paket Types
*
* @author Christian Plattner, plattner@trilead.com
* @version $Id: Packet.java,v 1.1 2007/10/15 12:49:55 cplattne Exp $
*
*/
public class Packet {
public static final int SSH_FXP_INIT = 1;
public static final int SSH_FXP_VERSION = 2;
public static final int SSH_FXP_OPEN = 3;
public static final int SSH_FXP_CLOSE = 4;
public static final int SSH_FXP_READ = 5;
public static final int SSH_FXP_WRITE = 6;
public static final int SSH_FXP_LSTAT = 7;
public static final int SSH_FXP_FSTAT = 8;
public static final int SSH_FXP_SETSTAT = 9;
public static final int SSH_FXP_FSETSTAT = 10;
public static final int SSH_FXP_OPENDIR = 11;
public static final int SSH_FXP_READDIR = 12;
public static final int SSH_FXP_REMOVE = 13;
public static final int SSH_FXP_MKDIR = 14;
public static final int SSH_FXP_RMDIR = 15;
public static final int SSH_FXP_REALPATH = 16;
public static final int SSH_FXP_STAT = 17;
public static final int SSH_FXP_RENAME = 18;
public static final int SSH_FXP_READLINK = 19;
public static final int SSH_FXP_SYMLINK = 20;
public static final int SSH_FXP_STATUS = 101;
public static final int SSH_FXP_HANDLE = 102;
public static final int SSH_FXP_DATA = 103;
public static final int SSH_FXP_NAME = 104;
public static final int SSH_FXP_ATTRS = 105;
public static final int SSH_FXP_EXTENDED = 200;
public static final int SSH_FXP_EXTENDED_REPLY = 201;
}
| 07pratik-myssh | src/com/trilead/ssh2/sftp/Packet.java | Java | gpl3 | 1,503 |
package com.trilead.ssh2.sftp;
/**
*
* Values for the 'text-hint' field in the SFTP ATTRS data type.
*
* @author Christian Plattner, plattner@trilead.com
* @version $Id: AttrTextHints.java,v 1.1 2007/10/15 12:49:55 cplattne Exp $
*
*/
public class AttrTextHints {
/**
* The server knows the file is a text file, and should be opened using the
* SSH_FXF_ACCESS_TEXT_MODE flag.
*/
public static final int SSH_FILEXFER_ATTR_KNOWN_TEXT = 0x00;
/**
* The server has applied a heuristic or other mechanism and believes that
* the file should be opened with the SSH_FXF_ACCESS_TEXT_MODE flag.
*/
public static final int SSH_FILEXFER_ATTR_GUESSED_TEXT = 0x01;
/**
* The server knows the file has binary content.
*/
public static final int SSH_FILEXFER_ATTR_KNOWN_BINARY = 0x02;
/**
* The server has applied a heuristic or other mechanism and believes has
* binary content, and should not be opened with the
* SSH_FXF_ACCESS_TEXT_MODE flag.
*/
public static final int SSH_FILEXFER_ATTR_GUESSED_BINARY = 0x03;
}
| 07pratik-myssh | src/com/trilead/ssh2/sftp/AttrTextHints.java | Java | gpl3 | 1,083 |
package com.trilead.ssh2.sftp;
/**
*
* SFTP Open Flags.
*
* The following table is provided to assist in mapping POSIX semantics to
* equivalent SFTP file open parameters:
* <p>
* TODO: This comment should be moved to the open method.
* <p>
* <ul>
* <li>O_RDONLY
* <ul>
* <li>desired-access = READ_DATA | READ_ATTRIBUTES</li>
* </ul>
* </li>
* </ul>
* <ul>
* <li>O_WRONLY
* <ul>
* <li>desired-access = WRITE_DATA | WRITE_ATTRIBUTES</li>
* </ul>
* </li>
* </ul>
* <ul>
* <li>O_RDWR
* <ul>
* <li>desired-access = READ_DATA | READ_ATTRIBUTES | WRITE_DATA |
* WRITE_ATTRIBUTES</li>
* </ul>
* </li>
* </ul>
* <ul>
* <li>O_APPEND
* <ul>
* <li>desired-access = WRITE_DATA | WRITE_ATTRIBUTES | APPEND_DATA</li>
* <li>flags = SSH_FXF_ACCESS_APPEND_DATA and or
* SSH_FXF_ACCESS_APPEND_DATA_ATOMIC</li>
* </ul>
* </li>
* </ul>
* <ul>
* <li>O_CREAT
* <ul>
* <li>flags = SSH_FXF_OPEN_OR_CREATE</li>
* </ul>
* </li>
* </ul>
* <ul>
* <li>O_TRUNC
* <ul>
* <li>flags = SSH_FXF_TRUNCATE_EXISTING</li>
* </ul>
* </li>
* </ul>
* <ul>
* <li>O_TRUNC|O_CREATE
* <ul>
* <li>flags = SSH_FXF_CREATE_TRUNCATE</li>
* </ul>
* </li>
* </ul>
*
* @author Christian Plattner, plattner@trilead.com
* @version $Id: OpenFlags.java,v 1.1 2007/10/15 12:49:55 cplattne Exp $
*/
public class OpenFlags {
/**
* Disposition is a 3 bit field that controls how the file is opened. The
* server MUST support these bits (possible enumaration values:
* SSH_FXF_CREATE_NEW, SSH_FXF_CREATE_TRUNCATE, SSH_FXF_OPEN_EXISTING,
* SSH_FXF_OPEN_OR_CREATE or SSH_FXF_TRUNCATE_EXISTING).
*/
public static final int SSH_FXF_ACCESS_DISPOSITION = 0x00000007;
/**
* A new file is created; if the file already exists, the server MUST return
* status SSH_FX_FILE_ALREADY_EXISTS.
*/
public static final int SSH_FXF_CREATE_NEW = 0x00000000;
/**
* A new file is created; if the file already exists, it is opened and
* truncated.
*/
public static final int SSH_FXF_CREATE_TRUNCATE = 0x00000001;
/**
* An existing file is opened. If the file does not exist, the server MUST
* return SSH_FX_NO_SUCH_FILE. If a directory in the path does not exist,
* the server SHOULD return SSH_FX_NO_SUCH_PATH. It is also acceptable if
* the server returns SSH_FX_NO_SUCH_FILE in this case.
*/
public static final int SSH_FXF_OPEN_EXISTING = 0x00000002;
/**
* If the file exists, it is opened. If the file does not exist, it is
* created.
*/
public static final int SSH_FXF_OPEN_OR_CREATE = 0x00000003;
/**
* An existing file is opened and truncated. If the file does not exist, the
* server MUST return the same error codes as defined for
* SSH_FXF_OPEN_EXISTING.
*/
public static final int SSH_FXF_TRUNCATE_EXISTING = 0x00000004;
/**
* Data is always written at the end of the file. The offset field of the
* SSH_FXP_WRITE requests are ignored.
* <p>
* Data is not required to be appended atomically. This means that if
* multiple writers attempt to append data simultaneously, data from the
* first may be lost. However, data MAY be appended atomically.
*/
public static final int SSH_FXF_ACCESS_APPEND_DATA = 0x00000008;
/**
* Data is always written at the end of the file. The offset field of the
* SSH_FXP_WRITE requests are ignored.
* <p>
* Data MUST be written atomically so that there is no chance that multiple
* appenders can collide and result in data being lost.
* <p>
* If both append flags are specified, the server SHOULD use atomic append
* if it is available, but SHOULD use non-atomic appends otherwise. The
* server SHOULD NOT fail the request in this case.
*/
public static final int SSH_FXF_ACCESS_APPEND_DATA_ATOMIC = 0x00000010;
/**
* Indicates that the server should treat the file as text and convert it to
* the canonical newline convention in use. (See Determining Server Newline
* Convention in section 5.3 in the SFTP standard draft).
* <p>
* When a file is opened with this flag, the offset field in the read and
* write functions is ignored.
* <p>
* Servers MUST process multiple, parallel reads and writes correctly in
* this mode. Naturally, it is permissible for them to do this by
* serializing the requests.
* <p>
* Clients SHOULD use the SSH_FXF_ACCESS_APPEND_DATA flag to append data to
* a text file rather then using write with a calculated offset.
*/
public static final int SSH_FXF_ACCESS_TEXT_MODE = 0x00000020;
/**
* The server MUST guarantee that no other handle has been opened with
* ACE4_READ_DATA access, and that no other handle will be opened with
* ACE4_READ_DATA access until the client closes the handle. (This MUST
* apply both to other clients and to other processes on the server.)
* <p>
* If there is a conflicting lock the server MUST return
* SSH_FX_LOCK_CONFLICT. If the server cannot make the locking guarantee, it
* MUST return SSH_FX_OP_UNSUPPORTED.
* <p>
* Other handles MAY be opened for ACE4_WRITE_DATA or any other combination
* of accesses, as long as ACE4_READ_DATA is not included in the mask.
*/
public static final int SSH_FXF_ACCESS_BLOCK_READ = 0x00000040;
/**
* The server MUST guarantee that no other handle has been opened with
* ACE4_WRITE_DATA or ACE4_APPEND_DATA access, and that no other handle will
* be opened with ACE4_WRITE_DATA or ACE4_APPEND_DATA access until the
* client closes the handle. (This MUST apply both to other clients and to
* other processes on the server.)
* <p>
* If there is a conflicting lock the server MUST return
* SSH_FX_LOCK_CONFLICT. If the server cannot make the locking guarantee, it
* MUST return SSH_FX_OP_UNSUPPORTED.
* <p>
* Other handles MAY be opened for ACE4_READ_DATA or any other combination
* of accesses, as long as neither ACE4_WRITE_DATA nor ACE4_APPEND_DATA are
* included in the mask.
*/
public static final int SSH_FXF_ACCESS_BLOCK_WRITE = 0x00000080;
/**
* The server MUST guarantee that no other handle has been opened with
* ACE4_DELETE access, opened with the SSH_FXF_ACCESS_DELETE_ON_CLOSE flag
* set, and that no other handle will be opened with ACE4_DELETE access or
* with the SSH_FXF_ACCESS_DELETE_ON_CLOSE flag set, and that the file
* itself is not deleted in any other way until the client closes the
* handle.
* <p>
* If there is a conflicting lock the server MUST return
* SSH_FX_LOCK_CONFLICT. If the server cannot make the locking guarantee, it
* MUST return SSH_FX_OP_UNSUPPORTED.
*/
public static final int SSH_FXF_ACCESS_BLOCK_DELETE = 0x00000100;
/**
* If this bit is set, the above BLOCK modes are advisory. In advisory mode,
* only other accesses that specify a BLOCK mode need be considered when
* determining whether the BLOCK can be granted, and the server need not
* prevent I/O operations that violate the block mode.
* <p>
* The server MAY perform mandatory locking even if the BLOCK_ADVISORY bit
* is set.
*/
public static final int SSH_FXF_ACCESS_BLOCK_ADVISORY = 0x00000200;
/**
* If the final component of the path is a symlink, then the open MUST fail,
* and the error SSH_FX_LINK_LOOP MUST be returned.
*/
public static final int SSH_FXF_ACCESS_NOFOLLOW = 0x00000400;
/**
* The file should be deleted when the last handle to it is closed. (The
* last handle may not be an sftp-handle.) This MAY be emulated by a server
* if the OS doesn't support it by deleting the file when this handle is
* closed.
* <p>
* It is implementation specific whether the directory entry is removed
* immediately or when the handle is closed.
*/
public static final int SSH_FXF_ACCESS_DELETE_ON_CLOSE = 0x00000800;
}
| 07pratik-myssh | src/com/trilead/ssh2/sftp/OpenFlags.java | Java | gpl3 | 7,931 |
/* proxydroid - Global / Individual Proxy App for Android
* Copyright (C) 2011 K's Maze <kafkasmaze@gmail.com>
*
* 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.ksmaze.android.preference;
import android.app.AlertDialog.Builder;
import android.content.Context;
import android.content.DialogInterface;
import android.preference.ListPreference;
import android.preference.Preference;
import android.util.AttributeSet;
/**
* A {@link Preference} that displays a list of entries as
* a dialog and allows multiple selections
* <p>
* This preference will store a string into the SharedPreferences. This string will be the values selected
* from the {@link #setEntryValues(CharSequence[])} array.
* </p>
*/
public class ListPreferenceMultiSelect extends ListPreference {
//Need to make sure the SEPARATOR is unique and weird enough that it doesn't match one of the entries.
//Not using any fancy symbols because this is interpreted as a regex for splitting strings.
private static final String SEPARATOR = " , ";
public static String[] parseStoredValue(CharSequence val) {
if (val == null)
return null;
if ( "".equals(val) )
return null;
else
return ((String)val).split(SEPARATOR);
}
private boolean[] mClickedDialogEntryIndices;
public ListPreferenceMultiSelect(Context context) {
this(context, null);
}
public ListPreferenceMultiSelect(Context context, AttributeSet attrs) {
super(context, attrs);
mClickedDialogEntryIndices = new boolean[getEntries().length];
}
@Override
protected void onDialogClosed(boolean positiveResult) {
// super.onDialogClosed(positiveResult);
CharSequence[] entryValues = getEntryValues();
if (positiveResult && entryValues != null) {
StringBuffer value = new StringBuffer();
for ( int i=0; i<entryValues.length; i++ ) {
if ( mClickedDialogEntryIndices[i] ) {
value.append(entryValues[i]).append(SEPARATOR);
}
}
if (callChangeListener(value)) {
String val = value.toString();
if ( val.length() > 0 )
val = val.substring(0, val.length()-SEPARATOR.length());
setValue(val);
}
}
}
@Override
protected void onPrepareDialogBuilder(Builder builder) {
CharSequence[] entries = getEntries();
CharSequence[] entryValues = getEntryValues();
if (entries == null || entryValues == null || entries.length != entryValues.length ) {
throw new IllegalStateException(
"ListPreference requires an entries array and an entryValues array which are both the same length");
}
restoreCheckedEntries();
builder.setMultiChoiceItems(entries, mClickedDialogEntryIndices,
new DialogInterface.OnMultiChoiceClickListener() {
@Override
public void onClick(DialogInterface dialog, int which, boolean val) {
mClickedDialogEntryIndices[which] = val;
}
});
}
private void restoreCheckedEntries() {
CharSequence[] entryValues = getEntryValues();
String[] vals = parseStoredValue(getValue());
if ( vals != null ) {
for ( int j=0; j<vals.length; j++ ) {
String val = vals[j].trim();
for ( int i=0; i<entryValues.length; i++ ) {
CharSequence entry = entryValues[i];
if ( entry.equals(val) ) {
mClickedDialogEntryIndices[i] = true;
break;
}
}
}
}
}
@Override
public void setEntries(CharSequence[] entries) {
super.setEntries(entries);
mClickedDialogEntryIndices = new boolean[entries.length];
}
}
| 07pratik-myssh | src/com/ksmaze/android/preference/ListPreferenceMultiSelect.java | Java | gpl3 | 4,571 |
/* -*-mode:java; c-basic-offset:2; indent-tabs-mode:nil -*- */
/*
Copyright (c) 2001 Lapo Luchini.
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 THE AUTHORS
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.FilterInputStream;
import java.io.IOException;
import java.io.InputStream;
public class ZInputStream extends FilterInputStream {
protected ZStream z = new ZStream();
protected int bufsize = 512;
protected int flush = JZlib.Z_NO_FLUSH;
protected byte[] buf = new byte[bufsize], buf1 = new byte[1];
protected boolean compress;
protected InputStream in = null;
private boolean nomoreinput = false;
public ZInputStream(InputStream in) {
this(in, false);
}
public ZInputStream(InputStream in, boolean nowrap) {
super(in);
this.in = in;
z.inflateInit(nowrap);
compress = false;
z.next_in = buf;
z.next_in_index = 0;
z.avail_in = 0;
}
/*
* public int available() throws IOException { return inf.finished() ? 0 :
* 1; }
*/
public ZInputStream(InputStream in, int level) {
super(in);
this.in = in;
z.deflateInit(level);
compress = true;
z.next_in = buf;
z.next_in_index = 0;
z.avail_in = 0;
}
@Override
public void close() throws IOException {
in.close();
}
public int getFlushMode() {
return (flush);
}
/**
* Returns the total number of bytes input so far.
*/
public long getTotalIn() {
return z.total_in;
}
/**
* Returns the total number of bytes output so far.
*/
public long getTotalOut() {
return z.total_out;
}
@Override
public int read() throws IOException {
if (read(buf1, 0, 1) == -1)
return (-1);
return (buf1[0] & 0xFF);
}
@Override
public int read(byte[] b, int off, int len) throws IOException {
if (len == 0)
return (0);
int err;
z.next_out = b;
z.next_out_index = off;
z.avail_out = len;
do {
if ((z.avail_in == 0) && (!nomoreinput)) { // if buffer is empty and
// more input is
// avaiable, refill it
z.next_in_index = 0;
z.avail_in = in.read(buf, 0, bufsize);// (bufsize<z.avail_out ?
// bufsize :
// z.avail_out));
if (z.avail_in == -1) {
z.avail_in = 0;
nomoreinput = true;
}
}
if (compress)
err = z.deflate(flush);
else
err = z.inflate(flush);
if (nomoreinput && (err == JZlib.Z_BUF_ERROR))
return (-1);
if (err != JZlib.Z_OK && err != JZlib.Z_STREAM_END)
throw new ZStreamException((compress ? "de" : "in")
+ "flating: " + z.msg);
if ((nomoreinput || err == JZlib.Z_STREAM_END)
&& (z.avail_out == len))
return (-1);
} while (z.avail_out == len && err == JZlib.Z_OK);
// System.err.print("("+(len-z.avail_out)+")");
return (len - z.avail_out);
}
public void setFlushMode(int flush) {
this.flush = flush;
}
@Override
public long skip(long n) throws IOException {
int len = 512;
if (n < len)
len = (int) n;
byte[] tmp = new byte[len];
return read(tmp);
}
}
| 07pratik-myssh | src/com/jcraft/jzlib/ZInputStream.java | Java | gpl3 | 4,456 |
/* -*-mode:java; c-basic-offset:2; indent-tabs-mode:nil -*- */
/*
Copyright (c) 2001 Lapo Luchini.
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 THE AUTHORS
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.IOException;
import java.io.OutputStream;
public class ZOutputStream extends OutputStream {
protected ZStream z = new ZStream();
protected int bufsize = 512;
protected int flush = JZlib.Z_NO_FLUSH;
protected byte[] buf = new byte[bufsize], buf1 = new byte[1];
protected boolean compress;
protected OutputStream out;
public ZOutputStream(OutputStream out) {
super();
this.out = out;
z.inflateInit();
compress = false;
}
public ZOutputStream(OutputStream out, int level) {
this(out, level, false);
}
public ZOutputStream(OutputStream out, int level, boolean nowrap) {
super();
this.out = out;
z.deflateInit(level, nowrap);
compress = true;
}
@Override
public void close() throws IOException {
try {
try {
finish();
} catch (IOException ignored) {
}
} finally {
end();
out.close();
out = null;
}
}
public void end() {
if (z == null)
return;
if (compress) {
z.deflateEnd();
} else {
z.inflateEnd();
}
z.free();
z = null;
}
public void finish() throws IOException {
int err;
do {
z.next_out = buf;
z.next_out_index = 0;
z.avail_out = bufsize;
if (compress) {
err = z.deflate(JZlib.Z_FINISH);
} else {
err = z.inflate(JZlib.Z_FINISH);
}
if (err != JZlib.Z_STREAM_END && err != JZlib.Z_OK)
throw new ZStreamException((compress ? "de" : "in")
+ "flating: " + z.msg);
if (bufsize - z.avail_out > 0) {
out.write(buf, 0, bufsize - z.avail_out);
}
} while (z.avail_in > 0 || z.avail_out == 0);
flush();
}
@Override
public void flush() throws IOException {
out.flush();
}
public int getFlushMode() {
return (flush);
}
/**
* Returns the total number of bytes input so far.
*/
public long getTotalIn() {
return z.total_in;
}
/**
* Returns the total number of bytes output so far.
*/
public long getTotalOut() {
return z.total_out;
}
public void setFlushMode(int flush) {
this.flush = flush;
}
@Override
public void write(byte b[], int off, int len) throws IOException {
if (len == 0)
return;
int err;
z.next_in = b;
z.next_in_index = off;
z.avail_in = len;
do {
z.next_out = buf;
z.next_out_index = 0;
z.avail_out = bufsize;
if (compress)
err = z.deflate(flush);
else
err = z.inflate(flush);
if (err != JZlib.Z_OK)
throw new ZStreamException((compress ? "de" : "in")
+ "flating: " + z.msg);
out.write(buf, 0, bufsize - z.avail_out);
} while (z.avail_in > 0 || z.avail_out == 0);
}
@Override
public void write(int b) throws IOException {
buf1[0] = (byte) b;
write(buf1, 0, 1);
}
}
| 07pratik-myssh | src/com/jcraft/jzlib/ZOutputStream.java | Java | gpl3 | 4,333 |
/* -*-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 public class JZlib {
private static final String version = "1.0.2";
// 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;
public static String version() {
return version;
}
}
| 07pratik-myssh | src/com/jcraft/jzlib/JZlib.java | Java | gpl3 | 2,824 |
/* -*-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);
}
}
| 07pratik-myssh | src/com/jcraft/jzlib/ZStreamException.java | Java | gpl3 | 1,919 |
/* -*-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
InfCodes() {
}
void free(ZStream z) {
// ZFREE(z, c);
}
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] + (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;
}
void init(int bl, int bd, int[] tl, int tl_index, int[] td, int td_index,
ZStream z) {
mode = START;
lbits = (byte) bl;
dbits = (byte) bd;
ltree = tl;
ltree_index = tl_index;
dtree = td;
dtree_index = td_index;
tree = null;
}
// 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 proc(InfBlocks s, ZStream z, 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(z, 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(z, 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(z, 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(z, 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(z, 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(z, 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(z, 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(z, 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(z, 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(z, 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(z, 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(z, 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(z, 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(z, 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(z, r);
}
}
}
}
| 07pratik-myssh | src/com/jcraft/jzlib/InfCodes.java | Java | gpl3 | 17,564 |
/* -*-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
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;
}
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] = (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;
}
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;
}
// for(int i=0; i<BMAX; i++){u[i]=0;}
System.arraycopy(c, 0, u, 0, BMAX);
// for(int i=0; i<BMAX+1; i++){x[i]=0;}
System.arraycopy(c, 0, x, 0, BMAX + 1);
}
}
| 07pratik-myssh | src/com/jcraft/jzlib/InfTree.java | Java | gpl3 | 18,173 |
/* -*-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 };
// Reverse the first len bits of a code, using straightforward code (a
// faster
// method would use a table)
// IN assertion: 1 <= len <= 15
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;
}
// 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)]);
}
// 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.
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 = new short[MAX_BITS + 1]; // next code value for each
// bit length
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.
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));
}
}
short[] dyn_tree; // the dynamic tree
int max_code; // largest code with non zero frequency
StaticTree stat_desc; // the corresponding static tree
// 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);
}
// 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])
* tree[m * 2];
tree[m * 2 + 1] = (short) bits;
}
n--;
}
}
}
}
| 07pratik-myssh | src/com/jcraft/jzlib/Tree.java | Java | gpl3 | 14,495 |
/* -*-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 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
InfCodes codes = new InfCodes(); // 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
Object checkfn; // check function
long check; // check on output
InfTree inftree = new InfTree();
InfBlocks(ZStream z, Object checkfn, int w) {
hufts = new int[MANY * 3];
window = new byte[w];
end = w;
this.checkfn = checkfn;
mode = TYPE;
reset(z, null);
}
void free(ZStream z) {
reset(z, null);
window = null;
hufts = null;
// ZFREE(z, s);
}
// copy as much as possible from the sliding window to the output area
int inflate_flush(ZStream z, 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 = ((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 (checkfn != null)
z.adler = check = z._adler.adler32(check, 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 (checkfn != null)
z.adler = check = z._adler.adler32(check, 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;
}
int proc(ZStream z, 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 = (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(z, r);
}
;
n--;
b |= (z.next_in[p++] & 0xff) << k;
k += 8;
}
t = (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
{
int[] bl = new int[1];
int[] bd = new int[1];
int[][] tl = new int[1][];
int[][] td = new int[1][];
InfTree.inflate_trees_fixed(bl, bd, tl, td, z);
codes.init(bl[0], bd[0], tl[0], 0, td[0], 0, z);
}
{
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(z, 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(z, 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(z, 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(z, r);
}
if (m == 0) {
if (q == end && read != 0) {
q = 0;
m = (q < read ? read - q - 1 : end - q);
}
if (m == 0) {
write = q;
r = inflate_flush(z, r);
q = write;
m = (q < read ? read - q - 1 : end - q);
if (q == end && read != 0) {
q = 0;
m = (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(z, 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(z, 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(z, 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(z, 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(z, 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(z, 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(z, 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(z, r);
}
c = c == 16 ? blens[i - 1] : 0;
do {
blens[i++] = c;
} while (--j != 0);
index = i;
}
}
tb[0] = -1;
{
int[] bl = new int[1];
int[] bd = new int[1];
int[] tl = new int[1];
int[] td = new int[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, tl, td,
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(z, r);
}
codes.init(bl[0], bd[0], hufts, tl[0], hufts, td[0], z);
}
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(this, z, r)) != Z_STREAM_END) {
return inflate_flush(z, r);
}
r = Z_OK;
codes.free(z);
p = z.next_in_index;
n = z.avail_in;
b = bitb;
k = bitk;
q = write;
m = (q < read ? read - q - 1 : end - q);
if (last == 0) {
mode = TYPE;
break;
}
mode = DRY;
case DRY:
write = q;
r = inflate_flush(z, r);
q = write;
m = (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(z, 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(z, 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(z, 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(z, r);
}
}
}
void reset(ZStream z, long[] c) {
if (c != null)
c[0] = check;
if (mode == BTREE || mode == DTREE) {
}
if (mode == CODES) {
codes.free(z);
}
mode = TYPE;
bitk = 0;
bitb = 0;
read = write = 0;
if (checkfn != null)
z.adler = check = z._adler.adler32(0L, null, 0, 0);
}
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;
}
}
| 07pratik-myssh | src/com/jcraft/jzlib/InfBlocks.java | Java | gpl3 | 16,176 |
/* -*-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 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
public long adler;
Adler32 _adler = new Adler32();
public int deflate(int flush) {
if (dstate == null) {
return Z_STREAM_ERROR;
}
return dstate.deflate(this, flush);
}
public int deflateEnd() {
if (dstate == null)
return Z_STREAM_ERROR;
int ret = dstate.deflateEnd();
dstate = null;
return ret;
}
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, boolean nowrap) {
dstate = new Deflate();
return dstate.deflateInit(this, level, nowrap ? -bits : bits);
}
public int deflateParams(int level, int strategy) {
if (dstate == null)
return Z_STREAM_ERROR;
return dstate.deflateParams(this, level, strategy);
}
public int deflateSetDictionary(byte[] dictionary, int dictLength) {
if (dstate == null)
return Z_STREAM_ERROR;
return dstate.deflateSetDictionary(this, 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;
}
}
public void free() {
next_in = null;
next_out = null;
msg = null;
_adler = null;
}
public int inflate(int f) {
if (istate == null)
return Z_STREAM_ERROR;
return istate.inflate(this, f);
}
public int inflateEnd() {
if (istate == null)
return Z_STREAM_ERROR;
int ret = istate.inflateEnd(this);
istate = null;
return ret;
}
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(int w, boolean nowrap) {
istate = new Inflate();
return istate.inflateInit(this, nowrap ? -w : w);
}
public int inflateSetDictionary(byte[] dictionary, int dictLength) {
if (istate == null)
return Z_STREAM_ERROR;
return istate.inflateSetDictionary(this, dictionary, dictLength);
}
public int inflateSync() {
if (istate == null)
return Z_STREAM_ERROR;
return istate.inflateSync(this);
}
// 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.noheader == 0) {
adler = _adler.adler32(adler, 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;
}
}
| 07pratik-myssh | src/com/jcraft/jzlib/ZStream.java | Java | gpl3 | 6,931 |
/* -*-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 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
int mode; // current inflate mode
// mode dependent information
int method; // if FLAGS, method byte
// if CHECK, check values to compare
long[] was = new long[1]; // computed check value
long need; // stream check value
// if BAD, inflateSync's marker bytes count
int marker;
// mode independent information
int nowrap; // flag for no wrapper
int wbits; // log2(window size) (8..15, defaults to 15)
InfBlocks blocks; // current inflate_blocks state
static private byte[] mark = { (byte) 0, (byte) 0, (byte) 0xff, (byte) 0xff };
int inflate(ZStream z, int f) {
int r;
int b;
if (z == null || z.istate == null || z.next_in == null)
return Z_STREAM_ERROR;
f = f == Z_FINISH ? Z_BUF_ERROR : Z_OK;
r = Z_BUF_ERROR;
while (true) {
// System.out.println("mode: "+z.istate.mode);
switch (z.istate.mode) {
case METHOD:
if (z.avail_in == 0)
return r;
r = f;
z.avail_in--;
z.total_in++;
if (((z.istate.method = z.next_in[z.next_in_index++]) & 0xf) != Z_DEFLATED) {
z.istate.mode = BAD;
z.msg = "unknown compression method";
z.istate.marker = 5; // can't try inflateSync
break;
}
if ((z.istate.method >> 4) + 8 > z.istate.wbits) {
z.istate.mode = BAD;
z.msg = "invalid window size";
z.istate.marker = 5; // can't try inflateSync
break;
}
z.istate.mode = FLAG;
case FLAG:
if (z.avail_in == 0)
return r;
r = f;
z.avail_in--;
z.total_in++;
b = (z.next_in[z.next_in_index++]) & 0xff;
if ((((z.istate.method << 8) + b) % 31) != 0) {
z.istate.mode = BAD;
z.msg = "incorrect header check";
z.istate.marker = 5; // can't try inflateSync
break;
}
if ((b & PRESET_DICT) == 0) {
z.istate.mode = BLOCKS;
break;
}
z.istate.mode = DICT4;
case DICT4:
if (z.avail_in == 0)
return r;
r = f;
z.avail_in--;
z.total_in++;
z.istate.need = ((z.next_in[z.next_in_index++] & 0xff) << 24) & 0xff000000L;
z.istate.mode = DICT3;
case DICT3:
if (z.avail_in == 0)
return r;
r = f;
z.avail_in--;
z.total_in++;
z.istate.need += ((z.next_in[z.next_in_index++] & 0xff) << 16) & 0xff0000L;
z.istate.mode = DICT2;
case DICT2:
if (z.avail_in == 0)
return r;
r = f;
z.avail_in--;
z.total_in++;
z.istate.need += ((z.next_in[z.next_in_index++] & 0xff) << 8) & 0xff00L;
z.istate.mode = DICT1;
case DICT1:
if (z.avail_in == 0)
return r;
r = f;
z.avail_in--;
z.total_in++;
z.istate.need += (z.next_in[z.next_in_index++] & 0xffL);
z.adler = z.istate.need;
z.istate.mode = DICT0;
return Z_NEED_DICT;
case DICT0:
z.istate.mode = BAD;
z.msg = "need dictionary";
z.istate.marker = 0; // can try inflateSync
return Z_STREAM_ERROR;
case BLOCKS:
r = z.istate.blocks.proc(z, r);
if (r == Z_DATA_ERROR) {
z.istate.mode = BAD;
z.istate.marker = 0; // can try inflateSync
break;
}
if (r == Z_OK) {
r = f;
}
if (r != Z_STREAM_END) {
return r;
}
r = f;
z.istate.blocks.reset(z, z.istate.was);
if (z.istate.nowrap != 0) {
z.istate.mode = DONE;
break;
}
z.istate.mode = CHECK4;
case CHECK4:
if (z.avail_in == 0)
return r;
r = f;
z.avail_in--;
z.total_in++;
z.istate.need = ((z.next_in[z.next_in_index++] & 0xff) << 24) & 0xff000000L;
z.istate.mode = CHECK3;
case CHECK3:
if (z.avail_in == 0)
return r;
r = f;
z.avail_in--;
z.total_in++;
z.istate.need += ((z.next_in[z.next_in_index++] & 0xff) << 16) & 0xff0000L;
z.istate.mode = CHECK2;
case CHECK2:
if (z.avail_in == 0)
return r;
r = f;
z.avail_in--;
z.total_in++;
z.istate.need += ((z.next_in[z.next_in_index++] & 0xff) << 8) & 0xff00L;
z.istate.mode = CHECK1;
case CHECK1:
if (z.avail_in == 0)
return r;
r = f;
z.avail_in--;
z.total_in++;
z.istate.need += (z.next_in[z.next_in_index++] & 0xffL);
if (((int) (z.istate.was[0])) != ((int) (z.istate.need))) {
z.istate.mode = BAD;
z.msg = "incorrect data check";
z.istate.marker = 5; // can't try inflateSync
break;
}
z.istate.mode = DONE;
case DONE:
return Z_STREAM_END;
case BAD:
return Z_DATA_ERROR;
default:
return Z_STREAM_ERROR;
}
}
}
int inflateEnd(ZStream z) {
if (blocks != null)
blocks.free(z);
blocks = null;
// ZFREE(z, z->state);
return Z_OK;
}
int inflateInit(ZStream z, int w) {
z.msg = null;
blocks = null;
// handle undocumented nowrap option (no zlib header or check)
nowrap = 0;
if (w < 0) {
w = -w;
nowrap = 1;
}
// set window size
if (w < 8 || w > 15) {
inflateEnd(z);
return Z_STREAM_ERROR;
}
wbits = w;
z.istate.blocks = new InfBlocks(z, z.istate.nowrap != 0 ? null : this,
1 << w);
// reset state
inflateReset(z);
return Z_OK;
}
int inflateReset(ZStream z) {
if (z == null || z.istate == null)
return Z_STREAM_ERROR;
z.total_in = z.total_out = 0;
z.msg = null;
z.istate.mode = z.istate.nowrap != 0 ? BLOCKS : METHOD;
z.istate.blocks.reset(z, null);
return Z_OK;
}
int inflateSetDictionary(ZStream z, byte[] dictionary, int dictLength) {
int index = 0;
int length = dictLength;
if (z == null || z.istate == null || z.istate.mode != DICT0)
return Z_STREAM_ERROR;
if (z._adler.adler32(1L, dictionary, 0, dictLength) != z.adler) {
return Z_DATA_ERROR;
}
z.adler = z._adler.adler32(0, null, 0, 0);
if (length >= (1 << z.istate.wbits)) {
length = (1 << z.istate.wbits) - 1;
index = dictLength - length;
}
z.istate.blocks.set_dictionary(dictionary, index, length);
z.istate.mode = BLOCKS;
return Z_OK;
}
int inflateSync(ZStream z) {
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 || z.istate == null)
return Z_STREAM_ERROR;
if (z.istate.mode != BAD) {
z.istate.mode = BAD;
z.istate.marker = 0;
}
if ((n = z.avail_in) == 0)
return Z_BUF_ERROR;
p = z.next_in_index;
m = z.istate.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;
z.istate.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);
z.total_in = r;
z.total_out = w;
z.istate.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(ZStream z) {
if (z == null || z.istate == null || z.istate.blocks == null)
return Z_STREAM_ERROR;
return z.istate.blocks.sync_point();
}
}
| 07pratik-myssh | src/com/jcraft/jzlib/Inflate.java | Java | gpl3 | 10,848 |
/* -*-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
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;
}
}
| 07pratik-myssh | src/com/jcraft/jzlib/StaticTree.java | Java | gpl3 | 5,533 |
/* -*-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 Adler32 {
// 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;
long adler32(long adler, byte[] buf, int index, int len) {
if (buf == null) {
return 1L;
}
long s1 = adler & 0xffff;
long s2 = (adler >> 16) & 0xffff;
int k;
while (len > 0) {
k = len < NMAX ? len : NMAX;
len -= k;
while (k >= 16) {
s1 += buf[index++] & 0xff;
s2 += s1;
s1 += buf[index++] & 0xff;
s2 += s1;
s1 += buf[index++] & 0xff;
s2 += s1;
s1 += buf[index++] & 0xff;
s2 += s1;
s1 += buf[index++] & 0xff;
s2 += s1;
s1 += buf[index++] & 0xff;
s2 += s1;
s1 += buf[index++] & 0xff;
s2 += s1;
s1 += buf[index++] & 0xff;
s2 += s1;
s1 += buf[index++] & 0xff;
s2 += s1;
s1 += buf[index++] & 0xff;
s2 += s1;
s1 += buf[index++] & 0xff;
s2 += s1;
s1 += buf[index++] & 0xff;
s2 += s1;
s1 += buf[index++] & 0xff;
s2 += s1;
s1 += buf[index++] & 0xff;
s2 += s1;
s1 += buf[index++] & 0xff;
s2 += s1;
s1 += buf[index++] & 0xff;
s2 += s1;
k -= 16;
}
if (k != 0) {
do {
s1 += buf[index++] & 0xff;
s2 += s1;
} while (--k != 0);
}
s1 %= BASE;
s2 %= BASE;
}
return (s2 << 16) | s1;
}
/*
* private java.util.zip.Adler32 adler=new java.util.zip.Adler32(); long
* adler32(long value, byte[] buf, int index, int len){ if(value==1)
* {adler.reset();} if(buf==null) {adler.reset();} else{adler.update(buf,
* index, len);} return adler.getValue(); }
*/
}
| 07pratik-myssh | src/com/jcraft/jzlib/Adler32.java | Java | gpl3 | 3,369 |
/* -*-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 final class Deflate {
static class Config {
int good_length; // reduce lazy search above this match length
int max_lazy; // do not perform lazy search above this match length
int nice_length; // quit search above this match length
int max_chain;
int func;
Config(int good_length, int max_lazy, int nice_length, int max_chain,
int func) {
this.good_length = good_length;
this.max_lazy = max_lazy;
this.nice_length = nice_length;
this.max_chain = max_chain;
this.func = func;
}
}
static final private int MAX_MEM_LEVEL = 9;
static final private int Z_DEFAULT_COMPRESSION = -1;
static final private int MAX_WBITS = 15; // 32K LZ77 window
static final private int DEF_MEM_LEVEL = 8;
static final private int STORED = 0;
static final private int FAST = 1;
static final private int SLOW = 2;
static final private Config[] config_table;
static {
config_table = new Config[10];
// good lazy nice chain
config_table[0] = new Config(0, 0, 0, 0, STORED);
config_table[1] = new Config(4, 4, 8, 4, FAST);
config_table[2] = new Config(4, 5, 16, 8, FAST);
config_table[3] = new Config(4, 6, 32, 32, FAST);
config_table[4] = new Config(4, 4, 16, 16, SLOW);
config_table[5] = new Config(8, 16, 32, 32, SLOW);
config_table[6] = new Config(8, 16, 128, 128, SLOW);
config_table[7] = new Config(8, 32, 128, 256, SLOW);
config_table[8] = new Config(32, 128, 258, 1024, SLOW);
config_table[9] = new Config(32, 258, 258, 4096, SLOW);
}
static final private String[] z_errmsg = { "need dictionary", // Z_NEED_DICT
// 2
"stream end", // Z_STREAM_END 1
"", // Z_OK 0
"file error", // Z_ERRNO (-1)
"stream error", // Z_STREAM_ERROR (-2)
"data error", // Z_DATA_ERROR (-3)
"insufficient memory", // Z_MEM_ERROR (-4)
"buffer error", // Z_BUF_ERROR (-5)
"incompatible version",// Z_VERSION_ERROR (-6)
"" };
// block not completed, need more input or more output
static final private int NeedMore = 0;
// block flush performed
static final private int BlockDone = 1;
// finish started, need only more output at next deflate
static final private int FinishStarted = 2;
// finish done, accept no more input or output
static final private int FinishDone = 3;
// preset dictionary flag in zlib header
static final private int PRESET_DICT = 0x20;
static final private int Z_FILTERED = 1;
static final private int Z_HUFFMAN_ONLY = 2;
static final private int Z_DEFAULT_STRATEGY = 0;
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 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 INIT_STATE = 42;
static final private int BUSY_STATE = 113;
static final private int FINISH_STATE = 666;
// The deflate compression method
static final private int Z_DEFLATED = 8;
static final private int STORED_BLOCK = 0;
static final private int STATIC_TREES = 1;
static final private int DYN_TREES = 2;
// The three kinds of block type
static final private int Z_BINARY = 0;
static final private int Z_ASCII = 1;
static final private int Z_UNKNOWN = 2;
static final private int Buf_size = 8 * 2;
// repeat previous bit length 3-6 times (2 bits of repeat count)
static final private int REP_3_6 = 16;
// repeat a zero length 3-10 times (3 bits of repeat count)
static final private int REPZ_3_10 = 17;
// repeat a zero length 11-138 times (7 bits of repeat count)
static final private int REPZ_11_138 = 18;
static final private int MIN_MATCH = 3;
static final private int MAX_MATCH = 258;
static final private int MIN_LOOKAHEAD = (MAX_MATCH + MIN_MATCH + 1);
static final private int MAX_BITS = 15;
static final private int D_CODES = 30;
static final private int BL_CODES = 19;
static final private int LENGTH_CODES = 29;
static final private int LITERALS = 256;
static final private int L_CODES = (LITERALS + 1 + LENGTH_CODES);
static final private int HEAP_SIZE = (2 * L_CODES + 1);
static final private int END_BLOCK = 256;
static boolean smaller(short[] tree, int n, int m, byte[] depth) {
short tn2 = tree[n * 2];
short tm2 = tree[m * 2];
return (tn2 < tm2 || (tn2 == tm2 && depth[n] <= depth[m]));
}
ZStream strm; // pointer back to this zlib stream
int status; // as the name implies
byte[] pending_buf; // output still pending
int pending_buf_size; // size of pending_buf
int pending_out; // next pending byte to output to the stream
int pending; // nb of bytes in the pending buffer
int noheader; // suppress zlib header and adler32
byte data_type; // UNKNOWN, BINARY or ASCII
byte method; // STORED (for zip only) or DEFLATED
int last_flush; // value of flush param for previous deflate call
int w_size; // LZ77 window size (32K by default)
int w_bits; // log2(w_size) (8..16)
int w_mask; // w_size - 1
byte[] window;
// Sliding window. Input bytes are read into the second half of the window,
// and move to the first half later to keep a dictionary of at least wSize
// bytes. With this organization, matches are limited to a distance of
// wSize-MAX_MATCH bytes, but this ensures that IO is always
// performed with a length multiple of the block size. Also, it limits
// the window size to 64K, which is quite useful on MSDOS.
// To do: use the user input buffer as sliding window.
int window_size;
// Actual size of window: 2*wSize, except when the user input buffer
// is directly used as sliding window.
short[] prev;
// Link to older string with same hash index. To limit the size of this
// array to 64K, this link is maintained only for the last 32K strings.
// An index in this array is thus a window index modulo 32K.
short[] head; // Heads of the hash chains or NIL.
int ins_h; // hash index of string to be inserted
int hash_size; // number of elements in hash table
int hash_bits; // log2(hash_size)
int hash_mask; // hash_size-1
// Window position at the beginning of the current output block. Gets
// negative when the window is moved backwards.
// Number of bits by which ins_h must be shifted at each input
// step. It must be such that after MIN_MATCH steps, the oldest
// byte no longer takes part in the hash key, that is:
// hash_shift * MIN_MATCH >= hash_bits
int hash_shift;
int block_start;
int match_length; // length of best match
int prev_match; // previous match
int match_available; // set if previous match exists
int strstart; // start of string to insert
int match_start; // start of matching string
int lookahead; // number of valid bytes ahead in window
// Length of the best match at previous step. Matches not greater than this
// are discarded. This is used in the lazy match evaluation.
int prev_length;
// To speed up deflation, hash chains are never searched beyond this
// length. A higher limit improves compression ratio but degrades the speed.
int max_chain_length;
// Insert new strings in the hash table only if the match length is not
// greater than this length. This saves time but degrades compression.
// max_insert_length is used only for compression levels <= 3.
// Attempt to find a better match only when the current match is strictly
// smaller than this value. This mechanism is used only for compression
// levels >= 4.
int max_lazy_match;
int level; // compression level (1..9)
int strategy; // favor or force Huffman coding
// Use a faster search when the previous match is longer than this
int good_match;
// Stop searching when current match exceeds this
int nice_match;
short[] dyn_ltree; // literal and length tree
short[] dyn_dtree; // distance tree
short[] bl_tree; // Huffman tree for bit lengths
Tree l_desc = new Tree(); // desc for literal tree
Tree d_desc = new Tree(); // desc for distance tree
Tree bl_desc = new Tree(); // desc for bit length tree
// number of codes at each bit length for an optimal tree
short[] bl_count = new short[MAX_BITS + 1];
// heap used to build the Huffman trees
int[] heap = new int[2 * L_CODES + 1];
int heap_len; // number of elements in the heap
int heap_max; // element of largest frequency
// The sons of heap[n] are heap[2*n] and heap[2*n+1]. heap[0] is not used.
// The same heap array is used to build all trees.
// Depth of each subtree used as tie breaker for trees of equal frequency
byte[] depth = new byte[2 * L_CODES + 1];
int l_buf; // index for literals or lengths */
// Size of match buffer for literals/lengths. There are 4 reasons for
// limiting lit_bufsize to 64K:
// - frequencies can be kept in 16 bit counters
// - if compression is not successful for the first block, all input
// data is still in the window so we can still emit a stored block even
// when input comes from standard input. (This can also be done for
// all blocks if lit_bufsize is not greater than 32K.)
// - if compression is not successful for a file smaller than 64K, we can
// even emit a stored file instead of a stored block (saving 5 bytes).
// This is applicable only for zip (not gzip or zlib).
// - creating new Huffman trees less frequently may not provide fast
// adaptation to changes in the input data statistics. (Take for
// example a binary file with poorly compressible code followed by
// a highly compressible string table.) Smaller buffer sizes give
// fast adaptation but have of course the overhead of transmitting
// trees more frequently.
// - I can't count above 4
int lit_bufsize;
// Buffer for distances. To simplify the code, d_buf and l_buf have
// the same number of elements. To use different lengths, an extra flag
// array would be necessary.
int last_lit; // running index in l_buf
int d_buf; // index of pendig_buf
int opt_len; // bit length of current block with optimal trees
int static_len; // bit length of current block with static trees
int matches; // number of string matches in current block
int last_eob_len; // bit length of EOB code for last block
// Output buffer. bits are inserted starting at the bottom (least
// significant bits).
short bi_buf;
// Number of valid bits in bi_buf. All bits above the last valid bit
// are always zero.
int bi_valid;
Deflate() {
dyn_ltree = new short[HEAP_SIZE * 2];
dyn_dtree = new short[(2 * D_CODES + 1) * 2]; // distance tree
bl_tree = new short[(2 * BL_CODES + 1) * 2]; // Huffman tree for bit
// lengths
}
// Send one empty static block to give enough lookahead for inflate.
// This takes 10 bits, of which 7 may remain in the bit buffer.
// The current inflate code requires 9 bits of lookahead. If the
// last two codes for the previous block (real code plus EOB) were coded
// on 5 bits or less, inflate may have only 5+3 bits of lookahead to decode
// the last real code. In this case we send two empty static blocks instead
// of one. (There are no problems if the previous block is stored or fixed.)
// To simplify the code, we assume the worst case of last real code encoded
// on one bit only.
void _tr_align() {
send_bits(STATIC_TREES << 1, 3);
send_code(END_BLOCK, StaticTree.static_ltree);
bi_flush();
// Of the 10 bits for the empty block, we have already sent
// (10 - bi_valid) bits. The lookahead for the last real code (before
// the EOB of the previous block) was thus at least one plus the length
// of the EOB plus what we have just sent of the empty static block.
if (1 + last_eob_len + 10 - bi_valid < 9) {
send_bits(STATIC_TREES << 1, 3);
send_code(END_BLOCK, StaticTree.static_ltree);
bi_flush();
}
last_eob_len = 7;
}
// Determine the best encoding for the current block: dynamic trees, static
// trees or store, and output the encoded block to the zip file.
void _tr_flush_block(int buf, // input block, or NULL if too old
int stored_len, // length of input block
boolean eof // true if this is the last block for a file
) {
int opt_lenb, static_lenb;// opt_len and static_len in bytes
int max_blindex = 0; // index of last bit length code of non zero freq
// Build the Huffman trees unless a stored block is forced
if (level > 0) {
// Check if the file is ascii or binary
if (data_type == Z_UNKNOWN)
set_data_type();
// Construct the literal and distance trees
l_desc.build_tree(this);
d_desc.build_tree(this);
// At this point, opt_len and static_len are the total bit lengths
// of
// the compressed block data, excluding the tree representations.
// Build the bit length tree for the above two trees, and get the
// index
// in bl_order of the last bit length code to send.
max_blindex = build_bl_tree();
// Determine the best encoding. Compute first the block length in
// bytes
opt_lenb = (opt_len + 3 + 7) >>> 3;
static_lenb = (static_len + 3 + 7) >>> 3;
if (static_lenb <= opt_lenb)
opt_lenb = static_lenb;
} else {
opt_lenb = static_lenb = stored_len + 5; // force a stored block
}
if (stored_len + 4 <= opt_lenb && buf != -1) {
// 4: two words for the lengths
// The test buf != NULL is only necessary if LIT_BUFSIZE > WSIZE.
// Otherwise we can't have processed more than WSIZE input bytes
// since
// the last block flush, because compression would have been
// successful. If LIT_BUFSIZE <= WSIZE, it is never too late to
// transform a block into a stored block.
_tr_stored_block(buf, stored_len, eof);
} else if (static_lenb == opt_lenb) {
send_bits((STATIC_TREES << 1) + (eof ? 1 : 0), 3);
compress_block(StaticTree.static_ltree, StaticTree.static_dtree);
} else {
send_bits((DYN_TREES << 1) + (eof ? 1 : 0), 3);
send_all_trees(l_desc.max_code + 1, d_desc.max_code + 1,
max_blindex + 1);
compress_block(dyn_ltree, dyn_dtree);
}
// The above check is made mod 2^32, for files larger than 512 MB
// and uLong implemented on 32 bits.
init_block();
if (eof) {
bi_windup();
}
}
// Send a stored block
void _tr_stored_block(int buf, // input block
int stored_len, // length of input block
boolean eof // true if this is the last block for a file
) {
send_bits((STORED_BLOCK << 1) + (eof ? 1 : 0), 3); // send block type
copy_block(buf, stored_len, true); // with header
}
// Save the match info and tally the frequency counts. Return true if
// the current block must be flushed.
boolean _tr_tally(int dist, // distance of matched string
int lc // match length-MIN_MATCH or unmatched char (if dist==0)
) {
pending_buf[d_buf + last_lit * 2] = (byte) (dist >>> 8);
pending_buf[d_buf + last_lit * 2 + 1] = (byte) dist;
pending_buf[l_buf + last_lit] = (byte) lc;
last_lit++;
if (dist == 0) {
// lc is the unmatched char
dyn_ltree[lc * 2]++;
} else {
matches++;
// Here, lc is the match length - MIN_MATCH
dist--; // dist = match distance - 1
dyn_ltree[(Tree._length_code[lc] + LITERALS + 1) * 2]++;
dyn_dtree[Tree.d_code(dist) * 2]++;
}
if ((last_lit & 0x1fff) == 0 && level > 2) {
// Compute an upper bound for the compressed length
int out_length = last_lit * 8;
int in_length = strstart - block_start;
int dcode;
for (dcode = 0; dcode < D_CODES; dcode++) {
out_length += dyn_dtree[dcode * 2]
* (5L + Tree.extra_dbits[dcode]);
}
out_length >>>= 3;
if ((matches < (last_lit / 2)) && out_length < in_length / 2)
return true;
}
return (last_lit == lit_bufsize - 1);
// We avoid equality with lit_bufsize because of wraparound at 64K
// on 16 bit machines and because stored blocks are restricted to
// 64K-1 bytes.
}
// Flush the bit buffer, keeping at most 7 bits in it.
void bi_flush() {
if (bi_valid == 16) {
put_short(bi_buf);
bi_buf = 0;
bi_valid = 0;
} else if (bi_valid >= 8) {
put_byte((byte) bi_buf);
bi_buf >>>= 8;
bi_valid -= 8;
}
}
// Flush the bit buffer and align the output on a byte boundary
void bi_windup() {
if (bi_valid > 8) {
put_short(bi_buf);
} else if (bi_valid > 0) {
put_byte((byte) bi_buf);
}
bi_buf = 0;
bi_valid = 0;
}
// Construct the Huffman tree for the bit lengths and return the index in
// bl_order of the last bit length code to send.
int build_bl_tree() {
int max_blindex; // index of last bit length code of non zero freq
// Determine the bit length frequencies for literal and distance trees
scan_tree(dyn_ltree, l_desc.max_code);
scan_tree(dyn_dtree, d_desc.max_code);
// Build the bit length tree:
bl_desc.build_tree(this);
// opt_len now includes the length of the tree representations, except
// the lengths of the bit lengths codes and the 5+5+4 bits for the
// counts.
// Determine the number of bit length codes to send. The pkzip format
// requires that at least 4 bit length codes be sent. (appnote.txt says
// 3 but the actual value used is 4.)
for (max_blindex = BL_CODES - 1; max_blindex >= 3; max_blindex--) {
if (bl_tree[Tree.bl_order[max_blindex] * 2 + 1] != 0)
break;
}
// Update opt_len to include the bit length tree and counts
opt_len += 3 * (max_blindex + 1) + 5 + 5 + 4;
return max_blindex;
}
// Send the block data compressed using the given Huffman trees
void compress_block(short[] ltree, short[] dtree) {
int dist; // distance of matched string
int lc; // match length or unmatched char (if dist == 0)
int lx = 0; // running index in l_buf
int code; // the code to send
int extra; // number of extra bits to send
if (last_lit != 0) {
do {
dist = ((pending_buf[d_buf + lx * 2] << 8) & 0xff00)
| (pending_buf[d_buf + lx * 2 + 1] & 0xff);
lc = (pending_buf[l_buf + lx]) & 0xff;
lx++;
if (dist == 0) {
send_code(lc, ltree); // send a literal byte
} else {
// Here, lc is the match length - MIN_MATCH
code = Tree._length_code[lc];
send_code(code + LITERALS + 1, ltree); // send the length
// code
extra = Tree.extra_lbits[code];
if (extra != 0) {
lc -= Tree.base_length[code];
send_bits(lc, extra); // send the extra length bits
}
dist--; // dist is now the match distance - 1
code = Tree.d_code(dist);
send_code(code, dtree); // send the distance code
extra = Tree.extra_dbits[code];
if (extra != 0) {
dist -= Tree.base_dist[code];
send_bits(dist, extra); // send the extra distance bits
}
} // literal or match pair ?
// Check that the overlay between pending_buf and d_buf+l_buf is
// ok:
} while (lx < last_lit);
}
send_code(END_BLOCK, ltree);
last_eob_len = ltree[END_BLOCK * 2 + 1];
}
// Copy a stored block, storing first the length and its
// one's complement if requested.
void copy_block(int buf, // the input data
int len, // its length
boolean header // true if block header must be written
) {
int index = 0;
bi_windup(); // align on byte boundary
last_eob_len = 8; // enough lookahead for inflate
if (header) {
put_short((short) len);
put_short((short) ~len);
}
// while(len--!=0) {
// put_byte(window[buf+index]);
// index++;
// }
put_byte(window, buf, len);
}
int deflate(ZStream strm, int flush) {
int old_flush;
if (flush > Z_FINISH || flush < 0) {
return Z_STREAM_ERROR;
}
if (strm.next_out == null
|| (strm.next_in == null && strm.avail_in != 0)
|| (status == FINISH_STATE && flush != Z_FINISH)) {
strm.msg = z_errmsg[Z_NEED_DICT - (Z_STREAM_ERROR)];
return Z_STREAM_ERROR;
}
if (strm.avail_out == 0) {
strm.msg = z_errmsg[Z_NEED_DICT - (Z_BUF_ERROR)];
return Z_BUF_ERROR;
}
this.strm = strm; // just in case
old_flush = last_flush;
last_flush = flush;
// Write the zlib header
if (status == INIT_STATE) {
int header = (Z_DEFLATED + ((w_bits - 8) << 4)) << 8;
int level_flags = ((level - 1) & 0xff) >> 1;
if (level_flags > 3)
level_flags = 3;
header |= (level_flags << 6);
if (strstart != 0)
header |= PRESET_DICT;
header += 31 - (header % 31);
status = BUSY_STATE;
putShortMSB(header);
// Save the adler32 of the preset dictionary:
if (strstart != 0) {
putShortMSB((int) (strm.adler >>> 16));
putShortMSB((int) (strm.adler & 0xffff));
}
strm.adler = strm._adler.adler32(0, null, 0, 0);
}
// Flush as much pending output as possible
if (pending != 0) {
strm.flush_pending();
if (strm.avail_out == 0) {
// System.out.println(" avail_out==0");
// Since avail_out is 0, deflate will be called again with
// more output space, but possibly with both pending and
// avail_in equal to zero. There won't be anything to do,
// but this is not an error situation so make sure we
// return OK instead of BUF_ERROR at next call of deflate:
last_flush = -1;
return Z_OK;
}
// Make sure there is something to do and avoid duplicate
// consecutive
// flushes. For repeated and useless calls with Z_FINISH, we keep
// returning Z_STREAM_END instead of Z_BUFF_ERROR.
} else if (strm.avail_in == 0 && flush <= old_flush
&& flush != Z_FINISH) {
strm.msg = z_errmsg[Z_NEED_DICT - (Z_BUF_ERROR)];
return Z_BUF_ERROR;
}
// User must not provide more input after the first FINISH:
if (status == FINISH_STATE && strm.avail_in != 0) {
strm.msg = z_errmsg[Z_NEED_DICT - (Z_BUF_ERROR)];
return Z_BUF_ERROR;
}
// Start a new block or continue the current one.
if (strm.avail_in != 0 || lookahead != 0
|| (flush != Z_NO_FLUSH && status != FINISH_STATE)) {
int bstate = -1;
switch (config_table[level].func) {
case STORED:
bstate = deflate_stored(flush);
break;
case FAST:
bstate = deflate_fast(flush);
break;
case SLOW:
bstate = deflate_slow(flush);
break;
default:
}
if (bstate == FinishStarted || bstate == FinishDone) {
status = FINISH_STATE;
}
if (bstate == NeedMore || bstate == FinishStarted) {
if (strm.avail_out == 0) {
last_flush = -1; // avoid BUF_ERROR next call, see above
}
return Z_OK;
// If flush != Z_NO_FLUSH && avail_out == 0, the next call
// of deflate should use the same flush parameter to make sure
// that the flush is complete. So we don't have to output an
// empty block here, this will be done at next call. This also
// ensures that for a very small output buffer, we emit at most
// one empty block.
}
if (bstate == BlockDone) {
if (flush == Z_PARTIAL_FLUSH) {
_tr_align();
} else { // FULL_FLUSH or SYNC_FLUSH
_tr_stored_block(0, 0, false);
// For a full flush, this empty block will be recognized
// as a special marker by inflate_sync().
if (flush == Z_FULL_FLUSH) {
// state.head[s.hash_size-1]=0;
for (int i = 0; i < hash_size/*-1*/; i++)
// forget history
head[i] = 0;
}
}
strm.flush_pending();
if (strm.avail_out == 0) {
last_flush = -1; // avoid BUF_ERROR at next call, see above
return Z_OK;
}
}
}
if (flush != Z_FINISH)
return Z_OK;
if (noheader != 0)
return Z_STREAM_END;
// Write the zlib trailer (adler32)
putShortMSB((int) (strm.adler >>> 16));
putShortMSB((int) (strm.adler & 0xffff));
strm.flush_pending();
// If avail_out is zero, the application will call deflate again
// to flush the rest.
noheader = -1; // write the trailer only once!
return pending != 0 ? Z_OK : Z_STREAM_END;
}
// Compress as much as possible from the input stream, return the current
// block state.
// This function does not perform lazy evaluation of matches and inserts
// new strings in the dictionary only for unmatched strings or for short
// matches. It is used only for the fast compression options.
int deflate_fast(int flush) {
// short hash_head = 0; // head of the hash chain
int hash_head = 0; // head of the hash chain
boolean bflush; // set if current block must be flushed
while (true) {
// Make sure that we always have enough lookahead, except
// at the end of the input file. We need MAX_MATCH bytes
// for the next match, plus MIN_MATCH bytes to insert the
// string following the next match.
if (lookahead < MIN_LOOKAHEAD) {
fill_window();
if (lookahead < MIN_LOOKAHEAD && flush == Z_NO_FLUSH) {
return NeedMore;
}
if (lookahead == 0)
break; // flush the current block
}
// Insert the string window[strstart .. strstart+2] in the
// dictionary, and set hash_head to the head of the hash chain:
if (lookahead >= MIN_MATCH) {
ins_h = (((ins_h) << hash_shift) ^ (window[(strstart)
+ (MIN_MATCH - 1)] & 0xff))
& hash_mask;
// prev[strstart&w_mask]=hash_head=head[ins_h];
hash_head = (head[ins_h] & 0xffff);
prev[strstart & w_mask] = head[ins_h];
head[ins_h] = (short) strstart;
}
// Find the longest match, discarding those <= prev_length.
// At this point we have always match_length < MIN_MATCH
if (hash_head != 0L
&& ((strstart - hash_head) & 0xffff) <= w_size
- MIN_LOOKAHEAD) {
// To simplify the code, we prevent matches with the string
// of window index 0 (in particular we have to avoid a match
// of the string with itself at the start of the input file).
if (strategy != Z_HUFFMAN_ONLY) {
match_length = longest_match(hash_head);
}
// longest_match() sets match_start
}
if (match_length >= MIN_MATCH) {
// check_match(strstart, match_start, match_length);
bflush = _tr_tally(strstart - match_start, match_length
- MIN_MATCH);
lookahead -= match_length;
// Insert new strings in the hash table only if the match length
// is not too large. This saves time but degrades compression.
if (match_length <= max_lazy_match && lookahead >= MIN_MATCH) {
match_length--; // string at strstart already in hash table
do {
strstart++;
ins_h = ((ins_h << hash_shift) ^ (window[(strstart)
+ (MIN_MATCH - 1)] & 0xff))
& hash_mask;
// prev[strstart&w_mask]=hash_head=head[ins_h];
hash_head = (head[ins_h] & 0xffff);
prev[strstart & w_mask] = head[ins_h];
head[ins_h] = (short) strstart;
// strstart never exceeds WSIZE-MAX_MATCH, so there are
// always MIN_MATCH bytes ahead.
} while (--match_length != 0);
strstart++;
} else {
strstart += match_length;
match_length = 0;
ins_h = window[strstart] & 0xff;
ins_h = (((ins_h) << hash_shift) ^ (window[strstart + 1] & 0xff))
& hash_mask;
// If lookahead < MIN_MATCH, ins_h is garbage, but it does
// not
// matter since it will be recomputed at next deflate call.
}
} else {
// No match, output a literal byte
bflush = _tr_tally(0, window[strstart] & 0xff);
lookahead--;
strstart++;
}
if (bflush) {
flush_block_only(false);
if (strm.avail_out == 0)
return NeedMore;
}
}
flush_block_only(flush == Z_FINISH);
if (strm.avail_out == 0) {
if (flush == Z_FINISH)
return FinishStarted;
else
return NeedMore;
}
return flush == Z_FINISH ? FinishDone : BlockDone;
}
// Same as above, but achieves better compression. We use a lazy
// evaluation for matches: a match is finally adopted only if there is
// no better match at the next window position.
int deflate_slow(int flush) {
// short hash_head = 0; // head of hash chain
int hash_head = 0; // head of hash chain
boolean bflush; // set if current block must be flushed
// Process the input block.
while (true) {
// Make sure that we always have enough lookahead, except
// at the end of the input file. We need MAX_MATCH bytes
// for the next match, plus MIN_MATCH bytes to insert the
// string following the next match.
if (lookahead < MIN_LOOKAHEAD) {
fill_window();
if (lookahead < MIN_LOOKAHEAD && flush == Z_NO_FLUSH) {
return NeedMore;
}
if (lookahead == 0)
break; // flush the current block
}
// Insert the string window[strstart .. strstart+2] in the
// dictionary, and set hash_head to the head of the hash chain:
if (lookahead >= MIN_MATCH) {
ins_h = (((ins_h) << hash_shift) ^ (window[(strstart)
+ (MIN_MATCH - 1)] & 0xff))
& hash_mask;
// prev[strstart&w_mask]=hash_head=head[ins_h];
hash_head = (head[ins_h] & 0xffff);
prev[strstart & w_mask] = head[ins_h];
head[ins_h] = (short) strstart;
}
// Find the longest match, discarding those <= prev_length.
prev_length = match_length;
prev_match = match_start;
match_length = MIN_MATCH - 1;
if (hash_head != 0
&& prev_length < max_lazy_match
&& ((strstart - hash_head) & 0xffff) <= w_size
- MIN_LOOKAHEAD) {
// To simplify the code, we prevent matches with the string
// of window index 0 (in particular we have to avoid a match
// of the string with itself at the start of the input file).
if (strategy != Z_HUFFMAN_ONLY) {
match_length = longest_match(hash_head);
}
// longest_match() sets match_start
if (match_length <= 5
&& (strategy == Z_FILTERED || (match_length == MIN_MATCH && strstart
- match_start > 4096))) {
// If prev_match is also MIN_MATCH, match_start is garbage
// but we will ignore the current match anyway.
match_length = MIN_MATCH - 1;
}
}
// If there was a match at the previous step and the current
// match is not better, output the previous match:
if (prev_length >= MIN_MATCH && match_length <= prev_length) {
int max_insert = strstart + lookahead - MIN_MATCH;
// Do not insert strings in hash table beyond this.
// check_match(strstart-1, prev_match, prev_length);
bflush = _tr_tally(strstart - 1 - prev_match, prev_length
- MIN_MATCH);
// Insert in hash table all strings up to the end of the match.
// strstart-1 and strstart are already inserted. If there is not
// enough lookahead, the last two strings are not inserted in
// the hash table.
lookahead -= prev_length - 1;
prev_length -= 2;
do {
if (++strstart <= max_insert) {
ins_h = (((ins_h) << hash_shift) ^ (window[(strstart)
+ (MIN_MATCH - 1)] & 0xff))
& hash_mask;
// prev[strstart&w_mask]=hash_head=head[ins_h];
hash_head = (head[ins_h] & 0xffff);
prev[strstart & w_mask] = head[ins_h];
head[ins_h] = (short) strstart;
}
} while (--prev_length != 0);
match_available = 0;
match_length = MIN_MATCH - 1;
strstart++;
if (bflush) {
flush_block_only(false);
if (strm.avail_out == 0)
return NeedMore;
}
} else if (match_available != 0) {
// If there was no match at the previous position, output a
// single literal. If there was a match but the current match
// is longer, truncate the previous match to a single literal.
bflush = _tr_tally(0, window[strstart - 1] & 0xff);
if (bflush) {
flush_block_only(false);
}
strstart++;
lookahead--;
if (strm.avail_out == 0)
return NeedMore;
} else {
// There is no previous match to compare with, wait for
// the next step to decide.
match_available = 1;
strstart++;
lookahead--;
}
}
if (match_available != 0) {
bflush = _tr_tally(0, window[strstart - 1] & 0xff);
match_available = 0;
}
flush_block_only(flush == Z_FINISH);
if (strm.avail_out == 0) {
if (flush == Z_FINISH)
return FinishStarted;
else
return NeedMore;
}
return flush == Z_FINISH ? FinishDone : BlockDone;
}
// Copy without compression as much as possible from the input stream,
// return
// the current block state.
// This function does not insert new strings in the dictionary since
// uncompressible data is probably not useful. This function is used
// only for the level=0 compression option.
// NOTE: this function should be optimized to avoid extra copying from
// window to pending_buf.
int deflate_stored(int flush) {
// Stored blocks are limited to 0xffff bytes, pending_buf is limited
// to pending_buf_size, and each stored block has a 5 byte header:
int max_block_size = 0xffff;
int max_start;
if (max_block_size > pending_buf_size - 5) {
max_block_size = pending_buf_size - 5;
}
// Copy as much as possible from input to output:
while (true) {
// Fill the window as much as possible:
if (lookahead <= 1) {
fill_window();
if (lookahead == 0 && flush == Z_NO_FLUSH)
return NeedMore;
if (lookahead == 0)
break; // flush the current block
}
strstart += lookahead;
lookahead = 0;
// Emit a stored block if pending_buf will be full:
max_start = block_start + max_block_size;
if (strstart == 0 || strstart >= max_start) {
// strstart == 0 is possible when wraparound on 16-bit machine
lookahead = (strstart - max_start);
strstart = max_start;
flush_block_only(false);
if (strm.avail_out == 0)
return NeedMore;
}
// Flush if we may have to slide, otherwise block_start may become
// negative and the data will be gone:
if (strstart - block_start >= w_size - MIN_LOOKAHEAD) {
flush_block_only(false);
if (strm.avail_out == 0)
return NeedMore;
}
}
flush_block_only(flush == Z_FINISH);
if (strm.avail_out == 0)
return (flush == Z_FINISH) ? FinishStarted : NeedMore;
return flush == Z_FINISH ? FinishDone : BlockDone;
}
int deflateEnd() {
if (status != INIT_STATE && status != BUSY_STATE
&& status != FINISH_STATE) {
return Z_STREAM_ERROR;
}
// Deallocate in reverse order of allocations:
pending_buf = null;
head = null;
prev = null;
window = null;
// free
// dstate=null;
return status == BUSY_STATE ? Z_DATA_ERROR : Z_OK;
}
int deflateInit(ZStream strm, int level) {
return deflateInit(strm, level, MAX_WBITS);
}
int deflateInit(ZStream strm, int level, int bits) {
return deflateInit2(strm, level, Z_DEFLATED, bits, DEF_MEM_LEVEL,
Z_DEFAULT_STRATEGY);
}
int deflateInit2(ZStream strm, int level, int method, int windowBits,
int memLevel, int strategy) {
int noheader = 0;
// byte[] my_version=ZLIB_VERSION;
//
// if (version == null || version[0] != my_version[0]
// || stream_size != sizeof(z_stream)) {
// return Z_VERSION_ERROR;
// }
strm.msg = null;
if (level == Z_DEFAULT_COMPRESSION)
level = 6;
if (windowBits < 0) { // undocumented feature: suppress zlib header
noheader = 1;
windowBits = -windowBits;
}
if (memLevel < 1 || memLevel > MAX_MEM_LEVEL || method != Z_DEFLATED
|| windowBits < 9 || windowBits > 15 || level < 0 || level > 9
|| strategy < 0 || strategy > Z_HUFFMAN_ONLY) {
return Z_STREAM_ERROR;
}
strm.dstate = this;
this.noheader = noheader;
w_bits = windowBits;
w_size = 1 << w_bits;
w_mask = w_size - 1;
hash_bits = memLevel + 7;
hash_size = 1 << hash_bits;
hash_mask = hash_size - 1;
hash_shift = ((hash_bits + MIN_MATCH - 1) / MIN_MATCH);
window = new byte[w_size * 2];
prev = new short[w_size];
head = new short[hash_size];
lit_bufsize = 1 << (memLevel + 6); // 16K elements by default
// We overlay pending_buf and d_buf+l_buf. This works since the average
// output size for (length,distance) codes is <= 24 bits.
pending_buf = new byte[lit_bufsize * 4];
pending_buf_size = lit_bufsize * 4;
d_buf = lit_bufsize / 2;
l_buf = (1 + 2) * lit_bufsize;
this.level = level;
// System.out.println("level="+level);
this.strategy = strategy;
this.method = (byte) method;
return deflateReset(strm);
}
int deflateParams(ZStream strm, int _level, int _strategy) {
int err = Z_OK;
if (_level == Z_DEFAULT_COMPRESSION) {
_level = 6;
}
if (_level < 0 || _level > 9 || _strategy < 0
|| _strategy > Z_HUFFMAN_ONLY) {
return Z_STREAM_ERROR;
}
if (config_table[level].func != config_table[_level].func
&& strm.total_in != 0) {
// Flush the last buffer:
err = strm.deflate(Z_PARTIAL_FLUSH);
}
if (level != _level) {
level = _level;
max_lazy_match = config_table[level].max_lazy;
good_match = config_table[level].good_length;
nice_match = config_table[level].nice_length;
max_chain_length = config_table[level].max_chain;
}
strategy = _strategy;
return err;
}
int deflateReset(ZStream strm) {
strm.total_in = strm.total_out = 0;
strm.msg = null; //
strm.data_type = Z_UNKNOWN;
pending = 0;
pending_out = 0;
if (noheader < 0) {
noheader = 0; // was set to -1 by deflate(..., Z_FINISH);
}
status = (noheader != 0) ? BUSY_STATE : INIT_STATE;
strm.adler = strm._adler.adler32(0, null, 0, 0);
last_flush = Z_NO_FLUSH;
tr_init();
lm_init();
return Z_OK;
}
int deflateSetDictionary(ZStream strm, byte[] dictionary, int dictLength) {
int length = dictLength;
int index = 0;
if (dictionary == null || status != INIT_STATE)
return Z_STREAM_ERROR;
strm.adler = strm._adler.adler32(strm.adler, dictionary, 0, dictLength);
if (length < MIN_MATCH)
return Z_OK;
if (length > w_size - MIN_LOOKAHEAD) {
length = w_size - MIN_LOOKAHEAD;
index = dictLength - length; // use the tail of the dictionary
}
System.arraycopy(dictionary, index, window, 0, length);
strstart = length;
block_start = length;
// Insert all strings in the hash table (except for the last two bytes).
// s->lookahead stays null, so s->ins_h will be recomputed at the next
// call of fill_window.
ins_h = window[0] & 0xff;
ins_h = (((ins_h) << hash_shift) ^ (window[1] & 0xff)) & hash_mask;
for (int n = 0; n <= length - MIN_MATCH; n++) {
ins_h = (((ins_h) << hash_shift) ^ (window[(n) + (MIN_MATCH - 1)] & 0xff))
& hash_mask;
prev[n & w_mask] = head[ins_h];
head[ins_h] = (short) n;
}
return Z_OK;
}
// Fill the window when the lookahead becomes insufficient.
// Updates strstart and lookahead.
//
// IN assertion: lookahead < MIN_LOOKAHEAD
// OUT assertions: strstart <= window_size-MIN_LOOKAHEAD
// At least one byte has been read, or avail_in == 0; reads are
// performed for at least two bytes (required for the zip translate_eol
// option -- not supported here).
void fill_window() {
int n, m;
int p;
int more; // Amount of free space at the end of the window.
do {
more = (window_size - lookahead - strstart);
// Deal with !@#$% 64K limit:
if (more == 0 && strstart == 0 && lookahead == 0) {
more = w_size;
} else if (more == -1) {
// Very unlikely, but possible on 16 bit machine if strstart ==
// 0
// and lookahead == 1 (input done one byte at time)
more--;
// If the window is almost full and there is insufficient
// lookahead,
// move the upper half to the lower one to make room in the
// upper half.
} else if (strstart >= w_size + w_size - MIN_LOOKAHEAD) {
System.arraycopy(window, w_size, window, 0, w_size);
match_start -= w_size;
strstart -= w_size; // we now have strstart >= MAX_DIST
block_start -= w_size;
// Slide the hash table (could be avoided with 32 bit values
// at the expense of memory usage). We slide even when level ==
// 0
// to keep the hash table consistent if we switch back to level
// > 0
// later. (Using level 0 permanently is not an optimal usage of
// zlib, so we don't care about this pathological case.)
n = hash_size;
p = n;
do {
m = (head[--p] & 0xffff);
head[p] = (m >= w_size ? (short) (m - w_size) : 0);
} while (--n != 0);
n = w_size;
p = n;
do {
m = (prev[--p] & 0xffff);
prev[p] = (m >= w_size ? (short) (m - w_size) : 0);
// If n is not on any hash chain, prev[n] is garbage but
// its value will never be used.
} while (--n != 0);
more += w_size;
}
if (strm.avail_in == 0)
return;
// If there was no sliding:
// strstart <= WSIZE+MAX_DIST-1 && lookahead <= MIN_LOOKAHEAD - 1 &&
// more == window_size - lookahead - strstart
// => more >= window_size - (MIN_LOOKAHEAD-1 + WSIZE + MAX_DIST-1)
// => more >= window_size - 2*WSIZE + 2
// In the BIG_MEM or MMAP case (not yet supported),
// window_size == input_size + MIN_LOOKAHEAD &&
// strstart + s->lookahead <= input_size => more >= MIN_LOOKAHEAD.
// Otherwise, window_size == 2*WSIZE so more >= 2.
// If there was sliding, more >= WSIZE. So in all cases, more >= 2.
n = strm.read_buf(window, strstart + lookahead, more);
lookahead += n;
// Initialize the hash value now that we have some input:
if (lookahead >= MIN_MATCH) {
ins_h = window[strstart] & 0xff;
ins_h = (((ins_h) << hash_shift) ^ (window[strstart + 1] & 0xff))
& hash_mask;
}
// If the whole input has less than MIN_MATCH bytes, ins_h is
// garbage,
// but this is not important since only literal bytes will be
// emitted.
} while (lookahead < MIN_LOOKAHEAD && strm.avail_in != 0);
}
void flush_block_only(boolean eof) {
_tr_flush_block(block_start >= 0 ? block_start : -1, strstart
- block_start, eof);
block_start = strstart;
strm.flush_pending();
}
void init_block() {
// Initialize the trees.
for (int i = 0; i < L_CODES; i++)
dyn_ltree[i * 2] = 0;
for (int i = 0; i < D_CODES; i++)
dyn_dtree[i * 2] = 0;
for (int i = 0; i < BL_CODES; i++)
bl_tree[i * 2] = 0;
dyn_ltree[END_BLOCK * 2] = 1;
opt_len = static_len = 0;
last_lit = matches = 0;
}
void lm_init() {
window_size = 2 * w_size;
head[hash_size - 1] = 0;
for (int i = 0; i < hash_size - 1; i++) {
head[i] = 0;
}
// Set the default configuration parameters:
max_lazy_match = Deflate.config_table[level].max_lazy;
good_match = Deflate.config_table[level].good_length;
nice_match = Deflate.config_table[level].nice_length;
max_chain_length = Deflate.config_table[level].max_chain;
strstart = 0;
block_start = 0;
lookahead = 0;
match_length = prev_length = MIN_MATCH - 1;
match_available = 0;
ins_h = 0;
}
int longest_match(int cur_match) {
int chain_length = max_chain_length; // max hash chain length
int scan = strstart; // current string
int match; // matched string
int len; // length of current match
int best_len = prev_length; // best match length so far
int limit = strstart > (w_size - MIN_LOOKAHEAD) ? strstart
- (w_size - MIN_LOOKAHEAD) : 0;
int nice_match = this.nice_match;
// Stop when cur_match becomes <= limit. To simplify the code,
// we prevent matches with the string of window index 0.
int wmask = w_mask;
int strend = strstart + MAX_MATCH;
byte scan_end1 = window[scan + best_len - 1];
byte scan_end = window[scan + best_len];
// The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of
// 16.
// It is easy to get rid of this optimization if necessary.
// Do not waste too much time if we already have a good match:
if (prev_length >= good_match) {
chain_length >>= 2;
}
// Do not look for matches beyond the end of the input. This is
// necessary
// to make deflate deterministic.
if (nice_match > lookahead)
nice_match = lookahead;
do {
match = cur_match;
// Skip to next match if the match length cannot increase
// or if the match length is less than 2:
if (window[match + best_len] != scan_end
|| window[match + best_len - 1] != scan_end1
|| window[match] != window[scan]
|| window[++match] != window[scan + 1])
continue;
// The check at best_len-1 can be removed because it will be made
// again later. (This heuristic is not always a win.)
// It is not necessary to compare scan[2] and match[2] since they
// are always equal when the other bytes match, given that
// the hash keys are equal and that HASH_BITS >= 8.
scan += 2;
match++;
// We check for insufficient lookahead only every 8th comparison;
// the 256th check will be made at strstart+258.
do {
} while (window[++scan] == window[++match]
&& window[++scan] == window[++match]
&& window[++scan] == window[++match]
&& window[++scan] == window[++match]
&& window[++scan] == window[++match]
&& window[++scan] == window[++match]
&& window[++scan] == window[++match]
&& window[++scan] == window[++match] && scan < strend);
len = MAX_MATCH - (strend - scan);
scan = strend - MAX_MATCH;
if (len > best_len) {
match_start = cur_match;
best_len = len;
if (len >= nice_match)
break;
scan_end1 = window[scan + best_len - 1];
scan_end = window[scan + best_len];
}
} while ((cur_match = (prev[cur_match & wmask] & 0xffff)) > limit
&& --chain_length != 0);
if (best_len <= lookahead)
return best_len;
return lookahead;
}
// Restore the heap property by moving down the tree starting at node k,
// exchanging a node with the smallest of its two sons if necessary,
// stopping
// when the heap property is re-established (each father smaller than its
// two sons).
void pqdownheap(short[] tree, // the tree to restore
int k // node to move down
) {
int v = heap[k];
int j = k << 1; // left son of k
while (j <= heap_len) {
// Set j to the smallest of the two sons:
if (j < heap_len && smaller(tree, heap[j + 1], heap[j], depth)) {
j++;
}
// Exit if v is smaller than both sons
if (smaller(tree, v, heap[j], depth))
break;
// Exchange v with the smallest son
heap[k] = heap[j];
k = j;
// And continue down the tree, setting j to the left son of k
j <<= 1;
}
heap[k] = v;
}
final void put_byte(byte c) {
pending_buf[pending++] = c;
}
// Output a byte on the stream.
// IN assertion: there is enough room in pending_buf.
final void put_byte(byte[] p, int start, int len) {
System.arraycopy(p, start, pending_buf, pending, len);
pending += len;
}
final void put_short(int w) {
put_byte((byte) (w/* &0xff */));
put_byte((byte) (w >>> 8));
}
final void putShortMSB(int b) {
put_byte((byte) (b >> 8));
put_byte((byte) (b/* &0xff */));
}
// Scan a literal or distance tree to determine the frequencies of the codes
// in the bit length tree.
void scan_tree(short[] tree,// the tree to be scanned
int max_code // and its largest code of non zero frequency
) {
int n; // iterates over all tree elements
int prevlen = -1; // last emitted length
int curlen; // length of current code
int nextlen = tree[0 * 2 + 1]; // length of next code
int count = 0; // repeat count of the current code
int max_count = 7; // max repeat count
int min_count = 4; // min repeat count
if (nextlen == 0) {
max_count = 138;
min_count = 3;
}
tree[(max_code + 1) * 2 + 1] = (short) 0xffff; // guard
for (n = 0; n <= max_code; n++) {
curlen = nextlen;
nextlen = tree[(n + 1) * 2 + 1];
if (++count < max_count && curlen == nextlen) {
continue;
} else if (count < min_count) {
bl_tree[curlen * 2] += count;
} else if (curlen != 0) {
if (curlen != prevlen)
bl_tree[curlen * 2]++;
bl_tree[REP_3_6 * 2]++;
} else if (count <= 10) {
bl_tree[REPZ_3_10 * 2]++;
} else {
bl_tree[REPZ_11_138 * 2]++;
}
count = 0;
prevlen = curlen;
if (nextlen == 0) {
max_count = 138;
min_count = 3;
} else if (curlen == nextlen) {
max_count = 6;
min_count = 3;
} else {
max_count = 7;
min_count = 4;
}
}
}
// Send the header for a block using dynamic Huffman trees: the counts, the
// lengths of the bit length codes, the literal tree and the distance tree.
// IN assertion: lcodes >= 257, dcodes >= 1, blcodes >= 4.
void send_all_trees(int lcodes, int dcodes, int blcodes) {
int rank; // index in bl_order
send_bits(lcodes - 257, 5); // not +255 as stated in appnote.txt
send_bits(dcodes - 1, 5);
send_bits(blcodes - 4, 4); // not -3 as stated in appnote.txt
for (rank = 0; rank < blcodes; rank++) {
send_bits(bl_tree[Tree.bl_order[rank] * 2 + 1], 3);
}
send_tree(dyn_ltree, lcodes - 1); // literal tree
send_tree(dyn_dtree, dcodes - 1); // distance tree
}
void send_bits(int value, int length) {
int len = length;
if (bi_valid > Buf_size - len) {
int val = value;
// bi_buf |= (val << bi_valid);
bi_buf |= ((val << bi_valid) & 0xffff);
put_short(bi_buf);
bi_buf = (short) (val >>> (Buf_size - bi_valid));
bi_valid += len - Buf_size;
} else {
// bi_buf |= (value) << bi_valid;
bi_buf |= (((value) << bi_valid) & 0xffff);
bi_valid += len;
}
}
final void send_code(int c, short[] tree) {
int c2 = c * 2;
send_bits((tree[c2] & 0xffff), (tree[c2 + 1] & 0xffff));
}
// Send a literal or distance tree in compressed form, using the codes in
// bl_tree.
void send_tree(short[] tree,// the tree to be sent
int max_code // and its largest code of non zero frequency
) {
int n; // iterates over all tree elements
int prevlen = -1; // last emitted length
int curlen; // length of current code
int nextlen = tree[0 * 2 + 1]; // length of next code
int count = 0; // repeat count of the current code
int max_count = 7; // max repeat count
int min_count = 4; // min repeat count
if (nextlen == 0) {
max_count = 138;
min_count = 3;
}
for (n = 0; n <= max_code; n++) {
curlen = nextlen;
nextlen = tree[(n + 1) * 2 + 1];
if (++count < max_count && curlen == nextlen) {
continue;
} else if (count < min_count) {
do {
send_code(curlen, bl_tree);
} while (--count != 0);
} else if (curlen != 0) {
if (curlen != prevlen) {
send_code(curlen, bl_tree);
count--;
}
send_code(REP_3_6, bl_tree);
send_bits(count - 3, 2);
} else if (count <= 10) {
send_code(REPZ_3_10, bl_tree);
send_bits(count - 3, 3);
} else {
send_code(REPZ_11_138, bl_tree);
send_bits(count - 11, 7);
}
count = 0;
prevlen = curlen;
if (nextlen == 0) {
max_count = 138;
min_count = 3;
} else if (curlen == nextlen) {
max_count = 6;
min_count = 3;
} else {
max_count = 7;
min_count = 4;
}
}
}
// Set the data type to ASCII or BINARY, using a crude approximation:
// binary if more than 20% of the bytes are <= 6 or >= 128, ascii otherwise.
// IN assertion: the fields freq of dyn_ltree are set and the total of all
// frequencies does not exceed 64K (to fit in an int on 16 bit machines).
void set_data_type() {
int n = 0;
int ascii_freq = 0;
int bin_freq = 0;
while (n < 7) {
bin_freq += dyn_ltree[n * 2];
n++;
}
while (n < 128) {
ascii_freq += dyn_ltree[n * 2];
n++;
}
while (n < LITERALS) {
bin_freq += dyn_ltree[n * 2];
n++;
}
data_type = (byte) (bin_freq > (ascii_freq >>> 2) ? Z_BINARY : Z_ASCII);
}
// Initialize the tree data structures for a new zlib stream.
void tr_init() {
l_desc.dyn_tree = dyn_ltree;
l_desc.stat_desc = StaticTree.static_l_desc;
d_desc.dyn_tree = dyn_dtree;
d_desc.stat_desc = StaticTree.static_d_desc;
bl_desc.dyn_tree = bl_tree;
bl_desc.stat_desc = StaticTree.static_bl_desc;
bi_buf = 0;
bi_valid = 0;
last_eob_len = 8; // enough lookahead for inflate
// Initialize the first block of the first file:
init_block();
}
}
| 07pratik-myssh | src/com/jcraft/jzlib/Deflate.java | Java | gpl3 | 53,285 |
package net.sourceforge.jsocks;
import java.io.DataInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.UnknownHostException;
/**
* SOCKS5 request/response message.
*/
public class Socks5Message extends ProxyMessage {
/** Address type of given message */
public int addrType;
byte[] data;
// SOCKS5 constants
public static final int SOCKS_VERSION = 5;
public static final int SOCKS_ATYP_IPV4 = 0x1; // Where is 2??
public static final int SOCKS_ATYP_DOMAINNAME = 0x3; // !!!!rfc1928
public static final int SOCKS_ATYP_IPV6 = 0x4;
public static final int SOCKS_IPV6_LENGTH = 16;
static boolean doResolveIP = true;
/**
* Wether to resolve hostIP returned from SOCKS server that is wether to
* create InetAddress object from the hostName string
*/
static public boolean resolveIP() {
return doResolveIP;
}
/**
* Wether to resolve hostIP returned from SOCKS server that is wether to
* create InetAddress object from the hostName string
*
* @param doResolve
* Wether to resolve hostIP from SOCKS server.
* @return Previous value.
*/
static public boolean resolveIP(boolean doResolve) {
boolean old = doResolveIP;
doResolveIP = doResolve;
return old;
}
/**
* Initialises Message from the stream. Reads server response from given
* stream.
*
* @param in
* Input stream to read response from.
* @throws SocksException
* If server response code is not SOCKS_SUCCESS(0), or if any
* error with protocol occurs.
* @throws IOException
* If any error happens with I/O.
*/
public Socks5Message(InputStream in) throws SocksException, IOException {
this(in, true);
}
/**
* Initialises Message from the stream. Reads server response or client
* request from given stream.
*
* @param in
* Input stream to read response from.
* @param clinetMode
* If true read server response, else read client request.
* @throws SocksException
* If server response code is not SOCKS_SUCCESS(0) and reading
* in client mode, or if any error with protocol occurs.
* @throws IOException
* If any error happens with I/O.
*/
public Socks5Message(InputStream in, boolean clientMode)
throws SocksException, IOException {
read(in, clientMode);
}
/**
* Server error response.
*
* @param cmd
* Error code.
*/
public Socks5Message(int cmd) {
super(cmd, null, 0);
data = new byte[3];
data[0] = SOCKS_VERSION; // Version.
data[1] = (byte) cmd; // Reply code for some kind of failure.
data[2] = 0; // Reserved byte.
}
/**
* Construct client request or server response.
*
* @param cmd
* - Request/Response code.
* @param ip
* - IP field.
* @paarm port - port field.
*/
public Socks5Message(int cmd, InetAddress ip, int port) {
super(cmd, ip, port);
this.host = ip == null ? "0.0.0.0" : ip.getHostName();
this.version = SOCKS_VERSION;
byte[] addr;
if (ip == null) {
addr = new byte[4];
addr[0] = addr[1] = addr[2] = addr[3] = 0;
} else
addr = ip.getAddress();
addrType = addr.length == 4 ? SOCKS_ATYP_IPV4 : SOCKS_ATYP_IPV6;
data = new byte[6 + addr.length];
data[0] = (byte) SOCKS_VERSION; // Version
data[1] = (byte) command; // Command
data[2] = (byte) 0; // Reserved byte
data[3] = (byte) addrType; // Address type
// Put Address
System.arraycopy(addr, 0, data, 4, addr.length);
// Put port
data[data.length - 2] = (byte) (port >> 8);
data[data.length - 1] = (byte) (port);
}
/*
* private static final void debug(String s){ if(DEBUG) System.out.print(s);
* } private static final boolean DEBUG = false;
*/
/**
* Construct client request or server response.
*
* @param cmd
* - Request/Response code.
* @param hostName
* - IP field as hostName, uses ADDR_TYPE of HOSTNAME.
* @paarm port - port field.
*/
public Socks5Message(int cmd, String hostName, int port) {
super(cmd, null, port);
this.host = hostName;
this.version = SOCKS_VERSION;
// System.out.println("Doing ATYP_DOMAINNAME");
addrType = SOCKS_ATYP_DOMAINNAME;
byte addr[] = hostName.getBytes();
data = new byte[7 + addr.length];
data[0] = (byte) SOCKS_VERSION; // Version
data[1] = (byte) command; // Command
data[2] = (byte) 0; // Reserved byte
data[3] = (byte) SOCKS_ATYP_DOMAINNAME; // Address type
data[4] = (byte) addr.length; // Length of the address
// Put Address
System.arraycopy(addr, 0, data, 5, addr.length);
// Put port
data[data.length - 2] = (byte) (port >> 8);
data[data.length - 1] = (byte) (port);
}
/**
* Returns IP field of the message as IP, if the message was created with
* ATYP of HOSTNAME, it will attempt to resolve the hostname, which might
* fail.
*
* @throws UnknownHostException
* if host can't be resolved.
*/
@Override
public InetAddress getInetAddress() throws UnknownHostException {
if (ip != null)
return ip;
return (ip = InetAddress.getByName(host));
}
/**
* Initialises Message from the stream. Reads server response from given
* stream.
*
* @param in
* Input stream to read response from.
* @throws SocksException
* If server response code is not SOCKS_SUCCESS(0), or if any
* error with protocol occurs.
* @throws IOException
* If any error happens with I/O.
*/
@Override
public void read(InputStream in) throws SocksException, IOException {
read(in, true);
}
/**
* Initialises Message from the stream. Reads server response or client
* request from given stream.
*
* @param in
* Input stream to read response from.
* @param clinetMode
* If true read server response, else read client request.
* @throws SocksException
* If server response code is not SOCKS_SUCCESS(0) and reading
* in client mode, or if any error with protocol occurs.
* @throws IOException
* If any error happens with I/O.
*/
@Override
public void read(InputStream in, boolean clientMode) throws SocksException,
IOException {
data = null;
ip = null;
DataInputStream di = new DataInputStream(in);
version = di.readUnsignedByte();
command = di.readUnsignedByte();
if (clientMode && command != 0)
throw new SocksException(command);
@SuppressWarnings("unused")
int reserved = di.readUnsignedByte();
addrType = di.readUnsignedByte();
byte addr[];
switch (addrType) {
case SOCKS_ATYP_IPV4:
addr = new byte[4];
di.readFully(addr);
host = bytes2IPV4(addr, 0);
break;
case SOCKS_ATYP_IPV6:
addr = new byte[SOCKS_IPV6_LENGTH];// I believe it is 16 bytes,huge!
di.readFully(addr);
host = bytes2IPV6(addr, 0);
break;
case SOCKS_ATYP_DOMAINNAME:
// System.out.println("Reading ATYP_DOMAINNAME");
addr = new byte[di.readUnsignedByte()];// Next byte shows the length
di.readFully(addr);
host = new String(addr);
break;
default:
throw (new SocksException(Proxy.SOCKS_JUST_ERROR));
}
port = di.readUnsignedShort();
if (addrType != SOCKS_ATYP_DOMAINNAME && doResolveIP) {
try {
ip = InetAddress.getByName(host);
} catch (UnknownHostException uh_ex) {
}
}
}
/**
* Returns string representation of the message.
*/
@Override
public String toString() {
String s = "Socks5Message:" + "\n" + "VN " + version + "\n" + "CMD "
+ command + "\n" + "ATYP " + addrType + "\n" + "ADDR " + host
+ "\n" + "PORT " + port + "\n";
return s;
}
/**
* Writes the message to the stream.
*
* @param out
* Output stream to which message should be written.
*/
@Override
public void write(OutputStream out) throws SocksException, IOException {
if (data == null) {
Socks5Message msg;
if (addrType == SOCKS_ATYP_DOMAINNAME)
msg = new Socks5Message(command, host, port);
else {
if (ip == null) {
try {
ip = InetAddress.getByName(host);
} catch (UnknownHostException uh_ex) {
throw new SocksException(Proxy.SOCKS_JUST_ERROR);
}
}
msg = new Socks5Message(command, ip, port);
}
data = msg.data;
}
out.write(data);
}
}
| 07pratik-myssh | src/net/sourceforge/jsocks/Socks5Message.java | Java | gpl3 | 8,675 |
package net.sourceforge.jsocks;
import java.io.DataInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.UnknownHostException;
/**
* SOCKS4 Reply/Request message.
*/
public class Socks4Message extends ProxyMessage {
private byte[] msgBytes;
private int msgLength;
static final String[] replyMessage = { "Request Granted",
"Request Rejected or Failed",
"Failed request, can't connect to Identd",
"Failed request, bad user name" };
static final int SOCKS_VERSION = 4;
public final static int REQUEST_CONNECT = 1;
public final static int REQUEST_BIND = 2;
public final static int REPLY_OK = 90;
public final static int REPLY_REJECTED = 91;
public final static int REPLY_NO_CONNECT = 92;
public final static int REPLY_BAD_IDENTD = 93;
// Class methods
static InetAddress bytes2IP(byte[] addr) {
String s = bytes2IPV4(addr, 0);
try {
return InetAddress.getByName(s);
} catch (UnknownHostException uh_ex) {
return null;
}
}
// Constants
/**
* Initialise from the stream If clientMode is true attempts to read a
* server response otherwise reads a client request see read for more detail
*/
public Socks4Message(InputStream in, boolean clientMode) throws IOException {
msgBytes = null;
read(in, clientMode);
}
/**
* Server failed reply, cmd command for failed request
*/
public Socks4Message(int cmd) {
super(cmd, null, 0);
this.user = null;
msgLength = 2;
msgBytes = new byte[2];
msgBytes[0] = (byte) 0;
msgBytes[1] = (byte) command;
}
/**
* Server successfull reply
*/
public Socks4Message(int cmd, InetAddress ip, int port) {
this(0, cmd, ip, port, null);
}
/**
* Client request
*/
public Socks4Message(int cmd, InetAddress ip, int port, String user) {
this(SOCKS_VERSION, cmd, ip, port, user);
}
/**
* Most general constructor
*/
public Socks4Message(int version, int cmd, InetAddress ip, int port,
String user) {
super(cmd, ip, port);
this.user = user;
this.version = version;
msgLength = user == null ? 8 : 9 + user.length();
msgBytes = new byte[msgLength];
msgBytes[0] = (byte) version;
msgBytes[1] = (byte) command;
msgBytes[2] = (byte) (port >> 8);
msgBytes[3] = (byte) port;
byte[] addr;
if (ip != null)
addr = ip.getAddress();
else {
addr = new byte[4];
addr[0] = addr[1] = addr[2] = addr[3] = 0;
}
System.arraycopy(addr, 0, msgBytes, 4, 4);
if (user != null) {
byte[] buf = user.getBytes();
System.arraycopy(buf, 0, msgBytes, 8, buf.length);
msgBytes[msgBytes.length - 1] = 0;
}
}
@Override
public void read(InputStream in) throws IOException {
read(in, true);
}
@Override
public void read(InputStream in, boolean clientMode) throws IOException {
boolean mode4a = false;
DataInputStream d_in = new DataInputStream(in);
version = d_in.readUnsignedByte();
command = d_in.readUnsignedByte();
if (clientMode && command != REPLY_OK) {
String errMsg;
if (command > REPLY_OK && command < REPLY_BAD_IDENTD)
errMsg = replyMessage[command - REPLY_OK];
else
errMsg = "Unknown Reply Code";
throw new SocksException(command, errMsg);
}
port = d_in.readUnsignedShort();
byte[] addr = new byte[4];
d_in.readFully(addr);
if (addr[0] == 0 && addr[1] == 0 && addr[2] == 0 && addr[3] != 0)
mode4a = true;
else {
ip = bytes2IP(addr);
host = ip.getHostName();
}
if (!clientMode) {
StringBuilder sb = new StringBuilder();
int b;
while ((b = in.read()) != 0)
sb.append((char) b);
user = sb.toString();
if (mode4a) {
sb.setLength(0);
while ((b = in.read()) != 0)
sb.append((char) b);
host = sb.toString();
}
}
}
@Override
public void write(OutputStream out) throws IOException {
if (msgBytes == null) {
Socks4Message msg = new Socks4Message(version, command, ip, port,
user);
msgBytes = msg.msgBytes;
msgLength = msg.msgLength;
}
out.write(msgBytes);
}
}
| 07pratik-myssh | src/net/sourceforge/jsocks/Socks4Message.java | Java | gpl3 | 4,198 |
package net.sourceforge.jsocks;
/**
* This interface provides for datagram encapsulation for SOCKSv5 protocol.
* <p>
* SOCKSv5 allows for datagrams to be encapsulated for purposes of integrity
* and/or authenticity. How it should be done is aggreed during the
* authentication stage, and is authentication dependent. This interface is
* provided to allow this encapsulation.
*
* @see Authentication
*/
public interface UDPEncapsulation {
/**
* This method should provide any authentication depended transformation on
* datagrams being send from/to the client.
*
* @param data
* Datagram data (including any SOCKS related bytes), to be
* encapsulated/decapsulated.
* @param out
* Wether the data is being send out. If true method should
* encapsulate/encrypt data, otherwise it should decapsulate/
* decrypt data.
* @throw IOException if for some reason data can be transformed correctly.
* @return Should return byte array containing data after transformation. It
* is possible to return same array as input, if transformation only
* involves bit mangling, and no additional data is being added or
* removed.
*/
byte[] udpEncapsulate(byte[] data, boolean out) throws java.io.IOException;
}
| 07pratik-myssh | src/net/sourceforge/jsocks/UDPEncapsulation.java | Java | gpl3 | 1,349 |
package net.sourceforge.jsocks;
import java.io.IOException;
import java.io.InputStream;
import java.io.InterruptedIOException;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
/**
* Abstract class Proxy, base for classes Socks4Proxy and Socks5Proxy. Defines
* methods for specifying default proxy, to be used by all classes of this
* package.
*/
public abstract class Proxy {
// Data members
// protected InetRange directHosts = new InetRange();
public static final int SOCKS_SUCCESS = 0;
public static final int SOCKS_FAILURE = 1;
public static final int SOCKS_BADCONNECT = 2;
public static final int SOCKS_BADNETWORK = 3;
public static final int SOCKS_HOST_UNREACHABLE = 4;
public static final int SOCKS_CONNECTION_REFUSED = 5;
public static final int SOCKS_TTL_EXPIRE = 6;
public static final int SOCKS_CMD_NOT_SUPPORTED = 7;
public static final int SOCKS_ADDR_NOT_SUPPORTED = 8;
public static final int SOCKS_NO_PROXY = 1 << 16;
public static final int SOCKS_PROXY_NO_CONNECT = 2 << 16;
public static final int SOCKS_PROXY_IO_ERROR = 3 << 16;
public static final int SOCKS_AUTH_NOT_SUPPORTED = 4 << 16;
// Public instance methods
// ========================
public static final int SOCKS_AUTH_FAILURE = 5 << 16;
public static final int SOCKS_JUST_ERROR = 6 << 16;
public static final int SOCKS_DIRECT_FAILED = 7 << 16;
// Public Static(Class) Methods
// ==============================
public static final int SOCKS_METHOD_NOTSUPPORTED = 8 << 16;
public static final int SOCKS_CMD_CONNECT = 0x1;
static final int SOCKS_CMD_BIND = 0x2;
static final int SOCKS_CMD_UDP_ASSOCIATE = 0x3;
/**
* Get current default proxy.
*
* @return Current default proxy, or null if none is set.
*/
public static Proxy getDefaultProxy() {
return defaultProxy;
}
/**
* Parses strings in the form: host[:port:user:password], and creates proxy
* from information obtained from parsing.
* <p>
* Defaults: port = 1080.<br>
* If user specified but not password, creates Socks4Proxy, if user not
* specified creates Socks5Proxy, if both user and password are speciefied
* creates Socks5Proxy with user/password authentication.
*
* @param proxy_entry
* String in the form host[:port:user:password]
* @return Proxy created from the string, null if entry was somehow
* invalid(host unknown for example, or empty string)
*/
public static Proxy parseProxy(String proxy_entry) {
String proxy_host;
int proxy_port = 1080;
String proxy_user = null;
String proxy_password = null;
Proxy proxy;
java.util.StringTokenizer st = new java.util.StringTokenizer(
proxy_entry, ":");
if (st.countTokens() < 1)
return null;
proxy_host = st.nextToken();
if (st.hasMoreTokens())
try {
proxy_port = Integer.parseInt(st.nextToken().trim());
} catch (NumberFormatException nfe) {
}
if (st.hasMoreTokens())
proxy_user = st.nextToken();
if (st.hasMoreTokens())
proxy_password = st.nextToken();
try {
if (proxy_user == null)
proxy = new Socks5Proxy(proxy_host, proxy_port);
else if (proxy_password == null)
proxy = new Socks4Proxy(proxy_host, proxy_port, proxy_user);
else {
proxy = new Socks5Proxy(proxy_host, proxy_port);
/*
* UserPasswordAuthentication upa = new
* UserPasswordAuthentication( proxy_user, proxy_password);
*
* ((Socks5Proxy)proxy).setAuthenticationMethod(upa.METHOD_ID,upa
* );
*/
}
} catch (UnknownHostException uhe) {
return null;
}
return proxy;
}
/**
* Sets SOCKS5 proxy as default. Default proxy only supports
* no-authentication.
*
* @param ipAddress
* Host address on which SOCKS5 server is running.
* @param port
* Port on which SOCKS5 server is running.
*/
public static void setDefaultProxy(InetAddress ipAddress, int port) {
defaultProxy = new Socks5Proxy(ipAddress, port);
}
// Protected Methods
// =================
/**
* Sets SOCKS4 proxy as default.
*
* @param ipAddress
* Host address on which SOCKS4 server is running.
* @param port
* Port on which SOCKS4 server is running.
* @param user
* Username to use for communications with proxy.
*/
public static void setDefaultProxy(InetAddress ipAddress, int port,
String user) {
defaultProxy = new Socks4Proxy(ipAddress, port, user);
}
/**
* Sets default proxy.
*
* @param p
* Proxy to use as default proxy.
*/
public static void setDefaultProxy(Proxy p) {
defaultProxy = p;
}
/**
* Sets SOCKS5 proxy as default. Default proxy only supports
* no-authentication.
*
* @param hostName
* Host name on which SOCKS5 server is running.
* @param port
* Port on which SOCKS5 server is running.
*/
public static void setDefaultProxy(String hostName, int port)
throws UnknownHostException {
defaultProxy = new Socks5Proxy(hostName, port);
}
/**
* Sets SOCKS4 proxy as default.
*
* @param hostName
* Host name on which SOCKS4 server is running.
* @param port
* Port on which SOCKS4 server is running.
* @param user
* Username to use for communications with proxy.
*/
public static void setDefaultProxy(String hostName, int port, String user)
throws UnknownHostException {
defaultProxy = new Socks4Proxy(hostName, port, user);
}
protected InetAddress proxyIP = null;
protected String proxyHost = null;
protected int proxyPort;
protected Socket proxySocket = null;
protected InputStream in;
protected OutputStream out;
protected int version;
protected Proxy chainProxy = null;
// Protected static/class variables
protected static Proxy defaultProxy = null;
Proxy(InetAddress proxyIP, int proxyPort) {
this.proxyIP = proxyIP;
this.proxyPort = proxyPort;
}
Proxy(Proxy p) {
this.proxyIP = p.proxyIP;
this.proxyPort = p.proxyPort;
this.version = p.version;
}
Proxy(Proxy chainProxy, InetAddress proxyIP, int proxyPort) {
this.chainProxy = chainProxy;
this.proxyIP = proxyIP;
this.proxyPort = proxyPort;
}
// Private methods
// ===============
// Constants
// Constructors
// ====================
Proxy(String proxyHost, int proxyPort) throws UnknownHostException {
this.proxyHost = proxyHost;
this.proxyIP = InetAddress.getByName(proxyHost);
this.proxyPort = proxyPort;
}
protected ProxyMessage accept() throws IOException, SocksException {
ProxyMessage msg;
try {
msg = formMessage(in);
} catch (InterruptedIOException iioe) {
throw iioe;
} catch (IOException io_ex) {
endSession();
throw new SocksException(SOCKS_PROXY_IO_ERROR,
"While Trying accept:" + io_ex);
}
return msg;
}
protected ProxyMessage bind(InetAddress ip, int port) throws SocksException {
try {
startSession();
ProxyMessage request = formMessage(SOCKS_CMD_BIND, ip, port);
return exchange(request);
} catch (SocksException se) {
endSession();
throw se;
}
}
protected ProxyMessage bind(String host, int port)
throws UnknownHostException, SocksException {
try {
startSession();
ProxyMessage request = formMessage(SOCKS_CMD_BIND, host, port);
return exchange(request);
} catch (SocksException se) {
endSession();
throw se;
}
}
protected ProxyMessage connect(InetAddress ip, int port)
throws SocksException {
try {
startSession();
ProxyMessage request = formMessage(SOCKS_CMD_CONNECT, ip, port);
return exchange(request);
} catch (SocksException se) {
endSession();
throw se;
}
}
protected ProxyMessage connect(String host, int port)
throws UnknownHostException, SocksException {
try {
startSession();
ProxyMessage request = formMessage(SOCKS_CMD_CONNECT, host, port);
return exchange(request);
} catch (SocksException se) {
endSession();
throw se;
}
}
protected abstract Proxy copy();
protected void endSession() {
try {
if (proxySocket != null)
proxySocket.close();
proxySocket = null;
} catch (IOException io_ex) {
}
}
/**
* Sends the request reads reply and returns it throws exception if
* something wrong with IO or the reply code is not zero
*/
protected ProxyMessage exchange(ProxyMessage request) throws SocksException {
ProxyMessage reply;
try {
request.write(out);
reply = formMessage(in);
} catch (SocksException s_ex) {
throw s_ex;
} catch (IOException ioe) {
throw (new SocksException(SOCKS_PROXY_IO_ERROR, "" + ioe));
}
return reply;
}
protected abstract ProxyMessage formMessage(InputStream in)
throws SocksException, IOException;
protected abstract ProxyMessage formMessage(int cmd, InetAddress ip,
int port);
protected abstract ProxyMessage formMessage(int cmd, String host, int port)
throws UnknownHostException;
/**
* Get the ip address of the proxy server host.
*
* @return Proxy InetAddress.
*/
public InetAddress getInetAddress() {
return proxyIP;
}
/**
* Get the port on which proxy server is running.
*
* @return Proxy port.
*/
public int getPort() {
return proxyPort;
}
/**
* Reads the reply from the SOCKS server
*/
protected ProxyMessage readMsg() throws SocksException, IOException {
return formMessage(in);
}
/**
* Sends the request to SOCKS server
*/
protected void sendMsg(ProxyMessage msg) throws SocksException, IOException {
msg.write(out);
}
protected void startSession() throws SocksException {
try {
proxySocket = new Socket(proxyIP, proxyPort);
in = proxySocket.getInputStream();
out = proxySocket.getOutputStream();
} catch (SocksException se) {
throw se;
} catch (IOException io_ex) {
throw new SocksException(SOCKS_PROXY_IO_ERROR, "" + io_ex);
}
}
/**
* Get string representation of this proxy.
*
* @returns string in the form:proxyHost:proxyPort \t Version versionNumber
*/
@Override
public String toString() {
return ("" + proxyIP.getHostName() + ":" + proxyPort + "\tVersion " + version);
}
protected ProxyMessage udpAssociate(InetAddress ip, int port)
throws SocksException {
try {
startSession();
ProxyMessage request = formMessage(SOCKS_CMD_UDP_ASSOCIATE, ip,
port);
if (request != null)
return exchange(request);
} catch (SocksException se) {
endSession();
throw se;
}
// Only get here if request was null
endSession();
throw new SocksException(SOCKS_METHOD_NOTSUPPORTED,
"This version of proxy does not support UDP associate, use version 5");
}
protected ProxyMessage udpAssociate(String host, int port)
throws UnknownHostException, SocksException {
try {
startSession();
ProxyMessage request = formMessage(SOCKS_CMD_UDP_ASSOCIATE, host,
port);
if (request != null)
return exchange(request);
} catch (SocksException se) {
endSession();
throw se;
}
// Only get here if request was null
endSession();
throw new SocksException(SOCKS_METHOD_NOTSUPPORTED,
"This version of proxy does not support UDP associate, use version 5");
}
}
| 07pratik-myssh | src/net/sourceforge/jsocks/Proxy.java | Java | gpl3 | 11,574 |
package net.sourceforge.jsocks;
import java.io.IOException;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketException;
import java.net.UnknownHostException;
/**
* SocksServerSocket allows to accept connections from one particular host
* through the SOCKS4 or SOCKS5 proxy.
*/
public class SocksServerSocket extends ServerSocket {
// Data members
protected Proxy proxy;
protected String localHost;
protected InetAddress localIP;
protected int localPort;
boolean doing_direct = false;
InetAddress remoteAddr;
/**
* Creates ServerSocket capable of accepting one connection through the
* firewall, uses default Proxy.
*
* @param ip
* Host from which the connection should be recieved.
* @param port
* Port number of the primary connection.
*/
public SocksServerSocket(InetAddress ip, int port) throws SocksException,
IOException {
this(Proxy.defaultProxy, ip, port);
}
/**
* Creates ServerSocket capable of accepting one connection through the
* firewall, uses given proxy.
*
* @param ip
* Host from which the connection should be recieved.
* @param port
* Port number of the primary connection.
*/
public SocksServerSocket(Proxy p, InetAddress ip, int port)
throws SocksException, IOException {
super(0);
remoteAddr = ip;
doDirect();
}
/**
* Creates ServerSocket capable of accepting one connection through the
* firewall, uses given proxy.
*
* @param host
* Host from which the connection should be recieved.
* @param port
* Port number of the primary connection.
*/
public SocksServerSocket(String host, int port) throws SocksException,
UnknownHostException, IOException {
super(0);
remoteAddr = InetAddress.getByName(host);
doDirect();
}
/**
* Accepts the incoming connection.
*/
@Override
public Socket accept() throws IOException {
Socket s;
if (!doing_direct) {
if (proxy == null)
return null;
ProxyMessage msg = proxy.accept();
s = msg.ip == null ? new SocksSocket(msg.host, msg.port, proxy)
: new SocksSocket(msg.ip, msg.port, proxy);
// Set timeout back to 0
proxy.proxySocket.setSoTimeout(0);
} else { // Direct Connection
// Mimic the proxy behaviour,
// only accept connections from the speciefed host.
while (true) {
s = super.accept();
if (s.getInetAddress().equals(remoteAddr)) {
// got the connection from the right host
// Close listenning socket.
break;
} else
s.close(); // Drop all connections from other hosts
}
}
proxy = null;
// Return accepted socket
return s;
}
/**
* Closes the connection to proxy if socket have not been accepted, if the
* direct connection is used, closes direct ServerSocket. If the client
* socket have been allready accepted, does nothing.
*/
@Override
public void close() throws IOException {
super.close();
if (proxy != null)
proxy.endSession();
proxy = null;
}
private void doDirect() {
doing_direct = true;
localPort = super.getLocalPort();
localIP = super.getInetAddress();
localHost = localIP.getHostName();
}
/**
* Get the name of the host proxy is using to listen for incoming
* connection.
* <P>
* Usefull when address is returned by proxy as the hostname.
*
* @return the hostname of the address proxy is using to listen for incoming
* connection.
*/
public String getHost() {
return localHost;
}
/**
* Get address assigned by proxy to listen for incomming connections, or the
* local machine address if doing direct connection.
*/
@Override
public InetAddress getInetAddress() {
if (localIP == null) {
try {
localIP = InetAddress.getByName(localHost);
} catch (UnknownHostException e) {
return null;
}
}
return localIP;
}
/**
* Get port assigned by proxy to listen for incoming connections, or the
* port chosen by local system, if accepting directly.
*/
@Override
public int getLocalPort() {
return localPort;
}
// Private Methods
// ////////////////
/**
* Set Timeout.
*
* @param timeout
* Amount of time in milliseconds, accept should wait for
* incoming connection before failing with exception. Zero
* timeout implies infinity.
*/
@Override
public void setSoTimeout(int timeout) throws SocketException {
super.setSoTimeout(timeout);
if (!doing_direct)
proxy.proxySocket.setSoTimeout(timeout);
}
}
| 07pratik-myssh | src/net/sourceforge/jsocks/SocksServerSocket.java | Java | gpl3 | 4,736 |
package net.sourceforge.jsocks;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.UnknownHostException;
/**
* Abstract class which describes SOCKS4/5 response/request.
*/
public abstract class ProxyMessage {
static final String bytes2IPV4(byte[] addr, int offset) {
String hostName = "" + (addr[offset] & 0xFF);
for (int i = offset + 1; i < offset + 4; ++i)
hostName += "." + (addr[i] & 0xFF);
return hostName;
}
static final String bytes2IPV6(byte[] addr, int offset) {
// Have no idea how they look like!
return null;
}
/** Host as an IP address */
public InetAddress ip = null;
/** SOCKS version, or version of the response for SOCKS4 */
public int version;
/** Port field of the request/response */
public int port;
/** Request/response code as an int */
public int command;
/** Host as string. */
public String host = null;
/** User field for SOCKS4 request messages */
public String user = null;
ProxyMessage() {
}
ProxyMessage(int command, InetAddress ip, int port) {
this.command = command;
this.ip = ip;
this.port = port;
}
/**
* Get the Address field of this message as InetAddress object.
*
* @return Host address or null, if one can't be determined.
*/
public InetAddress getInetAddress() throws UnknownHostException {
return ip;
}
/**
* Initialises Message from the stream. Reads server response from given
* stream.
*
* @param in
* Input stream to read response from.
* @throws SocksException
* If server response code is not SOCKS_SUCCESS(0), or if any
* error with protocol occurs.
* @throws IOException
* If any error happens with I/O.
*/
public abstract void read(InputStream in) throws SocksException,
IOException;
/**
* Initialises Message from the stream. Reads server response or client
* request from given stream.
*
* @param in
* Input stream to read response from.
* @param clinetMode
* If true read server response, else read client request.
* @throws SocksException
* If server response code is not SOCKS_SUCCESS(0) and reading
* in client mode, or if any error with protocol occurs.
* @throws IOException
* If any error happens with I/O.
*/
public abstract void read(InputStream in, boolean client_mode)
throws SocksException, IOException;
// Package methods
// ////////////////
/**
* Get string representaion of this message.
*
* @return string representation of this message.
*/
@Override
public String toString() {
return "Proxy Message:\n" + "Version:" + version + "\n" + "Command:"
+ command + "\n" + "IP: " + ip + "\n" + "Port: " + port
+ "\n" + "User: " + user + "\n";
}
/**
* Writes the message to the stream.
*
* @param out
* Output stream to which message should be written.
*/
public abstract void write(OutputStream out) throws SocksException,
IOException;
}
| 07pratik-myssh | src/net/sourceforge/jsocks/ProxyMessage.java | Java | gpl3 | 3,184 |
package net.sourceforge.jsocks.server;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PushbackInputStream;
import java.net.Socket;
import net.sourceforge.jsocks.ProxyMessage;
import net.sourceforge.jsocks.UDPEncapsulation;
/**
* An implementation of ServerAuthenticator, which does <b>not</b> do any
* authentication.
* <P>
* <FONT size="+3" color ="FF0000"> Warning!!</font><br>
* Should not be used on machines which are not behind the firewall.
* <p>
* It is only provided to make implementing other authentication schemes easier.
* <br>
* For Example: <tt><pre>
class MyAuth extends socks.server.ServerAuthenticator{
...
public ServerAuthenticator startSession(java.net.Socket s){
if(!checkHost(s.getInetAddress()) return null;
return super.startSession(s);
}
boolean checkHost(java.net.Inetaddress addr){
boolean allow;
//Do it somehow
return allow;
}
}
</pre></tt>
*/
public class ServerAuthenticatorNone implements ServerAuthenticator {
static final byte[] socks5response = { 5, 0 };
/**
* Convinience routine for selecting SOCKSv5 authentication.
* <p>
* This method reads in authentication methods that client supports, checks
* wether it supports given method. If it does, the notification method is
* written back to client, that this method have been chosen for
* authentication. If given method was not found, authentication failure
* message is send to client ([5,FF]).
*
* @param in
* Input stream, version byte should be removed from the stream
* before calling this method.
* @param out
* Output stream.
* @param methodId
* Method which should be selected.
* @return true if methodId was found, false otherwise.
*/
static public boolean selectSocks5Authentication(InputStream in,
OutputStream out, int methodId) throws IOException {
int num_methods = in.read();
if (num_methods <= 0)
return false;
byte method_ids[] = new byte[num_methods];
byte response[] = new byte[2];
boolean found = false;
response[0] = (byte) 5; // SOCKS version
response[1] = (byte) 0xFF; // Not found, we are pessimistic
int bread = 0; // bytes read so far
while (bread < num_methods)
bread += in.read(method_ids, bread, num_methods - bread);
for (int i = 0; i < num_methods; ++i)
if (method_ids[i] == methodId) {
found = true;
response[1] = (byte) methodId;
break;
}
out.write(response);
return found;
}
InputStream in;
OutputStream out;
/**
* Creates new instance of the ServerAuthenticatorNone.
*/
public ServerAuthenticatorNone() {
this.in = null;
this.out = null;
}
/**
* Constructs new ServerAuthenticatorNone object suitable for returning from
* the startSession function.
*
* @param in
* Input stream to return from getInputStream method.
* @param out
* Output stream to return from getOutputStream method.
*/
public ServerAuthenticatorNone(InputStream in, OutputStream out) {
this.in = in;
this.out = out;
}
/**
* Allways returns true.
*/
@Override
public boolean checkRequest(java.net.DatagramPacket dp, boolean out) {
return true;
}
/**
* Allways returns true.
*/
@Override
public boolean checkRequest(ProxyMessage msg) {
return true;
}
/**
* Does nothing.
*/
@Override
public void endSession() {
}
/**
* Get input stream.
*
* @return Input stream speciefied in the constructor.
*/
@Override
public InputStream getInputStream() {
return in;
}
/**
* Get output stream.
*
* @return Output stream speciefied in the constructor.
*/
@Override
public OutputStream getOutputStream() {
return out;
}
/**
* Allways returns null.
*
* @return null
*/
@Override
public UDPEncapsulation getUdpEncapsulation() {
return null;
}
/**
* Grants access to everyone.Removes authentication related bytes from the
* stream, when a SOCKS5 connection is being made, selects an authentication
* NONE.
*/
@Override
public ServerAuthenticator startSession(Socket s) throws IOException {
PushbackInputStream in = new PushbackInputStream(s.getInputStream());
OutputStream out = s.getOutputStream();
int version = in.read();
if (version == 5) {
if (!selectSocks5Authentication(in, out, 0))
return null;
} else if (version == 4) {
// Else it is the request message allready, version 4
in.unread(version);
} else
return null;
return new ServerAuthenticatorNone(in, out);
}
}
| 07pratik-myssh | src/net/sourceforge/jsocks/server/ServerAuthenticatorNone.java | Java | gpl3 | 4,784 |
package net.sourceforge.jsocks.server;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.DatagramPacket;
import java.net.Socket;
import net.sourceforge.jsocks.ProxyMessage;
import net.sourceforge.jsocks.UDPEncapsulation;
/**
* Classes implementing this interface should provide socks server with
* authentication and authorization of users.
**/
public interface ServerAuthenticator {
/**
* This method is called when datagram is received by the server.
* <p>
* Implementaions should decide wether it should be forwarded or dropped. It
* is expecteed that implementation will use datagram address and port
* information to make a decision, as well as anything else. Address and
* port of the datagram are always correspond to remote machine. It is
* either destination or source address. If out is true address is
* destination address, else it is a source address, address of the machine
* from which datagram have been received for the client.
* <p>
* Implementaions should return true if the datagram is to be forwarded, and
* false if the datagram should be dropped.
* <p>
* This method is called on the object returned from the startSession
* function.
*
* @param out
* If true the datagram is being send out(from the client),
* otherwise it is an incoming datagram.
* @return True to forward datagram false drop it silently.
*/
boolean checkRequest(DatagramPacket dp, boolean out);
/**
* This method is called when a request have been read.
* <p>
* Implementation should decide wether to grant request or not. Returning
* true implies granting the request, false means request should be
* rejected.
* <p>
* This method is called on the object returned from the startSession
* function.
*
* @param msg
* Request message.
* @return true to grant request, false to reject it.
*/
boolean checkRequest(ProxyMessage msg);
/**
* This method is called when session is completed. Either due to normal
* termination or due to any error condition.
* <p>
* This method is called on the object returned from the startSession
* function.
*/
void endSession();
/**
* This method should return input stream which should be used on the
* accepted socket.
* <p>
* SOCKSv5 allows to have multiple authentication methods, and these methods
* might require some kind of transformations being made on the data.
* <p>
* This method is called on the object returned from the startSession
* function.
*/
InputStream getInputStream();
/**
* This method should return output stream to use to write to the accepted
* socket.
* <p>
* SOCKSv5 allows to have multiple authentication methods, and these methods
* might require some kind of transformations being made on the data.
* <p>
* This method is called on the object returned from the startSession
* function.
*/
OutputStream getOutputStream();
/**
* This method should return UDPEncapsulation, which should be used on the
* datagrams being send in/out.
* <p>
* If no transformation should be done on the datagrams, this method should
* return null.
* <p>
* This method is called on the object returned from the startSession
* function.
*/
UDPEncapsulation getUdpEncapsulation();
/**
* This method is called when a new connection accepted by the server.
* <p>
* At this point no data have been extracted from the connection. It is
* responsibility of this method to ensure that the next byte in the stream
* after this method have been called is the first byte of the socks request
* message. For SOCKSv4 there is no authentication data and the first byte
* in the stream is part of the request. With SOCKSv5 however there is an
* authentication data first. It is expected that implementaions will
* process this authentication data.
* <p>
* If authentication was successful an instance of ServerAuthentication
* should be returned, it later will be used by the server to perform
* authorization and some other things. If authentication fails null should
* be returned, or an exception may be thrown.
*
* @param s
* Accepted Socket.
* @return An instance of ServerAuthenticator to be used for this connection
* or null
*/
ServerAuthenticator startSession(Socket s) throws IOException;
}
| 07pratik-myssh | src/net/sourceforge/jsocks/server/ServerAuthenticator.java | Java | gpl3 | 4,551 |
package net.sourceforge.jsocks;
import java.io.IOException;
import java.io.InputStream;
import java.net.InetAddress;
import java.net.UnknownHostException;
/**
* Proxy which describes SOCKS4 proxy.
*/
public class Socks4Proxy extends Proxy implements Cloneable {
// Data members
String user;
// Public Constructors
// ====================
/**
* Creates the SOCKS4 proxy
*
* @param proxyIP
* Address of the proxy server.
* @param proxyPort
* Port of the proxy server
* @param user
* User name to use for identification purposes.
*/
public Socks4Proxy(InetAddress proxyIP, int proxyPort, String user) {
this(null, proxyIP, proxyPort, user);
}
/**
* Creates the SOCKS4 proxy
*
* @param p
* Proxy to use to connect to this proxy, allows proxy chaining.
* @param proxyIP
* Address of the proxy server.
* @param proxyPort
* Port of the proxy server
* @param user
* User name to use for identification purposes.
*/
public Socks4Proxy(Proxy p, InetAddress proxyIP, int proxyPort, String user) {
super(p, proxyIP, proxyPort);
this.user = new String(user);
version = 4;
}
/**
* Creates the SOCKS4 proxy
*
* @param p
* Proxy to use to connect to this proxy, allows proxy chaining.
* @param proxyHost
* Address of the proxy server.
* @param proxyPort
* Port of the proxy server
* @param user
* User name to use for identification purposes.
* @throws UnknownHostException
* If proxyHost can't be resolved.
*/
public Socks4Proxy(String proxyHost, int proxyPort, String user)
throws UnknownHostException {
super(proxyHost, proxyPort);
this.user = new String(user);
version = 4;
}
// Public instance methods
// ========================
/**
* Creates a clone of this proxy. Changes made to the clone should not
* affect this object.
*/
@Override
public Object clone() {
Socks4Proxy newProxy = new Socks4Proxy(proxyIP, proxyPort, user);
newProxy.chainProxy = chainProxy;
return newProxy;
}
// Public Static(Class) Methods
// ==============================
// Protected Methods
// =================
@Override
protected Proxy copy() {
Socks4Proxy copy = new Socks4Proxy(proxyIP, proxyPort, user);
copy.chainProxy = chainProxy;
return copy;
}
@Override
protected ProxyMessage formMessage(InputStream in) throws SocksException,
IOException {
return new Socks4Message(in, true);
}
@Override
protected ProxyMessage formMessage(int cmd, InetAddress ip, int port) {
switch (cmd) {
case SOCKS_CMD_CONNECT:
cmd = Socks4Message.REQUEST_CONNECT;
break;
case SOCKS_CMD_BIND:
cmd = Socks4Message.REQUEST_BIND;
break;
default:
return null;
}
return new Socks4Message(cmd, ip, port, user);
}
@Override
protected ProxyMessage formMessage(int cmd, String host, int port)
throws UnknownHostException {
return formMessage(cmd, InetAddress.getByName(host), port);
}
}
| 07pratik-myssh | src/net/sourceforge/jsocks/Socks4Proxy.java | Java | gpl3 | 3,183 |
package net.sourceforge.jsocks;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.Socket;
import java.net.SocketException;
import java.net.UnknownHostException;
/**
* SocksSocket tryies to look very similar to normal Socket, while allowing
* connections through the SOCKS4 or 5 proxy. To use this class you will have to
* identify proxy you need to use, Proxy class allows you to set default proxy,
* which will be used by all Socks aware sockets. You can also create either
* Socks4Proxy or Socks5Proxy, and use them by passing to the appropriate
* constructors.
* <P>
* Using Socks package can be as easy as that:
*
* <pre>
* <tt>
*
* import Socks.*;
* ....
*
* try{
* //Specify SOCKS5 proxy
* Proxy.setDefaultProxy("socks-proxy",1080);
*
* //OR you still use SOCKS4
* //Code below uses SOCKS4 proxy
* //Proxy.setDefaultProxy("socks-proxy",1080,userName);
*
* Socket s = SocksSocket("some.host.of.mine",13);
* readTimeFromSock(s);
* }catch(SocksException sock_ex){
* //Usually it will turn in more or less meaningfull message
* System.err.println("SocksException:"+sock_ex);
* }
*
* </tt>
* </pre>
* <P>
* However if the need exist for more control, like resolving addresses
* remotely, or using some non-trivial authentication schemes, it can be done.
*/
public class SocksSocket extends Socket {
// Data members
protected Proxy proxy;
protected String localHost, remoteHost;
protected InetAddress localIP, remoteIP;
protected int localPort, remotePort;
private Socket directSock = null;
/**
* Connects to given ip and port using given Proxy server.
*
* @param p
* Proxy to use.
* @param ip
* Machine to connect to.
* @param port
* Port to which to connect.
*/
public SocksSocket(InetAddress ip, int port) throws SocksException {
this.remoteIP = ip;
this.remotePort = port;
this.remoteHost = ip.getHostName();
doDirect();
}
protected SocksSocket(InetAddress ip, int port, Proxy proxy) {
remoteIP = ip;
remotePort = port;
this.proxy = proxy;
this.localIP = proxy.proxySocket.getLocalAddress();
this.localPort = proxy.proxySocket.getLocalPort();
remoteHost = remoteIP.getHostName();
}
/**
* Connects to host port using given proxy server.
*
* @param p
* Proxy to use.
* @param host
* Machine to connect to.
* @param port
* Port to which to connect.
* @throws UnknownHostException
* If one of the following happens:
* <ol>
*
* <li>Proxy settings say that address should be resolved
* locally, but this fails.
* <li>Proxy settings say that the host should be contacted
* directly but host name can't be resolved.
* </ol>
* @throws SocksException
* If one of the following happens:
* <ul>
* <li>Proxy is is null.
* <li>Proxy settings say that the host should be contacted
* directly but this fails.
* <li>Socks Server can't be contacted.
* <li>Authentication fails.
* <li>Connection is not allowed by the SOCKS proxy.
* <li>SOCKS proxy can't establish the connection.
* <li>Any IO error occured.
* <li>Any protocol error occured.
* </ul>
* @throws IOexception
* if anything is wrong with I/O.
* @see Socks5Proxy#resolveAddrLocally
*/
public SocksSocket(Proxy p, String host, int port) throws SocksException,
UnknownHostException {
remoteHost = host;
remotePort = port;
remoteIP = InetAddress.getByName(host);
doDirect();
}
/**
* Tryies to connect to given host and port using default proxy. If no
* default proxy speciefied it throws SocksException with error code
* SOCKS_NO_PROXY.
*
* @param host
* Machine to connect to.
* @param port
* Port to which to connect.
* @see SocksSocket#SocksSocket(Proxy,String,int)
* @see Socks5Proxy#resolveAddrLocally
*/
public SocksSocket(String host, int port) throws SocksException,
UnknownHostException {
this(Proxy.defaultProxy, host, port);
}
/**
* These 2 constructors are used by the SocksServerSocket. This socket
* simply overrides remoteHost, remotePort
*/
protected SocksSocket(String host, int port, Proxy proxy) {
this.remotePort = port;
this.proxy = proxy;
this.localIP = proxy.proxySocket.getLocalAddress();
this.localPort = proxy.proxySocket.getLocalPort();
this.remoteHost = host;
}
/**
* Same as Socket
*/
@Override
public void close() throws IOException {
if (proxy != null)
proxy.endSession();
proxy = null;
}
private void doDirect() throws SocksException {
try {
// System.out.println("IP:"+remoteIP+":"+remotePort);
directSock = new Socket(remoteIP, remotePort);
proxy.out = directSock.getOutputStream();
proxy.in = directSock.getInputStream();
proxy.proxySocket = directSock;
localIP = directSock.getLocalAddress();
localPort = directSock.getLocalPort();
} catch (IOException io_ex) {
throw new SocksException(Proxy.SOCKS_DIRECT_FAILED,
"Direct connect failed:" + io_ex);
}
}
/**
* Returns remote host name, it is usefull in cases when addresses are
* resolved by proxy, and we can't create InetAddress object.
*
* @return The name of the host this socket is connected to.
*/
public String getHost() {
return remoteHost;
}
/**
* Get remote host as InetAddress object, might return null if addresses are
* resolved by proxy, and it is not possible to resolve it locally
*
* @return Ip address of the host this socket is connected to, or null if
* address was returned by the proxy as DOMAINNAME and can't be
* resolved locally.
*/
@Override
public InetAddress getInetAddress() {
if (remoteIP == null) {
try {
remoteIP = InetAddress.getByName(remoteHost);
} catch (UnknownHostException e) {
return null;
}
}
return remoteIP;
}
/**
* Same as Socket
*/
@Override
public InputStream getInputStream() {
return proxy.in;
}
/**
* Get address assigned by proxy to make a remote connection, it might be
* different from the host specified for the proxy. Can return null if socks
* server returned this address as hostname and it can't be resolved
* locally, use getLocalHost() then.
*
* @return Address proxy is using to make a connection.
*/
@Override
public InetAddress getLocalAddress() {
if (localIP == null) {
try {
localIP = InetAddress.getByName(localHost);
} catch (UnknownHostException e) {
return null;
}
}
return localIP;
}
/**
* Get name of the host, proxy has assigned to make a remote connection for
* this socket. This method is usefull when proxy have returned address as
* hostname, and we can't resolve it on this machine.
*
* @return The name of the host proxy is using to make a connection.
*/
public String getLocalHost() {
return localHost;
}
/**
* Get the port assigned by the proxy for the socket, not the port on locall
* machine as in Socket.
*
* @return Port of the socket used on the proxy server.
*/
@Override
public int getLocalPort() {
return localPort;
}
/**
* Same as Socket
*/
@Override
public OutputStream getOutputStream() {
return proxy.out;
}
/**
* Same as Socket
*/
@Override
public int getPort() {
return remotePort;
}
/**
* Same as socket.
*/
public int getSoLinger(int timeout) throws SocketException {
return proxy.proxySocket.getSoLinger();
}
/**
* Same as socket.
*/
public int getSoTimeout(int timeout) throws SocketException {
return proxy.proxySocket.getSoTimeout();
}
/**
* Same as socket.
*/
@Override
public boolean getTcpNoDelay() throws SocketException {
return proxy.proxySocket.getTcpNoDelay();
}
/**
* Same as socket.
*/
@Override
public void setSoLinger(boolean on, int val) throws SocketException {
proxy.proxySocket.setSoLinger(on, val);
}
/**
* Same as socket.
*/
@Override
public void setSoTimeout(int timeout) throws SocketException {
proxy.proxySocket.setSoTimeout(timeout);
}
/**
* Same as socket.
*/
@Override
public void setTcpNoDelay(boolean on) throws SocketException {
proxy.proxySocket.setTcpNoDelay(on);
}
// Private Methods
// ////////////////
/**
* Get string representation of the socket.
*/
@Override
public String toString() {
if (directSock != null)
return "Direct connection:" + directSock;
return ("Proxy:" + proxy + ";" + "addr:" + remoteHost + ",port:"
+ remotePort + ",localport:" + localPort);
}
}
| 07pratik-myssh | src/net/sourceforge/jsocks/SocksSocket.java | Java | gpl3 | 9,224 |
package net.sourceforge.jsocks;
/**
* SOCKS5 none authentication. Dummy class does almost nothing.
*/
public class AuthenticationNone implements Authentication {
@Override
public Object[] doSocksAuthentication(int methodId,
java.net.Socket proxySocket) throws java.io.IOException {
if (methodId != 0)
return null;
return new Object[] { proxySocket.getInputStream(),
proxySocket.getOutputStream() };
}
}
| 07pratik-myssh | src/net/sourceforge/jsocks/AuthenticationNone.java | Java | gpl3 | 444 |
package net.sourceforge.jsocks;
import java.io.IOException;
import java.io.InterruptedIOException;
import java.io.PrintStream;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
import net.sourceforge.jsocks.server.ServerAuthenticator;
/**
* UDP Relay server, used by ProxyServer to perform udp forwarding.
*/
class UDPRelayServer implements Runnable {
DatagramSocket client_sock;
DatagramSocket remote_sock;
Socket controlConnection;
int relayPort;
InetAddress relayIP;
Thread pipe_thread1, pipe_thread2;
Thread master_thread;
ServerAuthenticator auth;
long lastReadTime;
static PrintStream log = null;
static Proxy proxy = null;
static int datagramSize = 0xFFFF;// 64K, a bit more than max udp size
static int iddleTimeout = 180000;// 3 minutes
static private void log(String s) {
if (log != null) {
log.println(s);
log.flush();
}
}
// Public methods
// ///////////////
/**
* Sets the size of the datagrams used in the UDPRelayServer.<br>
* Default size is 64K, a bit more than maximum possible size of the
* datagram.
*/
static public void setDatagramSize(int size) {
datagramSize = size;
}
/**
* Sets the timeout for UDPRelay server.<br>
* Zero timeout implies infinity.<br>
* Default timeout is 3 minutes.
*/
static public void setTimeout(int timeout) {
iddleTimeout = timeout;
}
/**
* Constructs UDP relay server to communicate with client on given ip and
* port.
*
* @param clientIP
* Address of the client from whom datagrams will be recieved and
* to whom they will be forwarded.
* @param clientPort
* Clients port.
* @param master_thread
* Thread which will be interrupted, when UDP relay server
* stoppes for some reason.
* @param controlConnection
* Socket which will be closed, before interrupting the master
* thread, it is introduced due to a bug in windows JVM which
* does not throw InterruptedIOException in threads which block
* in I/O operation.
*/
public UDPRelayServer(InetAddress clientIP, int clientPort,
Thread master_thread, Socket controlConnection,
ServerAuthenticator auth) throws IOException {
this.master_thread = master_thread;
this.controlConnection = controlConnection;
this.auth = auth;
client_sock = new Socks5DatagramSocket(true,
auth.getUdpEncapsulation(), clientIP, clientPort);
relayPort = client_sock.getLocalPort();
relayIP = client_sock.getLocalAddress();
if (relayIP.getHostAddress().equals("0.0.0.0"))
relayIP = InetAddress.getLocalHost();
if (proxy == null)
remote_sock = new DatagramSocket();
else
remote_sock = new Socks5DatagramSocket(proxy, 0, null);
}
// Private methods
// ///////////////
private synchronized void abort() {
if (pipe_thread1 == null)
return;
log("Aborting UDP Relay Server");
remote_sock.close();
client_sock.close();
if (controlConnection != null)
try {
controlConnection.close();
} catch (IOException ioe) {
}
if (master_thread != null)
master_thread.interrupt();
pipe_thread1.interrupt();
pipe_thread2.interrupt();
pipe_thread1 = null;
}
/**
* IP address to which client should send datagrams for association.
*/
public InetAddress getRelayIP() {
return relayIP;
}
/**
* Port to which client should send datagram for association.
*/
public int getRelayPort() {
return relayPort;
}
private void pipe(DatagramSocket from, DatagramSocket to, boolean out)
throws IOException {
byte[] data = new byte[datagramSize];
DatagramPacket dp = new DatagramPacket(data, data.length);
while (true) {
try {
from.receive(dp);
lastReadTime = System.currentTimeMillis();
if (auth.checkRequest(dp, out))
to.send(dp);
} catch (UnknownHostException uhe) {
log("Dropping datagram for unknown host");
} catch (InterruptedIOException iioe) {
// log("Interrupted: "+iioe);
// If we were interrupted by other thread.
if (iddleTimeout == 0)
return;
// If last datagram was received, long time ago, return.
long timeSinceRead = System.currentTimeMillis() - lastReadTime;
if (timeSinceRead >= iddleTimeout - 100) // -100 for adjustment
return;
}
dp.setLength(data.length);
}
}
// Runnable interface
// //////////////////
@Override
public void run() {
try {
if (Thread.currentThread().getName().equals("pipe1"))
pipe(remote_sock, client_sock, false);
else
pipe(client_sock, remote_sock, true);
} catch (IOException ioe) {
} finally {
abort();
log("UDP Pipe thread " + Thread.currentThread().getName()
+ " stopped.");
}
}
/**
* Starts udp relay server. Spawns two threads of execution and returns.
*/
public void start() throws IOException {
remote_sock.setSoTimeout(iddleTimeout);
client_sock.setSoTimeout(iddleTimeout);
log("Starting UDP relay server on " + relayIP + ":" + relayPort);
log("Remote socket " + remote_sock.getLocalAddress() + ":"
+ remote_sock.getLocalPort());
pipe_thread1 = new Thread(this, "pipe1");
pipe_thread2 = new Thread(this, "pipe2");
lastReadTime = System.currentTimeMillis();
pipe_thread1.start();
pipe_thread2.start();
}
/**
* Stops Relay server.
* <p>
* Does not close control connection, does not interrupt master_thread.
*/
public synchronized void stop() {
master_thread = null;
controlConnection = null;
abort();
}
}
| 07pratik-myssh | src/net/sourceforge/jsocks/UDPRelayServer.java | Java | gpl3 | 5,817 |
package net.sourceforge.jsocks;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InterruptedIOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
/**
* Datagram socket to interract through the firewall.<BR>
* Can be used same way as the normal DatagramSocket. One should be carefull
* though with the datagram sizes used, as additional data is present in both
* incomming and outgoing datagrams.
* <p>
* SOCKS5 protocol allows to send host address as either:
* <ul>
* <li>IPV4, normal 4 byte address. (10 bytes header size)
* <li>IPV6, version 6 ip address (not supported by Java as for now). 22 bytes
* header size.
* <li>Host name,(7+length of the host name bytes header size).
* </ul>
* As with other Socks equivalents, direct addresses are handled transparently,
* that is data will be send directly when required by the proxy settings.
* <p>
* <b>NOTE:</b><br>
* Unlike other SOCKS Sockets, it <b>does not</b> support proxy chaining, and
* will throw an exception if proxy has a chain proxy attached. The reason for
* that is not my laziness, but rather the restrictions of the SOCKSv5 protocol.
* Basicaly SOCKSv5 proxy server, needs to know from which host:port datagrams
* will be send for association, and returns address to which datagrams should
* be send by the client, but it does not inform client from which host:port it
* is going to send datagrams, in fact there is even no guarantee they will be
* send at all and from the same address each time.
*/
public class Socks5DatagramSocket extends DatagramSocket {
InetAddress relayIP;
int relayPort;
Socks5Proxy proxy;
private boolean server_mode = false;
UDPEncapsulation encapsulation;
/**
* Construct Datagram socket for communication over SOCKS5 proxy server.
* This constructor uses default proxy, the one set with
* Proxy.setDefaultProxy() method. If default proxy is not set or it is set
* to version4 proxy, which does not support datagram forwarding, throws
* SocksException.
*/
public Socks5DatagramSocket() throws SocksException, IOException {
this(Proxy.defaultProxy, 0, null);
}
/**
* Used by UDPRelayServer.
*/
Socks5DatagramSocket(boolean server_mode, UDPEncapsulation encapsulation,
InetAddress relayIP, int relayPort) throws IOException {
super();
this.server_mode = server_mode;
this.relayIP = relayIP;
this.relayPort = relayPort;
this.encapsulation = encapsulation;
this.proxy = null;
}
/**
* Construct Datagram socket for communication over SOCKS5 proxy server. And
* binds it to the specified local port. This constructor uses default
* proxy, the one set with Proxy.setDefaultProxy() method. If default proxy
* is not set or it is set to version4 proxy, which does not support
* datagram forwarding, throws SocksException.
*/
public Socks5DatagramSocket(int port) throws SocksException, IOException {
this(Proxy.defaultProxy, port, null);
}
/**
* Construct Datagram socket for communication over SOCKS5 proxy server. And
* binds it to the specified local port and address. This constructor uses
* default proxy, the one set with Proxy.setDefaultProxy() method. If
* default proxy is not set or it is set to version4 proxy, which does not
* support datagram forwarding, throws SocksException.
*/
public Socks5DatagramSocket(int port, InetAddress ip)
throws SocksException, IOException {
this(Proxy.defaultProxy, port, ip);
}
/**
* Constructs datagram socket for communication over specified proxy. And
* binds it to the given local address and port. Address of null and port of
* 0, signify any availabale port/address. Might throw SocksException, if:
* <ol>
* <li>Given version of proxy does not support UDP_ASSOCIATE.
* <li>Proxy can't be reached.
* <li>Authorization fails.
* <li>Proxy does not want to perform udp forwarding, for any reason.
* </ol>
* Might throw IOException if binding dtagram socket to given address/port
* fails. See java.net.DatagramSocket for more details.
*/
public Socks5DatagramSocket(Proxy p, int port, InetAddress ip)
throws SocksException, IOException {
super(port, ip);
if (p == null)
throw new SocksException(Proxy.SOCKS_NO_PROXY);
if (!(p instanceof Socks5Proxy))
throw new SocksException(-1,
"Datagram Socket needs Proxy version 5");
if (p.chainProxy != null)
throw new SocksException(Proxy.SOCKS_JUST_ERROR,
"Datagram Sockets do not support proxy chaining.");
proxy = (Socks5Proxy) p.copy();
ProxyMessage msg = proxy.udpAssociate(super.getLocalAddress(),
super.getLocalPort());
relayIP = msg.ip;
if (relayIP.getHostAddress().equals("0.0.0.0"))
relayIP = proxy.proxyIP;
relayPort = msg.port;
encapsulation = proxy.udp_encapsulation;
// debug("Datagram Socket:"+getLocalAddress()+":"+getLocalPort()+"\n");
// debug("Socks5Datagram: "+relayIP+":"+relayPort+"\n");
}
/**
* Closes datagram socket, and proxy connection.
*/
@Override
public void close() {
if (!server_mode)
proxy.endSession();
super.close();
}
private byte[] formHeader(InetAddress ip, int port) {
Socks5Message request = new Socks5Message(0, ip, port);
request.data[0] = 0;
return request.data;
}
/**
* Address assigned by the proxy, to which datagrams are send for relay. It
* is not necesseraly the same address, to which other party should send
* datagrams.
*
* @return Address to which datagrams are send for association.
*/
@Override
public InetAddress getLocalAddress() {
if (server_mode)
return super.getLocalAddress();
return relayIP;
}
/**
* Returns port assigned by the proxy, to which datagrams are relayed. It is
* not the same port to which other party should send datagrams.
*
* @return Port assigned by socks server to which datagrams are send for
* association.
*/
@Override
public int getLocalPort() {
if (server_mode)
return super.getLocalPort();
return relayPort;
}
/**
* This method checks wether proxy still runs udp forwarding service for
* this socket.
* <p>
* This methods checks wether the primary connection to proxy server is
* active. If it is, chances are that proxy continues to forward datagrams
* being send from this socket. If it was closed, most likely datagrams are
* no longer being forwarded by the server.
* <p>
* Proxy might decide to stop forwarding datagrams, in which case it should
* close primary connection. This method allows to check, wether this have
* been done.
* <p>
* You can specify timeout for which we should be checking EOF condition on
* the primary connection. Timeout is in milliseconds. Specifying 0 as
* timeout implies infinity, in which case method will block, until
* connection to proxy is closed or an error happens, and then return false.
* <p>
* One possible scenario is to call isProxyactive(0) in separate thread, and
* once it returned notify other threads about this event.
*
* @param timeout
* For how long this method should block, before returning.
* @return true if connection to proxy is active, false if eof or error
* condition have been encountered on the connection.
*/
public boolean isProxyAlive(int timeout) {
if (server_mode)
return false;
if (proxy != null) {
try {
proxy.proxySocket.setSoTimeout(timeout);
int eof = proxy.in.read();
if (eof < 0)
return false; // EOF encountered.
else
return true; // This really should not happen
} catch (InterruptedIOException iioe) {
return true; // read timed out.
} catch (IOException ioe) {
return false;
}
}
return false;
}
/**
* Receives udp packet. If packet have arrived from the proxy relay server,
* it is processed and address and port of the packet are set to the address
* and port of sending host.<BR>
* If the packet arrived from anywhere else it is not changed.<br>
* <B> NOTE: </B> DatagramPacket size should be at least 10 bytes bigger
* than the largest packet you expect (this is for IPV4 addresses). For
* hostnames and IPV6 it is even more.
*
* @param dp
* Datagram in which all relevent information will be copied.
*/
@Override
public void receive(DatagramPacket dp) throws IOException {
super.receive(dp);
if (server_mode) {
// Drop all datagrams not from relayIP/relayPort
int init_length = dp.getLength();
int initTimeout = getSoTimeout();
long startTime = System.currentTimeMillis();
while (!relayIP.equals(dp.getAddress())
|| relayPort != dp.getPort()) {
// Restore datagram size
dp.setLength(init_length);
// If there is a non-infinit timeout on this socket
// Make sure that it happens no matter how often unexpected
// packets arrive.
if (initTimeout != 0) {
int newTimeout = initTimeout
- (int) (System.currentTimeMillis() - startTime);
if (newTimeout <= 0)
throw new InterruptedIOException(
"In Socks5DatagramSocket->receive()");
setSoTimeout(newTimeout);
}
super.receive(dp);
}
// Restore timeout settings
if (initTimeout != 0)
setSoTimeout(initTimeout);
} else if (!relayIP.equals(dp.getAddress())
|| relayPort != dp.getPort())
return; // Recieved direct packet
// If the datagram is not from the relay server, return it it as is.
byte[] data;
data = dp.getData();
if (encapsulation != null)
data = encapsulation.udpEncapsulate(data, false);
int offset = 0; // Java 1.1
// int offset = dp.getOffset(); //Java 1.2
ByteArrayInputStream bIn = new ByteArrayInputStream(data, offset,
dp.getLength());
ProxyMessage msg = new Socks5Message(bIn);
dp.setPort(msg.port);
dp.setAddress(msg.getInetAddress());
// what wasn't read by the Message is the data
int data_length = bIn.available();
// Shift data to the left
System.arraycopy(data, offset + dp.getLength() - data_length, data,
offset, data_length);
dp.setLength(data_length);
}
/**
* Sends the Datagram either through the proxy or directly depending on
* current proxy settings and destination address. <BR>
*
* <B> NOTE: </B> DatagramPacket size should be at least 10 bytes less than
* the systems limit.
*
* <P>
* See documentation on java.net.DatagramSocket for full details on how to
* use this method.
*
* @param dp
* Datagram to send.
* @throws IOException
* If error happens with I/O.
*/
@Override
public void send(DatagramPacket dp) throws IOException {
// If the host should be accessed directly, send it as is.
if (!server_mode) {
super.send(dp);
// debug("Sending directly:");
return;
}
byte[] head = formHeader(dp.getAddress(), dp.getPort());
byte[] buf = new byte[head.length + dp.getLength()];
byte[] data = dp.getData();
// Merge head and data
System.arraycopy(head, 0, buf, 0, head.length);
// System.arraycopy(data,dp.getOffset(),buf,head.length,dp.getLength());
System.arraycopy(data, 0, buf, head.length, dp.getLength());
if (encapsulation != null)
buf = encapsulation.udpEncapsulate(buf, true);
super.send(new DatagramPacket(buf, buf.length, relayIP, relayPort));
}
// PRIVATE METHODS
// ////////////////
/**
* This method allows to send datagram packets with address type DOMAINNAME.
* SOCKS5 allows to specify host as names rather than ip addresses.Using
* this method one can send udp datagrams through the proxy, without having
* to know the ip address of the destination host.
* <p>
* If proxy specified for that socket has an option resolveAddrLocally set
* to true host will be resolved, and the datagram will be send with address
* type IPV4, if resolve fails, UnknownHostException is thrown.
*
* @param dp
* Datagram to send, it should contain valid port and data
* @param host
* Host name to which datagram should be send.
* @throws IOException
* If error happens with I/O, or the host can't be resolved when
* proxy settings say that hosts should be resolved locally.
* @see Socks5Proxy#resolveAddrLocally(boolean)
*/
public void send(DatagramPacket dp, String host) throws IOException {
dp.setAddress(InetAddress.getByName(host));
super.send(dp);
}
/*
* ======================================================================
*
* //Mainly Test functions //////////////////////
*
* private String bytes2String(byte[] b){ String s=""; char[] hex_digit = {
* '0','1','2','3','4','5','6','7','8','9', 'A','B','C','D','E','F'};
* for(int i=0;i<b.length;++i){ int i1 = (b[i] & 0xF0) >> 4; int i2 = b[i] &
* 0xF; s+=hex_digit[i1]; s+=hex_digit[i2]; s+=" "; } return s; } private
* static final void debug(String s){ if(DEBUG) System.out.print(s); }
*
* private static final boolean DEBUG = true;
*
*
* public static void usage(){ System.err.print(
* "Usage: java Socks.SocksDatagramSocket host port [socksHost socksPort]\n"
* ); }
*
* static final int defaultProxyPort = 1080; //Default Port static final
* String defaultProxyHost = "www-proxy"; //Default proxy
*
* public static void main(String args[]){ int port; String host; int
* proxyPort; String proxyHost; InetAddress ip;
*
* if(args.length > 1 && args.length < 5){ try{
*
* host = args[0]; port = Integer.parseInt(args[1]);
*
* proxyPort =(args.length > 3)? Integer.parseInt(args[3]) :
* defaultProxyPort;
*
* host = args[0]; ip = InetAddress.getByName(host);
*
* proxyHost =(args.length > 2)? args[2] : defaultProxyHost;
*
* Proxy.setDefaultProxy(proxyHost,proxyPort); Proxy p =
* Proxy.getDefaultProxy(); p.addDirect("lux");
*
*
* DatagramSocket ds = new Socks5DatagramSocket();
*
*
* BufferedReader in = new BufferedReader( new
* InputStreamReader(System.in)); String s;
*
* System.out.print("Enter line:"); s = in.readLine();
*
* while(s != null){ byte[] data = (s+"\r\n").getBytes(); DatagramPacket dp
* = new DatagramPacket(data,0,data.length, ip,port);
* System.out.println("Sending to: "+ip+":"+port); ds.send(dp); dp = new
* DatagramPacket(new byte[1024],1024);
*
* System.out.println("Trying to recieve on port:"+ ds.getLocalPort());
* ds.receive(dp); System.out.print("Recieved:\n"+
* "From:"+dp.getAddress()+":"+dp.getPort()+ "\n\n"+ new
* String(dp.getData(),dp.getOffset(),dp.getLength())+"\n" );
* System.out.print("Enter line:"); s = in.readLine();
*
* } ds.close(); System.exit(1);
*
* }catch(SocksException s_ex){ System.err.println("SocksException:"+s_ex);
* s_ex.printStackTrace(); System.exit(1); }catch(IOException io_ex){
* io_ex.printStackTrace(); System.exit(1); }catch(NumberFormatException
* num_ex){ usage(); num_ex.printStackTrace(); System.exit(1); }
*
* }else{ usage(); } }
*/
}
| 07pratik-myssh | src/net/sourceforge/jsocks/Socks5DatagramSocket.java | Java | gpl3 | 15,375 |
package net.sourceforge.jsocks;
/**
* The Authentication interface provides for performing method specific
* authentication for SOCKS5 connections.
*/
public interface Authentication {
/**
* This method is called when SOCKS5 server have selected a particular
* authentication method, for whch an implementaion have been registered.
*
* <p>
* This method should return an array {inputstream,outputstream
* [,UDPEncapsulation]}. The reason for that is that SOCKS5 protocol allows
* to have method specific encapsulation of data on the socket for purposes
* of integrity or security. And this encapsulation should be performed by
* those streams returned from the method. It is also possible to
* encapsulate datagrams. If authentication method supports such
* encapsulation an instance of the UDPEncapsulation interface should be
* returned as third element of the array, otherwise either null should be
* returned as third element, or array should contain only 2 elements.
*
* @param methodId
* Authentication method selected by the server.
* @param proxySocket
* Socket used to conect to the proxy.
* @return Two or three element array containing Input/Output streams which
* should be used on this connection. Third argument is optional and
* should contain an instance of UDPEncapsulation. It should be
* provided if the authentication method used requires any
* encapsulation to be done on the datagrams.
*/
Object[] doSocksAuthentication(int methodId, java.net.Socket proxySocket)
throws java.io.IOException;
}
| 07pratik-myssh | src/net/sourceforge/jsocks/Authentication.java | Java | gpl3 | 1,663 |
package net.sourceforge.jsocks;
/**
* Exception thrown by various socks classes to indicate errors with protocol or
* unsuccessful server responses.
*/
public class SocksException extends java.io.IOException {
private static final long serialVersionUID = 6141184566248512277L;
static final String UNASSIGNED_ERROR_MESSAGE = "Unknown error message";
static final String serverReplyMessage[] = { "Succeeded",
"General SOCKS server failure",
"Connection not allowed by ruleset", "Network unreachable",
"Host unreachable", "Connection refused", "TTL expired",
"Command not supported", "Address type not supported" };
static final String localErrorMessage[] = { "SOCKS server not specified",
"Unable to contact SOCKS server", "IO error",
"None of Authentication methods are supported",
"Authentication failed", "General SOCKS fault" };
String errString;
public int errCode;
/**
* Construct a SocksException with given error code.
* <p>
* Tries to look up message which corresponds to this error code.
*
* @param errCode
* Error code for this exception.
*/
public SocksException(int errCode) {
this.errCode = errCode;
if ((errCode >> 16) == 0) {
// Server reply error message
errString = errCode <= serverReplyMessage.length ? serverReplyMessage[errCode]
: UNASSIGNED_ERROR_MESSAGE;
} else {
// Local error
errCode = (errCode >> 16) - 1;
errString = errCode <= localErrorMessage.length ? localErrorMessage[errCode]
: UNASSIGNED_ERROR_MESSAGE;
}
}
/**
* Constructs a SocksException with given error code and message.
*
* @param errCode
* Error code.
* @param errString
* Error Message.
*/
public SocksException(int errCode, String errString) {
this.errCode = errCode;
this.errString = errString;
}
/**
* Get the error code associated with this exception.
*
* @return Error code associated with this exception.
*/
public int getErrorCode() {
return errCode;
}
/**
* Get human readable representation of this exception.
*
* @return String represntation of this exception.
*/
@Override
public String toString() {
return errString;
}
}// End of SocksException class
| 07pratik-myssh | src/net/sourceforge/jsocks/SocksException.java | Java | gpl3 | 2,310 |
package net.sourceforge.jsocks;
import java.io.EOFException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InterruptedIOException;
import java.io.OutputStream;
import java.io.PrintStream;
import java.io.PushbackInputStream;
import java.net.ConnectException;
import java.net.InetAddress;
import java.net.NoRouteToHostException;
import java.net.ServerSocket;
import java.net.Socket;
import net.sourceforge.jsocks.server.ServerAuthenticator;
/**
* SOCKS4 and SOCKS5 proxy, handles both protocols simultaniously. Implements
* all SOCKS commands, including UDP relaying.
* <p>
* In order to use it you will need to implement ServerAuthenticator interface.
* There is an implementation of this interface which does no authentication
* ServerAuthenticatorNone, but it is very dangerous to use, as it will give
* access to your local network to anybody in the world. One should never use
* this authentication scheme unless one have pretty good reason to do so. There
* is a couple of other authentication schemes in socks.server package.
*
* @see socks.server.ServerAuthenticator
*/
public class ProxyServer implements Runnable {
ServerAuthenticator auth;
ProxyMessage msg = null;
Socket sock = null, remote_sock = null;
ServerSocket ss = null;
UDPRelayServer relayServer = null;
InputStream in, remote_in;
OutputStream out, remote_out;
int mode;
static final int START_MODE = 0;
static final int ACCEPT_MODE = 1;
static final int PIPE_MODE = 2;
static final int ABORT_MODE = 3;
static final int BUF_SIZE = 8192;
Thread pipe_thread1, pipe_thread2;
long lastReadTime;
protected static int iddleTimeout = 180000; // 3 minutes
static int acceptTimeout = 180000; // 3 minutes
static PrintStream log = null;
static Proxy proxy;
// Public Constructors
// ///////////////////
static final String command_names[] = { "CONNECT", "BIND", "UDP_ASSOCIATE" };
// Other constructors
// //////////////////
static final String command2String(int cmd) {
if (cmd > 0 && cmd < 4)
return command_names[cmd - 1];
else
return "Unknown Command " + cmd;
}
// Public methods
// ///////////////
/**
* Get proxy.
*
* @return Proxy wich is used to handle user requests.
*/
public static Proxy getProxy() {
return proxy;
}
static final void log(ProxyMessage msg) {
log("Request version:" + msg.version + "\tCommand: "
+ command2String(msg.command));
log("IP:" + msg.ip + "\tPort:" + msg.port
+ (msg.version == 4 ? "\tUser:" + msg.user : ""));
}
static final void log(String s) {
if (log != null) {
log.println(s);
log.flush();
}
}
/**
* Sets the timeout for BIND command, how long the server should wait for
* the incoming connection.<br>
* Zero timeout implies infinity.<br>
* Default timeout is 3 minutes.
*/
public static void setAcceptTimeout(int timeout) {
acceptTimeout = timeout;
}
/**
* Sets the size of the datagrams used in the UDPRelayServer.<br>
* Default size is 64K, a bit more than maximum possible size of the
* datagram.
*/
public static void setDatagramSize(int size) {
UDPRelayServer.setDatagramSize(size);
}
/**
* Sets the timeout for connections, how long shoud server wait for data to
* arrive before dropping the connection.<br>
* Zero timeout implies infinity.<br>
* Default timeout is 3 minutes.
*/
public static void setIddleTimeout(int timeout) {
iddleTimeout = timeout;
}
/**
* Set the logging stream. Specifying null disables logging.
*/
public static void setLog(OutputStream out) {
if (out == null) {
log = null;
} else {
log = new PrintStream(out, true);
}
UDPRelayServer.log = log;
}
/**
* Set proxy.
* <p>
* Allows Proxy chaining so that one Proxy server is connected to another
* and so on. If proxy supports SOCKSv4, then only some SOCKSv5 requests can
* be handled, UDP would not work, however CONNECT and BIND will be
* translated.
*
* @param p
* Proxy which should be used to handle user requests.
*/
public static void setProxy(Proxy p) {
proxy = p;
UDPRelayServer.proxy = proxy;
}
/**
* Sets the timeout for UDPRelay server.<br>
* Zero timeout implies infinity.<br>
* Default timeout is 3 minutes.
*/
public static void setUDPTimeout(int timeout) {
UDPRelayServer.setTimeout(timeout);
}
/**
* Creates a proxy server with given Authentication scheme.
*
* @param auth
* Authentication scheme to be used.
*/
public ProxyServer(ServerAuthenticator auth) {
this.auth = auth;
}
protected ProxyServer(ServerAuthenticator auth, Socket s) {
this.auth = auth;
this.sock = s;
mode = START_MODE;
}
private synchronized void abort() {
if (mode == ABORT_MODE)
return;
mode = ABORT_MODE;
try {
log("Aborting operation");
if (remote_sock != null)
remote_sock.close();
if (sock != null)
sock.close();
if (relayServer != null)
relayServer.stop();
if (ss != null)
ss.close();
if (pipe_thread1 != null)
pipe_thread1.interrupt();
if (pipe_thread2 != null)
pipe_thread2.interrupt();
} catch (IOException ioe) {
}
}
private void doAccept() throws IOException {
Socket s;
long startTime = System.currentTimeMillis();
while (true) {
s = ss.accept();
if (s.getInetAddress().equals(msg.ip)) {
// got the connection from the right host
// Close listenning socket.
ss.close();
break;
} else if (ss instanceof SocksServerSocket) {
// We can't accept more then one connection
s.close();
ss.close();
throw new SocksException(Proxy.SOCKS_FAILURE);
} else {
if (acceptTimeout != 0) { // If timeout is not infinit
int newTimeout = acceptTimeout
- (int) (System.currentTimeMillis() - startTime);
if (newTimeout <= 0)
throw new InterruptedIOException("In doAccept()");
ss.setSoTimeout(newTimeout);
}
s.close(); // Drop all connections from other hosts
}
}
// Accepted connection
remote_sock = s;
remote_in = s.getInputStream();
remote_out = s.getOutputStream();
// Set timeout
remote_sock.setSoTimeout(iddleTimeout);
log("Accepted from " + s.getInetAddress() + ":" + s.getPort());
ProxyMessage response;
if (msg.version == 5)
response = new Socks5Message(Proxy.SOCKS_SUCCESS,
s.getInetAddress(), s.getPort());
else
response = new Socks4Message(Socks4Message.REPLY_OK,
s.getInetAddress(), s.getPort());
response.write(out);
}
private void handleException(IOException ioe) {
// If we couldn't read the request, return;
if (msg == null)
return;
// If have been aborted by other thread
if (mode == ABORT_MODE)
return;
// If the request was successfully completed, but exception happened
// later
if (mode == PIPE_MODE)
return;
int error_code = Proxy.SOCKS_FAILURE;
if (ioe instanceof SocksException)
error_code = ((SocksException) ioe).errCode;
else if (ioe instanceof NoRouteToHostException)
error_code = Proxy.SOCKS_HOST_UNREACHABLE;
else if (ioe instanceof ConnectException)
error_code = Proxy.SOCKS_CONNECTION_REFUSED;
else if (ioe instanceof InterruptedIOException)
error_code = Proxy.SOCKS_TTL_EXPIRE;
if (error_code > Proxy.SOCKS_ADDR_NOT_SUPPORTED || error_code < 0) {
error_code = Proxy.SOCKS_FAILURE;
}
sendErrorMessage(error_code);
}
protected void handleRequest(ProxyMessage msg) throws IOException {
if (!auth.checkRequest(msg))
throw new SocksException(Proxy.SOCKS_FAILURE);
if (msg.ip == null) {
if (msg instanceof Socks5Message) {
msg.ip = InetAddress.getByName(msg.host);
} else
throw new SocksException(Proxy.SOCKS_FAILURE);
}
log(msg);
switch (msg.command) {
case Proxy.SOCKS_CMD_CONNECT:
onConnect(msg);
break;
case Proxy.SOCKS_CMD_BIND:
onBind(msg);
break;
case Proxy.SOCKS_CMD_UDP_ASSOCIATE:
onUDP(msg);
break;
default:
throw new SocksException(Proxy.SOCKS_CMD_NOT_SUPPORTED);
}
}
private void onBind(ProxyMessage msg) throws IOException {
ProxyMessage response = null;
if (proxy == null)
ss = new ServerSocket(0);
else
ss = new SocksServerSocket(proxy, msg.ip, msg.port);
ss.setSoTimeout(acceptTimeout);
log("Trying accept on " + ss.getInetAddress() + ":" + ss.getLocalPort());
if (msg.version == 5)
response = new Socks5Message(Proxy.SOCKS_SUCCESS,
ss.getInetAddress(), ss.getLocalPort());
else
response = new Socks4Message(Socks4Message.REPLY_OK,
ss.getInetAddress(), ss.getLocalPort());
response.write(out);
mode = ACCEPT_MODE;
pipe_thread1 = Thread.currentThread();
pipe_thread2 = new Thread(this);
pipe_thread2.start();
// Make timeout infinit.
sock.setSoTimeout(0);
int eof = 0;
try {
while ((eof = in.read()) >= 0) {
if (mode != ACCEPT_MODE) {
if (mode != PIPE_MODE)
return;// Accept failed
remote_out.write(eof);
break;
}
}
} catch (EOFException eofe) {
// System.out.println("EOF exception");
return;// Connection closed while we were trying to accept.
} catch (InterruptedIOException iioe) {
// Accept thread interrupted us.
// System.out.println("Interrupted");
if (mode != PIPE_MODE)
return;// If accept thread was not successfull return.
} finally {
// System.out.println("Finnaly!");
}
if (eof < 0)// Connection closed while we were trying to accept;
return;
// Do not restore timeout, instead timeout is set on the
// remote socket. It does not make any difference.
pipe(in, remote_out);
}
private void onConnect(ProxyMessage msg) throws IOException {
Socket s;
ProxyMessage response = null;
s = new Socket(msg.ip, msg.port);
log("Connected to " + s.getInetAddress() + ":" + s.getPort());
if (msg instanceof Socks5Message) {
response = new Socks5Message(Proxy.SOCKS_SUCCESS,
s.getLocalAddress(), s.getLocalPort());
} else {
response = new Socks4Message(Socks4Message.REPLY_OK,
s.getLocalAddress(), s.getLocalPort());
}
response.write(out);
startPipe(s);
}
// Private methods
// ////////////////
private void onUDP(ProxyMessage msg) throws IOException {
if (msg.ip.getHostAddress().equals("0.0.0.0"))
msg.ip = sock.getInetAddress();
log("Creating UDP relay server for " + msg.ip + ":" + msg.port);
relayServer = new UDPRelayServer(msg.ip, msg.port,
Thread.currentThread(), sock, auth);
ProxyMessage response;
response = new Socks5Message(Proxy.SOCKS_SUCCESS, relayServer.relayIP,
relayServer.relayPort);
response.write(out);
relayServer.start();
// Make timeout infinit.
sock.setSoTimeout(0);
try {
while (in.read() >= 0)
/* do nothing */;
} catch (EOFException eofe) {
}
}
private void pipe(InputStream in, OutputStream out) throws IOException {
lastReadTime = System.currentTimeMillis();
byte[] buf = new byte[BUF_SIZE];
int len = 0;
while (len >= 0) {
try {
if (len != 0) {
out.write(buf, 0, len);
out.flush();
}
len = in.read(buf);
lastReadTime = System.currentTimeMillis();
} catch (InterruptedIOException iioe) {
if (iddleTimeout == 0)
return;// Other thread interrupted us.
long timeSinceRead = System.currentTimeMillis() - lastReadTime;
if (timeSinceRead >= iddleTimeout - 1000) // -1s for adjustment.
return;
len = 0;
}
}
}
protected ProxyMessage readMsg(InputStream in) throws IOException {
PushbackInputStream push_in;
if (in instanceof PushbackInputStream)
push_in = (PushbackInputStream) in;
else
push_in = new PushbackInputStream(in);
int version = push_in.read();
push_in.unread(version);
ProxyMessage msg;
if (version == 5) {
msg = new Socks5Message(push_in, false);
} else if (version == 4) {
msg = new Socks4Message(push_in, false);
} else {
throw new SocksException(Proxy.SOCKS_FAILURE);
}
return msg;
}
// Runnable interface
// //////////////////
@Override
public void run() {
switch (mode) {
case START_MODE:
try {
startSession();
} catch (IOException ioe) {
handleException(ioe);
// ioe.printStackTrace();
} finally {
abort();
if (auth != null)
auth.endSession();
log("Main thread(client->remote)stopped.");
}
break;
case ACCEPT_MODE:
try {
doAccept();
mode = PIPE_MODE;
pipe_thread1.interrupt(); // Tell other thread that connection
// have
// been accepted.
pipe(remote_in, out);
} catch (IOException ioe) {
// log("Accept exception:"+ioe);
handleException(ioe);
} finally {
abort();
log("Accept thread(remote->client) stopped");
}
break;
case PIPE_MODE:
try {
pipe(remote_in, out);
} catch (IOException ioe) {
} finally {
abort();
log("Support thread(remote->client) stopped");
}
break;
case ABORT_MODE:
break;
default:
log("Unexpected MODE " + mode);
}
}
private void sendErrorMessage(int error_code) {
ProxyMessage err_msg;
if (msg instanceof Socks4Message)
err_msg = new Socks4Message(Socks4Message.REPLY_REJECTED);
else
err_msg = new Socks5Message(error_code);
try {
err_msg.write(out);
} catch (IOException ioe) {
}
}
/**
* Start the Proxy server at given port.<br>
* This methods blocks.
*/
public void start(int port) {
start(port, 5, null);
}
/**
* Create a server with the specified port, listen backlog, and local IP
* address to bind to. The localIP argument can be used on a multi-homed
* host for a ServerSocket that will only accept connect requests to one of
* its addresses. If localIP is null, it will default accepting connections
* on any/all local addresses. The port must be between 0 and 65535,
* inclusive. <br>
* This methods blocks.
*/
public void start(int port, int backlog, InetAddress localIP) {
try {
ss = new ServerSocket(port, backlog, localIP);
log("Starting SOCKS Proxy on:"
+ ss.getInetAddress().getHostAddress() + ":"
+ ss.getLocalPort());
while (true) {
Socket s = ss.accept();
log("Accepted from:" + s.getInetAddress().getHostName() + ":"
+ s.getPort());
ProxyServer ps = new ProxyServer(auth, s);
(new Thread(ps)).start();
}
} catch (IOException ioe) {
ioe.printStackTrace();
} finally {
}
}
private void startPipe(Socket s) {
mode = PIPE_MODE;
remote_sock = s;
try {
remote_in = s.getInputStream();
remote_out = s.getOutputStream();
pipe_thread1 = Thread.currentThread();
pipe_thread2 = new Thread(this);
pipe_thread2.start();
pipe(in, remote_out);
} catch (IOException ioe) {
}
}
// Private methods
// ///////////////
private void startSession() throws IOException {
sock.setSoTimeout(iddleTimeout);
try {
auth = auth.startSession(sock);
} catch (IOException ioe) {
log("Auth throwed exception:" + ioe);
auth = null;
return;
}
if (auth == null) { // Authentication failed
log("Authentication failed");
return;
}
in = auth.getInputStream();
out = auth.getOutputStream();
msg = readMsg(in);
handleRequest(msg);
}
/**
* Stop server operation.It would be wise to interrupt thread running the
* server afterwards.
*/
public void stop() {
try {
if (ss != null)
ss.close();
} catch (IOException ioe) {
}
}
}
| 07pratik-myssh | src/net/sourceforge/jsocks/ProxyServer.java | Java | gpl3 | 15,938 |
package net.sourceforge.jsocks;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.Socket;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.Enumeration;
import java.util.Hashtable;
/**
* SOCKS5 Proxy.
*/
public class Socks5Proxy extends Proxy implements Cloneable {
// Data members
private Hashtable<Integer, Authentication> authMethods = new Hashtable<Integer, Authentication>();
private int selectedMethod;
boolean resolveAddrLocally = true;
UDPEncapsulation udp_encapsulation = null;
// Public Constructors
// ====================
/**
* Creates SOCKS5 proxy.
*
* @param proxyIP
* Host on which a Proxy server runs.
* @param proxyPort
* Port on which a Proxy server listens for connections.
*/
public Socks5Proxy(InetAddress proxyIP, int proxyPort) {
super(proxyIP, proxyPort);
version = 5;
setAuthenticationMethod(0, new AuthenticationNone());
}
/**
* Creates SOCKS5 proxy.
*
* @param proxyHost
* Host on which a Proxy server runs.
* @param proxyPort
* Port on which a Proxy server listens for connections.
* @throws UnknownHostException
* If proxyHost can't be resolved.
*/
public Socks5Proxy(String proxyHost, int proxyPort)
throws UnknownHostException {
super(proxyHost, proxyPort);
version = 5;
setAuthenticationMethod(0, new AuthenticationNone());
}
// Public instance methods
// ========================
/**
* Creates a clone of this Proxy.
*/
@Override
@SuppressWarnings("unchecked")
public Object clone() {
Socks5Proxy newProxy = new Socks5Proxy(proxyIP, proxyPort);
newProxy.authMethods = (Hashtable<Integer, Authentication>) this.authMethods
.clone();
newProxy.resolveAddrLocally = resolveAddrLocally;
newProxy.chainProxy = chainProxy;
return newProxy;
}
@Override
protected Proxy copy() {
Socks5Proxy copy = new Socks5Proxy(proxyIP, proxyPort);
copy.authMethods = this.authMethods; // same Hash, no copy
copy.chainProxy = this.chainProxy;
copy.resolveAddrLocally = this.resolveAddrLocally;
return copy;
}
@Override
protected ProxyMessage formMessage(InputStream in) throws SocksException,
IOException {
return new Socks5Message(in);
}
@Override
protected ProxyMessage formMessage(int cmd, InetAddress ip, int port) {
return new Socks5Message(cmd, ip, port);
}
@Override
protected ProxyMessage formMessage(int cmd, String host, int port)
throws UnknownHostException {
if (resolveAddrLocally)
return formMessage(cmd, InetAddress.getByName(host), port);
else
return new Socks5Message(cmd, host, port);
}
// Public Static(Class) Methods
// ==============================
// Protected Methods
// =================
/**
* Get authentication method, which corresponds to given method id
*
* @param methodId
* Authentication method id.
* @return Implementation for given method or null, if one was not set.
*/
public Authentication getAuthenticationMethod(int methodId) {
Object method = authMethods.get(new Integer(methodId));
if (method == null)
return null;
return (Authentication) method;
}
/**
* Get current setting on how the addresses should be handled.
*
* @return Current setting for address resolution.
* @see Socks5Proxy#resolveAddrLocally(boolean doResolve)
*/
public boolean resolveAddrLocally() {
return resolveAddrLocally;
}
/**
* Wether to resolve address locally or to let proxy do so.
* <p>
* SOCKS5 protocol allows to send host names rather then IPs in the
* requests, this option controls wether the hostnames should be send to the
* proxy server as names, or should they be resolved locally.
*
* @param doResolve
* Wether to perform resolution locally.
* @return Previous settings.
*/
public boolean resolveAddrLocally(boolean doResolve) {
boolean old = resolveAddrLocally;
resolveAddrLocally = doResolve;
return old;
}
/**
* Adds another authentication method.
*
* @param methodId
* Authentication method id, see rfc1928
* @param method
* Implementation of Authentication
* @see Authentication
*/
public boolean setAuthenticationMethod(int methodId, Authentication method) {
if (methodId < 0 || methodId > 255)
return false;
if (method == null) {
// Want to remove a particular method
return (authMethods.remove(new Integer(methodId)) != null);
} else {// Add the method, or rewrite old one
authMethods.put(new Integer(methodId), method);
}
return true;
}
/**
*
*
*/
@Override
protected void startSession() throws SocksException {
super.startSession();
Authentication auth;
Socket ps = proxySocket; // The name is too long
try {
byte nMethods = (byte) authMethods.size(); // Number of methods
byte[] buf = new byte[2 + nMethods]; // 2 is for VER,NMETHODS
buf[0] = (byte) version;
buf[1] = nMethods; // Number of methods
int i = 2;
Enumeration<Integer> ids = authMethods.keys();
while (ids.hasMoreElements())
buf[i++] = (byte) ids.nextElement().intValue();
out.write(buf);
out.flush();
int versionNumber = in.read();
selectedMethod = in.read();
if (versionNumber < 0 || selectedMethod < 0) {
// EOF condition was reached
endSession();
throw (new SocksException(SOCKS_PROXY_IO_ERROR,
"Connection to proxy lost."));
}
if (versionNumber < version) {
// What should we do??
}
if (selectedMethod == 0xFF) { // No method selected
ps.close();
throw (new SocksException(SOCKS_AUTH_NOT_SUPPORTED));
}
auth = getAuthenticationMethod(selectedMethod);
if (auth == null) {
// This shouldn't happen, unless method was removed by other
// thread, or the server stuffed up
throw (new SocksException(SOCKS_JUST_ERROR,
"Speciefied Authentication not found!"));
}
Object[] in_out = auth.doSocksAuthentication(selectedMethod, ps);
if (in_out == null) {
// Authentication failed by some reason
throw (new SocksException(SOCKS_AUTH_FAILURE));
}
// Most authentication methods are expected to return
// simply the input/output streams associated with
// the socket. However if the auth. method requires
// some kind of encryption/decryption being done on the
// connection it should provide classes to handle I/O.
in = (InputStream) in_out[0];
out = (OutputStream) in_out[1];
if (in_out.length > 2)
udp_encapsulation = (UDPEncapsulation) in_out[2];
} catch (SocksException s_ex) {
throw s_ex;
} catch (UnknownHostException uh_ex) {
throw (new SocksException(SOCKS_PROXY_NO_CONNECT));
} catch (SocketException so_ex) {
throw (new SocksException(SOCKS_PROXY_NO_CONNECT));
} catch (IOException io_ex) {
// System.err.println(io_ex);
throw (new SocksException(SOCKS_PROXY_IO_ERROR, "" + io_ex));
}
}
}
| 07pratik-myssh | src/net/sourceforge/jsocks/Socks5Proxy.java | Java | gpl3 | 7,257 |
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
<title>12 Days of Christmas | Harjit Sandhu</title>
<link href="assets/default.css" rel="stylesheet" type="text/css" />
<script type="text/javascript">
var games = {} || games;
games.helper = {
getRandomNumber: function (low, high) {
return Math.floor(Math.random() * high) + low;
}
}
</script>
<script src="http://12-games-of-christmas.googlecode.com/svn/trunk/assets/jquery.js" type="text/javascript"></script>
<script src="http://konami-js.googlecode.com/svn/trunk/konami.js" type="text/javascript"></script>
<script src="http://12-games-of-christmas.googlecode.com/svn/trunk/assets/extensions.js" type="text/javascript"></script>
<script src="http://12-games-of-christmas.googlecode.com/svn/trunk/assets/asteroid.js" type="text/javascript"></script>
<script src="assets/sideways-scroller.js" type="text/javascript"></script>
<script src="http://12-games-of-christmas.googlecode.com/svn/trunk/assets/default.js" type="text/javascript"></script>
<script src="http://12-games-of-christmas.googlecode.com/svn/trunk/assets/game1.js" type="text/javascript"></script>
<script src="http://12-games-of-christmas.googlecode.com/svn/trunk/assets/game2.js" type="text/javascript"></script>
<script src="http://12-games-of-christmas.googlecode.com/svn/trunk/assets/game3.js" type="text/javascript"></script>
<script src="http://12-games-of-christmas.googlecode.com/svn/trunk/assets/game4.js" type="text/javascript"></script>
<script src="http://12-games-of-christmas.googlecode.com/svn/trunk/assets/game5.js" type="text/javascript"></script>
<script src="http://12-games-of-christmas.googlecode.com/svn/trunk/assets/game6.js" type="text/javascript"></script>
<script src="assets/game7.js" type="text/javascript"></script>
<script src="http://12-games-of-christmas.googlecode.com/svn/trunk/assets/game8.js" type="text/javascript"></script>
<script src="http://12-games-of-christmas.googlecode.com/svn/trunk/assets/game9.js" type="text/javascript"></script>
<script src="http://12-games-of-christmas.googlecode.com/svn/trunk/assets/game10.js" type="text/javascript"></script>
<script src="http://12-games-of-christmas.googlecode.com/svn/trunk/assets/game11.js" type="text/javascript"></script>
<script src="http://12-games-of-christmas.googlecode.com/svn/trunk/assets/game12.js" type="text/javascript"></script>
<script type="text/javascript">
todaysDate = 24;
games.gamezone ={bind:function(){/* */}}
$(document).ready(function(){
games.game7.init();
});
</script>
</head>
<body>
<div id="console"></div>
<div id="container">
<div id="gameboard-holder"><div id="gamezone"></div></div>
</div>
</body>
</html> | 12-games-of-christmas | trunk/open.html | HTML | mit | 3,028 |
<html>
<head>
<title>hello world</title>
<script src="scripts/jquery-1.8.3.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function () {
(function () {
$("#gamezone").html('<canvas id="gamezone-arena" width="500" height="500"></canvas>');
var engine = {
players: [{ health: 100, x: 240, y: 210, heading: 270, distanceToObsticle: 100, isFacingEnemy: false, id: 0, ai: undefined },
{ health: 100, x: 260, y: 210, heading: 270, distanceToObsticle: 100, isFacingEnemy: false, id: 0, ai: undefined}],
world: {
h: 0, w: 0,
bullets: [],
render: function () {
var ctx = $("#gamezone-arena")[0].getContext("2d");
this.h = $("#gamezone-arena")[0].height;
this.w = $("#gamezone-arena")[0].width;
//render the map
ctx.clearRect(0, 0, $("#gamezone-arena")[0].width, $("#gamezone-arena")[0].height);
ctx.strokeRect(0, 0, $("#gamezone-arena")[0].width, $("#gamezone-arena")[0].height);
//render the player
for (var i = 0; i < engine.players.length; i++) {
var currentPlayer = engine.players[i];
if (currentPlayer.health < 0) {
//dead
engine.destory();
} else {
//i
ctx.fillStyle = i != 0 ? 'blue' : 'black';
ctx.beginPath();
ctx.arc(currentPlayer.x, currentPlayer.y, 10, 0, Math.PI * 2, true);
ctx.closePath();
ctx.fill();
ctx.beginPath();
ctx.moveTo(currentPlayer.x, currentPlayer.y);
var endOfLineX = Math.sin(currentPlayer.heading * Math.PI / 180) * 20;
var endOfLiney = Math.cos(currentPlayer.heading * Math.PI / 180) * 20;
ctx.lineTo(currentPlayer.x + endOfLineX, currentPlayer.y + endOfLiney);
ctx.closePath();
ctx.stroke();
}
}
for (var i = 0; i < this.bullets.length; i++) {
var currentbullet = this.bullets[i];
if (currentbullet.active) {
currentbullet.x = currentbullet.x + Math.sin(currentbullet.heading * Math.PI / 180) * 2;
currentbullet.y = currentbullet.y + Math.cos(currentbullet.heading * Math.PI / 180) * 2;
ctx.beginPath();
ctx.arc(currentbullet.x, currentbullet.y, 3, 0, Math.PI * 2, true);
ctx.closePath();
ctx.fill();
for (var j = 0; j < engine.players.length; j++) {
var currentPlayer = engine.players[j];
if (currentPlayer.id != currentbullet.id && currentPlayer.health >= 0) {
if (currentPlayer.x - 10 < currentbullet.x && currentPlayer.x + 10 > currentbullet.x && currentPlayer.y - 10 < currentbullet.y && currentPlayer.y + 10 > currentbullet.y) {
currentbullet.active = false;
currentPlayer.health -= 100;
}
}
}
if ((this.w < currentbullet.x || 0 > currentbullet.x) || (this.h < currentbullet.y || 0 > currentbullet.y)) {
currentbullet.active = false;
}
}
}
},
fire: function (player) {
for (var i = 0; i < this.bullets.length; i++) {
var currentbullet = this.bullets[i];
if (currentbullet.active && currentbullet.id == player.id) {
return;
}
}
this.bullets[this.bullets.length] = {
active: true, id: player.id, x: player.x, y: player.y, heading: player.heading
};
},
isMoveLegal: function (player) {
var xDiff = Math.sin(player.heading * Math.PI / 180) * 1;
var yDiff = Math.cos(player.heading * Math.PI / 180) * 1;
var newx = player.x + xDiff;
var newy = player.y + yDiff;
if ((newx > this.w || newx < 0) || (newy > this.h || newy < 0)) {
return false;
}
return true;
},
getPlayerDistanceToObsticle: function (player) {
var FOV = 160;
var rayCastedArray = [];
for (var i = player.heading - FOV / 2; i < player.heading + FOV / 2; i++) {
rayCastedArray[rayCastedArray.length] = this.getPlayerDistanceToObsticleByDegree(i, player);
}
return rayCastedArray;
},
getPlayerDistanceToObsticleByDegree: function (deg, player) {
var moveAmount = 0;
while (true) {
var lineOfSightX = Math.sin(deg * Math.PI / 180) * moveAmount + player.x;
var lineOfSightY = Math.cos(deg * Math.PI / 180) * moveAmount + player.y;
if (lineOfSightX > this.w || lineOfSightY > this.h || lineOfSightX < 0 || lineOfSightY < 0) {
break;
}
for (var i = 0; i < engine.players.length; i++) {
var enemy = engine.players[i];
if (enemy.x - 10 < lineOfSightX && enemy.x + 10 > lineOfSightX && enemy.y - 10 < lineOfSightY && enemy.y + 10 > lineOfSightY && enemy.id != player.id) {
return { distanceToObsticle: moveAmount, isFacingEnemy: true };
}
}
moveAmount++;
}
return { distanceToObsticle: moveAmount, isFacingEnemy: false };
}
},
renderTick: undefined,
thinkTick: undefined,
register: function (index, player) {
var guid = 0;
var isUnique = true;
do {
guid = Math.floor(Math.random() * 0x10000).toString(16);
for (var i = 0; i < this.players.length; i++) {
if (this.players[i].id == guid) {
isUnique = false;
}
}
} while (!isUnique);
this.players[index].ai = player;
this.players[index].id = guid;
return guid;
},
getPlayer: function (index) {
return this.players[index];
},
init: function () {
var that = this;
window.gameCheck = {
register: function (player) {
pIndex = that.getPlayer(0).ai == undefined ? 0 : 1;
player.moves = {
playerIndex: pIndex,
advance: function () {
var player = that.getPlayer(this.playerIndex);
if (engine.world.isMoveLegal(player)) {
var xDiff = Math.sin(player.heading * Math.PI / 180) * 1;
var yDiff = Math.cos(player.heading * Math.PI / 180) * 1;
player.x = player.x + xDiff;
player.y = player.y + yDiff;
}
},
rotate: function (direction) {
var player = that.getPlayer(this.playerIndex);
player.heading += (direction > 0) ? -1 : direction < 0 ? 1 : 0;
player.heading = player.heading % 360;
},
fire: function () {
var player = that.getPlayer(this.playerIndex);
engine.world.fire(player);
}
};
return that.register(pIndex, player);
},
getMyEnvironment: function (id) {
var pIndex = that.getPlayer(0).id == id ? 0 : that.getPlayer(1).id == id ? 1 : 2;
if (pIndex == 2) {
return {
isError: true, name: "er001", message: "invalid id supplied"
};
}
var player = that.getPlayer(pIndex);
var returnData = engine.world.getPlayerDistanceToObsticle(player);
return {
health: player.health,
fov: returnData
};
}
};
this.renderTick = setInterval(function () {
that.world.render();
}, 40);
this.thinkTick = setInterval(function () {
for (var i = 0; i < that.players.length; i++) {
that.players[i].ai.think();
}
}, 40);
},
destory: function () {
clearInterval(this.renderTick);
clearInterval(this.thinkTick);
}
};
engine.init();
})();
});
$(document).ready(function () {
var f7ejsd = {
advance: 100,
rotate: 90,
think: function () {
var gameVariables = gameCheck.getMyEnvironment(this.id);
if (this.advance > 0) {
this.moves.advance();
this.advance--;
} else {
if (this.rotate > 0) {
this.moves.rotate(-1);
this.rotate--;
} else {
this.rotate=90;
this.advance=100;
}
}
},
init: function () {
this.id = gameCheck.register(this);
}
};
f7ejsd.init();
var p3odnr = {
myHeading: 0,
lastIterationData: undefined,
lastEnemyMin: undefined,
lastEnemyMax: undefined,
foundEnemy: function () {
},
think: function () {
var gameVariables = gameCheck.getMyEnvironment(this.id);
this.myHeading %= this.myHeading + 360;
var currentFov = gameVariables.fov;
var fovValue = gameVariables.fov.length;
var currentEnemyMin = undefined, currentEnemyMax = undefined;
var toRotate = 0;
for (var i = 6; i < currentFov.length - 6; i++) {
if (currentFov[i].isFacingEnemy) {
currentEnemyMin = this.myHeading - i - fovValue / 2;
for (var j = currentFov.length - 1; j >= 0; j--) {
if (currentFov[j].isFacingEnemy) {
currentEnemyMax = this.myHeading - j - fovValue / 2;
break;
}
}
break;
}
}
if (currentEnemyMin != undefined && currentEnemyMax != undefined && this.lastEnemyMin != undefined && this.lastEnemyMax != undefined) {
//calculate what enemy is doing
if (currentEnemyMin < this.lastEnemyMin) {
//moving left to right
console.log("r2l");
toRotate = -1;
} else if (currentEnemyMin > this.lastEnemyMin) {
//moving left to right
console.log("l2r");
toRotate = 1;
} else {
//still
console.log("still");
}
} else {
//toRotate = -1;
}
this.myHeading += toRotate;
this.moves.rotate(toRotate);
if (toRotate != 0) {
this.moves.advance();
}
//gameVariables.isFacingEnemy
//gameVariables.distanceToObsticle
//gameVariables.health
//this.moves.fire();
//this.moves.advance();
//this.moves.rotate(+/-1);
this.lastEnemyMin = currentEnemyMin;
this.lastEnemyMax = currentEnemyMax;
this.lastIterationData = gameVariables;
},
init: function () {
this.id = window.gameCheck.register(this);
}
};
p3odnr.init();
});
</script>
</head>
<body>
<div id="gamezone"></div>
<table id="logger"></table>
</body></html> | 12-games-of-christmas | trunk/airobot/harness.html | HTML | mit | 15,031 |
(function ($) {
$.extend($.fx.step, {
backgroundPosition: function (fx) {
if (fx.state === 0 && typeof fx.end == 'string') {
var start = $.curCSS(fx.elem, 'backgroundPosition');
start = toArray(start);
fx.start = [start[0], start[2]];
var end = toArray(fx.end);
fx.end = [end[0], end[2]];
fx.unit = [end[1], end[3]];
}
var nowPosX = [];
nowPosX[0] = ((fx.end[0] - fx.start[0]) * fx.pos) + fx.start[0] + fx.unit[0];
nowPosX[1] = ((fx.end[1] - fx.start[1]) * fx.pos) + fx.start[1] + fx.unit[1];
fx.elem.style.backgroundPosition = nowPosX[0] + ' ' + nowPosX[1];
function toArray(strg) {
strg = strg.replace(/left|top/g, '0px');
strg = strg.replace(/right|bottom/g, '100%');
strg = strg.replace(/([0-9\.]+)(\s|\)|$)/g, "$1px$2");
var res = strg.match(/(-?[0-9\.]+)(px|\%|em|pt)\s(-?[0-9\.]+)(px|\%|em|pt)/);
return [parseFloat(res[1], 10), res[2], parseFloat(res[3], 10), res[4]];
}
}
});
})(jQuery); | 12-games-of-christmas | trunk/assets/extensions.js | JavaScript | mit | 1,221 |
games.game5 = {
//breakout
init: function () {
$("#gamezone").html("<p style='font-size:18pt;padding:30px;'><strong style='font-size:20pt;'>Snowball Breakout</strong><br/>Use <span style='color:#939'>left</span> and <span style='color:#393'>right</span> to control the paddle</p><canvas id='game5-breakout' width='400' height='400' style='border:1px solid #000;margin:150px 50px;float:right;'></canvas>");
this.breakout($("#game5-breakout"), 400, 400);
},
breakout: function (element, h, w) {
engine = {
h: 0, w: 0,
gameBoard: undefined,
keysDown: new Array(),
engineloop: undefined,
keyloop: undefined,
init: function (gameBoard, h, w) {
this.gameBoard = gameBoard;
this.h = h;
this.w = w;
var that = this;
this.world.init(that, this.h, this.w, function () {
clearInterval(that.engineloop);
clearInterval(that.keyloop);
});
document.onkeydown = function (e) {
var KeyID = (window.event) ? event.keyCode : e.keyCode;
return that.handleKeyDown(KeyID);
}
document.onkeyup = function (e) {
var KeyID = (window.event) ? event.keyCode : e.keyCode;
return that.handleKeyUp(KeyID);
}
alert("are you ready... left and right");
this.engineloop = setInterval(function () {
that.tick();
}, 1);
this.keyloop = setInterval(function () {
that.handleKeys();
}, 1);
},
handleKeys: function () {
if (this.keysDown[39]) {
//right
this.world.internalPlayer.moveRight();
}
if (this.keysDown[37]) {
//left
this.world.internalPlayer.moveLeft();
}
if (!(this.keysDown[39] & this.keysDown[37])) {
}
},
handleKeyUp: function (keyId) {
this.keysDown[keyId] = false;
return !(keyId == 37 | keyId == 39);
},
handleKeyDown: function (keyId) {
this.keysDown[keyId] = true;
return !(keyId == 37 | keyId == 39);
},
player: {
x: 0,
y: 390,
h: 10,
w: 100,
color: '#000',
max: 0, min: 0,
speed: 2,
moveRight: function () {
this.x = this.x + this.w > this.max ? this.x : this.x + this.speed;
},
moveLeft: function () {
this.x = this.x < this.min ? this.x : this.x - this.speed;
},
render: function (ctx) {
ctx.fillStyle = this.color; // blue
ctx.strokeStyle = '#000'; // red
ctx.fillRect(this.x, this.y, this.w, this.h);
ctx.fillRect(this.x, this.y, this.w, this.h);
}
},
target: function (x, y, h, w, row) {
this.x = x;
this.y = y;
this.h = h;
this.w = w;
this.destroy = false;
this.getRowColour = function (row) {
switch (row) {
case 0: return '#f00';
case 1: return '#ff0';
case 2: return '#0f0';
case 3: return '#0ff';
case 4: return '#00f';
case 5: return '#fff';
case 6: return '#000';
case 7: return '#f00';
case 8: return '#ff0';
case 9: return '#0f0';
case 10: return '#0ff';
case 11: return '#00f';
case 12: return '#fff';
case 13: return '#000';
default: return '#ccc';
}
}
this.color = this.getRowColour(row);
this.render = function (ctx) {
if (this.destroy) { return; }
ctx.fillStyle = this.color; // blue
ctx.strokeStyle = '#000'; // red
ctx.fillRect(this.x, this.y, this.w, this.h);
ctx.strokeRect(this.x, this.y, this.w, this.h);
}
},
ball: {
x: 0,
y: 0,
h: 10,
w: 10,
angle: 0,
color: '#fff',
max: 0, min: 0,
xinc: false,
yinc: false,
speed: 2,
adjust: function () {
var xDiff = Math.sin(this.angle * Math.PI / 180) * this.speed;
var yDiff = Math.cos(this.angle * Math.PI / 180) * this.speed;
this.x = this.xinc ? this.x + xDiff : this.x - xDiff;
this.y = this.yinc ? this.y + yDiff : this.y - yDiff;
},
render: function (ctx) {
ctx.strokeStyle = '#000'; // red
ctx.fillStyle = this.color; // blue
ctx.beginPath();
ctx.arc(this.x, this.y, this.w, 0, Math.PI * 2, true);
ctx.stroke();
ctx.fill();
ctx.closePath();
}
},
world: {
internalPlayer: undefined,
internalBall: undefined,
internalBlocks: [],
h: 0, w: 0,
killCallback: undefined,
init: function (that, h, w, killCallback) {
for (var i = 0; i < 6; i++) { //y
for (var k = 0; k < 6; k++) { //x
var spaceBetweenBlocks = 10;
var target = new that.target(k * 10 + k * spaceBetweenBlocks + k * 50, i * 10, 5, 50, i);
this.internalBlocks[this.internalBlocks.length] = target;
}
}
this.internalPlayer = that.player;
this.internalBall = that.ball;
this.internalPlayer.max = h;
this.internalPlayer.min = 0;
this.internalBall.max = h;
this.internalBall.min = 0;
this.h = h;
this.w = w;
this.internalBall.y = games.helper.getRandomNumber(h / 4, (h / 4) * 3);
this.internalBall.x = games.helper.getRandomNumber(h / 4, (h / 4) * 3);
this.killCallback = killCallback;
},
render: function (ctx) {
this.internalPlayer.render(ctx);
this.internalBall.render(ctx);
var destroyed = 0;
for (var i = 0; i < this.internalBlocks.length; i++) {
destroyed += !this.internalBlocks[i].destroy ? 1 : 0;
this.internalBlocks[i].render(ctx);
}
if (destroyed == 0) {
if (this.killCallback != undefined) {
this.killCallback();
}
alert("Wll done! you won!");
}
},
adjust: function () {
this.internalBall.adjust();
/*## collision detection algo starts here :( ##*/
//is ball inside the world?
if (this.internalBall.x - this.internalBall.w < 0) {
this.internalBall.xinc = true;
}
if (this.internalBall.y - this.internalBall.h < 0) {
this.internalBall.yinc = true;
}
if (this.internalBall.x + this.internalBall.w > this.w) {
this.internalBall.xinc = false;
}
if (this.internalBall.y + this.internalBall.h > this.h) {
if (this.killCallback != undefined) {
this.killCallback();
}
alert("Uh oh, you died... but well done!");
}
//has ball hit paddle
if (this.internalBall.y + this.internalBall.h > this.internalPlayer.y) {
if (this.internalBall.x > this.internalPlayer.x) {
if (this.internalBall.x < this.internalPlayer.x + this.internalPlayer.w) {
this.internalBall.yinc = false;
var newAngle = (this.internalBall.x - this.internalPlayer.x) * 1.4 - 70;
this.internalBall.xinc = newAngle > 0;
this.internalBall.angle = newAngle < 0 ? newAngle * -1 : newAngle;
}
}
}
for (var i = 0; i < this.internalBlocks.length; i++) {
var currentBlock = this.internalBlocks[i];
if (!currentBlock.destroy) {
if (currentBlock.y < this.internalBall.y + this.internalBall.h) {
if (currentBlock.y + currentBlock.h > this.internalBall.y - this.internalBall.h) {
if (currentBlock.x < this.internalBall.x + this.internalBall.w) {
if (currentBlock.x > this.internalBall.x - this.internalBall.w) {
this.internalBall.xinc = false;
currentBlock.destroy = true;
}
}
if (currentBlock.x + currentBlock.w < this.internalBall.x + this.internalBall.w) {
if (currentBlock.x + currentBlock.w > this.internalBall.x - this.internalBall.w) {
this.internalBall.xinc = true;
currentBlock.destroy = true;
}
}
}
}
if (currentBlock.x < this.internalBall.x + this.internalBall.w) {
if (currentBlock.x + currentBlock.w > this.internalBall.x - this.internalBall.w) {
if (currentBlock.y < this.internalBall.y + this.internalBall.h) {
if (currentBlock.y > this.internalBall.y - this.internalBall.h) {
this.internalBall.yinc = false;
currentBlock.destroy = true;
}
}
if (currentBlock.y + currentBlock.h < this.internalBall.y + this.internalBall.h) {
if (currentBlock.y + currentBlock.h > this.internalBall.y - this.internalBall.h) {
this.internalBall.yinc = true;
currentBlock.destroy = true;
}
}
}
}
}
}
}
},
tick: function () {
this.gameBoard.clearRect(0, 0, 400, 400);
this.world.render(this.gameBoard);
this.world.adjust();
}
}
gameBoard = element[0].getContext('2d');
engine.init(gameBoard, h, w);
}
}; | 12-games-of-christmas | trunk/assets/game5.js | JavaScript | mit | 12,743 |
games.game6 = {
firstChosenCard: undefined,
secondChosenCard: undefined,
matches: 0,
init: function () {
games.game6.firstChosenCard = undefined;
games.game6.secondChosenCard = undefined;
games.game6.matches = 0;
var grid = "0,1,2,3,4,5,6,7,0,1,2,3,4,5,6,7,0,1,2,3,4,5,6,7,0,1,2,3,4,5,6,7,0,1,2,3,4,5,6,7,0,1,2,3,4,5,6,7,0,1,2,3,4,5,6,7,0,1,2,3,4,5,6,7".split(",");
this.randomiseArray(grid);
var html = "<ul id='game6-pairs'>";
for (var i = 0; i < grid.length; i++) {
html += "<li><a href='#' class='card" + grid[i] + "' id='game6-pairs-card" + i + "'> </li>";
}
html += "</ul>";
$("#gamezone").html(html);
$("#gamezone ul#game6-pairs li a").click(function () {
$(this).css("background-image", "url(http://12-games-of-christmas.googlecode.com/svn/trunk/assets/" + $(this).attr("class") + ".jpg)");
if (games.game6.firstChosenCard == undefined) {
games.game6.firstChosenCard = $(this);
} else if (games.game6.secondChosenCard == undefined) {
games.game6.secondChosenCard = $(this);
if (games.game6.firstChosenCard.attr("class") == games.game6.secondChosenCard.attr("class") && games.game6.firstChosenCard.attr("id") != games.game6.secondChosenCard.attr("id")) {
games.game6.firstChosenCard.unbind('click');
games.game6.secondChosenCard.unbind('click');
games.game6.firstChosenCard = undefined;
games.game6.secondChosenCard = undefined;
games.game6.matches++;
if (games.game6.matches == 32) {
alert("YAY!!!! you did it! Come back tomorow for another game! Or click the date again at the top to reset");
}
} else {
setTimeout(function () {
var resetBackground = "url(http://12-games-of-christmas.googlecode.com/svn/trunk/assets/back-of-card.png)";
games.game6.firstChosenCard.css("background-image", resetBackground);
games.game6.secondChosenCard.css("background-image", resetBackground);
games.game6.firstChosenCard = undefined;
games.game6.secondChosenCard = undefined;
}, 500);
}
}
});
},
randomiseArray: function (myArray) {
var i = myArray.length;
if (i == 0) return false;
while (--i) {
var j = Math.floor(Math.random() * (i + 1));
var tempi = myArray[i];
var tempj = myArray[j];
myArray[i] = tempj;
myArray[j] = tempi;
}
}
}; | 12-games-of-christmas | trunk/assets/game6.js | JavaScript | mit | 2,874 |
games.game8 = {
//hangman
words: "paris,newyork,london,frankfurt,harjit,dilshini,may,february,september,germany,paddington,plumstead,ealing,georgia,jackson,starbucks".split(","),
currentWord: "",
usedLetters: "",
guesses: 0,
errors: 0,
init: function () {
this.playRound();
$(document).keyup(function (event) {
var alphaKey = String.fromCharCode(event.keyCode).toLowerCase();
if ("abcdefghijklmnopqrstuvwxyz".indexOf(alphaKey) > -1) {
if (games.game8.usedLetters.indexOf(alphaKey) < 0) {
games.game8.guesses++;
games.game8.usedLetters += alphaKey;
$("#game8-hangman span span").each(function () {
var thisLetter = $(this).text();
if (thisLetter == alphaKey) {
$(this).css("visibility", "visible");
}
});
if (games.game8.currentWord.indexOf(alphaKey) < 0) {
games.game8.errors++;
}
var remaining = 0;
$("#game8-hangman span span").each(function () {
remaining = remaining + ($(this).css("visibility") == "hidden" ? 1 : 0);
});
if (remaining == 0) {
alert("well done, selecting another word");
games.game8.playRound();
}
if (games.game8.errors >= 10) {
alert("You loose, the word was..." + games.game8.currentWord + ". Never mind, play again!");
games.game8.playRound();
}
var livesBox = "";
for (var i = 0; i < games.game8.guesses - (games.game8.currentWord.length - remaining); i++) {
livesBox += " X";
}
$("#game8-hangman .lives").text(livesBox);
$("#game8-hangman .guesses").text(games.game8.usedLetters);
}
}
});
},
playRound: function () {
games.game8.usedLetters = "";
games.game8.guesses = 0;
games.game8.errors = 0;
games.game8.currentWord = games.game3.words[games.helper.getRandomNumber(0, games.game3.words.length)];
var html = "";
html += "<div id='game8-hangman'><h1>Hang Man</h1>";
for (var i = 0; i < games.game8.currentWord.length; i++) {
html += "<span><span style='visibility:hidden'>{0}</span></span>".replace("{0}", games.game8.currentWord[i]);
}
html += "<div class='lives'></div>";
html += "<div class='guesses'></div>";
html += "</div>";
$("#gamezone").html(html);
}
}; | 12-games-of-christmas | trunk/assets/game8.js | JavaScript | mit | 2,925 |
games.game10 = {
//asteroid
init: function () {
$("#gamezone").html('<table align="center" id="game10-asteroid"><tr><td align="center"><h4>[^]feed deer | [<]anti-clock | [>]clock-wise | [V]dead stop | [SPACE]drop | [c]steermode | [q]weapons</h4></td></tr><tr><td align="center" valign="middle"><canvas id="game10-asteroid-canvas" width="750" height="700"></canvas></td></tr></table>');
Asteroid("game10-asteroid-canvas");
}
}; | 12-games-of-christmas | trunk/assets/game10.js | JavaScript | mit | 463 |
var todaysDate = 25; todaysDate = (new Date()).getDate(); todaysDate = todaysDate >= 25 ? 24 : todaysDate;
var kn = new Konami(); kn.code = function() { alert("unlocked all days"); todaysDate = 24; games.gamezone.bind(); }; kn.load()
$(document).ready(function () { games.gamezone.bind(); }); | 12-games-of-christmas | trunk/assets/default.js | JavaScript | mit | 294 |
games.game7 = {
//snakes and ladders
//Render big 10x10 table
init: function () {
var html = "<table id='game7-snakes-ladders'>";
html += "<tr><td colspan='10'><h1>Roll Dice</h1><div class='dice-value'>?</div><div class='piece-holder'></div></td></td>";
for (var i = 9; i >= 0; i--) {
html += "<tr>";
var maxNo = 0;
for (var k = 9; k >= 0; k--) {
var rowVal = (i * 10) + (k == 10 ? 0 : k) + 1;
maxNo = rowVal % 10 == 0 ? rowVal : maxNo;
rowVal = i % 2 == 0 ? ((rowVal * (-1)) + (-9) + (maxNo * 2)) : rowVal;
html += "<td class='cell{0}'> </td>".replace("{0}", rowVal);
}
html += "</tr>";
}
html += "</table>";
$("#gamezone").html(html);
$(".piece-holder").append($("<img src='http://12-games-of-christmas.googlecode.com/svn/trunk/assets/player1.png' style='float:left;' class='player'/>"));
$(".piece-holder").append($("<img src='http://12-games-of-christmas.googlecode.com/svn/trunk/assets/player2.png' style='float:left;' class='npc'/>"));
$("#game7-snakes-ladders h1").click(function () {
if (games.game7.userLockOut) return;
games.game7.userLockOut = true;
var diceValue = games.game7.rollDice();
games.game7.player[1] += diceValue;
games.game7.movePiece();
setTimeout(function () {
games.game7.npcRoll();
}, diceValue * 300);
});
},
userLockOut: false,
npcRoll: function () {
games.game7.npc[1] += games.game7.rollDice();
games.game7.movePiece();
games.game7.userLockOut = false;
},
rollDice: function () {
games.game7.diceValue = games.helper.getRandomNumber(1, 6);
$("#game7-snakes-ladders .dice-value").text(games.game7.diceValue);
return games.game7.diceValue;
},
isPlayersGo: true,
moveTicker: undefined,
diceValue: 0,
player: [1, 1],
npc: [1, 1],
isActionCell: function (cellNo, element, playerCoords) {
cellNo--;
switch (cellNo) {
case 1: //promote to 38
$(".cell{0}".replace("{0}", 38)).append(element);
playerCoords[0] = 38; playerCoords[1] = 38;
break;
case 4: //promote to 14
$(".cell{0}".replace("{0}", 14)).append(element);
playerCoords[0] = 14; playerCoords[1] = 14;
break;
case 9: //promote to 31
$(".cell{0}".replace("{0}", 31)).append(element);
playerCoords[0] = 31; playerCoords[1] = 31;
break;
case 28: //promote to 84
$(".cell{0}".replace("{0}", 84)).append(element);
playerCoords[0] = 84; playerCoords[1] = 84;
break;
case 21: //promote to 42
$(".cell{0}".replace("{0}", 42)).append(element);
playerCoords[0] = 42; playerCoords[1] = 42;
break;
case 51: //promote to 67
$(".cell{0}".replace("{0}", 67)).append(element);
playerCoords[0] = 67; playerCoords[1] = 67;
break;
case 71: //promote to 91
$(".cell{0}".replace("{0}", 91)).append(element);
playerCoords[0] = 91; playerCoords[1] = 91;
break;
case 80: //promote to 100
$(".cell{0}".replace("{0}", 100)).append(element);
playerCoords[0] = 100; playerCoords[1] = 100;
break;
case 17: //relegate to 38
$(".cell{0}".replace("{0}", 7)).append(element);
playerCoords[0] = 7; playerCoords[1] = 7;
break;
case 62: //relegate to 14
$(".cell{0}".replace("{0}", 19)).append(element);
playerCoords[0] = 19; playerCoords[1] = 19;
break;
case 87: //relegate to 31
$(".cell{0}".replace("{0}", 24)).append(element);
playerCoords[0] = 24; playerCoords[1] = 24;
break;
case 54: //relegate to 84
$(".cell{0}".replace("{0}", 34)).append(element);
playerCoords[0] = 34; playerCoords[1] = 34;
break;
case 64: //relegate to 42
$(".cell{0}".replace("{0}", 60)).append(element);
playerCoords[0] = 60; playerCoords[1] = 60;
break;
case 93: //relegate to 67
$(".cell{0}".replace("{0}", 73)).append(element);
playerCoords[0] = 73; playerCoords[1] = 73;
break;
case 95: //relegate to 91
$(".cell{0}".replace("{0}", 75)).append(element);
playerCoords[0] = 75; playerCoords[1] = 75;
break;
case 98: //relegate to 100
$(".cell{0}".replace("{0}", 79)).append(element);
playerCoords[0] = 79; playerCoords[1] = 79;
break;
}
},
movePiece: function () {
games.game7.moveTicker = setInterval(function () {
if (games.game7.isPlayersGo) {
if (games.game7.player[0] == games.game7.player[1]) {
clearInterval(games.game7.moveTicker);
games.game7.isActionCell(games.game7.player[0], $("#game7-snakes-ladders .player"), games.game7.player);
if (games.game7.player[0] == 100) {
setInterval(function () { clearInterval(games.game7.moveTicker); }, 1);
alert("You WON!!!!! Come back tomorow for some more.");
}
games.game7.isPlayersGo = false;
} else {
$(".cell{0}".replace("{0}", games.game7.player[0]++)).append($("#game7-snakes-ladders .player"));
games.game7.player[0] = games.game7.player[0] == 100 ? 100 : games.game7.player[0];
games.game7.player[1] = games.game7.player[1] == 100 ? 100 : games.game7.player[1];
}
} else {
if (games.game7.npc[0] == games.game7.npc[1]) {
setInterval(function () { clearInterval(games.game7.moveTicker); }, 1);
games.game7.isActionCell(games.game7.npc[0], $("#game7-snakes-ladders .npc"), games.game7.npc);
if (games.game7.npc[0] == 100) {
setInterval(function () { clearInterval(games.game7.moveTicker); }, 1);
alert("You loose, why not try again.");
}
games.game7.isPlayersGo = true;
} else {
$(".cell{0}".replace("{0}", games.game7.npc[0]++)).append($("#game7-snakes-ladders .npc"));
games.game7.npc[0] = games.game7.npc[0] == 100 ? 100 : games.game7.npc[0];
games.game7.npc[1] = games.game7.npc[1] == 100 ? 100 : games.game7.npc[1];
}
}
}, 250);
}
}; | 12-games-of-christmas | trunk/assets/game7.js | JavaScript | mit | 7,355 |
function Asteroid(boardIdin, scrCallBack) {
function GameLoader(boardId) {
var canvas = document.getElementById(boardId);
var ctx = canvas.getContext("2d");
this.ScoreCallBack = scrCallBack;
this.boardX = 750;
this.boardY = 700;
this.levelUp = true;
this.level = 0;
this.rocks = new Array();
this.noRocks = 0;
this.score = 0;
this.RenderHud = function() {
ctx.fillStyle = "rgb(128,128,32)";
ctx.font = "20pt Arial";
ctx.fillText("Level: " + this.level, 50, 25);
ctx.fillText("Lives: " + this.Ship.life, 180, 25);
ctx.fillText("Score: " + this.score, 310, 25);
if (this.Ship.maxNukes > 0) {
ctx.fillText("Nukes: " + this.Ship.maxNukes, 440, 25);
}
ctx.fillText("Weapons mode:", 50, 50);
ctx.fillText(this.Ship.getWeaponsType(), 300, 50);
ctx.fillText("Steering mode:", 50, 75);
ctx.fillText(this.Ship.getSteeringType(), 300, 75);
//ctx.font = "20pt Arial"; + this.Ship.fireType
//ctx.fillText(("Score: " + this.score), 0, 30);
}
this.Ship = new function() {
//starboard = right, port = left
this.steeringType = 1;
this.bullets = new Array();
this.noBullets = 0;
this.shipLength = 50;
this.shipWidth = 30;
this.bowDeg = 0;
this.thrustDeg = 0;
this.shipX = 350;
this.shipY = 400;
this.shipDeg = 0;
this.thrust = 0;
this.rotation = 0;
this.life = 3;
this.fireType = 0;
this.maxNukes = 0;
this.die = function() {
this.shipX = window.GameLoaderAsteroid.boardX / 2;
this.shipY = window.GameLoaderAsteroid.boardY / 2;
this.dead = true;
this.thrust = 0;
this.bowDeg = 0;
this.life--;
}
this.getWeaponsType = function() {
switch (this.fireType) {
case 0:
return "Canon";
case 1:
return "Mine";
case 2:
return "Laser";
case 3:
return "Nuke";
}
}
this.getSteeringType = function() {
switch (this.steeringType) {
case 0:
return "Zero-G";
case 1:
return "Classic";
}
}
this.toggleArms = function(intlevel) {
this.fireType++;
document.title = intlevel;
if (intlevel > 9) {
this.fireType = this.fireType > 3 ? 0 : this.fireType; //nuke (unlimited)
} else if (intlevel > 6) {
this.fireType = this.fireType > 2 ? 0 : this.fireType; //laser (unlimited)
} else if (intlevel > 3) {
this.fireType = this.fireType > 1 ? 0 : this.fireType; //mine (unlimited)
} else {
this.fireType = 0; //canon (unlimited)
}
}
this.draw = function() {
if ((this.shipX < 0 | this.shipX > window.GameLoaderAsteroid.boardX) | (this.shipY < 0 | this.shipY > window.GameLoaderAsteroid.boardY)) {
if (this.shipX < 0) {
this.shipX = window.GameLoaderAsteroid.boardX;
}
if (this.shipX > window.GameLoaderAsteroid.boardX) {
this.shipX = 0;
}
if (this.shipY < 0) {
this.shipY = window.GameLoaderAsteroid.boardY;
}
if (this.shipY > window.GameLoaderAsteroid.boardY) {
this.shipY = 0;
}
}
this.shipDeg += this.rotation;
this.thrust = this.thrust > 20 ? 20 : this.thrust;
this.thrust = this.thrust < 0 ? 0 : this.thrust;
var steerDegree = 0;
switch (this.steeringType) {
case 0:
this.shipX = this.shipX + Math.sin(this.thrustDeg * Math.PI / 180) * this.thrust;
this.shipY = this.shipY - Math.cos(this.thrustDeg * Math.PI / 180) * this.thrust;
break;
case 1:
this.shipX = this.shipX + Math.sin(this.shipDeg * Math.PI / 180) * this.thrust;
this.shipY = this.shipY - Math.cos(this.shipDeg * Math.PI / 180) * this.thrust;
break;
}
var bowX = Math.sin(this.shipDeg * Math.PI / 180) * (this.shipLength / 2) + (this.shipX);
var bowY = this.shipY - Math.cos(this.shipDeg * Math.PI / 180) * (this.shipWidth / 2);
var shipimage = new Image();
shipimage.src = 'http://12-games-of-christmas.googlecode.com/svn/trunk/assets/ship.gif';
ctx.translate(bowX, bowY);
ctx.rotate(this.shipDeg * Math.PI / 180);
ctx.drawImage(shipimage, (-this.shipWidth / 2), (-this.shipLength / 2), this.shipWidth, this.shipLength);
ctx.rotate(-this.shipDeg * Math.PI / 180);
ctx.translate(-bowX, -bowY);
document.title = "";
for (var i = 0; i < this.noBullets; i++) {
if (this.bullets[i].inAction == true) {
ctx.fillStyle = "rgb(200,0,0)";
this.bullets[i].draw();
}
}
};
this.fire = function() {
this.bullets[this.noBullets] = new function() {
this.type = window.GameLoaderAsteroid.Ship.fireType;
this.range = 10;
this.inAction = true;
this.bulletHeading = window.GameLoaderAsteroid.Ship.shipDeg;
this.baseX = window.GameLoaderAsteroid.Ship.shipX;
this.baseY = window.GameLoaderAsteroid.Ship.shipY;
this.boxX = window.GameLoaderAsteroid.Ship.shipX;
this.boxY = window.GameLoaderAsteroid.Ship.shipY;
this.w = 0;
this.h = 0;
this.checkColision = function(x, y, w, h) {
var colided = false;
switch (this.type) {
case 0:
case 1:
case 3: //boxes
if (x > this.boxX & x < this.boxX + this.w) {
if (y > this.boxY & y < this.boxY + this.h) {
colided = true;
}
}
if (this.boxX > x & this.boxX < x + w) {
if (this.boxY > y & this.boxY < y + h) {
colided = true;
}
}
break;
case 2: //lasers
for (var i = 0; i < this.range; i++) {
var laserTestX = this.baseX + Math.sin(this.bulletHeading * Math.PI / 180) * i;
var laserTestY = this.baseY - Math.cos(this.bulletHeading * Math.PI / 180) * i;
if (x < laserTestX & (x + w) > laserTestX) {
if (y < laserTestY & (y + h) > laserTestY) {
colided = true;
}
}
}
break;
}
if (colided & this.type != 3) {
this.inAction = false;
}
return colided;
}
this.draw = function() {
switch (this.type) {
case 0: //canon
this.w = 5;
this.h = 5;
this.boxX = this.baseX + Math.sin(this.bulletHeading * Math.PI / 180) * this.range;
this.boxY = this.baseY - Math.cos(this.bulletHeading * Math.PI / 180) * this.range;
ctx.fillRect(this.boxX, this.boxY, this.w, this.h);
break;
case 1: //mine
this.w = 10;
this.h = 10;
this.boxX = this.baseX;
this.boxY = this.baseY;
ctx.fillRect(this.boxX, this.boxY, this.w, this.h);
break;
case 2: //laser
ctx.beginPath();
this.boxX = this.baseX + Math.sin(this.bulletHeading * Math.PI / 180) * this.range;
this.boxY = this.baseY - Math.cos(this.bulletHeading * Math.PI / 180) * this.range;
ctx.lineWidth = 2;
ctx.moveTo(this.baseX, this.baseY); // give the (x,y) coordinates
ctx.lineTo(this.boxX, this.boxY);
ctx.lineTo(this.baseX, this.baseY);
ctx.strokeStyle = "#f00";
ctx.stroke();
ctx.closePath();
break;
case 3: //nuke
this.w = window.GameLoaderAsteroid.boardX;
this.h = window.GameLoaderAsteroid.boardY;
this.boxX = 0;
this.boxY = 0;
ctx.fillStyle = "rgba(200,0,0," + (this.range / 300) + ")";
ctx.fillRect(this.boxX, this.boxY, this.w, this.h);
this.range += 40;
break;
}
this.range += 10;
if (this.range > 300) {
this.inAction = false;
}
}
}
this.noBullets++;
};
};
this.tick = function() {
window.GameLoaderAsteroid.tickCounter++;
if (window.GameLoaderAsteroid.Ship.dead == true) {
if (window.GameLoaderAsteroid.Ship.life == 0) {
ctx.fillStyle = "rgb(128,128,32)";
ctx.font = "40pt Arial";
ctx.fillText("Game Over", this.boardX / 2, this.boardY / 2);
ctx.font = "20pt Arial";
ctx.fillText(("Score - " + this.score), this.boardX / 2, this.boardY / 2 + 30);
return;
}
ctx.clearRect(0, 0, this.boardX, this.boardY);
window.GameLoaderAsteroid.Ship.dead = false;
ctx.fillStyle = "rgb(128,128,32)";
ctx.font = "40pt Arial";
ctx.fillText("Lost a life", this.boardX / 2, this.boardY / 2);
ctx.fillText("Get Ready", this.boardX / 2, this.boardY / 2 + 50);
setTimeout("window.GameLoaderAsteroid.tick()", 1000);
return;
}
if (this.levelUp) {
this.noBullets = 0;
if(this.level%10 ==0){
window.GameLoaderAsteroid.Ship.life++;
window.GameLoaderAsteroid.Ship.maxNukes++;
}
window.GameLoaderAsteroid.Ship.maxNukes = this.level - 8;
this.level++;
this.levelUp = false;
this.noRocks = this.level * 1;
for (var i = 0; i < this.noRocks; i++) {
this.rocks[i] = new function() {
this.rockHeading = Math.floor(Math.random() * 361);
this.rockDistance = Math.floor(Math.random() * 200) + 50;
this.baseX = Math.floor(Math.random() * window.GameLoaderAsteroid.boardX);
this.baseY = Math.floor(Math.random() * window.GameLoaderAsteroid.boardY);
this.rockX = this.baseX + Math.sin(this.rockHeading * Math.PI / 180) * this.rockDistance;
this.rockY = this.baseY - Math.cos(this.rockHeading * Math.PI / 180) * this.rockDistance;
this.width = 20+(window.GameLoaderAsteroid.level * 5);
this.height = 20+(window.GameLoaderAsteroid.level * 5);
this.destroyed = false;
this.draw = function() {
this.rockX = this.baseX + Math.sin(this.rockHeading * Math.PI / 180) * this.rockDistance;
this.rockY = this.baseY - Math.cos(this.rockHeading * Math.PI / 180) * this.rockDistance;
this.rockHeading += 5;
var rockimage = new Image();
rockimage.src = 'http://12-games-of-christmas.googlecode.com/svn/trunk/assets/asteroid2.gif';
ctx.drawImage(rockimage, this.rockX, this.rockY, this.width, this.height);
//ctx.fillRect(this.rockX, this.rockY, 30, 30);
}
}
}
ctx.fillStyle = "rgb(128,32,32)";
ctx.font = "20pt Arial";
ctx.fillText("Level: " + window.GameLoaderAsteroid.level, window.GameLoaderAsteroid.boardX / 2, window.GameLoaderAsteroid.boardY / 2);
ctx.fillText("Get Ready", window.GameLoaderAsteroid.boardX / 2, window.GameLoaderAsteroid.boardY / 2 + 50);
if (this.level == 4) {
ctx.fillText("Upgrade weapons: mine", window.GameLoaderAsteroid.boardX / 2, window.GameLoaderAsteroid.boardY / 2 + 100);
} else if (this.level == 1) {
ctx.fillText("Upgrade weapons: canon", window.GameLoaderAsteroid.boardX / 2, window.GameLoaderAsteroid.boardY / 2 + 100);
}
var bonus = ((30)*this.level)-window.GameLoaderAsteroid.tickCounter;
if (bonus > 0){
window.GameLoaderAsteroid.score +=bonus;
ctx.fillText("Time Bonus: "+bonus, window.GameLoaderAsteroid.boardX / 2, window.GameLoaderAsteroid.boardY / 2 + 150);
}
window.GameLoaderAsteroid.tickCounter = 0;
setTimeout("window.GameLoaderAsteroid.tick()", 2000);
return;
}
ctx.clearRect(0, 0, this.boardX, this.boardY);
window.GameLoaderAsteroid.RenderHud();
for (var i = 0; i < this.noRocks; i++) {
var rock = this.rocks[i];
var ship = window.GameLoaderAsteroid.Ship;
if (rock.rockX < ship.shipX & (rock.rockX + rock.width) > ship.shipX) {
if (rock.rockY < ship.shipY & (rock.rockY + rock.height) > ship.shipY) {
if (!rock.destroyed) {
rock.destroyed = true;
ship.die();
setTimeout("window.GameLoaderAsteroid.tick()", 40);
return;
}
}
}
if (!this.rocks[i].destroyed) {
for (var j = 0; j < window.GameLoaderAsteroid.Ship.noBullets; j++) {
if (window.GameLoaderAsteroid.Ship.bullets[j].inAction) {
var blt = window.GameLoaderAsteroid.Ship.bullets[j];
if (blt.checkColision(rock.rockX, rock.rockY, rock.width, rock.height)) {
rock.destroyed = true;
this.score++;
}
}
}
}
}
var noRocksLeft = 0;
for (var i = 0; i < this.noRocks; i++) {
if (!this.rocks[i].destroyed) {
ctx.fillStyle = "rgb(64,64,64)";
this.rocks[i].draw();
noRocksLeft++;
}
}
this.levelUp = (noRocksLeft == 0);
this.Ship.draw();
if (this.ScoreCallBack != undefined) {
this.ScoreCallBack(this.level, this.score, window.GameLoaderAsteroid.Ship.life);
}
setTimeout("window.GameLoaderAsteroid.tick()", 100);
};
canvas.onclick = function () {
canvas.onclick = function () { };
this.style.backgroundImage = "url(http://12-games-of-christmas.googlecode.com/svn/trunk/assets/space.jpg)";
document.onkeyup = function (e) {
var charCode = this.KeyID = (window.event) ? event.keyCode : e.keyCode;
switch (charCode) {
case 32:
if (!(window.GameLoaderAsteroid.Ship.maxNukes == 0 && window.GameLoaderAsteroid.Ship.fireType == 3)) {
window.GameLoaderAsteroid.Ship.fire();
if (window.GameLoaderAsteroid.Ship.fireType == 3) {
window.GameLoaderAsteroid.Ship.maxNukes--;
}
}
break;
case 81:
window.GameLoaderAsteroid.Ship.toggleArms(window.GameLoaderAsteroid.level);
if (window.GameLoaderAsteroid.Ship.maxNukes == 0) {
if (window.GameLoaderAsteroid.Ship.fireType == 3) {
window.GameLoaderAsteroid.Ship.fireType = 0;
}
}
break;
case 39:
window.GameLoaderAsteroid.Ship.rotation = 0;
break;
case 37:
window.GameLoaderAsteroid.Ship.rotation = 0;
break;
case 67:
window.GameLoaderAsteroid.Ship.steeringType = window.GameLoaderAsteroid.Ship.steeringType == 0 ? 1 : 0;
break;
}
if (charCode == 81 || charCode == 39 || charCode == 37 || charCode == 67 || charCode == 32) {
return false;
}
};
document.onkeydown = function (e) {
var charCode = this.KeyID = (window.event) ? event.keyCode : e.keyCode;
switch (charCode) {
case 39:
window.GameLoaderAsteroid.Ship.rotation = 10;
break;
case 37:
window.GameLoaderAsteroid.Ship.rotation = -10;
break;
case 38:
if (window.GameLoaderAsteroid.Ship.thrustDeg != window.GameLoaderAsteroid.Ship.shipDeg) {
window.GameLoaderAsteroid.Ship.thrust -= 5;
}
if (window.GameLoaderAsteroid.Ship.thrust < 1) {
window.GameLoaderAsteroid.Ship.thrustDeg = window.GameLoaderAsteroid.Ship.shipDeg;
}
window.GameLoaderAsteroid.Ship.thrust += 3;
break;
case 40:
window.GameLoaderAsteroid.Ship.thrust = 0;
break;
}
if (charCode == 37 || charCode == 38 || charCode == 39 || charCode == 40) {
return false;
}
};
window.GameLoaderAsteroid.tick();
}
}
window.GameLoaderAsteroid = new GameLoader(boardIdin, scrCallBack);
} | 12-games-of-christmas | trunk/assets/asteroid.js | JavaScript | mit | 22,413 |
games.game2 = {
played: new Array(),
colors: "red,blue,green,yellow".split(","),
clickIndex: 0,
init: function () {
var html = "<ul id='game2-pattern'>";
for (var i = 0; i < this.colors.length; i++) {
html += "<li><a href='#' class='" + this.colors[i] + "'> </li>";
}
html += "</ul>";
$("#gamezone").html(html);
games.game2.clickIndex = 0;
this.played = new Array();
setTimeout(function () {
games.game2.playColours();
}, 1000);
},
handlerUser: function () {
games.game2.flashElement(0, $("#gamezone ul#game2-pattern li a." + $(this).attr("class")), false);
if ($(this).attr("class") == games.game2.played[games.game2.clickIndex]) {
games.game2.clickIndex++;
if (games.game2.clickIndex == games.game2.played.length) {
games.game2.clickIndex = 0;
setTimeout(function () {
games.game2.playColours();
}, 1000);
}
} else {
alert("lost with a score of " + games.game2.played.length + ", resetting the game so you can try again. ");
games.game2.init();
}
},
playColours: function () {
$("#gamezone ul#game2-pattern li a").unbind("click");
this.played[this.played.length] = this.colors[games.helper.getRandomNumber(0, 4)];
for (var i = 0; i < this.played.length; i++) {
this.flashElement(i, $("#gamezone ul#game2-pattern li a." + this.played[i]), false);
}
this.flashElement(i + 1, $("<span>"), true);
},
flashElement: function (timeout, element, enableClick) {
setTimeout(function () {
element.addClass("play");
setTimeout(function () {
element.removeClass("play");
}, 150);
if (enableClick) {
$("#gamezone ul#game2-pattern li a").click(games.game2.handlerUser);
}
}, 500 * timeout);
}
}; | 12-games-of-christmas | trunk/assets/game2.js | JavaScript | mit | 2,101 |
games.game12 = {
//snakes
init: function () {
$("#gamezone").html("<p style='font-size:18pt;padding:30px;'><strong style='font-size:20pt;'>Snakes</strong><br/>Use <span style='color:#933'>up</span>, <span style='color:#939'>down</span>, <span style='color:#339'>left</span> and <span style='color:#393'>right</span> to control the paddle</p><canvas id='game12-snakes' width='400' height='400' style='border:1px solid #000;margin:50px 50px;float:right;'></canvas>");
this.breakout($("#game12-snakes"), 400, 400);
},
breakout: function (element, h, w) {
engine = {
h: 0, w: 0,
gameBoard: undefined,
keysDown: new Array(),
engineloop: undefined,
keyloop: undefined,
init: function (gameBoard, h, w) {
this.gameBoard = gameBoard;
this.h = h;
this.w = w;
var that = this;
this.world.init(that, this.h, this.w, function () {
clearInterval(that.engineloop);
clearInterval(that.keyloop);
});
document.onkeydown = function (e) {
var KeyID = (window.event) ? event.keyCode : e.keyCode;
return that.handleKeyDown(KeyID);
}
document.onkeyup = function (e) {
var KeyID = (window.event) ? event.keyCode : e.keyCode;
return that.handleKeyUp(KeyID);
}
alert("are you ready... left and right");
this.engineloop = setInterval(function () {
that.tick();
}, 100);
this.keyloop = setInterval(function () {
that.handleKeys();
}, 1);
},
handleKeys: function () {
if (this.keysDown[39]) {
this.world.internalPlayer.moveRight();
}
if (this.keysDown[37]) {
this.world.internalPlayer.moveLeft();
}
if (this.keysDown[40]) {
this.world.internalPlayer.moveDown();
}
if (this.keysDown[38]) {
this.world.internalPlayer.moveUp();
}
},
handleKeyUp: function (keyId) {
this.keysDown[keyId] = false;
return !(keyId == 37 | keyId == 39 | keyId == 38 | keyId == 40);
},
handleKeyDown: function (keyId) {
this.keysDown[keyId] = true;
return !(keyId == 37 | keyId == 39 | keyId == 38 | keyId == 40);
},
player: {
limbs: [{ x: 0, y: 390, color: '#fff'}],
x: 0,
y: 390,
h: 10,
w: 10,
l: 5,
max: 0, min: 0,
speed: 2,
facing: 'e',
score: 0,
moveRight: function () { this.facing = this.facing == 'w' ? 'w' : 'e'; },
moveLeft: function () { this.facing = this.facing == 'e' ? 'e' : 'w'; },
moveUp: function () { this.facing = this.facing == 's' ? 's' : 'n'; },
moveDown: function () { this.facing = this.facing == 'n' ? 'n' : 's'; },
grow: function (growBy, newx, newy) {
var letters = '0369cf'.split('');
var color = '#';
for (var i = 0; i < 3; i++) {
color += letters[Math.round(Math.random() * 6)];
}
this.limbs[this.limbs.length] = { x: newx, y: newy, color: color };
},
render: function (ctx) {
ctx.fillStyle = '#000';
ctx.font = "bold 150px sans-serif";
ctx.fillText(this.score, 150, 225);
ctx.strokeColor = '#000';
for (l in this.limbs) {
ctx.fillStyle = this.limbs[l].color;
ctx.fillRect(this.limbs[l].x, this.limbs[l].y, this.w, this.h);
ctx.strokeRect(this.limbs[l].x, this.limbs[l].y, this.w, this.h);
}
}
},
target: {
x: undefined,
y: undefined,
h: 10,
w: 10,
init: function (x, y) {
this.x = x;
this.y = y;
},
color: '#f00',
render: function (ctx) {
if (this.x == undefined && this.y == undefined) { return; }
ctx.fillStyle = this.color;
ctx.fillRect(this.x, this.y, this.w, this.h);
}
},
world: {
internalPlayer: undefined,
internalApple: undefined,
h: 0, w: 0,
killCallback: undefined,
init: function (that, h, w, killCallback) {
this.h = h;
this.w = w;
this.killCallback = killCallback;
this.internalPlayer = that.player;
this.internalApple = that.target;
this.internalApple.init(games.helper.getRandomNumber(0, this.w / 10) * 10, games.helper.getRandomNumber(0, this.h / 10) * 10);
this.internalPlayer.max = h;
this.internalPlayer.min = 0;
},
render: function (ctx) {
ctx.clearRect(0, 0, this.h, this.w);
this.internalPlayer.render(ctx);
this.internalApple.render(ctx);
},
adjust: function () {
var tailx = this.internalPlayer.limbs[this.internalPlayer.limbs.length - 1].x;
var taily = this.internalPlayer.limbs[this.internalPlayer.limbs.length - 1].y;
var headx = this.internalPlayer.limbs[0].x;
var heady = this.internalPlayer.limbs[0].y;
switch (this.internalPlayer.facing) {
case 'n':
this.internalPlayer.limbs[0].y -= this.internalPlayer.h;
break;
case 's':
this.internalPlayer.limbs[0].y += this.internalPlayer.h;
break;
case 'e':
this.internalPlayer.limbs[0].x += this.internalPlayer.w;
break;
case 'w':
this.internalPlayer.limbs[0].x -= this.internalPlayer.w;
break;
}
for (var i = 1; i < this.internalPlayer.limbs.length; i++) {
var headxtemp = this.internalPlayer.limbs[i].x;
var headytemp = this.internalPlayer.limbs[i].y;
if (headxtemp == this.internalApple.x && headytemp == this.internalApple.y) {
this.internalApple.init(games.helper.getRandomNumber(0, this.w / 10) * 10, games.helper.getRandomNumber(0, this.h / 10) * 10);
this.internalPlayer.l += 4;
}
if (this.internalPlayer.limbs[0].x == headxtemp && this.internalPlayer.limbs[0].y == headytemp && i > 2) {
if (this.killCallback != undefined) {
this.killCallback();
}
alert("Uh oh, you died!");
return false;
}
this.internalPlayer.limbs[i].x = headx;
this.internalPlayer.limbs[i].y = heady;
headx = headxtemp;
heady = headytemp;
}
if (this.internalPlayer.limbs[0].x == this.internalApple.x && this.internalPlayer.limbs[0].y == this.internalApple.y) {
this.internalApple.init(games.helper.getRandomNumber(0, this.w / 10) * 10, games.helper.getRandomNumber(0, this.h / 10) * 10);
this.internalPlayer.l += 4;
this.internalPlayer.score++;
}
if (this.internalPlayer.l > 0) {
this.internalPlayer.l--;
this.internalPlayer.grow(1, tailx, taily);
}
if (this.internalPlayer.limbs[0].x > this.w - this.internalPlayer.w || this.internalPlayer.limbs[0].y > this.h - this.internalPlayer.h || this.internalPlayer.limbs[0].x < 0 || this.internalPlayer.limbs[0].y < 0) {
if (this.killCallback != undefined) {
this.killCallback();
}
alert("Uh oh, you died!");
return false;
}
return true;
}
},
tick: function () {
if (this.world.adjust())
this.world.render(this.gameBoard);
}
}
gameBoard = element[0].getContext('2d');
engine.init(gameBoard, h, w);
}
}; | 12-games-of-christmas | trunk/assets/game12.js | JavaScript | mit | 9,742 |