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.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; }
1030365071-xuechao
src/com/trilead/ssh2/transport/KexState.java
Java
asf20
746
package com.trilead.ssh2; /** * In most cases you probably do not need the information contained in here. * * @author Christian Plattner, plattner@trilead.com * @version $Id: ConnectionInfo.java,v 1.1 2007/10/15 12:49:56 cplattne Exp $ */ public class ConnectionInfo { /** * The used key exchange (KEX) algorithm in the latest key exchange. */ public String keyExchangeAlgorithm; /** * The currently used crypto algorithm for packets from to the client to the * server. */ public String clientToServerCryptoAlgorithm; /** * The currently used crypto algorithm for packets from to the server to the * client. */ public String serverToClientCryptoAlgorithm; /** * The currently used MAC algorithm for packets from to the client to the * server. */ public String clientToServerMACAlgorithm; /** * The currently used MAC algorithm for packets from to the server to the * client. */ public String serverToClientMACAlgorithm; /** * The type of the server host key (currently either "ssh-dss" or * "ssh-rsa"). */ public String serverHostKeyAlgorithm; /** * The server host key that was sent during the latest key exchange. */ public byte[] serverHostKey; /** * Number of kex exchanges performed on this connection so far. */ public int keyExchangeCounter = 0; }
1030365071-xuechao
src/com/trilead/ssh2/ConnectionInfo.java
Java
asf20
1,378
package com.trilead.ssh2.crypto.cipher; /* This file was shamelessly taken from the Bouncy Castle Crypto package. Their licence file states the following: Copyright (c) 2000 - 2004 The Legion Of The Bouncy Castle (http://www.bouncycastle.org) Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /** * An implementation of the AES (Rijndael), from FIPS-197. * <p> * For further details see: <a * href="http://csrc.nist.gov/encryption/aes/">http://csrc.nist.gov/encryption/aes/ * </a>. * * This implementation is based on optimizations from Dr. Brian Gladman's paper * and C code at <a * href="http://fp.gladman.plus.com/cryptography_technology/rijndael/">http://fp.gladman.plus.com/cryptography_technology/rijndael/ * </a> * * There are three levels of tradeoff of speed vs memory Because java has no * preprocessor, they are written as three separate classes from which to choose * * The fastest uses 8Kbytes of static tables to precompute round calculations, 4 * 256 word tables for encryption and 4 for decryption. * * The middle performance version uses only one 256 word table for each, for a * total of 2Kbytes, adding 12 rotate operations per round to compute the values * contained in the other tables from the contents of the first * * The slowest version uses no static tables at all and computes the values in * each round * <p> * This file contains the fast version with 8Kbytes of static tables for round * precomputation * * @author See comments in the source file * @version $Id: AES.java,v 1.1 2007/10/15 12:49:55 cplattne Exp $ */ public class AES implements BlockCipher { // The S box private static final byte[] S = { (byte) 99, (byte) 124, (byte) 119, (byte) 123, (byte) 242, (byte) 107, (byte) 111, (byte) 197, (byte) 48, (byte) 1, (byte) 103, (byte) 43, (byte) 254, (byte) 215, (byte) 171, (byte) 118, (byte) 202, (byte) 130, (byte) 201, (byte) 125, (byte) 250, (byte) 89, (byte) 71, (byte) 240, (byte) 173, (byte) 212, (byte) 162, (byte) 175, (byte) 156, (byte) 164, (byte) 114, (byte) 192, (byte) 183, (byte) 253, (byte) 147, (byte) 38, (byte) 54, (byte) 63, (byte) 247, (byte) 204, (byte) 52, (byte) 165, (byte) 229, (byte) 241, (byte) 113, (byte) 216, (byte) 49, (byte) 21, (byte) 4, (byte) 199, (byte) 35, (byte) 195, (byte) 24, (byte) 150, (byte) 5, (byte) 154, (byte) 7, (byte) 18, (byte) 128, (byte) 226, (byte) 235, (byte) 39, (byte) 178, (byte) 117, (byte) 9, (byte) 131, (byte) 44, (byte) 26, (byte) 27, (byte) 110, (byte) 90, (byte) 160, (byte) 82, (byte) 59, (byte) 214, (byte) 179, (byte) 41, (byte) 227, (byte) 47, (byte) 132, (byte) 83, (byte) 209, (byte) 0, (byte) 237, (byte) 32, (byte) 252, (byte) 177, (byte) 91, (byte) 106, (byte) 203, (byte) 190, (byte) 57, (byte) 74, (byte) 76, (byte) 88, (byte) 207, (byte) 208, (byte) 239, (byte) 170, (byte) 251, (byte) 67, (byte) 77, (byte) 51, (byte) 133, (byte) 69, (byte) 249, (byte) 2, (byte) 127, (byte) 80, (byte) 60, (byte) 159, (byte) 168, (byte) 81, (byte) 163, (byte) 64, (byte) 143, (byte) 146, (byte) 157, (byte) 56, (byte) 245, (byte) 188, (byte) 182, (byte) 218, (byte) 33, (byte) 16, (byte) 255, (byte) 243, (byte) 210, (byte) 205, (byte) 12, (byte) 19, (byte) 236, (byte) 95, (byte) 151, (byte) 68, (byte) 23, (byte) 196, (byte) 167, (byte) 126, (byte) 61, (byte) 100, (byte) 93, (byte) 25, (byte) 115, (byte) 96, (byte) 129, (byte) 79, (byte) 220, (byte) 34, (byte) 42, (byte) 144, (byte) 136, (byte) 70, (byte) 238, (byte) 184, (byte) 20, (byte) 222, (byte) 94, (byte) 11, (byte) 219, (byte) 224, (byte) 50, (byte) 58, (byte) 10, (byte) 73, (byte) 6, (byte) 36, (byte) 92, (byte) 194, (byte) 211, (byte) 172, (byte) 98, (byte) 145, (byte) 149, (byte) 228, (byte) 121, (byte) 231, (byte) 200, (byte) 55, (byte) 109, (byte) 141, (byte) 213, (byte) 78, (byte) 169, (byte) 108, (byte) 86, (byte) 244, (byte) 234, (byte) 101, (byte) 122, (byte) 174, (byte) 8, (byte) 186, (byte) 120, (byte) 37, (byte) 46, (byte) 28, (byte) 166, (byte) 180, (byte) 198, (byte) 232, (byte) 221, (byte) 116, (byte) 31, (byte) 75, (byte) 189, (byte) 139, (byte) 138, (byte) 112, (byte) 62, (byte) 181, (byte) 102, (byte) 72, (byte) 3, (byte) 246, (byte) 14, (byte) 97, (byte) 53, (byte) 87, (byte) 185, (byte) 134, (byte) 193, (byte) 29, (byte) 158, (byte) 225, (byte) 248, (byte) 152, (byte) 17, (byte) 105, (byte) 217, (byte) 142, (byte) 148, (byte) 155, (byte) 30, (byte) 135, (byte) 233, (byte) 206, (byte) 85, (byte) 40, (byte) 223, (byte) 140, (byte) 161, (byte) 137, (byte) 13, (byte) 191, (byte) 230, (byte) 66, (byte) 104, (byte) 65, (byte) 153, (byte) 45, (byte) 15, (byte) 176, (byte) 84, (byte) 187, (byte) 22, }; // The inverse S-box private static final byte[] Si = { (byte) 82, (byte) 9, (byte) 106, (byte) 213, (byte) 48, (byte) 54, (byte) 165, (byte) 56, (byte) 191, (byte) 64, (byte) 163, (byte) 158, (byte) 129, (byte) 243, (byte) 215, (byte) 251, (byte) 124, (byte) 227, (byte) 57, (byte) 130, (byte) 155, (byte) 47, (byte) 255, (byte) 135, (byte) 52, (byte) 142, (byte) 67, (byte) 68, (byte) 196, (byte) 222, (byte) 233, (byte) 203, (byte) 84, (byte) 123, (byte) 148, (byte) 50, (byte) 166, (byte) 194, (byte) 35, (byte) 61, (byte) 238, (byte) 76, (byte) 149, (byte) 11, (byte) 66, (byte) 250, (byte) 195, (byte) 78, (byte) 8, (byte) 46, (byte) 161, (byte) 102, (byte) 40, (byte) 217, (byte) 36, (byte) 178, (byte) 118, (byte) 91, (byte) 162, (byte) 73, (byte) 109, (byte) 139, (byte) 209, (byte) 37, (byte) 114, (byte) 248, (byte) 246, (byte) 100, (byte) 134, (byte) 104, (byte) 152, (byte) 22, (byte) 212, (byte) 164, (byte) 92, (byte) 204, (byte) 93, (byte) 101, (byte) 182, (byte) 146, (byte) 108, (byte) 112, (byte) 72, (byte) 80, (byte) 253, (byte) 237, (byte) 185, (byte) 218, (byte) 94, (byte) 21, (byte) 70, (byte) 87, (byte) 167, (byte) 141, (byte) 157, (byte) 132, (byte) 144, (byte) 216, (byte) 171, (byte) 0, (byte) 140, (byte) 188, (byte) 211, (byte) 10, (byte) 247, (byte) 228, (byte) 88, (byte) 5, (byte) 184, (byte) 179, (byte) 69, (byte) 6, (byte) 208, (byte) 44, (byte) 30, (byte) 143, (byte) 202, (byte) 63, (byte) 15, (byte) 2, (byte) 193, (byte) 175, (byte) 189, (byte) 3, (byte) 1, (byte) 19, (byte) 138, (byte) 107, (byte) 58, (byte) 145, (byte) 17, (byte) 65, (byte) 79, (byte) 103, (byte) 220, (byte) 234, (byte) 151, (byte) 242, (byte) 207, (byte) 206, (byte) 240, (byte) 180, (byte) 230, (byte) 115, (byte) 150, (byte) 172, (byte) 116, (byte) 34, (byte) 231, (byte) 173, (byte) 53, (byte) 133, (byte) 226, (byte) 249, (byte) 55, (byte) 232, (byte) 28, (byte) 117, (byte) 223, (byte) 110, (byte) 71, (byte) 241, (byte) 26, (byte) 113, (byte) 29, (byte) 41, (byte) 197, (byte) 137, (byte) 111, (byte) 183, (byte) 98, (byte) 14, (byte) 170, (byte) 24, (byte) 190, (byte) 27, (byte) 252, (byte) 86, (byte) 62, (byte) 75, (byte) 198, (byte) 210, (byte) 121, (byte) 32, (byte) 154, (byte) 219, (byte) 192, (byte) 254, (byte) 120, (byte) 205, (byte) 90, (byte) 244, (byte) 31, (byte) 221, (byte) 168, (byte) 51, (byte) 136, (byte) 7, (byte) 199, (byte) 49, (byte) 177, (byte) 18, (byte) 16, (byte) 89, (byte) 39, (byte) 128, (byte) 236, (byte) 95, (byte) 96, (byte) 81, (byte) 127, (byte) 169, (byte) 25, (byte) 181, (byte) 74, (byte) 13, (byte) 45, (byte) 229, (byte) 122, (byte) 159, (byte) 147, (byte) 201, (byte) 156, (byte) 239, (byte) 160, (byte) 224, (byte) 59, (byte) 77, (byte) 174, (byte) 42, (byte) 245, (byte) 176, (byte) 200, (byte) 235, (byte) 187, (byte) 60, (byte) 131, (byte) 83, (byte) 153, (byte) 97, (byte) 23, (byte) 43, (byte) 4, (byte) 126, (byte) 186, (byte) 119, (byte) 214, (byte) 38, (byte) 225, (byte) 105, (byte) 20, (byte) 99, (byte) 85, (byte) 33, (byte) 12, (byte) 125, }; // vector used in calculating key schedule (powers of x in GF(256)) private static final int[] rcon = { 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36, 0x6c, 0xd8, 0xab, 0x4d, 0x9a, 0x2f, 0x5e, 0xbc, 0x63, 0xc6, 0x97, 0x35, 0x6a, 0xd4, 0xb3, 0x7d, 0xfa, 0xef, 0xc5, 0x91 }; // precomputation tables of calculations for rounds private static final int[] T0 = { 0xa56363c6, 0x847c7cf8, 0x997777ee, 0x8d7b7bf6, 0x0df2f2ff, 0xbd6b6bd6, 0xb16f6fde, 0x54c5c591, 0x50303060, 0x03010102, 0xa96767ce, 0x7d2b2b56, 0x19fefee7, 0x62d7d7b5, 0xe6abab4d, 0x9a7676ec, 0x45caca8f, 0x9d82821f, 0x40c9c989, 0x877d7dfa, 0x15fafaef, 0xeb5959b2, 0xc947478e, 0x0bf0f0fb, 0xecadad41, 0x67d4d4b3, 0xfda2a25f, 0xeaafaf45, 0xbf9c9c23, 0xf7a4a453, 0x967272e4, 0x5bc0c09b, 0xc2b7b775, 0x1cfdfde1, 0xae93933d, 0x6a26264c, 0x5a36366c, 0x413f3f7e, 0x02f7f7f5, 0x4fcccc83, 0x5c343468, 0xf4a5a551, 0x34e5e5d1, 0x08f1f1f9, 0x937171e2, 0x73d8d8ab, 0x53313162, 0x3f15152a, 0x0c040408, 0x52c7c795, 0x65232346, 0x5ec3c39d, 0x28181830, 0xa1969637, 0x0f05050a, 0xb59a9a2f, 0x0907070e, 0x36121224, 0x9b80801b, 0x3de2e2df, 0x26ebebcd, 0x6927274e, 0xcdb2b27f, 0x9f7575ea, 0x1b090912, 0x9e83831d, 0x742c2c58, 0x2e1a1a34, 0x2d1b1b36, 0xb26e6edc, 0xee5a5ab4, 0xfba0a05b, 0xf65252a4, 0x4d3b3b76, 0x61d6d6b7, 0xceb3b37d, 0x7b292952, 0x3ee3e3dd, 0x712f2f5e, 0x97848413, 0xf55353a6, 0x68d1d1b9, 0x00000000, 0x2cededc1, 0x60202040, 0x1ffcfce3, 0xc8b1b179, 0xed5b5bb6, 0xbe6a6ad4, 0x46cbcb8d, 0xd9bebe67, 0x4b393972, 0xde4a4a94, 0xd44c4c98, 0xe85858b0, 0x4acfcf85, 0x6bd0d0bb, 0x2aefefc5, 0xe5aaaa4f, 0x16fbfbed, 0xc5434386, 0xd74d4d9a, 0x55333366, 0x94858511, 0xcf45458a, 0x10f9f9e9, 0x06020204, 0x817f7ffe, 0xf05050a0, 0x443c3c78, 0xba9f9f25, 0xe3a8a84b, 0xf35151a2, 0xfea3a35d, 0xc0404080, 0x8a8f8f05, 0xad92923f, 0xbc9d9d21, 0x48383870, 0x04f5f5f1, 0xdfbcbc63, 0xc1b6b677, 0x75dadaaf, 0x63212142, 0x30101020, 0x1affffe5, 0x0ef3f3fd, 0x6dd2d2bf, 0x4ccdcd81, 0x140c0c18, 0x35131326, 0x2fececc3, 0xe15f5fbe, 0xa2979735, 0xcc444488, 0x3917172e, 0x57c4c493, 0xf2a7a755, 0x827e7efc, 0x473d3d7a, 0xac6464c8, 0xe75d5dba, 0x2b191932, 0x957373e6, 0xa06060c0, 0x98818119, 0xd14f4f9e, 0x7fdcdca3, 0x66222244, 0x7e2a2a54, 0xab90903b, 0x8388880b, 0xca46468c, 0x29eeeec7, 0xd3b8b86b, 0x3c141428, 0x79dedea7, 0xe25e5ebc, 0x1d0b0b16, 0x76dbdbad, 0x3be0e0db, 0x56323264, 0x4e3a3a74, 0x1e0a0a14, 0xdb494992, 0x0a06060c, 0x6c242448, 0xe45c5cb8, 0x5dc2c29f, 0x6ed3d3bd, 0xefacac43, 0xa66262c4, 0xa8919139, 0xa4959531, 0x37e4e4d3, 0x8b7979f2, 0x32e7e7d5, 0x43c8c88b, 0x5937376e, 0xb76d6dda, 0x8c8d8d01, 0x64d5d5b1, 0xd24e4e9c, 0xe0a9a949, 0xb46c6cd8, 0xfa5656ac, 0x07f4f4f3, 0x25eaeacf, 0xaf6565ca, 0x8e7a7af4, 0xe9aeae47, 0x18080810, 0xd5baba6f, 0x887878f0, 0x6f25254a, 0x722e2e5c, 0x241c1c38, 0xf1a6a657, 0xc7b4b473, 0x51c6c697, 0x23e8e8cb, 0x7cdddda1, 0x9c7474e8, 0x211f1f3e, 0xdd4b4b96, 0xdcbdbd61, 0x868b8b0d, 0x858a8a0f, 0x907070e0, 0x423e3e7c, 0xc4b5b571, 0xaa6666cc, 0xd8484890, 0x05030306, 0x01f6f6f7, 0x120e0e1c, 0xa36161c2, 0x5f35356a, 0xf95757ae, 0xd0b9b969, 0x91868617, 0x58c1c199, 0x271d1d3a, 0xb99e9e27, 0x38e1e1d9, 0x13f8f8eb, 0xb398982b, 0x33111122, 0xbb6969d2, 0x70d9d9a9, 0x898e8e07, 0xa7949433, 0xb69b9b2d, 0x221e1e3c, 0x92878715, 0x20e9e9c9, 0x49cece87, 0xff5555aa, 0x78282850, 0x7adfdfa5, 0x8f8c8c03, 0xf8a1a159, 0x80898909, 0x170d0d1a, 0xdabfbf65, 0x31e6e6d7, 0xc6424284, 0xb86868d0, 0xc3414182, 0xb0999929, 0x772d2d5a, 0x110f0f1e, 0xcbb0b07b, 0xfc5454a8, 0xd6bbbb6d, 0x3a16162c }; private static final int[] T1 = { 0x6363c6a5, 0x7c7cf884, 0x7777ee99, 0x7b7bf68d, 0xf2f2ff0d, 0x6b6bd6bd, 0x6f6fdeb1, 0xc5c59154, 0x30306050, 0x01010203, 0x6767cea9, 0x2b2b567d, 0xfefee719, 0xd7d7b562, 0xabab4de6, 0x7676ec9a, 0xcaca8f45, 0x82821f9d, 0xc9c98940, 0x7d7dfa87, 0xfafaef15, 0x5959b2eb, 0x47478ec9, 0xf0f0fb0b, 0xadad41ec, 0xd4d4b367, 0xa2a25ffd, 0xafaf45ea, 0x9c9c23bf, 0xa4a453f7, 0x7272e496, 0xc0c09b5b, 0xb7b775c2, 0xfdfde11c, 0x93933dae, 0x26264c6a, 0x36366c5a, 0x3f3f7e41, 0xf7f7f502, 0xcccc834f, 0x3434685c, 0xa5a551f4, 0xe5e5d134, 0xf1f1f908, 0x7171e293, 0xd8d8ab73, 0x31316253, 0x15152a3f, 0x0404080c, 0xc7c79552, 0x23234665, 0xc3c39d5e, 0x18183028, 0x969637a1, 0x05050a0f, 0x9a9a2fb5, 0x07070e09, 0x12122436, 0x80801b9b, 0xe2e2df3d, 0xebebcd26, 0x27274e69, 0xb2b27fcd, 0x7575ea9f, 0x0909121b, 0x83831d9e, 0x2c2c5874, 0x1a1a342e, 0x1b1b362d, 0x6e6edcb2, 0x5a5ab4ee, 0xa0a05bfb, 0x5252a4f6, 0x3b3b764d, 0xd6d6b761, 0xb3b37dce, 0x2929527b, 0xe3e3dd3e, 0x2f2f5e71, 0x84841397, 0x5353a6f5, 0xd1d1b968, 0x00000000, 0xededc12c, 0x20204060, 0xfcfce31f, 0xb1b179c8, 0x5b5bb6ed, 0x6a6ad4be, 0xcbcb8d46, 0xbebe67d9, 0x3939724b, 0x4a4a94de, 0x4c4c98d4, 0x5858b0e8, 0xcfcf854a, 0xd0d0bb6b, 0xefefc52a, 0xaaaa4fe5, 0xfbfbed16, 0x434386c5, 0x4d4d9ad7, 0x33336655, 0x85851194, 0x45458acf, 0xf9f9e910, 0x02020406, 0x7f7ffe81, 0x5050a0f0, 0x3c3c7844, 0x9f9f25ba, 0xa8a84be3, 0x5151a2f3, 0xa3a35dfe, 0x404080c0, 0x8f8f058a, 0x92923fad, 0x9d9d21bc, 0x38387048, 0xf5f5f104, 0xbcbc63df, 0xb6b677c1, 0xdadaaf75, 0x21214263, 0x10102030, 0xffffe51a, 0xf3f3fd0e, 0xd2d2bf6d, 0xcdcd814c, 0x0c0c1814, 0x13132635, 0xececc32f, 0x5f5fbee1, 0x979735a2, 0x444488cc, 0x17172e39, 0xc4c49357, 0xa7a755f2, 0x7e7efc82, 0x3d3d7a47, 0x6464c8ac, 0x5d5dbae7, 0x1919322b, 0x7373e695, 0x6060c0a0, 0x81811998, 0x4f4f9ed1, 0xdcdca37f, 0x22224466, 0x2a2a547e, 0x90903bab, 0x88880b83, 0x46468cca, 0xeeeec729, 0xb8b86bd3, 0x1414283c, 0xdedea779, 0x5e5ebce2, 0x0b0b161d, 0xdbdbad76, 0xe0e0db3b, 0x32326456, 0x3a3a744e, 0x0a0a141e, 0x494992db, 0x06060c0a, 0x2424486c, 0x5c5cb8e4, 0xc2c29f5d, 0xd3d3bd6e, 0xacac43ef, 0x6262c4a6, 0x919139a8, 0x959531a4, 0xe4e4d337, 0x7979f28b, 0xe7e7d532, 0xc8c88b43, 0x37376e59, 0x6d6ddab7, 0x8d8d018c, 0xd5d5b164, 0x4e4e9cd2, 0xa9a949e0, 0x6c6cd8b4, 0x5656acfa, 0xf4f4f307, 0xeaeacf25, 0x6565caaf, 0x7a7af48e, 0xaeae47e9, 0x08081018, 0xbaba6fd5, 0x7878f088, 0x25254a6f, 0x2e2e5c72, 0x1c1c3824, 0xa6a657f1, 0xb4b473c7, 0xc6c69751, 0xe8e8cb23, 0xdddda17c, 0x7474e89c, 0x1f1f3e21, 0x4b4b96dd, 0xbdbd61dc, 0x8b8b0d86, 0x8a8a0f85, 0x7070e090, 0x3e3e7c42, 0xb5b571c4, 0x6666ccaa, 0x484890d8, 0x03030605, 0xf6f6f701, 0x0e0e1c12, 0x6161c2a3, 0x35356a5f, 0x5757aef9, 0xb9b969d0, 0x86861791, 0xc1c19958, 0x1d1d3a27, 0x9e9e27b9, 0xe1e1d938, 0xf8f8eb13, 0x98982bb3, 0x11112233, 0x6969d2bb, 0xd9d9a970, 0x8e8e0789, 0x949433a7, 0x9b9b2db6, 0x1e1e3c22, 0x87871592, 0xe9e9c920, 0xcece8749, 0x5555aaff, 0x28285078, 0xdfdfa57a, 0x8c8c038f, 0xa1a159f8, 0x89890980, 0x0d0d1a17, 0xbfbf65da, 0xe6e6d731, 0x424284c6, 0x6868d0b8, 0x414182c3, 0x999929b0, 0x2d2d5a77, 0x0f0f1e11, 0xb0b07bcb, 0x5454a8fc, 0xbbbb6dd6, 0x16162c3a }; private static final int[] T2 = { 0x63c6a563, 0x7cf8847c, 0x77ee9977, 0x7bf68d7b, 0xf2ff0df2, 0x6bd6bd6b, 0x6fdeb16f, 0xc59154c5, 0x30605030, 0x01020301, 0x67cea967, 0x2b567d2b, 0xfee719fe, 0xd7b562d7, 0xab4de6ab, 0x76ec9a76, 0xca8f45ca, 0x821f9d82, 0xc98940c9, 0x7dfa877d, 0xfaef15fa, 0x59b2eb59, 0x478ec947, 0xf0fb0bf0, 0xad41ecad, 0xd4b367d4, 0xa25ffda2, 0xaf45eaaf, 0x9c23bf9c, 0xa453f7a4, 0x72e49672, 0xc09b5bc0, 0xb775c2b7, 0xfde11cfd, 0x933dae93, 0x264c6a26, 0x366c5a36, 0x3f7e413f, 0xf7f502f7, 0xcc834fcc, 0x34685c34, 0xa551f4a5, 0xe5d134e5, 0xf1f908f1, 0x71e29371, 0xd8ab73d8, 0x31625331, 0x152a3f15, 0x04080c04, 0xc79552c7, 0x23466523, 0xc39d5ec3, 0x18302818, 0x9637a196, 0x050a0f05, 0x9a2fb59a, 0x070e0907, 0x12243612, 0x801b9b80, 0xe2df3de2, 0xebcd26eb, 0x274e6927, 0xb27fcdb2, 0x75ea9f75, 0x09121b09, 0x831d9e83, 0x2c58742c, 0x1a342e1a, 0x1b362d1b, 0x6edcb26e, 0x5ab4ee5a, 0xa05bfba0, 0x52a4f652, 0x3b764d3b, 0xd6b761d6, 0xb37dceb3, 0x29527b29, 0xe3dd3ee3, 0x2f5e712f, 0x84139784, 0x53a6f553, 0xd1b968d1, 0x00000000, 0xedc12ced, 0x20406020, 0xfce31ffc, 0xb179c8b1, 0x5bb6ed5b, 0x6ad4be6a, 0xcb8d46cb, 0xbe67d9be, 0x39724b39, 0x4a94de4a, 0x4c98d44c, 0x58b0e858, 0xcf854acf, 0xd0bb6bd0, 0xefc52aef, 0xaa4fe5aa, 0xfbed16fb, 0x4386c543, 0x4d9ad74d, 0x33665533, 0x85119485, 0x458acf45, 0xf9e910f9, 0x02040602, 0x7ffe817f, 0x50a0f050, 0x3c78443c, 0x9f25ba9f, 0xa84be3a8, 0x51a2f351, 0xa35dfea3, 0x4080c040, 0x8f058a8f, 0x923fad92, 0x9d21bc9d, 0x38704838, 0xf5f104f5, 0xbc63dfbc, 0xb677c1b6, 0xdaaf75da, 0x21426321, 0x10203010, 0xffe51aff, 0xf3fd0ef3, 0xd2bf6dd2, 0xcd814ccd, 0x0c18140c, 0x13263513, 0xecc32fec, 0x5fbee15f, 0x9735a297, 0x4488cc44, 0x172e3917, 0xc49357c4, 0xa755f2a7, 0x7efc827e, 0x3d7a473d, 0x64c8ac64, 0x5dbae75d, 0x19322b19, 0x73e69573, 0x60c0a060, 0x81199881, 0x4f9ed14f, 0xdca37fdc, 0x22446622, 0x2a547e2a, 0x903bab90, 0x880b8388, 0x468cca46, 0xeec729ee, 0xb86bd3b8, 0x14283c14, 0xdea779de, 0x5ebce25e, 0x0b161d0b, 0xdbad76db, 0xe0db3be0, 0x32645632, 0x3a744e3a, 0x0a141e0a, 0x4992db49, 0x060c0a06, 0x24486c24, 0x5cb8e45c, 0xc29f5dc2, 0xd3bd6ed3, 0xac43efac, 0x62c4a662, 0x9139a891, 0x9531a495, 0xe4d337e4, 0x79f28b79, 0xe7d532e7, 0xc88b43c8, 0x376e5937, 0x6ddab76d, 0x8d018c8d, 0xd5b164d5, 0x4e9cd24e, 0xa949e0a9, 0x6cd8b46c, 0x56acfa56, 0xf4f307f4, 0xeacf25ea, 0x65caaf65, 0x7af48e7a, 0xae47e9ae, 0x08101808, 0xba6fd5ba, 0x78f08878, 0x254a6f25, 0x2e5c722e, 0x1c38241c, 0xa657f1a6, 0xb473c7b4, 0xc69751c6, 0xe8cb23e8, 0xdda17cdd, 0x74e89c74, 0x1f3e211f, 0x4b96dd4b, 0xbd61dcbd, 0x8b0d868b, 0x8a0f858a, 0x70e09070, 0x3e7c423e, 0xb571c4b5, 0x66ccaa66, 0x4890d848, 0x03060503, 0xf6f701f6, 0x0e1c120e, 0x61c2a361, 0x356a5f35, 0x57aef957, 0xb969d0b9, 0x86179186, 0xc19958c1, 0x1d3a271d, 0x9e27b99e, 0xe1d938e1, 0xf8eb13f8, 0x982bb398, 0x11223311, 0x69d2bb69, 0xd9a970d9, 0x8e07898e, 0x9433a794, 0x9b2db69b, 0x1e3c221e, 0x87159287, 0xe9c920e9, 0xce8749ce, 0x55aaff55, 0x28507828, 0xdfa57adf, 0x8c038f8c, 0xa159f8a1, 0x89098089, 0x0d1a170d, 0xbf65dabf, 0xe6d731e6, 0x4284c642, 0x68d0b868, 0x4182c341, 0x9929b099, 0x2d5a772d, 0x0f1e110f, 0xb07bcbb0, 0x54a8fc54, 0xbb6dd6bb, 0x162c3a16 }; private static final int[] T3 = { 0xc6a56363, 0xf8847c7c, 0xee997777, 0xf68d7b7b, 0xff0df2f2, 0xd6bd6b6b, 0xdeb16f6f, 0x9154c5c5, 0x60503030, 0x02030101, 0xcea96767, 0x567d2b2b, 0xe719fefe, 0xb562d7d7, 0x4de6abab, 0xec9a7676, 0x8f45caca, 0x1f9d8282, 0x8940c9c9, 0xfa877d7d, 0xef15fafa, 0xb2eb5959, 0x8ec94747, 0xfb0bf0f0, 0x41ecadad, 0xb367d4d4, 0x5ffda2a2, 0x45eaafaf, 0x23bf9c9c, 0x53f7a4a4, 0xe4967272, 0x9b5bc0c0, 0x75c2b7b7, 0xe11cfdfd, 0x3dae9393, 0x4c6a2626, 0x6c5a3636, 0x7e413f3f, 0xf502f7f7, 0x834fcccc, 0x685c3434, 0x51f4a5a5, 0xd134e5e5, 0xf908f1f1, 0xe2937171, 0xab73d8d8, 0x62533131, 0x2a3f1515, 0x080c0404, 0x9552c7c7, 0x46652323, 0x9d5ec3c3, 0x30281818, 0x37a19696, 0x0a0f0505, 0x2fb59a9a, 0x0e090707, 0x24361212, 0x1b9b8080, 0xdf3de2e2, 0xcd26ebeb, 0x4e692727, 0x7fcdb2b2, 0xea9f7575, 0x121b0909, 0x1d9e8383, 0x58742c2c, 0x342e1a1a, 0x362d1b1b, 0xdcb26e6e, 0xb4ee5a5a, 0x5bfba0a0, 0xa4f65252, 0x764d3b3b, 0xb761d6d6, 0x7dceb3b3, 0x527b2929, 0xdd3ee3e3, 0x5e712f2f, 0x13978484, 0xa6f55353, 0xb968d1d1, 0x00000000, 0xc12ceded, 0x40602020, 0xe31ffcfc, 0x79c8b1b1, 0xb6ed5b5b, 0xd4be6a6a, 0x8d46cbcb, 0x67d9bebe, 0x724b3939, 0x94de4a4a, 0x98d44c4c, 0xb0e85858, 0x854acfcf, 0xbb6bd0d0, 0xc52aefef, 0x4fe5aaaa, 0xed16fbfb, 0x86c54343, 0x9ad74d4d, 0x66553333, 0x11948585, 0x8acf4545, 0xe910f9f9, 0x04060202, 0xfe817f7f, 0xa0f05050, 0x78443c3c, 0x25ba9f9f, 0x4be3a8a8, 0xa2f35151, 0x5dfea3a3, 0x80c04040, 0x058a8f8f, 0x3fad9292, 0x21bc9d9d, 0x70483838, 0xf104f5f5, 0x63dfbcbc, 0x77c1b6b6, 0xaf75dada, 0x42632121, 0x20301010, 0xe51affff, 0xfd0ef3f3, 0xbf6dd2d2, 0x814ccdcd, 0x18140c0c, 0x26351313, 0xc32fecec, 0xbee15f5f, 0x35a29797, 0x88cc4444, 0x2e391717, 0x9357c4c4, 0x55f2a7a7, 0xfc827e7e, 0x7a473d3d, 0xc8ac6464, 0xbae75d5d, 0x322b1919, 0xe6957373, 0xc0a06060, 0x19988181, 0x9ed14f4f, 0xa37fdcdc, 0x44662222, 0x547e2a2a, 0x3bab9090, 0x0b838888, 0x8cca4646, 0xc729eeee, 0x6bd3b8b8, 0x283c1414, 0xa779dede, 0xbce25e5e, 0x161d0b0b, 0xad76dbdb, 0xdb3be0e0, 0x64563232, 0x744e3a3a, 0x141e0a0a, 0x92db4949, 0x0c0a0606, 0x486c2424, 0xb8e45c5c, 0x9f5dc2c2, 0xbd6ed3d3, 0x43efacac, 0xc4a66262, 0x39a89191, 0x31a49595, 0xd337e4e4, 0xf28b7979, 0xd532e7e7, 0x8b43c8c8, 0x6e593737, 0xdab76d6d, 0x018c8d8d, 0xb164d5d5, 0x9cd24e4e, 0x49e0a9a9, 0xd8b46c6c, 0xacfa5656, 0xf307f4f4, 0xcf25eaea, 0xcaaf6565, 0xf48e7a7a, 0x47e9aeae, 0x10180808, 0x6fd5baba, 0xf0887878, 0x4a6f2525, 0x5c722e2e, 0x38241c1c, 0x57f1a6a6, 0x73c7b4b4, 0x9751c6c6, 0xcb23e8e8, 0xa17cdddd, 0xe89c7474, 0x3e211f1f, 0x96dd4b4b, 0x61dcbdbd, 0x0d868b8b, 0x0f858a8a, 0xe0907070, 0x7c423e3e, 0x71c4b5b5, 0xccaa6666, 0x90d84848, 0x06050303, 0xf701f6f6, 0x1c120e0e, 0xc2a36161, 0x6a5f3535, 0xaef95757, 0x69d0b9b9, 0x17918686, 0x9958c1c1, 0x3a271d1d, 0x27b99e9e, 0xd938e1e1, 0xeb13f8f8, 0x2bb39898, 0x22331111, 0xd2bb6969, 0xa970d9d9, 0x07898e8e, 0x33a79494, 0x2db69b9b, 0x3c221e1e, 0x15928787, 0xc920e9e9, 0x8749cece, 0xaaff5555, 0x50782828, 0xa57adfdf, 0x038f8c8c, 0x59f8a1a1, 0x09808989, 0x1a170d0d, 0x65dabfbf, 0xd731e6e6, 0x84c64242, 0xd0b86868, 0x82c34141, 0x29b09999, 0x5a772d2d, 0x1e110f0f, 0x7bcbb0b0, 0xa8fc5454, 0x6dd6bbbb, 0x2c3a1616 }; private static final int[] Tinv0 = { 0x50a7f451, 0x5365417e, 0xc3a4171a, 0x965e273a, 0xcb6bab3b, 0xf1459d1f, 0xab58faac, 0x9303e34b, 0x55fa3020, 0xf66d76ad, 0x9176cc88, 0x254c02f5, 0xfcd7e54f, 0xd7cb2ac5, 0x80443526, 0x8fa362b5, 0x495ab1de, 0x671bba25, 0x980eea45, 0xe1c0fe5d, 0x02752fc3, 0x12f04c81, 0xa397468d, 0xc6f9d36b, 0xe75f8f03, 0x959c9215, 0xeb7a6dbf, 0xda595295, 0x2d83bed4, 0xd3217458, 0x2969e049, 0x44c8c98e, 0x6a89c275, 0x78798ef4, 0x6b3e5899, 0xdd71b927, 0xb64fe1be, 0x17ad88f0, 0x66ac20c9, 0xb43ace7d, 0x184adf63, 0x82311ae5, 0x60335197, 0x457f5362, 0xe07764b1, 0x84ae6bbb, 0x1ca081fe, 0x942b08f9, 0x58684870, 0x19fd458f, 0x876cde94, 0xb7f87b52, 0x23d373ab, 0xe2024b72, 0x578f1fe3, 0x2aab5566, 0x0728ebb2, 0x03c2b52f, 0x9a7bc586, 0xa50837d3, 0xf2872830, 0xb2a5bf23, 0xba6a0302, 0x5c8216ed, 0x2b1ccf8a, 0x92b479a7, 0xf0f207f3, 0xa1e2694e, 0xcdf4da65, 0xd5be0506, 0x1f6234d1, 0x8afea6c4, 0x9d532e34, 0xa055f3a2, 0x32e18a05, 0x75ebf6a4, 0x39ec830b, 0xaaef6040, 0x069f715e, 0x51106ebd, 0xf98a213e, 0x3d06dd96, 0xae053edd, 0x46bde64d, 0xb58d5491, 0x055dc471, 0x6fd40604, 0xff155060, 0x24fb9819, 0x97e9bdd6, 0xcc434089, 0x779ed967, 0xbd42e8b0, 0x888b8907, 0x385b19e7, 0xdbeec879, 0x470a7ca1, 0xe90f427c, 0xc91e84f8, 0x00000000, 0x83868009, 0x48ed2b32, 0xac70111e, 0x4e725a6c, 0xfbff0efd, 0x5638850f, 0x1ed5ae3d, 0x27392d36, 0x64d90f0a, 0x21a65c68, 0xd1545b9b, 0x3a2e3624, 0xb1670a0c, 0x0fe75793, 0xd296eeb4, 0x9e919b1b, 0x4fc5c080, 0xa220dc61, 0x694b775a, 0x161a121c, 0x0aba93e2, 0xe52aa0c0, 0x43e0223c, 0x1d171b12, 0x0b0d090e, 0xadc78bf2, 0xb9a8b62d, 0xc8a91e14, 0x8519f157, 0x4c0775af, 0xbbdd99ee, 0xfd607fa3, 0x9f2601f7, 0xbcf5725c, 0xc53b6644, 0x347efb5b, 0x7629438b, 0xdcc623cb, 0x68fcedb6, 0x63f1e4b8, 0xcadc31d7, 0x10856342, 0x40229713, 0x2011c684, 0x7d244a85, 0xf83dbbd2, 0x1132f9ae, 0x6da129c7, 0x4b2f9e1d, 0xf330b2dc, 0xec52860d, 0xd0e3c177, 0x6c16b32b, 0x99b970a9, 0xfa489411, 0x2264e947, 0xc48cfca8, 0x1a3ff0a0, 0xd82c7d56, 0xef903322, 0xc74e4987, 0xc1d138d9, 0xfea2ca8c, 0x360bd498, 0xcf81f5a6, 0x28de7aa5, 0x268eb7da, 0xa4bfad3f, 0xe49d3a2c, 0x0d927850, 0x9bcc5f6a, 0x62467e54, 0xc2138df6, 0xe8b8d890, 0x5ef7392e, 0xf5afc382, 0xbe805d9f, 0x7c93d069, 0xa92dd56f, 0xb31225cf, 0x3b99acc8, 0xa77d1810, 0x6e639ce8, 0x7bbb3bdb, 0x097826cd, 0xf418596e, 0x01b79aec, 0xa89a4f83, 0x656e95e6, 0x7ee6ffaa, 0x08cfbc21, 0xe6e815ef, 0xd99be7ba, 0xce366f4a, 0xd4099fea, 0xd67cb029, 0xafb2a431, 0x31233f2a, 0x3094a5c6, 0xc066a235, 0x37bc4e74, 0xa6ca82fc, 0xb0d090e0, 0x15d8a733, 0x4a9804f1, 0xf7daec41, 0x0e50cd7f, 0x2ff69117, 0x8dd64d76, 0x4db0ef43, 0x544daacc, 0xdf0496e4, 0xe3b5d19e, 0x1b886a4c, 0xb81f2cc1, 0x7f516546, 0x04ea5e9d, 0x5d358c01, 0x737487fa, 0x2e410bfb, 0x5a1d67b3, 0x52d2db92, 0x335610e9, 0x1347d66d, 0x8c61d79a, 0x7a0ca137, 0x8e14f859, 0x893c13eb, 0xee27a9ce, 0x35c961b7, 0xede51ce1, 0x3cb1477a, 0x59dfd29c, 0x3f73f255, 0x79ce1418, 0xbf37c773, 0xeacdf753, 0x5baafd5f, 0x146f3ddf, 0x86db4478, 0x81f3afca, 0x3ec468b9, 0x2c342438, 0x5f40a3c2, 0x72c31d16, 0x0c25e2bc, 0x8b493c28, 0x41950dff, 0x7101a839, 0xdeb30c08, 0x9ce4b4d8, 0x90c15664, 0x6184cb7b, 0x70b632d5, 0x745c6c48, 0x4257b8d0 }; private static final int[] Tinv1 = { 0xa7f45150, 0x65417e53, 0xa4171ac3, 0x5e273a96, 0x6bab3bcb, 0x459d1ff1, 0x58faacab, 0x03e34b93, 0xfa302055, 0x6d76adf6, 0x76cc8891, 0x4c02f525, 0xd7e54ffc, 0xcb2ac5d7, 0x44352680, 0xa362b58f, 0x5ab1de49, 0x1bba2567, 0x0eea4598, 0xc0fe5de1, 0x752fc302, 0xf04c8112, 0x97468da3, 0xf9d36bc6, 0x5f8f03e7, 0x9c921595, 0x7a6dbfeb, 0x595295da, 0x83bed42d, 0x217458d3, 0x69e04929, 0xc8c98e44, 0x89c2756a, 0x798ef478, 0x3e58996b, 0x71b927dd, 0x4fe1beb6, 0xad88f017, 0xac20c966, 0x3ace7db4, 0x4adf6318, 0x311ae582, 0x33519760, 0x7f536245, 0x7764b1e0, 0xae6bbb84, 0xa081fe1c, 0x2b08f994, 0x68487058, 0xfd458f19, 0x6cde9487, 0xf87b52b7, 0xd373ab23, 0x024b72e2, 0x8f1fe357, 0xab55662a, 0x28ebb207, 0xc2b52f03, 0x7bc5869a, 0x0837d3a5, 0x872830f2, 0xa5bf23b2, 0x6a0302ba, 0x8216ed5c, 0x1ccf8a2b, 0xb479a792, 0xf207f3f0, 0xe2694ea1, 0xf4da65cd, 0xbe0506d5, 0x6234d11f, 0xfea6c48a, 0x532e349d, 0x55f3a2a0, 0xe18a0532, 0xebf6a475, 0xec830b39, 0xef6040aa, 0x9f715e06, 0x106ebd51, 0x8a213ef9, 0x06dd963d, 0x053eddae, 0xbde64d46, 0x8d5491b5, 0x5dc47105, 0xd406046f, 0x155060ff, 0xfb981924, 0xe9bdd697, 0x434089cc, 0x9ed96777, 0x42e8b0bd, 0x8b890788, 0x5b19e738, 0xeec879db, 0x0a7ca147, 0x0f427ce9, 0x1e84f8c9, 0x00000000, 0x86800983, 0xed2b3248, 0x70111eac, 0x725a6c4e, 0xff0efdfb, 0x38850f56, 0xd5ae3d1e, 0x392d3627, 0xd90f0a64, 0xa65c6821, 0x545b9bd1, 0x2e36243a, 0x670a0cb1, 0xe757930f, 0x96eeb4d2, 0x919b1b9e, 0xc5c0804f, 0x20dc61a2, 0x4b775a69, 0x1a121c16, 0xba93e20a, 0x2aa0c0e5, 0xe0223c43, 0x171b121d, 0x0d090e0b, 0xc78bf2ad, 0xa8b62db9, 0xa91e14c8, 0x19f15785, 0x0775af4c, 0xdd99eebb, 0x607fa3fd, 0x2601f79f, 0xf5725cbc, 0x3b6644c5, 0x7efb5b34, 0x29438b76, 0xc623cbdc, 0xfcedb668, 0xf1e4b863, 0xdc31d7ca, 0x85634210, 0x22971340, 0x11c68420, 0x244a857d, 0x3dbbd2f8, 0x32f9ae11, 0xa129c76d, 0x2f9e1d4b, 0x30b2dcf3, 0x52860dec, 0xe3c177d0, 0x16b32b6c, 0xb970a999, 0x489411fa, 0x64e94722, 0x8cfca8c4, 0x3ff0a01a, 0x2c7d56d8, 0x903322ef, 0x4e4987c7, 0xd138d9c1, 0xa2ca8cfe, 0x0bd49836, 0x81f5a6cf, 0xde7aa528, 0x8eb7da26, 0xbfad3fa4, 0x9d3a2ce4, 0x9278500d, 0xcc5f6a9b, 0x467e5462, 0x138df6c2, 0xb8d890e8, 0xf7392e5e, 0xafc382f5, 0x805d9fbe, 0x93d0697c, 0x2dd56fa9, 0x1225cfb3, 0x99acc83b, 0x7d1810a7, 0x639ce86e, 0xbb3bdb7b, 0x7826cd09, 0x18596ef4, 0xb79aec01, 0x9a4f83a8, 0x6e95e665, 0xe6ffaa7e, 0xcfbc2108, 0xe815efe6, 0x9be7bad9, 0x366f4ace, 0x099fead4, 0x7cb029d6, 0xb2a431af, 0x233f2a31, 0x94a5c630, 0x66a235c0, 0xbc4e7437, 0xca82fca6, 0xd090e0b0, 0xd8a73315, 0x9804f14a, 0xdaec41f7, 0x50cd7f0e, 0xf691172f, 0xd64d768d, 0xb0ef434d, 0x4daacc54, 0x0496e4df, 0xb5d19ee3, 0x886a4c1b, 0x1f2cc1b8, 0x5165467f, 0xea5e9d04, 0x358c015d, 0x7487fa73, 0x410bfb2e, 0x1d67b35a, 0xd2db9252, 0x5610e933, 0x47d66d13, 0x61d79a8c, 0x0ca1377a, 0x14f8598e, 0x3c13eb89, 0x27a9ceee, 0xc961b735, 0xe51ce1ed, 0xb1477a3c, 0xdfd29c59, 0x73f2553f, 0xce141879, 0x37c773bf, 0xcdf753ea, 0xaafd5f5b, 0x6f3ddf14, 0xdb447886, 0xf3afca81, 0xc468b93e, 0x3424382c, 0x40a3c25f, 0xc31d1672, 0x25e2bc0c, 0x493c288b, 0x950dff41, 0x01a83971, 0xb30c08de, 0xe4b4d89c, 0xc1566490, 0x84cb7b61, 0xb632d570, 0x5c6c4874, 0x57b8d042 }; private static final int[] Tinv2 = { 0xf45150a7, 0x417e5365, 0x171ac3a4, 0x273a965e, 0xab3bcb6b, 0x9d1ff145, 0xfaacab58, 0xe34b9303, 0x302055fa, 0x76adf66d, 0xcc889176, 0x02f5254c, 0xe54ffcd7, 0x2ac5d7cb, 0x35268044, 0x62b58fa3, 0xb1de495a, 0xba25671b, 0xea45980e, 0xfe5de1c0, 0x2fc30275, 0x4c8112f0, 0x468da397, 0xd36bc6f9, 0x8f03e75f, 0x9215959c, 0x6dbfeb7a, 0x5295da59, 0xbed42d83, 0x7458d321, 0xe0492969, 0xc98e44c8, 0xc2756a89, 0x8ef47879, 0x58996b3e, 0xb927dd71, 0xe1beb64f, 0x88f017ad, 0x20c966ac, 0xce7db43a, 0xdf63184a, 0x1ae58231, 0x51976033, 0x5362457f, 0x64b1e077, 0x6bbb84ae, 0x81fe1ca0, 0x08f9942b, 0x48705868, 0x458f19fd, 0xde94876c, 0x7b52b7f8, 0x73ab23d3, 0x4b72e202, 0x1fe3578f, 0x55662aab, 0xebb20728, 0xb52f03c2, 0xc5869a7b, 0x37d3a508, 0x2830f287, 0xbf23b2a5, 0x0302ba6a, 0x16ed5c82, 0xcf8a2b1c, 0x79a792b4, 0x07f3f0f2, 0x694ea1e2, 0xda65cdf4, 0x0506d5be, 0x34d11f62, 0xa6c48afe, 0x2e349d53, 0xf3a2a055, 0x8a0532e1, 0xf6a475eb, 0x830b39ec, 0x6040aaef, 0x715e069f, 0x6ebd5110, 0x213ef98a, 0xdd963d06, 0x3eddae05, 0xe64d46bd, 0x5491b58d, 0xc471055d, 0x06046fd4, 0x5060ff15, 0x981924fb, 0xbdd697e9, 0x4089cc43, 0xd967779e, 0xe8b0bd42, 0x8907888b, 0x19e7385b, 0xc879dbee, 0x7ca1470a, 0x427ce90f, 0x84f8c91e, 0x00000000, 0x80098386, 0x2b3248ed, 0x111eac70, 0x5a6c4e72, 0x0efdfbff, 0x850f5638, 0xae3d1ed5, 0x2d362739, 0x0f0a64d9, 0x5c6821a6, 0x5b9bd154, 0x36243a2e, 0x0a0cb167, 0x57930fe7, 0xeeb4d296, 0x9b1b9e91, 0xc0804fc5, 0xdc61a220, 0x775a694b, 0x121c161a, 0x93e20aba, 0xa0c0e52a, 0x223c43e0, 0x1b121d17, 0x090e0b0d, 0x8bf2adc7, 0xb62db9a8, 0x1e14c8a9, 0xf1578519, 0x75af4c07, 0x99eebbdd, 0x7fa3fd60, 0x01f79f26, 0x725cbcf5, 0x6644c53b, 0xfb5b347e, 0x438b7629, 0x23cbdcc6, 0xedb668fc, 0xe4b863f1, 0x31d7cadc, 0x63421085, 0x97134022, 0xc6842011, 0x4a857d24, 0xbbd2f83d, 0xf9ae1132, 0x29c76da1, 0x9e1d4b2f, 0xb2dcf330, 0x860dec52, 0xc177d0e3, 0xb32b6c16, 0x70a999b9, 0x9411fa48, 0xe9472264, 0xfca8c48c, 0xf0a01a3f, 0x7d56d82c, 0x3322ef90, 0x4987c74e, 0x38d9c1d1, 0xca8cfea2, 0xd498360b, 0xf5a6cf81, 0x7aa528de, 0xb7da268e, 0xad3fa4bf, 0x3a2ce49d, 0x78500d92, 0x5f6a9bcc, 0x7e546246, 0x8df6c213, 0xd890e8b8, 0x392e5ef7, 0xc382f5af, 0x5d9fbe80, 0xd0697c93, 0xd56fa92d, 0x25cfb312, 0xacc83b99, 0x1810a77d, 0x9ce86e63, 0x3bdb7bbb, 0x26cd0978, 0x596ef418, 0x9aec01b7, 0x4f83a89a, 0x95e6656e, 0xffaa7ee6, 0xbc2108cf, 0x15efe6e8, 0xe7bad99b, 0x6f4ace36, 0x9fead409, 0xb029d67c, 0xa431afb2, 0x3f2a3123, 0xa5c63094, 0xa235c066, 0x4e7437bc, 0x82fca6ca, 0x90e0b0d0, 0xa73315d8, 0x04f14a98, 0xec41f7da, 0xcd7f0e50, 0x91172ff6, 0x4d768dd6, 0xef434db0, 0xaacc544d, 0x96e4df04, 0xd19ee3b5, 0x6a4c1b88, 0x2cc1b81f, 0x65467f51, 0x5e9d04ea, 0x8c015d35, 0x87fa7374, 0x0bfb2e41, 0x67b35a1d, 0xdb9252d2, 0x10e93356, 0xd66d1347, 0xd79a8c61, 0xa1377a0c, 0xf8598e14, 0x13eb893c, 0xa9ceee27, 0x61b735c9, 0x1ce1ede5, 0x477a3cb1, 0xd29c59df, 0xf2553f73, 0x141879ce, 0xc773bf37, 0xf753eacd, 0xfd5f5baa, 0x3ddf146f, 0x447886db, 0xafca81f3, 0x68b93ec4, 0x24382c34, 0xa3c25f40, 0x1d1672c3, 0xe2bc0c25, 0x3c288b49, 0x0dff4195, 0xa8397101, 0x0c08deb3, 0xb4d89ce4, 0x566490c1, 0xcb7b6184, 0x32d570b6, 0x6c48745c, 0xb8d04257 }; private static final int[] Tinv3 = { 0x5150a7f4, 0x7e536541, 0x1ac3a417, 0x3a965e27, 0x3bcb6bab, 0x1ff1459d, 0xacab58fa, 0x4b9303e3, 0x2055fa30, 0xadf66d76, 0x889176cc, 0xf5254c02, 0x4ffcd7e5, 0xc5d7cb2a, 0x26804435, 0xb58fa362, 0xde495ab1, 0x25671bba, 0x45980eea, 0x5de1c0fe, 0xc302752f, 0x8112f04c, 0x8da39746, 0x6bc6f9d3, 0x03e75f8f, 0x15959c92, 0xbfeb7a6d, 0x95da5952, 0xd42d83be, 0x58d32174, 0x492969e0, 0x8e44c8c9, 0x756a89c2, 0xf478798e, 0x996b3e58, 0x27dd71b9, 0xbeb64fe1, 0xf017ad88, 0xc966ac20, 0x7db43ace, 0x63184adf, 0xe582311a, 0x97603351, 0x62457f53, 0xb1e07764, 0xbb84ae6b, 0xfe1ca081, 0xf9942b08, 0x70586848, 0x8f19fd45, 0x94876cde, 0x52b7f87b, 0xab23d373, 0x72e2024b, 0xe3578f1f, 0x662aab55, 0xb20728eb, 0x2f03c2b5, 0x869a7bc5, 0xd3a50837, 0x30f28728, 0x23b2a5bf, 0x02ba6a03, 0xed5c8216, 0x8a2b1ccf, 0xa792b479, 0xf3f0f207, 0x4ea1e269, 0x65cdf4da, 0x06d5be05, 0xd11f6234, 0xc48afea6, 0x349d532e, 0xa2a055f3, 0x0532e18a, 0xa475ebf6, 0x0b39ec83, 0x40aaef60, 0x5e069f71, 0xbd51106e, 0x3ef98a21, 0x963d06dd, 0xddae053e, 0x4d46bde6, 0x91b58d54, 0x71055dc4, 0x046fd406, 0x60ff1550, 0x1924fb98, 0xd697e9bd, 0x89cc4340, 0x67779ed9, 0xb0bd42e8, 0x07888b89, 0xe7385b19, 0x79dbeec8, 0xa1470a7c, 0x7ce90f42, 0xf8c91e84, 0x00000000, 0x09838680, 0x3248ed2b, 0x1eac7011, 0x6c4e725a, 0xfdfbff0e, 0x0f563885, 0x3d1ed5ae, 0x3627392d, 0x0a64d90f, 0x6821a65c, 0x9bd1545b, 0x243a2e36, 0x0cb1670a, 0x930fe757, 0xb4d296ee, 0x1b9e919b, 0x804fc5c0, 0x61a220dc, 0x5a694b77, 0x1c161a12, 0xe20aba93, 0xc0e52aa0, 0x3c43e022, 0x121d171b, 0x0e0b0d09, 0xf2adc78b, 0x2db9a8b6, 0x14c8a91e, 0x578519f1, 0xaf4c0775, 0xeebbdd99, 0xa3fd607f, 0xf79f2601, 0x5cbcf572, 0x44c53b66, 0x5b347efb, 0x8b762943, 0xcbdcc623, 0xb668fced, 0xb863f1e4, 0xd7cadc31, 0x42108563, 0x13402297, 0x842011c6, 0x857d244a, 0xd2f83dbb, 0xae1132f9, 0xc76da129, 0x1d4b2f9e, 0xdcf330b2, 0x0dec5286, 0x77d0e3c1, 0x2b6c16b3, 0xa999b970, 0x11fa4894, 0x472264e9, 0xa8c48cfc, 0xa01a3ff0, 0x56d82c7d, 0x22ef9033, 0x87c74e49, 0xd9c1d138, 0x8cfea2ca, 0x98360bd4, 0xa6cf81f5, 0xa528de7a, 0xda268eb7, 0x3fa4bfad, 0x2ce49d3a, 0x500d9278, 0x6a9bcc5f, 0x5462467e, 0xf6c2138d, 0x90e8b8d8, 0x2e5ef739, 0x82f5afc3, 0x9fbe805d, 0x697c93d0, 0x6fa92dd5, 0xcfb31225, 0xc83b99ac, 0x10a77d18, 0xe86e639c, 0xdb7bbb3b, 0xcd097826, 0x6ef41859, 0xec01b79a, 0x83a89a4f, 0xe6656e95, 0xaa7ee6ff, 0x2108cfbc, 0xefe6e815, 0xbad99be7, 0x4ace366f, 0xead4099f, 0x29d67cb0, 0x31afb2a4, 0x2a31233f, 0xc63094a5, 0x35c066a2, 0x7437bc4e, 0xfca6ca82, 0xe0b0d090, 0x3315d8a7, 0xf14a9804, 0x41f7daec, 0x7f0e50cd, 0x172ff691, 0x768dd64d, 0x434db0ef, 0xcc544daa, 0xe4df0496, 0x9ee3b5d1, 0x4c1b886a, 0xc1b81f2c, 0x467f5165, 0x9d04ea5e, 0x015d358c, 0xfa737487, 0xfb2e410b, 0xb35a1d67, 0x9252d2db, 0xe9335610, 0x6d1347d6, 0x9a8c61d7, 0x377a0ca1, 0x598e14f8, 0xeb893c13, 0xceee27a9, 0xb735c961, 0xe1ede51c, 0x7a3cb147, 0x9c59dfd2, 0x553f73f2, 0x1879ce14, 0x73bf37c7, 0x53eacdf7, 0x5f5baafd, 0xdf146f3d, 0x7886db44, 0xca81f3af, 0xb93ec468, 0x382c3424, 0xc25f40a3, 0x1672c31d, 0xbc0c25e2, 0x288b493c, 0xff41950d, 0x397101a8, 0x08deb30c, 0xd89ce4b4, 0x6490c156, 0x7b6184cb, 0xd570b632, 0x48745c6c, 0xd04257b8 }; private final int shift(int r, int shift) { return (((r >>> shift) | (r << (32 - shift)))); } /* multiply four bytes in GF(2^8) by 'x' {02} in parallel */ private static final int m1 = 0x80808080; private static final int m2 = 0x7f7f7f7f; private static final int m3 = 0x0000001b; private final int FFmulX(int x) { return (((x & m2) << 1) ^ (((x & m1) >>> 7) * m3)); } /* * The following defines provide alternative definitions of FFmulX that * might give improved performance if a fast 32-bit multiply is not * available. * * private int FFmulX(int x) { int u = x & m1; u |= (u >> 1); return ((x & * m2) < < 1) ^ ((u >>> 3) | (u >>> 6)); } private static final int m4 = * 0x1b1b1b1b; private int FFmulX(int x) { int u = x & m1; return ((x & m2) < < * 1) ^ ((u - (u >>> 7)) & m4); } * */ private final int inv_mcol(int x) { int f2 = FFmulX(x); int f4 = FFmulX(f2); int f8 = FFmulX(f4); int f9 = x ^ f8; return f2 ^ f4 ^ f8 ^ shift(f2 ^ f9, 8) ^ shift(f4 ^ f9, 16) ^ shift(f9, 24); } private final int subWord(int x) { return (S[x & 255] & 255 | ((S[(x >> 8) & 255] & 255) << 8) | ((S[(x >> 16) & 255] & 255) << 16) | S[(x >> 24) & 255] << 24); } /** * Calculate the necessary round keys The number of calculations depends on * key size and block size AES specified a fixed block size of 128 bits and * key sizes 128/192/256 bits This code is written assuming those are the * only possible values */ private final int[][] generateWorkingKey(byte[] key, boolean forEncryption) { int KC = key.length / 4; // key length in words int t; if (((KC != 4) && (KC != 6) && (KC != 8)) || ((KC * 4) != key.length)) { throw new IllegalArgumentException("Key length not 128/192/256 bits."); } ROUNDS = KC + 6; // This is not always true for the generalized // Rijndael that allows larger block sizes int[][] W = new int[ROUNDS + 1][4]; // 4 words in a block // // copy the key into the round key array // t = 0; for (int i = 0; i < key.length; t++) { W[t >> 2][t & 3] = (key[i] & 0xff) | ((key[i + 1] & 0xff) << 8) | ((key[i + 2] & 0xff) << 16) | (key[i + 3] << 24); i += 4; } // // while not enough round key material calculated // calculate new values // int k = (ROUNDS + 1) << 2; for (int i = KC; (i < k); i++) { int temp = W[(i - 1) >> 2][(i - 1) & 3]; if ((i % KC) == 0) { temp = subWord(shift(temp, 8)) ^ rcon[(i / KC) - 1]; } else if ((KC > 6) && ((i % KC) == 4)) { temp = subWord(temp); } W[i >> 2][i & 3] = W[(i - KC) >> 2][(i - KC) & 3] ^ temp; } if (!forEncryption) { for (int j = 1; j < ROUNDS; j++) { for (int i = 0; i < 4; i++) { W[j][i] = inv_mcol(W[j][i]); } } } return W; } private int ROUNDS; private int[][] WorkingKey = null; private int C0, C1, C2, C3; private boolean doEncrypt; private static final int BLOCK_SIZE = 16; /** * default constructor - 128 bit block size. */ public AES() { } /** * initialise an AES cipher. * * @param forEncryption * whether or not we are for encryption. * @param key * the key required to set up the cipher. * @exception IllegalArgumentException * if the params argument is inappropriate. */ public final void init(boolean forEncryption, byte[] key) { WorkingKey = generateWorkingKey(key, forEncryption); this.doEncrypt = forEncryption; } public final String getAlgorithmName() { return "AES"; } public final int getBlockSize() { return BLOCK_SIZE; } public final int processBlock(byte[] in, int inOff, byte[] out, int outOff) { if (WorkingKey == null) { throw new IllegalStateException("AES engine not initialised"); } if ((inOff + (32 / 2)) > in.length) { throw new IllegalArgumentException("input buffer too short"); } if ((outOff + (32 / 2)) > out.length) { throw new IllegalArgumentException("output buffer too short"); } if (doEncrypt) { unpackBlock(in, inOff); encryptBlock(WorkingKey); packBlock(out, outOff); } else { unpackBlock(in, inOff); decryptBlock(WorkingKey); packBlock(out, outOff); } return BLOCK_SIZE; } public final void reset() { } private final void unpackBlock(byte[] bytes, int off) { int index = off; C0 = (bytes[index++] & 0xff); C0 |= (bytes[index++] & 0xff) << 8; C0 |= (bytes[index++] & 0xff) << 16; C0 |= bytes[index++] << 24; C1 = (bytes[index++] & 0xff); C1 |= (bytes[index++] & 0xff) << 8; C1 |= (bytes[index++] & 0xff) << 16; C1 |= bytes[index++] << 24; C2 = (bytes[index++] & 0xff); C2 |= (bytes[index++] & 0xff) << 8; C2 |= (bytes[index++] & 0xff) << 16; C2 |= bytes[index++] << 24; C3 = (bytes[index++] & 0xff); C3 |= (bytes[index++] & 0xff) << 8; C3 |= (bytes[index++] & 0xff) << 16; C3 |= bytes[index++] << 24; } private final void packBlock(byte[] bytes, int off) { int index = off; bytes[index++] = (byte) C0; bytes[index++] = (byte) (C0 >> 8); bytes[index++] = (byte) (C0 >> 16); bytes[index++] = (byte) (C0 >> 24); bytes[index++] = (byte) C1; bytes[index++] = (byte) (C1 >> 8); bytes[index++] = (byte) (C1 >> 16); bytes[index++] = (byte) (C1 >> 24); bytes[index++] = (byte) C2; bytes[index++] = (byte) (C2 >> 8); bytes[index++] = (byte) (C2 >> 16); bytes[index++] = (byte) (C2 >> 24); bytes[index++] = (byte) C3; bytes[index++] = (byte) (C3 >> 8); bytes[index++] = (byte) (C3 >> 16); bytes[index++] = (byte) (C3 >> 24); } private final void encryptBlock(int[][] KW) { int r, r0, r1, r2, r3; C0 ^= KW[0][0]; C1 ^= KW[0][1]; C2 ^= KW[0][2]; C3 ^= KW[0][3]; for (r = 1; r < ROUNDS - 1;) { r0 = T0[C0 & 255] ^ T1[(C1 >> 8) & 255] ^ T2[(C2 >> 16) & 255] ^ T3[(C3 >> 24) & 255] ^ KW[r][0]; r1 = T0[C1 & 255] ^ T1[(C2 >> 8) & 255] ^ T2[(C3 >> 16) & 255] ^ T3[(C0 >> 24) & 255] ^ KW[r][1]; r2 = T0[C2 & 255] ^ T1[(C3 >> 8) & 255] ^ T2[(C0 >> 16) & 255] ^ T3[(C1 >> 24) & 255] ^ KW[r][2]; r3 = T0[C3 & 255] ^ T1[(C0 >> 8) & 255] ^ T2[(C1 >> 16) & 255] ^ T3[(C2 >> 24) & 255] ^ KW[r++][3]; C0 = T0[r0 & 255] ^ T1[(r1 >> 8) & 255] ^ T2[(r2 >> 16) & 255] ^ T3[(r3 >> 24) & 255] ^ KW[r][0]; C1 = T0[r1 & 255] ^ T1[(r2 >> 8) & 255] ^ T2[(r3 >> 16) & 255] ^ T3[(r0 >> 24) & 255] ^ KW[r][1]; C2 = T0[r2 & 255] ^ T1[(r3 >> 8) & 255] ^ T2[(r0 >> 16) & 255] ^ T3[(r1 >> 24) & 255] ^ KW[r][2]; C3 = T0[r3 & 255] ^ T1[(r0 >> 8) & 255] ^ T2[(r1 >> 16) & 255] ^ T3[(r2 >> 24) & 255] ^ KW[r++][3]; } r0 = T0[C0 & 255] ^ T1[(C1 >> 8) & 255] ^ T2[(C2 >> 16) & 255] ^ T3[(C3 >> 24) & 255] ^ KW[r][0]; r1 = T0[C1 & 255] ^ T1[(C2 >> 8) & 255] ^ T2[(C3 >> 16) & 255] ^ T3[(C0 >> 24) & 255] ^ KW[r][1]; r2 = T0[C2 & 255] ^ T1[(C3 >> 8) & 255] ^ T2[(C0 >> 16) & 255] ^ T3[(C1 >> 24) & 255] ^ KW[r][2]; r3 = T0[C3 & 255] ^ T1[(C0 >> 8) & 255] ^ T2[(C1 >> 16) & 255] ^ T3[(C2 >> 24) & 255] ^ KW[r++][3]; // the final round's table is a simple function of S so we don't use a // whole other four tables for it C0 = (S[r0 & 255] & 255) ^ ((S[(r1 >> 8) & 255] & 255) << 8) ^ ((S[(r2 >> 16) & 255] & 255) << 16) ^ (S[(r3 >> 24) & 255] << 24) ^ KW[r][0]; C1 = (S[r1 & 255] & 255) ^ ((S[(r2 >> 8) & 255] & 255) << 8) ^ ((S[(r3 >> 16) & 255] & 255) << 16) ^ (S[(r0 >> 24) & 255] << 24) ^ KW[r][1]; C2 = (S[r2 & 255] & 255) ^ ((S[(r3 >> 8) & 255] & 255) << 8) ^ ((S[(r0 >> 16) & 255] & 255) << 16) ^ (S[(r1 >> 24) & 255] << 24) ^ KW[r][2]; C3 = (S[r3 & 255] & 255) ^ ((S[(r0 >> 8) & 255] & 255) << 8) ^ ((S[(r1 >> 16) & 255] & 255) << 16) ^ (S[(r2 >> 24) & 255] << 24) ^ KW[r][3]; } private final void decryptBlock(int[][] KW) { int r, r0, r1, r2, r3; C0 ^= KW[ROUNDS][0]; C1 ^= KW[ROUNDS][1]; C2 ^= KW[ROUNDS][2]; C3 ^= KW[ROUNDS][3]; for (r = ROUNDS - 1; r > 1;) { r0 = Tinv0[C0 & 255] ^ Tinv1[(C3 >> 8) & 255] ^ Tinv2[(C2 >> 16) & 255] ^ Tinv3[(C1 >> 24) & 255] ^ KW[r][0]; r1 = Tinv0[C1 & 255] ^ Tinv1[(C0 >> 8) & 255] ^ Tinv2[(C3 >> 16) & 255] ^ Tinv3[(C2 >> 24) & 255] ^ KW[r][1]; r2 = Tinv0[C2 & 255] ^ Tinv1[(C1 >> 8) & 255] ^ Tinv2[(C0 >> 16) & 255] ^ Tinv3[(C3 >> 24) & 255] ^ KW[r][2]; r3 = Tinv0[C3 & 255] ^ Tinv1[(C2 >> 8) & 255] ^ Tinv2[(C1 >> 16) & 255] ^ Tinv3[(C0 >> 24) & 255] ^ KW[r--][3]; C0 = Tinv0[r0 & 255] ^ Tinv1[(r3 >> 8) & 255] ^ Tinv2[(r2 >> 16) & 255] ^ Tinv3[(r1 >> 24) & 255] ^ KW[r][0]; C1 = Tinv0[r1 & 255] ^ Tinv1[(r0 >> 8) & 255] ^ Tinv2[(r3 >> 16) & 255] ^ Tinv3[(r2 >> 24) & 255] ^ KW[r][1]; C2 = Tinv0[r2 & 255] ^ Tinv1[(r1 >> 8) & 255] ^ Tinv2[(r0 >> 16) & 255] ^ Tinv3[(r3 >> 24) & 255] ^ KW[r][2]; C3 = Tinv0[r3 & 255] ^ Tinv1[(r2 >> 8) & 255] ^ Tinv2[(r1 >> 16) & 255] ^ Tinv3[(r0 >> 24) & 255] ^ KW[r--][3]; } r0 = Tinv0[C0 & 255] ^ Tinv1[(C3 >> 8) & 255] ^ Tinv2[(C2 >> 16) & 255] ^ Tinv3[(C1 >> 24) & 255] ^ KW[r][0]; r1 = Tinv0[C1 & 255] ^ Tinv1[(C0 >> 8) & 255] ^ Tinv2[(C3 >> 16) & 255] ^ Tinv3[(C2 >> 24) & 255] ^ KW[r][1]; r2 = Tinv0[C2 & 255] ^ Tinv1[(C1 >> 8) & 255] ^ Tinv2[(C0 >> 16) & 255] ^ Tinv3[(C3 >> 24) & 255] ^ KW[r][2]; r3 = Tinv0[C3 & 255] ^ Tinv1[(C2 >> 8) & 255] ^ Tinv2[(C1 >> 16) & 255] ^ Tinv3[(C0 >> 24) & 255] ^ KW[r--][3]; // the final round's table is a simple function of Si so we don't use a // whole other four tables for it C0 = (Si[r0 & 255] & 255) ^ ((Si[(r3 >> 8) & 255] & 255) << 8) ^ ((Si[(r2 >> 16) & 255] & 255) << 16) ^ (Si[(r1 >> 24) & 255] << 24) ^ KW[0][0]; C1 = (Si[r1 & 255] & 255) ^ ((Si[(r0 >> 8) & 255] & 255) << 8) ^ ((Si[(r3 >> 16) & 255] & 255) << 16) ^ (Si[(r2 >> 24) & 255] << 24) ^ KW[0][1]; C2 = (Si[r2 & 255] & 255) ^ ((Si[(r1 >> 8) & 255] & 255) << 8) ^ ((Si[(r0 >> 16) & 255] & 255) << 16) ^ (Si[(r3 >> 24) & 255] << 24) ^ KW[0][2]; C3 = (Si[r3 & 255] & 255) ^ ((Si[(r2 >> 8) & 255] & 255) << 8) ^ ((Si[(r1 >> 16) & 255] & 255) << 16) ^ (Si[(r0 >> 24) & 255] << 24) ^ KW[0][3]; } public void transformBlock(byte[] src, int srcoff, byte[] dst, int dstoff) { processBlock(src, srcoff, dst, dstoff); } }
1030365071-xuechao
src/com/trilead/ssh2/crypto/cipher/AES.java
Java
asf20
45,563
package com.trilead.ssh2.crypto.cipher; import java.io.IOException; import java.io.InputStream; /** * CipherInputStream. * * @author Christian Plattner, plattner@trilead.com * @version $Id: CipherInputStream.java,v 1.1 2007/10/15 12:49:55 cplattne Exp $ */ public class CipherInputStream { BlockCipher currentCipher; InputStream bi; byte[] buffer; byte[] enc; int blockSize; int pos; /* * We cannot use java.io.BufferedInputStream, since that is not available in * J2ME. Everything could be improved alot here. */ final int BUFF_SIZE = 2048; byte[] input_buffer = new byte[BUFF_SIZE]; int input_buffer_pos = 0; int input_buffer_size = 0; public CipherInputStream(BlockCipher tc, InputStream bi) { this.bi = bi; changeCipher(tc); } private int fill_buffer() throws IOException { input_buffer_pos = 0; input_buffer_size = bi.read(input_buffer, 0, BUFF_SIZE); return input_buffer_size; } private int internal_read(byte[] b, int off, int len) throws IOException { if (input_buffer_size < 0) return -1; if (input_buffer_pos >= input_buffer_size) { if (fill_buffer() <= 0) return -1; } int avail = input_buffer_size - input_buffer_pos; int thiscopy = (len > avail) ? avail : len; System.arraycopy(input_buffer, input_buffer_pos, b, off, thiscopy); input_buffer_pos += thiscopy; return thiscopy; } public void changeCipher(BlockCipher bc) { this.currentCipher = bc; blockSize = bc.getBlockSize(); buffer = new byte[blockSize]; enc = new byte[blockSize]; pos = blockSize; } private void getBlock() throws IOException { int n = 0; while (n < blockSize) { int len = internal_read(enc, n, blockSize - n); if (len < 0) throw new IOException("Cannot read full block, EOF reached."); n += len; } try { currentCipher.transformBlock(enc, 0, buffer, 0); } catch (Exception e) { throw new IOException("Error while decrypting block."); } pos = 0; } public int read(byte[] dst) throws IOException { return read(dst, 0, dst.length); } public int read(byte[] dst, int off, int len) throws IOException { int count = 0; while (len > 0) { if (pos >= blockSize) getBlock(); int avail = blockSize - pos; int copy = Math.min(avail, len); System.arraycopy(buffer, pos, dst, off, copy); pos += copy; off += copy; len -= copy; count += copy; } return count; } public int read() throws IOException { if (pos >= blockSize) { getBlock(); } return buffer[pos++] & 0xff; } public int readPlain(byte[] b, int off, int len) throws IOException { if (pos != blockSize) throw new IOException("Cannot read plain since crypto buffer is not aligned."); int n = 0; while (n < len) { int cnt = internal_read(b, off + n, len - n); if (cnt < 0) throw new IOException("Cannot fill buffer, EOF reached."); n += cnt; } return n; } }
1030365071-xuechao
src/com/trilead/ssh2/crypto/cipher/CipherInputStream.java
Java
asf20
3,067
package com.trilead.ssh2.crypto.cipher; /** * CBCMode. * * @author Christian Plattner, plattner@trilead.com * @version $Id: CBCMode.java,v 1.1 2007/10/15 12:49:55 cplattne Exp $ */ public class CBCMode implements BlockCipher { BlockCipher tc; int blockSize; boolean doEncrypt; byte[] cbc_vector; byte[] tmp_vector; public void init(boolean forEncryption, byte[] key) { } public CBCMode(BlockCipher tc, byte[] iv, boolean doEncrypt) throws IllegalArgumentException { this.tc = tc; this.blockSize = tc.getBlockSize(); this.doEncrypt = doEncrypt; if (this.blockSize != iv.length) throw new IllegalArgumentException("IV must be " + blockSize + " bytes long! (currently " + iv.length + ")"); this.cbc_vector = new byte[blockSize]; this.tmp_vector = new byte[blockSize]; System.arraycopy(iv, 0, cbc_vector, 0, blockSize); } public int getBlockSize() { return blockSize; } private void encryptBlock(byte[] src, int srcoff, byte[] dst, int dstoff) { for (int i = 0; i < blockSize; i++) cbc_vector[i] ^= src[srcoff + i]; tc.transformBlock(cbc_vector, 0, dst, dstoff); System.arraycopy(dst, dstoff, cbc_vector, 0, blockSize); } private void decryptBlock(byte[] src, int srcoff, byte[] dst, int dstoff) { /* Assume the worst, src and dst are overlapping... */ System.arraycopy(src, srcoff, tmp_vector, 0, blockSize); tc.transformBlock(src, srcoff, dst, dstoff); for (int i = 0; i < blockSize; i++) dst[dstoff + i] ^= cbc_vector[i]; /* ...that is why we need a tmp buffer. */ byte[] swap = cbc_vector; cbc_vector = tmp_vector; tmp_vector = swap; } public void transformBlock(byte[] src, int srcoff, byte[] dst, int dstoff) { if (doEncrypt) encryptBlock(src, srcoff, dst, dstoff); else decryptBlock(src, srcoff, dst, dstoff); } }
1030365071-xuechao
src/com/trilead/ssh2/crypto/cipher/CBCMode.java
Java
asf20
1,915
package com.trilead.ssh2.crypto.cipher; /* This file is based on the 3DES implementation from the Bouncy Castle Crypto package. Their licence file states the following: Copyright (c) 2000 - 2004 The Legion Of The Bouncy Castle (http://www.bouncycastle.org) Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /** * DES. * * @author See comments in the source file * @version $Id: DES.java,v 1.1 2007/10/15 12:49:55 cplattne Exp $ * */ public class DES implements BlockCipher { private int[] workingKey = null; /** * standard constructor. */ public DES() { } /** * initialise a DES cipher. * * @param encrypting * whether or not we are for encryption. * @param key * the parameters required to set up the cipher. * @exception IllegalArgumentException * if the params argument is inappropriate. */ public void init(boolean encrypting, byte[] key) { this.workingKey = generateWorkingKey(encrypting, key, 0); } public String getAlgorithmName() { return "DES"; } public int getBlockSize() { return 8; } public void transformBlock(byte[] in, int inOff, byte[] out, int outOff) { if (workingKey == null) { throw new IllegalStateException("DES engine not initialised!"); } desFunc(workingKey, in, inOff, out, outOff); } public void reset() { } /** * what follows is mainly taken from "Applied Cryptography", by Bruce * Schneier, however it also bears great resemblance to Richard * Outerbridge's D3DES... */ static short[] Df_Key = { 0x01, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, 0xef, 0xfe, 0xdc, 0xba, 0x98, 0x76, 0x54, 0x32, 0x10, 0x89, 0xab, 0xcd, 0xef, 0x01, 0x23, 0x45, 0x67 }; static short[] bytebit = { 0200, 0100, 040, 020, 010, 04, 02, 01 }; static int[] bigbyte = { 0x800000, 0x400000, 0x200000, 0x100000, 0x80000, 0x40000, 0x20000, 0x10000, 0x8000, 0x4000, 0x2000, 0x1000, 0x800, 0x400, 0x200, 0x100, 0x80, 0x40, 0x20, 0x10, 0x8, 0x4, 0x2, 0x1 }; /* * Use the key schedule specified in the Standard (ANSI X3.92-1981). */ static byte[] pc1 = { 56, 48, 40, 32, 24, 16, 8, 0, 57, 49, 41, 33, 25, 17, 9, 1, 58, 50, 42, 34, 26, 18, 10, 2, 59, 51, 43, 35, 62, 54, 46, 38, 30, 22, 14, 6, 61, 53, 45, 37, 29, 21, 13, 5, 60, 52, 44, 36, 28, 20, 12, 4, 27, 19, 11, 3 }; static byte[] totrot = { 1, 2, 4, 6, 8, 10, 12, 14, 15, 17, 19, 21, 23, 25, 27, 28 }; static byte[] pc2 = { 13, 16, 10, 23, 0, 4, 2, 27, 14, 5, 20, 9, 22, 18, 11, 3, 25, 7, 15, 6, 26, 19, 12, 1, 40, 51, 30, 36, 46, 54, 29, 39, 50, 44, 32, 47, 43, 48, 38, 55, 33, 52, 45, 41, 49, 35, 28, 31 }; static int[] SP1 = { 0x01010400, 0x00000000, 0x00010000, 0x01010404, 0x01010004, 0x00010404, 0x00000004, 0x00010000, 0x00000400, 0x01010400, 0x01010404, 0x00000400, 0x01000404, 0x01010004, 0x01000000, 0x00000004, 0x00000404, 0x01000400, 0x01000400, 0x00010400, 0x00010400, 0x01010000, 0x01010000, 0x01000404, 0x00010004, 0x01000004, 0x01000004, 0x00010004, 0x00000000, 0x00000404, 0x00010404, 0x01000000, 0x00010000, 0x01010404, 0x00000004, 0x01010000, 0x01010400, 0x01000000, 0x01000000, 0x00000400, 0x01010004, 0x00010000, 0x00010400, 0x01000004, 0x00000400, 0x00000004, 0x01000404, 0x00010404, 0x01010404, 0x00010004, 0x01010000, 0x01000404, 0x01000004, 0x00000404, 0x00010404, 0x01010400, 0x00000404, 0x01000400, 0x01000400, 0x00000000, 0x00010004, 0x00010400, 0x00000000, 0x01010004 }; static int[] SP2 = { 0x80108020, 0x80008000, 0x00008000, 0x00108020, 0x00100000, 0x00000020, 0x80100020, 0x80008020, 0x80000020, 0x80108020, 0x80108000, 0x80000000, 0x80008000, 0x00100000, 0x00000020, 0x80100020, 0x00108000, 0x00100020, 0x80008020, 0x00000000, 0x80000000, 0x00008000, 0x00108020, 0x80100000, 0x00100020, 0x80000020, 0x00000000, 0x00108000, 0x00008020, 0x80108000, 0x80100000, 0x00008020, 0x00000000, 0x00108020, 0x80100020, 0x00100000, 0x80008020, 0x80100000, 0x80108000, 0x00008000, 0x80100000, 0x80008000, 0x00000020, 0x80108020, 0x00108020, 0x00000020, 0x00008000, 0x80000000, 0x00008020, 0x80108000, 0x00100000, 0x80000020, 0x00100020, 0x80008020, 0x80000020, 0x00100020, 0x00108000, 0x00000000, 0x80008000, 0x00008020, 0x80000000, 0x80100020, 0x80108020, 0x00108000 }; static int[] SP3 = { 0x00000208, 0x08020200, 0x00000000, 0x08020008, 0x08000200, 0x00000000, 0x00020208, 0x08000200, 0x00020008, 0x08000008, 0x08000008, 0x00020000, 0x08020208, 0x00020008, 0x08020000, 0x00000208, 0x08000000, 0x00000008, 0x08020200, 0x00000200, 0x00020200, 0x08020000, 0x08020008, 0x00020208, 0x08000208, 0x00020200, 0x00020000, 0x08000208, 0x00000008, 0x08020208, 0x00000200, 0x08000000, 0x08020200, 0x08000000, 0x00020008, 0x00000208, 0x00020000, 0x08020200, 0x08000200, 0x00000000, 0x00000200, 0x00020008, 0x08020208, 0x08000200, 0x08000008, 0x00000200, 0x00000000, 0x08020008, 0x08000208, 0x00020000, 0x08000000, 0x08020208, 0x00000008, 0x00020208, 0x00020200, 0x08000008, 0x08020000, 0x08000208, 0x00000208, 0x08020000, 0x00020208, 0x00000008, 0x08020008, 0x00020200 }; static int[] SP4 = { 0x00802001, 0x00002081, 0x00002081, 0x00000080, 0x00802080, 0x00800081, 0x00800001, 0x00002001, 0x00000000, 0x00802000, 0x00802000, 0x00802081, 0x00000081, 0x00000000, 0x00800080, 0x00800001, 0x00000001, 0x00002000, 0x00800000, 0x00802001, 0x00000080, 0x00800000, 0x00002001, 0x00002080, 0x00800081, 0x00000001, 0x00002080, 0x00800080, 0x00002000, 0x00802080, 0x00802081, 0x00000081, 0x00800080, 0x00800001, 0x00802000, 0x00802081, 0x00000081, 0x00000000, 0x00000000, 0x00802000, 0x00002080, 0x00800080, 0x00800081, 0x00000001, 0x00802001, 0x00002081, 0x00002081, 0x00000080, 0x00802081, 0x00000081, 0x00000001, 0x00002000, 0x00800001, 0x00002001, 0x00802080, 0x00800081, 0x00002001, 0x00002080, 0x00800000, 0x00802001, 0x00000080, 0x00800000, 0x00002000, 0x00802080 }; static int[] SP5 = { 0x00000100, 0x02080100, 0x02080000, 0x42000100, 0x00080000, 0x00000100, 0x40000000, 0x02080000, 0x40080100, 0x00080000, 0x02000100, 0x40080100, 0x42000100, 0x42080000, 0x00080100, 0x40000000, 0x02000000, 0x40080000, 0x40080000, 0x00000000, 0x40000100, 0x42080100, 0x42080100, 0x02000100, 0x42080000, 0x40000100, 0x00000000, 0x42000000, 0x02080100, 0x02000000, 0x42000000, 0x00080100, 0x00080000, 0x42000100, 0x00000100, 0x02000000, 0x40000000, 0x02080000, 0x42000100, 0x40080100, 0x02000100, 0x40000000, 0x42080000, 0x02080100, 0x40080100, 0x00000100, 0x02000000, 0x42080000, 0x42080100, 0x00080100, 0x42000000, 0x42080100, 0x02080000, 0x00000000, 0x40080000, 0x42000000, 0x00080100, 0x02000100, 0x40000100, 0x00080000, 0x00000000, 0x40080000, 0x02080100, 0x40000100 }; static int[] SP6 = { 0x20000010, 0x20400000, 0x00004000, 0x20404010, 0x20400000, 0x00000010, 0x20404010, 0x00400000, 0x20004000, 0x00404010, 0x00400000, 0x20000010, 0x00400010, 0x20004000, 0x20000000, 0x00004010, 0x00000000, 0x00400010, 0x20004010, 0x00004000, 0x00404000, 0x20004010, 0x00000010, 0x20400010, 0x20400010, 0x00000000, 0x00404010, 0x20404000, 0x00004010, 0x00404000, 0x20404000, 0x20000000, 0x20004000, 0x00000010, 0x20400010, 0x00404000, 0x20404010, 0x00400000, 0x00004010, 0x20000010, 0x00400000, 0x20004000, 0x20000000, 0x00004010, 0x20000010, 0x20404010, 0x00404000, 0x20400000, 0x00404010, 0x20404000, 0x00000000, 0x20400010, 0x00000010, 0x00004000, 0x20400000, 0x00404010, 0x00004000, 0x00400010, 0x20004010, 0x00000000, 0x20404000, 0x20000000, 0x00400010, 0x20004010 }; static int[] SP7 = { 0x00200000, 0x04200002, 0x04000802, 0x00000000, 0x00000800, 0x04000802, 0x00200802, 0x04200800, 0x04200802, 0x00200000, 0x00000000, 0x04000002, 0x00000002, 0x04000000, 0x04200002, 0x00000802, 0x04000800, 0x00200802, 0x00200002, 0x04000800, 0x04000002, 0x04200000, 0x04200800, 0x00200002, 0x04200000, 0x00000800, 0x00000802, 0x04200802, 0x00200800, 0x00000002, 0x04000000, 0x00200800, 0x04000000, 0x00200800, 0x00200000, 0x04000802, 0x04000802, 0x04200002, 0x04200002, 0x00000002, 0x00200002, 0x04000000, 0x04000800, 0x00200000, 0x04200800, 0x00000802, 0x00200802, 0x04200800, 0x00000802, 0x04000002, 0x04200802, 0x04200000, 0x00200800, 0x00000000, 0x00000002, 0x04200802, 0x00000000, 0x00200802, 0x04200000, 0x00000800, 0x04000002, 0x04000800, 0x00000800, 0x00200002 }; static int[] SP8 = { 0x10001040, 0x00001000, 0x00040000, 0x10041040, 0x10000000, 0x10001040, 0x00000040, 0x10000000, 0x00040040, 0x10040000, 0x10041040, 0x00041000, 0x10041000, 0x00041040, 0x00001000, 0x00000040, 0x10040000, 0x10000040, 0x10001000, 0x00001040, 0x00041000, 0x00040040, 0x10040040, 0x10041000, 0x00001040, 0x00000000, 0x00000000, 0x10040040, 0x10000040, 0x10001000, 0x00041040, 0x00040000, 0x00041040, 0x00040000, 0x10041000, 0x00001000, 0x00000040, 0x10040040, 0x00001000, 0x00041040, 0x10001000, 0x00000040, 0x10000040, 0x10040000, 0x10040040, 0x10000000, 0x00040000, 0x10001040, 0x00000000, 0x10041040, 0x00040040, 0x10000040, 0x10040000, 0x10001000, 0x10001040, 0x00000000, 0x10041040, 0x00041000, 0x00041000, 0x00001040, 0x00001040, 0x00040040, 0x10000000, 0x10041000 }; /** * generate an integer based working key based on our secret key and what we * processing we are planning to do. * * Acknowledgements for this routine go to James Gillogly & Phil Karn. * (whoever, and wherever they are!). */ protected int[] generateWorkingKey(boolean encrypting, byte[] key, int off) { int[] newKey = new int[32]; boolean[] pc1m = new boolean[56], pcr = new boolean[56]; for (int j = 0; j < 56; j++) { int l = pc1[j]; pc1m[j] = ((key[off + (l >>> 3)] & bytebit[l & 07]) != 0); } for (int i = 0; i < 16; i++) { int l, m, n; if (encrypting) { m = i << 1; } else { m = (15 - i) << 1; } n = m + 1; newKey[m] = newKey[n] = 0; for (int j = 0; j < 28; j++) { l = j + totrot[i]; if (l < 28) { pcr[j] = pc1m[l]; } else { pcr[j] = pc1m[l - 28]; } } for (int j = 28; j < 56; j++) { l = j + totrot[i]; if (l < 56) { pcr[j] = pc1m[l]; } else { pcr[j] = pc1m[l - 28]; } } for (int j = 0; j < 24; j++) { if (pcr[pc2[j]]) { newKey[m] |= bigbyte[j]; } if (pcr[pc2[j + 24]]) { newKey[n] |= bigbyte[j]; } } } // // store the processed key // for (int i = 0; i != 32; i += 2) { int i1, i2; i1 = newKey[i]; i2 = newKey[i + 1]; newKey[i] = ((i1 & 0x00fc0000) << 6) | ((i1 & 0x00000fc0) << 10) | ((i2 & 0x00fc0000) >>> 10) | ((i2 & 0x00000fc0) >>> 6); newKey[i + 1] = ((i1 & 0x0003f000) << 12) | ((i1 & 0x0000003f) << 16) | ((i2 & 0x0003f000) >>> 4) | (i2 & 0x0000003f); } return newKey; } /** * the DES engine. */ protected void desFunc(int[] wKey, byte[] in, int inOff, byte[] out, int outOff) { int work, right, left; left = (in[inOff + 0] & 0xff) << 24; left |= (in[inOff + 1] & 0xff) << 16; left |= (in[inOff + 2] & 0xff) << 8; left |= (in[inOff + 3] & 0xff); right = (in[inOff + 4] & 0xff) << 24; right |= (in[inOff + 5] & 0xff) << 16; right |= (in[inOff + 6] & 0xff) << 8; right |= (in[inOff + 7] & 0xff); work = ((left >>> 4) ^ right) & 0x0f0f0f0f; right ^= work; left ^= (work << 4); work = ((left >>> 16) ^ right) & 0x0000ffff; right ^= work; left ^= (work << 16); work = ((right >>> 2) ^ left) & 0x33333333; left ^= work; right ^= (work << 2); work = ((right >>> 8) ^ left) & 0x00ff00ff; left ^= work; right ^= (work << 8); right = ((right << 1) | ((right >>> 31) & 1)) & 0xffffffff; work = (left ^ right) & 0xaaaaaaaa; left ^= work; right ^= work; left = ((left << 1) | ((left >>> 31) & 1)) & 0xffffffff; for (int round = 0; round < 8; round++) { int fval; work = (right << 28) | (right >>> 4); work ^= wKey[round * 4 + 0]; fval = SP7[work & 0x3f]; fval |= SP5[(work >>> 8) & 0x3f]; fval |= SP3[(work >>> 16) & 0x3f]; fval |= SP1[(work >>> 24) & 0x3f]; work = right ^ wKey[round * 4 + 1]; fval |= SP8[work & 0x3f]; fval |= SP6[(work >>> 8) & 0x3f]; fval |= SP4[(work >>> 16) & 0x3f]; fval |= SP2[(work >>> 24) & 0x3f]; left ^= fval; work = (left << 28) | (left >>> 4); work ^= wKey[round * 4 + 2]; fval = SP7[work & 0x3f]; fval |= SP5[(work >>> 8) & 0x3f]; fval |= SP3[(work >>> 16) & 0x3f]; fval |= SP1[(work >>> 24) & 0x3f]; work = left ^ wKey[round * 4 + 3]; fval |= SP8[work & 0x3f]; fval |= SP6[(work >>> 8) & 0x3f]; fval |= SP4[(work >>> 16) & 0x3f]; fval |= SP2[(work >>> 24) & 0x3f]; right ^= fval; } right = (right << 31) | (right >>> 1); work = (left ^ right) & 0xaaaaaaaa; left ^= work; right ^= work; left = (left << 31) | (left >>> 1); work = ((left >>> 8) ^ right) & 0x00ff00ff; right ^= work; left ^= (work << 8); work = ((left >>> 2) ^ right) & 0x33333333; right ^= work; left ^= (work << 2); work = ((right >>> 16) ^ left) & 0x0000ffff; left ^= work; right ^= (work << 16); work = ((right >>> 4) ^ left) & 0x0f0f0f0f; left ^= work; right ^= (work << 4); out[outOff + 0] = (byte) ((right >>> 24) & 0xff); out[outOff + 1] = (byte) ((right >>> 16) & 0xff); out[outOff + 2] = (byte) ((right >>> 8) & 0xff); out[outOff + 3] = (byte) (right & 0xff); out[outOff + 4] = (byte) ((left >>> 24) & 0xff); out[outOff + 5] = (byte) ((left >>> 16) & 0xff); out[outOff + 6] = (byte) ((left >>> 8) & 0xff); out[outOff + 7] = (byte) (left & 0xff); } }
1030365071-xuechao
src/com/trilead/ssh2/crypto/cipher/DES.java
Java
asf20
14,918
package com.trilead.ssh2.crypto.cipher; /** * This is CTR mode as described in draft-ietf-secsh-newmodes-XY.txt * * @author Christian Plattner, plattner@trilead.com * @version $Id: CTRMode.java,v 1.1 2007/10/15 12:49:55 cplattne Exp $ */ public class CTRMode implements BlockCipher { byte[] X; byte[] Xenc; BlockCipher bc; int blockSize; boolean doEncrypt; int count = 0; public void init(boolean forEncryption, byte[] key) { } public CTRMode(BlockCipher tc, byte[] iv, boolean doEnc) throws IllegalArgumentException { bc = tc; blockSize = bc.getBlockSize(); doEncrypt = doEnc; if (blockSize != iv.length) throw new IllegalArgumentException("IV must be " + blockSize + " bytes long! (currently " + iv.length + ")"); X = new byte[blockSize]; Xenc = new byte[blockSize]; System.arraycopy(iv, 0, X, 0, blockSize); } public final int getBlockSize() { return blockSize; } public final void transformBlock(byte[] src, int srcoff, byte[] dst, int dstoff) { bc.transformBlock(X, 0, Xenc, 0); for (int i = 0; i < blockSize; i++) { dst[dstoff + i] = (byte) (src[srcoff + i] ^ Xenc[i]); } for (int i = (blockSize - 1); i >= 0; i--) { X[i]++; if (X[i] != 0) break; } } }
1030365071-xuechao
src/com/trilead/ssh2/crypto/cipher/CTRMode.java
Java
asf20
1,305
package com.trilead.ssh2.crypto.cipher; import java.io.IOException; import java.io.OutputStream; /** * CipherOutputStream. * * @author Christian Plattner, plattner@trilead.com * @version $Id: CipherOutputStream.java,v 1.1 2007/10/15 12:49:55 cplattne Exp $ */ public class CipherOutputStream { BlockCipher currentCipher; OutputStream bo; byte[] buffer; byte[] enc; int blockSize; int pos; /* * We cannot use java.io.BufferedOutputStream, since that is not available * in J2ME. Everything could be improved here alot. */ final int BUFF_SIZE = 2048; byte[] out_buffer = new byte[BUFF_SIZE]; int out_buffer_pos = 0; public CipherOutputStream(BlockCipher tc, OutputStream bo) { this.bo = bo; changeCipher(tc); } private void internal_write(byte[] src, int off, int len) throws IOException { while (len > 0) { int space = BUFF_SIZE - out_buffer_pos; int copy = (len > space) ? space : len; System.arraycopy(src, off, out_buffer, out_buffer_pos, copy); off += copy; out_buffer_pos += copy; len -= copy; if (out_buffer_pos >= BUFF_SIZE) { bo.write(out_buffer, 0, BUFF_SIZE); out_buffer_pos = 0; } } } private void internal_write(int b) throws IOException { out_buffer[out_buffer_pos++] = (byte) b; if (out_buffer_pos >= BUFF_SIZE) { bo.write(out_buffer, 0, BUFF_SIZE); out_buffer_pos = 0; } } public void flush() throws IOException { if (pos != 0) throw new IOException("FATAL: cannot flush since crypto buffer is not aligned."); if (out_buffer_pos > 0) { bo.write(out_buffer, 0, out_buffer_pos); out_buffer_pos = 0; } bo.flush(); } public void changeCipher(BlockCipher bc) { this.currentCipher = bc; blockSize = bc.getBlockSize(); buffer = new byte[blockSize]; enc = new byte[blockSize]; pos = 0; } private void writeBlock() throws IOException { try { currentCipher.transformBlock(buffer, 0, enc, 0); } catch (Exception e) { throw (IOException) new IOException("Error while decrypting block.").initCause(e); } internal_write(enc, 0, blockSize); pos = 0; } public void write(byte[] src, int off, int len) throws IOException { while (len > 0) { int avail = blockSize - pos; int copy = Math.min(avail, len); System.arraycopy(src, off, buffer, pos, copy); pos += copy; off += copy; len -= copy; if (pos >= blockSize) writeBlock(); } } public void write(int b) throws IOException { buffer[pos++] = (byte) b; if (pos >= blockSize) writeBlock(); } public void writePlain(int b) throws IOException { if (pos != 0) throw new IOException("Cannot write plain since crypto buffer is not aligned."); internal_write(b); } public void writePlain(byte[] b, int off, int len) throws IOException { if (pos != 0) throw new IOException("Cannot write plain since crypto buffer is not aligned."); internal_write(b, off, len); } }
1030365071-xuechao
src/com/trilead/ssh2/crypto/cipher/CipherOutputStream.java
Java
asf20
3,080
package com.trilead.ssh2.crypto.cipher; import java.util.Vector; /** * BlockCipherFactory. * * @author Christian Plattner, plattner@trilead.com * @version $Id: BlockCipherFactory.java,v 1.2 2008/04/01 12:38:09 cplattne Exp $ */ public class BlockCipherFactory { static class CipherEntry { String type; int blocksize; int keysize; String cipherClass; public CipherEntry(String type, int blockSize, int keySize, String cipherClass) { this.type = type; this.blocksize = blockSize; this.keysize = keySize; this.cipherClass = cipherClass; } } static Vector<CipherEntry> ciphers = new Vector<CipherEntry>(); static { /* Higher Priority First */ ciphers.addElement(new CipherEntry("aes256-ctr", 16, 32, "com.trilead.ssh2.crypto.cipher.AES")); ciphers.addElement(new CipherEntry("aes192-ctr", 16, 24, "com.trilead.ssh2.crypto.cipher.AES")); ciphers.addElement(new CipherEntry("aes128-ctr", 16, 16, "com.trilead.ssh2.crypto.cipher.AES")); ciphers.addElement(new CipherEntry("blowfish-ctr", 8, 16, "com.trilead.ssh2.crypto.cipher.BlowFish")); ciphers.addElement(new CipherEntry("aes256-cbc", 16, 32, "com.trilead.ssh2.crypto.cipher.AES")); ciphers.addElement(new CipherEntry("aes192-cbc", 16, 24, "com.trilead.ssh2.crypto.cipher.AES")); ciphers.addElement(new CipherEntry("aes128-cbc", 16, 16, "com.trilead.ssh2.crypto.cipher.AES")); ciphers.addElement(new CipherEntry("blowfish-cbc", 8, 16, "com.trilead.ssh2.crypto.cipher.BlowFish")); ciphers.addElement(new CipherEntry("3des-ctr", 8, 24, "com.trilead.ssh2.crypto.cipher.DESede")); ciphers.addElement(new CipherEntry("3des-cbc", 8, 24, "com.trilead.ssh2.crypto.cipher.DESede")); } public static String[] getDefaultCipherList() { String list[] = new String[ciphers.size()]; for (int i = 0; i < ciphers.size(); i++) { CipherEntry ce = ciphers.elementAt(i); list[i] = new String(ce.type); } return list; } public static void checkCipherList(String[] cipherCandidates) { for (int i = 0; i < cipherCandidates.length; i++) getEntry(cipherCandidates[i]); } public static BlockCipher createCipher(String type, boolean encrypt, byte[] key, byte[] iv) { try { CipherEntry ce = getEntry(type); Class cc = Class.forName(ce.cipherClass); BlockCipher bc = (BlockCipher) cc.newInstance(); if (type.endsWith("-cbc")) { bc.init(encrypt, key); return new CBCMode(bc, iv, encrypt); } else if (type.endsWith("-ctr")) { bc.init(true, key); return new CTRMode(bc, iv, encrypt); } throw new IllegalArgumentException("Cannot instantiate " + type); } catch (Exception e) { throw new IllegalArgumentException("Cannot instantiate " + type); } } private static CipherEntry getEntry(String type) { for (int i = 0; i < ciphers.size(); i++) { CipherEntry ce = ciphers.elementAt(i); if (ce.type.equals(type)) return ce; } throw new IllegalArgumentException("Unkown algorithm " + type); } public static int getBlockSize(String type) { CipherEntry ce = getEntry(type); return ce.blocksize; } public static int getKeySize(String type) { CipherEntry ce = getEntry(type); return ce.keysize; } }
1030365071-xuechao
src/com/trilead/ssh2/crypto/cipher/BlockCipherFactory.java
Java
asf20
3,320
package com.trilead.ssh2.crypto.cipher; /** * BlockCipher. * * @author Christian Plattner, plattner@trilead.com * @version $Id: BlockCipher.java,v 1.1 2007/10/15 12:49:55 cplattne Exp $ */ public interface BlockCipher { public void init(boolean forEncryption, byte[] key); public int getBlockSize(); public void transformBlock(byte[] src, int srcoff, byte[] dst, int dstoff); }
1030365071-xuechao
src/com/trilead/ssh2/crypto/cipher/BlockCipher.java
Java
asf20
406
package com.trilead.ssh2.crypto.cipher; /* This file was shamelessly taken (and modified) from the Bouncy Castle Crypto package. Their licence file states the following: Copyright (c) 2000 - 2004 The Legion Of The Bouncy Castle (http://www.bouncycastle.org) Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /** * DESede. * * @author See comments in the source file * @version $Id: DESede.java,v 1.1 2007/10/15 12:49:55 cplattne Exp $ * */ public class DESede extends DES { private int[] key1 = null; private int[] key2 = null; private int[] key3 = null; private boolean encrypt; /** * standard constructor. */ public DESede() { } /** * initialise a DES cipher. * * @param encrypting * whether or not we are for encryption. * @param key * the parameters required to set up the cipher. * @exception IllegalArgumentException * if the params argument is inappropriate. */ public void init(boolean encrypting, byte[] key) { key1 = generateWorkingKey(encrypting, key, 0); key2 = generateWorkingKey(!encrypting, key, 8); key3 = generateWorkingKey(encrypting, key, 16); encrypt = encrypting; } public String getAlgorithmName() { return "DESede"; } public int getBlockSize() { return 8; } public void transformBlock(byte[] in, int inOff, byte[] out, int outOff) { if (key1 == null) { throw new IllegalStateException("DESede engine not initialised!"); } if (encrypt) { desFunc(key1, in, inOff, out, outOff); desFunc(key2, out, outOff, out, outOff); desFunc(key3, out, outOff, out, outOff); } else { desFunc(key3, in, inOff, out, outOff); desFunc(key2, out, outOff, out, outOff); desFunc(key1, out, outOff, out, outOff); } } public void reset() { } }
1030365071-xuechao
src/com/trilead/ssh2/crypto/cipher/DESede.java
Java
asf20
2,900
package com.trilead.ssh2.crypto.cipher; /* This file was shamelessly taken from the Bouncy Castle Crypto package. Their licence file states the following: Copyright (c) 2000 - 2004 The Legion Of The Bouncy Castle (http://www.bouncycastle.org) Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /** * A class that provides Blowfish key encryption operations, such as encoding * data and generating keys. All the algorithms herein are from Applied * Cryptography and implement a simplified cryptography interface. * * @author See comments in the source file * @version $Id: BlowFish.java,v 1.1 2007/10/15 12:49:55 cplattne Exp $ */ public class BlowFish implements BlockCipher { private final static int[] KP = { 0x243F6A88, 0x85A308D3, 0x13198A2E, 0x03707344, 0xA4093822, 0x299F31D0, 0x082EFA98, 0xEC4E6C89, 0x452821E6, 0x38D01377, 0xBE5466CF, 0x34E90C6C, 0xC0AC29B7, 0xC97C50DD, 0x3F84D5B5, 0xB5470917, 0x9216D5D9, 0x8979FB1B }, KS0 = { 0xD1310BA6, 0x98DFB5AC, 0x2FFD72DB, 0xD01ADFB7, 0xB8E1AFED, 0x6A267E96, 0xBA7C9045, 0xF12C7F99, 0x24A19947, 0xB3916CF7, 0x0801F2E2, 0x858EFC16, 0x636920D8, 0x71574E69, 0xA458FEA3, 0xF4933D7E, 0x0D95748F, 0x728EB658, 0x718BCD58, 0x82154AEE, 0x7B54A41D, 0xC25A59B5, 0x9C30D539, 0x2AF26013, 0xC5D1B023, 0x286085F0, 0xCA417918, 0xB8DB38EF, 0x8E79DCB0, 0x603A180E, 0x6C9E0E8B, 0xB01E8A3E, 0xD71577C1, 0xBD314B27, 0x78AF2FDA, 0x55605C60, 0xE65525F3, 0xAA55AB94, 0x57489862, 0x63E81440, 0x55CA396A, 0x2AAB10B6, 0xB4CC5C34, 0x1141E8CE, 0xA15486AF, 0x7C72E993, 0xB3EE1411, 0x636FBC2A, 0x2BA9C55D, 0x741831F6, 0xCE5C3E16, 0x9B87931E, 0xAFD6BA33, 0x6C24CF5C, 0x7A325381, 0x28958677, 0x3B8F4898, 0x6B4BB9AF, 0xC4BFE81B, 0x66282193, 0x61D809CC, 0xFB21A991, 0x487CAC60, 0x5DEC8032, 0xEF845D5D, 0xE98575B1, 0xDC262302, 0xEB651B88, 0x23893E81, 0xD396ACC5, 0x0F6D6FF3, 0x83F44239, 0x2E0B4482, 0xA4842004, 0x69C8F04A, 0x9E1F9B5E, 0x21C66842, 0xF6E96C9A, 0x670C9C61, 0xABD388F0, 0x6A51A0D2, 0xD8542F68, 0x960FA728, 0xAB5133A3, 0x6EEF0B6C, 0x137A3BE4, 0xBA3BF050, 0x7EFB2A98, 0xA1F1651D, 0x39AF0176, 0x66CA593E, 0x82430E88, 0x8CEE8619, 0x456F9FB4, 0x7D84A5C3, 0x3B8B5EBE, 0xE06F75D8, 0x85C12073, 0x401A449F, 0x56C16AA6, 0x4ED3AA62, 0x363F7706, 0x1BFEDF72, 0x429B023D, 0x37D0D724, 0xD00A1248, 0xDB0FEAD3, 0x49F1C09B, 0x075372C9, 0x80991B7B, 0x25D479D8, 0xF6E8DEF7, 0xE3FE501A, 0xB6794C3B, 0x976CE0BD, 0x04C006BA, 0xC1A94FB6, 0x409F60C4, 0x5E5C9EC2, 0x196A2463, 0x68FB6FAF, 0x3E6C53B5, 0x1339B2EB, 0x3B52EC6F, 0x6DFC511F, 0x9B30952C, 0xCC814544, 0xAF5EBD09, 0xBEE3D004, 0xDE334AFD, 0x660F2807, 0x192E4BB3, 0xC0CBA857, 0x45C8740F, 0xD20B5F39, 0xB9D3FBDB, 0x5579C0BD, 0x1A60320A, 0xD6A100C6, 0x402C7279, 0x679F25FE, 0xFB1FA3CC, 0x8EA5E9F8, 0xDB3222F8, 0x3C7516DF, 0xFD616B15, 0x2F501EC8, 0xAD0552AB, 0x323DB5FA, 0xFD238760, 0x53317B48, 0x3E00DF82, 0x9E5C57BB, 0xCA6F8CA0, 0x1A87562E, 0xDF1769DB, 0xD542A8F6, 0x287EFFC3, 0xAC6732C6, 0x8C4F5573, 0x695B27B0, 0xBBCA58C8, 0xE1FFA35D, 0xB8F011A0, 0x10FA3D98, 0xFD2183B8, 0x4AFCB56C, 0x2DD1D35B, 0x9A53E479, 0xB6F84565, 0xD28E49BC, 0x4BFB9790, 0xE1DDF2DA, 0xA4CB7E33, 0x62FB1341, 0xCEE4C6E8, 0xEF20CADA, 0x36774C01, 0xD07E9EFE, 0x2BF11FB4, 0x95DBDA4D, 0xAE909198, 0xEAAD8E71, 0x6B93D5A0, 0xD08ED1D0, 0xAFC725E0, 0x8E3C5B2F, 0x8E7594B7, 0x8FF6E2FB, 0xF2122B64, 0x8888B812, 0x900DF01C, 0x4FAD5EA0, 0x688FC31C, 0xD1CFF191, 0xB3A8C1AD, 0x2F2F2218, 0xBE0E1777, 0xEA752DFE, 0x8B021FA1, 0xE5A0CC0F, 0xB56F74E8, 0x18ACF3D6, 0xCE89E299, 0xB4A84FE0, 0xFD13E0B7, 0x7CC43B81, 0xD2ADA8D9, 0x165FA266, 0x80957705, 0x93CC7314, 0x211A1477, 0xE6AD2065, 0x77B5FA86, 0xC75442F5, 0xFB9D35CF, 0xEBCDAF0C, 0x7B3E89A0, 0xD6411BD3, 0xAE1E7E49, 0x00250E2D, 0x2071B35E, 0x226800BB, 0x57B8E0AF, 0x2464369B, 0xF009B91E, 0x5563911D, 0x59DFA6AA, 0x78C14389, 0xD95A537F, 0x207D5BA2, 0x02E5B9C5, 0x83260376, 0x6295CFA9, 0x11C81968, 0x4E734A41, 0xB3472DCA, 0x7B14A94A, 0x1B510052, 0x9A532915, 0xD60F573F, 0xBC9BC6E4, 0x2B60A476, 0x81E67400, 0x08BA6FB5, 0x571BE91F, 0xF296EC6B, 0x2A0DD915, 0xB6636521, 0xE7B9F9B6, 0xFF34052E, 0xC5855664, 0x53B02D5D, 0xA99F8FA1, 0x08BA4799, 0x6E85076A }, KS1 = { 0x4B7A70E9, 0xB5B32944, 0xDB75092E, 0xC4192623, 0xAD6EA6B0, 0x49A7DF7D, 0x9CEE60B8, 0x8FEDB266, 0xECAA8C71, 0x699A17FF, 0x5664526C, 0xC2B19EE1, 0x193602A5, 0x75094C29, 0xA0591340, 0xE4183A3E, 0x3F54989A, 0x5B429D65, 0x6B8FE4D6, 0x99F73FD6, 0xA1D29C07, 0xEFE830F5, 0x4D2D38E6, 0xF0255DC1, 0x4CDD2086, 0x8470EB26, 0x6382E9C6, 0x021ECC5E, 0x09686B3F, 0x3EBAEFC9, 0x3C971814, 0x6B6A70A1, 0x687F3584, 0x52A0E286, 0xB79C5305, 0xAA500737, 0x3E07841C, 0x7FDEAE5C, 0x8E7D44EC, 0x5716F2B8, 0xB03ADA37, 0xF0500C0D, 0xF01C1F04, 0x0200B3FF, 0xAE0CF51A, 0x3CB574B2, 0x25837A58, 0xDC0921BD, 0xD19113F9, 0x7CA92FF6, 0x94324773, 0x22F54701, 0x3AE5E581, 0x37C2DADC, 0xC8B57634, 0x9AF3DDA7, 0xA9446146, 0x0FD0030E, 0xECC8C73E, 0xA4751E41, 0xE238CD99, 0x3BEA0E2F, 0x3280BBA1, 0x183EB331, 0x4E548B38, 0x4F6DB908, 0x6F420D03, 0xF60A04BF, 0x2CB81290, 0x24977C79, 0x5679B072, 0xBCAF89AF, 0xDE9A771F, 0xD9930810, 0xB38BAE12, 0xDCCF3F2E, 0x5512721F, 0x2E6B7124, 0x501ADDE6, 0x9F84CD87, 0x7A584718, 0x7408DA17, 0xBC9F9ABC, 0xE94B7D8C, 0xEC7AEC3A, 0xDB851DFA, 0x63094366, 0xC464C3D2, 0xEF1C1847, 0x3215D908, 0xDD433B37, 0x24C2BA16, 0x12A14D43, 0x2A65C451, 0x50940002, 0x133AE4DD, 0x71DFF89E, 0x10314E55, 0x81AC77D6, 0x5F11199B, 0x043556F1, 0xD7A3C76B, 0x3C11183B, 0x5924A509, 0xF28FE6ED, 0x97F1FBFA, 0x9EBABF2C, 0x1E153C6E, 0x86E34570, 0xEAE96FB1, 0x860E5E0A, 0x5A3E2AB3, 0x771FE71C, 0x4E3D06FA, 0x2965DCB9, 0x99E71D0F, 0x803E89D6, 0x5266C825, 0x2E4CC978, 0x9C10B36A, 0xC6150EBA, 0x94E2EA78, 0xA5FC3C53, 0x1E0A2DF4, 0xF2F74EA7, 0x361D2B3D, 0x1939260F, 0x19C27960, 0x5223A708, 0xF71312B6, 0xEBADFE6E, 0xEAC31F66, 0xE3BC4595, 0xA67BC883, 0xB17F37D1, 0x018CFF28, 0xC332DDEF, 0xBE6C5AA5, 0x65582185, 0x68AB9802, 0xEECEA50F, 0xDB2F953B, 0x2AEF7DAD, 0x5B6E2F84, 0x1521B628, 0x29076170, 0xECDD4775, 0x619F1510, 0x13CCA830, 0xEB61BD96, 0x0334FE1E, 0xAA0363CF, 0xB5735C90, 0x4C70A239, 0xD59E9E0B, 0xCBAADE14, 0xEECC86BC, 0x60622CA7, 0x9CAB5CAB, 0xB2F3846E, 0x648B1EAF, 0x19BDF0CA, 0xA02369B9, 0x655ABB50, 0x40685A32, 0x3C2AB4B3, 0x319EE9D5, 0xC021B8F7, 0x9B540B19, 0x875FA099, 0x95F7997E, 0x623D7DA8, 0xF837889A, 0x97E32D77, 0x11ED935F, 0x16681281, 0x0E358829, 0xC7E61FD6, 0x96DEDFA1, 0x7858BA99, 0x57F584A5, 0x1B227263, 0x9B83C3FF, 0x1AC24696, 0xCDB30AEB, 0x532E3054, 0x8FD948E4, 0x6DBC3128, 0x58EBF2EF, 0x34C6FFEA, 0xFE28ED61, 0xEE7C3C73, 0x5D4A14D9, 0xE864B7E3, 0x42105D14, 0x203E13E0, 0x45EEE2B6, 0xA3AAABEA, 0xDB6C4F15, 0xFACB4FD0, 0xC742F442, 0xEF6ABBB5, 0x654F3B1D, 0x41CD2105, 0xD81E799E, 0x86854DC7, 0xE44B476A, 0x3D816250, 0xCF62A1F2, 0x5B8D2646, 0xFC8883A0, 0xC1C7B6A3, 0x7F1524C3, 0x69CB7492, 0x47848A0B, 0x5692B285, 0x095BBF00, 0xAD19489D, 0x1462B174, 0x23820E00, 0x58428D2A, 0x0C55F5EA, 0x1DADF43E, 0x233F7061, 0x3372F092, 0x8D937E41, 0xD65FECF1, 0x6C223BDB, 0x7CDE3759, 0xCBEE7460, 0x4085F2A7, 0xCE77326E, 0xA6078084, 0x19F8509E, 0xE8EFD855, 0x61D99735, 0xA969A7AA, 0xC50C06C2, 0x5A04ABFC, 0x800BCADC, 0x9E447A2E, 0xC3453484, 0xFDD56705, 0x0E1E9EC9, 0xDB73DBD3, 0x105588CD, 0x675FDA79, 0xE3674340, 0xC5C43465, 0x713E38D8, 0x3D28F89E, 0xF16DFF20, 0x153E21E7, 0x8FB03D4A, 0xE6E39F2B, 0xDB83ADF7 }, KS2 = { 0xE93D5A68, 0x948140F7, 0xF64C261C, 0x94692934, 0x411520F7, 0x7602D4F7, 0xBCF46B2E, 0xD4A20068, 0xD4082471, 0x3320F46A, 0x43B7D4B7, 0x500061AF, 0x1E39F62E, 0x97244546, 0x14214F74, 0xBF8B8840, 0x4D95FC1D, 0x96B591AF, 0x70F4DDD3, 0x66A02F45, 0xBFBC09EC, 0x03BD9785, 0x7FAC6DD0, 0x31CB8504, 0x96EB27B3, 0x55FD3941, 0xDA2547E6, 0xABCA0A9A, 0x28507825, 0x530429F4, 0x0A2C86DA, 0xE9B66DFB, 0x68DC1462, 0xD7486900, 0x680EC0A4, 0x27A18DEE, 0x4F3FFEA2, 0xE887AD8C, 0xB58CE006, 0x7AF4D6B6, 0xAACE1E7C, 0xD3375FEC, 0xCE78A399, 0x406B2A42, 0x20FE9E35, 0xD9F385B9, 0xEE39D7AB, 0x3B124E8B, 0x1DC9FAF7, 0x4B6D1856, 0x26A36631, 0xEAE397B2, 0x3A6EFA74, 0xDD5B4332, 0x6841E7F7, 0xCA7820FB, 0xFB0AF54E, 0xD8FEB397, 0x454056AC, 0xBA489527, 0x55533A3A, 0x20838D87, 0xFE6BA9B7, 0xD096954B, 0x55A867BC, 0xA1159A58, 0xCCA92963, 0x99E1DB33, 0xA62A4A56, 0x3F3125F9, 0x5EF47E1C, 0x9029317C, 0xFDF8E802, 0x04272F70, 0x80BB155C, 0x05282CE3, 0x95C11548, 0xE4C66D22, 0x48C1133F, 0xC70F86DC, 0x07F9C9EE, 0x41041F0F, 0x404779A4, 0x5D886E17, 0x325F51EB, 0xD59BC0D1, 0xF2BCC18F, 0x41113564, 0x257B7834, 0x602A9C60, 0xDFF8E8A3, 0x1F636C1B, 0x0E12B4C2, 0x02E1329E, 0xAF664FD1, 0xCAD18115, 0x6B2395E0, 0x333E92E1, 0x3B240B62, 0xEEBEB922, 0x85B2A20E, 0xE6BA0D99, 0xDE720C8C, 0x2DA2F728, 0xD0127845, 0x95B794FD, 0x647D0862, 0xE7CCF5F0, 0x5449A36F, 0x877D48FA, 0xC39DFD27, 0xF33E8D1E, 0x0A476341, 0x992EFF74, 0x3A6F6EAB, 0xF4F8FD37, 0xA812DC60, 0xA1EBDDF8, 0x991BE14C, 0xDB6E6B0D, 0xC67B5510, 0x6D672C37, 0x2765D43B, 0xDCD0E804, 0xF1290DC7, 0xCC00FFA3, 0xB5390F92, 0x690FED0B, 0x667B9FFB, 0xCEDB7D9C, 0xA091CF0B, 0xD9155EA3, 0xBB132F88, 0x515BAD24, 0x7B9479BF, 0x763BD6EB, 0x37392EB3, 0xCC115979, 0x8026E297, 0xF42E312D, 0x6842ADA7, 0xC66A2B3B, 0x12754CCC, 0x782EF11C, 0x6A124237, 0xB79251E7, 0x06A1BBE6, 0x4BFB6350, 0x1A6B1018, 0x11CAEDFA, 0x3D25BDD8, 0xE2E1C3C9, 0x44421659, 0x0A121386, 0xD90CEC6E, 0xD5ABEA2A, 0x64AF674E, 0xDA86A85F, 0xBEBFE988, 0x64E4C3FE, 0x9DBC8057, 0xF0F7C086, 0x60787BF8, 0x6003604D, 0xD1FD8346, 0xF6381FB0, 0x7745AE04, 0xD736FCCC, 0x83426B33, 0xF01EAB71, 0xB0804187, 0x3C005E5F, 0x77A057BE, 0xBDE8AE24, 0x55464299, 0xBF582E61, 0x4E58F48F, 0xF2DDFDA2, 0xF474EF38, 0x8789BDC2, 0x5366F9C3, 0xC8B38E74, 0xB475F255, 0x46FCD9B9, 0x7AEB2661, 0x8B1DDF84, 0x846A0E79, 0x915F95E2, 0x466E598E, 0x20B45770, 0x8CD55591, 0xC902DE4C, 0xB90BACE1, 0xBB8205D0, 0x11A86248, 0x7574A99E, 0xB77F19B6, 0xE0A9DC09, 0x662D09A1, 0xC4324633, 0xE85A1F02, 0x09F0BE8C, 0x4A99A025, 0x1D6EFE10, 0x1AB93D1D, 0x0BA5A4DF, 0xA186F20F, 0x2868F169, 0xDCB7DA83, 0x573906FE, 0xA1E2CE9B, 0x4FCD7F52, 0x50115E01, 0xA70683FA, 0xA002B5C4, 0x0DE6D027, 0x9AF88C27, 0x773F8641, 0xC3604C06, 0x61A806B5, 0xF0177A28, 0xC0F586E0, 0x006058AA, 0x30DC7D62, 0x11E69ED7, 0x2338EA63, 0x53C2DD94, 0xC2C21634, 0xBBCBEE56, 0x90BCB6DE, 0xEBFC7DA1, 0xCE591D76, 0x6F05E409, 0x4B7C0188, 0x39720A3D, 0x7C927C24, 0x86E3725F, 0x724D9DB9, 0x1AC15BB4, 0xD39EB8FC, 0xED545578, 0x08FCA5B5, 0xD83D7CD3, 0x4DAD0FC4, 0x1E50EF5E, 0xB161E6F8, 0xA28514D9, 0x6C51133C, 0x6FD5C7E7, 0x56E14EC4, 0x362ABFCE, 0xDDC6C837, 0xD79A3234, 0x92638212, 0x670EFA8E, 0x406000E0 }, KS3 = { 0x3A39CE37, 0xD3FAF5CF, 0xABC27737, 0x5AC52D1B, 0x5CB0679E, 0x4FA33742, 0xD3822740, 0x99BC9BBE, 0xD5118E9D, 0xBF0F7315, 0xD62D1C7E, 0xC700C47B, 0xB78C1B6B, 0x21A19045, 0xB26EB1BE, 0x6A366EB4, 0x5748AB2F, 0xBC946E79, 0xC6A376D2, 0x6549C2C8, 0x530FF8EE, 0x468DDE7D, 0xD5730A1D, 0x4CD04DC6, 0x2939BBDB, 0xA9BA4650, 0xAC9526E8, 0xBE5EE304, 0xA1FAD5F0, 0x6A2D519A, 0x63EF8CE2, 0x9A86EE22, 0xC089C2B8, 0x43242EF6, 0xA51E03AA, 0x9CF2D0A4, 0x83C061BA, 0x9BE96A4D, 0x8FE51550, 0xBA645BD6, 0x2826A2F9, 0xA73A3AE1, 0x4BA99586, 0xEF5562E9, 0xC72FEFD3, 0xF752F7DA, 0x3F046F69, 0x77FA0A59, 0x80E4A915, 0x87B08601, 0x9B09E6AD, 0x3B3EE593, 0xE990FD5A, 0x9E34D797, 0x2CF0B7D9, 0x022B8B51, 0x96D5AC3A, 0x017DA67D, 0xD1CF3ED6, 0x7C7D2D28, 0x1F9F25CF, 0xADF2B89B, 0x5AD6B472, 0x5A88F54C, 0xE029AC71, 0xE019A5E6, 0x47B0ACFD, 0xED93FA9B, 0xE8D3C48D, 0x283B57CC, 0xF8D56629, 0x79132E28, 0x785F0191, 0xED756055, 0xF7960E44, 0xE3D35E8C, 0x15056DD4, 0x88F46DBA, 0x03A16125, 0x0564F0BD, 0xC3EB9E15, 0x3C9057A2, 0x97271AEC, 0xA93A072A, 0x1B3F6D9B, 0x1E6321F5, 0xF59C66FB, 0x26DCF319, 0x7533D928, 0xB155FDF5, 0x03563482, 0x8ABA3CBB, 0x28517711, 0xC20AD9F8, 0xABCC5167, 0xCCAD925F, 0x4DE81751, 0x3830DC8E, 0x379D5862, 0x9320F991, 0xEA7A90C2, 0xFB3E7BCE, 0x5121CE64, 0x774FBE32, 0xA8B6E37E, 0xC3293D46, 0x48DE5369, 0x6413E680, 0xA2AE0810, 0xDD6DB224, 0x69852DFD, 0x09072166, 0xB39A460A, 0x6445C0DD, 0x586CDECF, 0x1C20C8AE, 0x5BBEF7DD, 0x1B588D40, 0xCCD2017F, 0x6BB4E3BB, 0xDDA26A7E, 0x3A59FF45, 0x3E350A44, 0xBCB4CDD5, 0x72EACEA8, 0xFA6484BB, 0x8D6612AE, 0xBF3C6F47, 0xD29BE463, 0x542F5D9E, 0xAEC2771B, 0xF64E6370, 0x740E0D8D, 0xE75B1357, 0xF8721671, 0xAF537D5D, 0x4040CB08, 0x4EB4E2CC, 0x34D2466A, 0x0115AF84, 0xE1B00428, 0x95983A1D, 0x06B89FB4, 0xCE6EA048, 0x6F3F3B82, 0x3520AB82, 0x011A1D4B, 0x277227F8, 0x611560B1, 0xE7933FDC, 0xBB3A792B, 0x344525BD, 0xA08839E1, 0x51CE794B, 0x2F32C9B7, 0xA01FBAC9, 0xE01CC87E, 0xBCC7D1F6, 0xCF0111C3, 0xA1E8AAC7, 0x1A908749, 0xD44FBD9A, 0xD0DADECB, 0xD50ADA38, 0x0339C32A, 0xC6913667, 0x8DF9317C, 0xE0B12B4F, 0xF79E59B7, 0x43F5BB3A, 0xF2D519FF, 0x27D9459C, 0xBF97222C, 0x15E6FC2A, 0x0F91FC71, 0x9B941525, 0xFAE59361, 0xCEB69CEB, 0xC2A86459, 0x12BAA8D1, 0xB6C1075E, 0xE3056A0C, 0x10D25065, 0xCB03A442, 0xE0EC6E0E, 0x1698DB3B, 0x4C98A0BE, 0x3278E964, 0x9F1F9532, 0xE0D392DF, 0xD3A0342B, 0x8971F21E, 0x1B0A7441, 0x4BA3348C, 0xC5BE7120, 0xC37632D8, 0xDF359F8D, 0x9B992F2E, 0xE60B6F47, 0x0FE3F11D, 0xE54CDA54, 0x1EDAD891, 0xCE6279CF, 0xCD3E7E6F, 0x1618B166, 0xFD2C1D05, 0x848FD2C5, 0xF6FB2299, 0xF523F357, 0xA6327623, 0x93A83531, 0x56CCCD02, 0xACF08162, 0x5A75EBB5, 0x6E163697, 0x88D273CC, 0xDE966292, 0x81B949D0, 0x4C50901B, 0x71C65614, 0xE6C6C7BD, 0x327A140A, 0x45E1D006, 0xC3F27B9A, 0xC9AA53FD, 0x62A80F00, 0xBB25BFE2, 0x35BDD2F6, 0x71126905, 0xB2040222, 0xB6CBCF7C, 0xCD769C2B, 0x53113EC0, 0x1640E3D3, 0x38ABBD60, 0x2547ADF0, 0xBA38209C, 0xF746CE76, 0x77AFA1C5, 0x20756060, 0x85CBFE4E, 0x8AE88DD8, 0x7AAAF9B0, 0x4CF9AA7E, 0x1948C25C, 0x02FB8A8C, 0x01C36AE4, 0xD6EBE1F9, 0x90D4F869, 0xA65CDEA0, 0x3F09252D, 0xC208E69F, 0xB74E6132, 0xCE77E25B, 0x578FDFE3, 0x3AC372E6 }; // ==================================== // Useful constants // ==================================== private static final int ROUNDS = 16; private static final int BLOCK_SIZE = 8; // bytes = 64 bits private static final int SBOX_SK = 256; private static final int P_SZ = ROUNDS + 2; private final int[] S0, S1, S2, S3; // the s-boxes private final int[] P; // the p-array private boolean doEncrypt = false; private byte[] workingKey = null; public BlowFish() { S0 = new int[SBOX_SK]; S1 = new int[SBOX_SK]; S2 = new int[SBOX_SK]; S3 = new int[SBOX_SK]; P = new int[P_SZ]; } /** * initialise a Blowfish cipher. * * @param encrypting * whether or not we are for encryption. * @param key * the key required to set up the cipher. * @exception IllegalArgumentException * if the params argument is inappropriate. */ public void init(boolean encrypting, byte[] key) { this.doEncrypt = encrypting; this.workingKey = key; setKey(this.workingKey); } public String getAlgorithmName() { return "Blowfish"; } public final void transformBlock(byte[] in, int inOff, byte[] out, int outOff) { if (workingKey == null) { throw new IllegalStateException("Blowfish not initialised"); } if (doEncrypt) { encryptBlock(in, inOff, out, outOff); } else { decryptBlock(in, inOff, out, outOff); } } public void reset() { } public int getBlockSize() { return BLOCK_SIZE; } // ================================== // Private Implementation // ================================== private int F(int x) { return (((S0[(x >>> 24)] + S1[(x >>> 16) & 0xff]) ^ S2[(x >>> 8) & 0xff]) + S3[x & 0xff]); } /** * apply the encryption cycle to each value pair in the table. */ private void processTable(int xl, int xr, int[] table) { int size = table.length; for (int s = 0; s < size; s += 2) { xl ^= P[0]; for (int i = 1; i < ROUNDS; i += 2) { xr ^= F(xl) ^ P[i]; xl ^= F(xr) ^ P[i + 1]; } xr ^= P[ROUNDS + 1]; table[s] = xr; table[s + 1] = xl; xr = xl; // end of cycle swap xl = table[s]; } } private void setKey(byte[] key) { /* * - comments are from _Applied Crypto_, Schneier, p338 please be * careful comparing the two, AC numbers the arrays from 1, the enclosed * code from 0. * * (1) Initialise the S-boxes and the P-array, with a fixed string This * string contains the hexadecimal digits of pi (3.141...) */ System.arraycopy(KS0, 0, S0, 0, SBOX_SK); System.arraycopy(KS1, 0, S1, 0, SBOX_SK); System.arraycopy(KS2, 0, S2, 0, SBOX_SK); System.arraycopy(KS3, 0, S3, 0, SBOX_SK); System.arraycopy(KP, 0, P, 0, P_SZ); /* * (2) Now, XOR P[0] with the first 32 bits of the key, XOR P[1] with * the second 32-bits of the key, and so on for all bits of the key (up * to P[17]). Repeatedly cycle through the key bits until the entire * P-array has been XOR-ed with the key bits */ int keyLength = key.length; int keyIndex = 0; for (int i = 0; i < P_SZ; i++) { // get the 32 bits of the key, in 4 * 8 bit chunks int data = 0x0000000; for (int j = 0; j < 4; j++) { // create a 32 bit block data = (data << 8) | (key[keyIndex++] & 0xff); // wrap when we get to the end of the key if (keyIndex >= keyLength) { keyIndex = 0; } } // XOR the newly created 32 bit chunk onto the P-array P[i] ^= data; } /* * (3) Encrypt the all-zero string with the Blowfish algorithm, using * the subkeys described in (1) and (2) * * (4) Replace P1 and P2 with the output of step (3) * * (5) Encrypt the output of step(3) using the Blowfish algorithm, with * the modified subkeys. * * (6) Replace P3 and P4 with the output of step (5) * * (7) Continue the process, replacing all elements of the P-array and * then all four S-boxes in order, with the output of the continuously * changing Blowfish algorithm */ processTable(0, 0, P); processTable(P[P_SZ - 2], P[P_SZ - 1], S0); processTable(S0[SBOX_SK - 2], S0[SBOX_SK - 1], S1); processTable(S1[SBOX_SK - 2], S1[SBOX_SK - 1], S2); processTable(S2[SBOX_SK - 2], S2[SBOX_SK - 1], S3); } /** * Encrypt the given input starting at the given offset and place the result * in the provided buffer starting at the given offset. The input will be an * exact multiple of our blocksize. */ private void encryptBlock(byte[] src, int srcIndex, byte[] dst, int dstIndex) { int xl = BytesTo32bits(src, srcIndex); int xr = BytesTo32bits(src, srcIndex + 4); xl ^= P[0]; for (int i = 1; i < ROUNDS; i += 2) { xr ^= F(xl) ^ P[i]; xl ^= F(xr) ^ P[i + 1]; } xr ^= P[ROUNDS + 1]; Bits32ToBytes(xr, dst, dstIndex); Bits32ToBytes(xl, dst, dstIndex + 4); } /** * Decrypt the given input starting at the given offset and place the result * in the provided buffer starting at the given offset. The input will be an * exact multiple of our blocksize. */ private void decryptBlock(byte[] src, int srcIndex, byte[] dst, int dstIndex) { int xl = BytesTo32bits(src, srcIndex); int xr = BytesTo32bits(src, srcIndex + 4); xl ^= P[ROUNDS + 1]; for (int i = ROUNDS; i > 0; i -= 2) { xr ^= F(xl) ^ P[i]; xl ^= F(xr) ^ P[i - 1]; } xr ^= P[0]; Bits32ToBytes(xr, dst, dstIndex); Bits32ToBytes(xl, dst, dstIndex + 4); } private int BytesTo32bits(byte[] b, int i) { return ((b[i] & 0xff) << 24) | ((b[i + 1] & 0xff) << 16) | ((b[i + 2] & 0xff) << 8) | ((b[i + 3] & 0xff)); } private void Bits32ToBytes(int in, byte[] b, int offset) { b[offset + 3] = (byte) in; b[offset + 2] = (byte) (in >> 8); b[offset + 1] = (byte) (in >> 16); b[offset] = (byte) (in >> 24); } }
1030365071-xuechao
src/com/trilead/ssh2/crypto/cipher/BlowFish.java
Java
asf20
20,816
package com.trilead.ssh2.crypto.cipher; /** * NullCipher. * * @author Christian Plattner, plattner@trilead.com * @version $Id: NullCipher.java,v 1.1 2007/10/15 12:49:55 cplattne Exp $ */ public class NullCipher implements BlockCipher { private int blockSize = 8; public NullCipher() { } public NullCipher(int blockSize) { this.blockSize = blockSize; } public void init(boolean forEncryption, byte[] key) { } public int getBlockSize() { return blockSize; } public void transformBlock(byte[] src, int srcoff, byte[] dst, int dstoff) { System.arraycopy(src, srcoff, dst, dstoff, blockSize); } }
1030365071-xuechao
src/com/trilead/ssh2/crypto/cipher/NullCipher.java
Java
asf20
663
package com.trilead.ssh2.crypto.digest; import java.math.BigInteger; /** * HashForSSH2Types. * * @author Christian Plattner, plattner@trilead.com * @version $Id: HashForSSH2Types.java,v 1.1 2007/10/15 12:49:57 cplattne Exp $ */ public class HashForSSH2Types { Digest md; public HashForSSH2Types(Digest md) { this.md = md; } public HashForSSH2Types(String type) { if (type.equals("SHA1")) { md = new SHA1(); } else if (type.equals("MD5")) { md = new MD5(); } else throw new IllegalArgumentException("Unknown algorithm " + type); } public void updateByte(byte b) { /* HACK - to test it with J2ME */ byte[] tmp = new byte[1]; tmp[0] = b; md.update(tmp); } public void updateBytes(byte[] b) { md.update(b); } public void updateUINT32(int v) { md.update((byte) (v >> 24)); md.update((byte) (v >> 16)); md.update((byte) (v >> 8)); md.update((byte) (v)); } public void updateByteString(byte[] b) { updateUINT32(b.length); updateBytes(b); } public void updateBigInt(BigInteger b) { updateByteString(b.toByteArray()); } public void reset() { md.reset(); } public int getDigestLength() { return md.getDigestLength(); } public byte[] getDigest() { byte[] tmp = new byte[md.getDigestLength()]; getDigest(tmp); return tmp; } public void getDigest(byte[] out) { getDigest(out, 0); } public void getDigest(byte[] out, int off) { md.digest(out, off); } }
1030365071-xuechao
src/com/trilead/ssh2/crypto/digest/HashForSSH2Types.java
Java
asf20
1,553
package com.trilead.ssh2.crypto.digest; /** * MAC. * * @author Christian Plattner, plattner@trilead.com * @version $Id: MAC.java,v 1.1 2007/10/15 12:49:57 cplattne Exp $ */ public final class MAC { Digest mac; int size; public final static String[] getMacList() { /* Higher Priority First */ return new String[] { "hmac-sha1-96", "hmac-sha1", "hmac-md5-96", "hmac-md5" }; } public final static void checkMacList(String[] macs) { for (int i = 0; i < macs.length; i++) getKeyLen(macs[i]); } public final static int getKeyLen(String type) { if (type.equals("hmac-sha1")) return 20; if (type.equals("hmac-sha1-96")) return 20; if (type.equals("hmac-md5")) return 16; if (type.equals("hmac-md5-96")) return 16; throw new IllegalArgumentException("Unkown algorithm " + type); } public MAC(String type, byte[] key) { if (type.equals("hmac-sha1")) { mac = new HMAC(new SHA1(), key, 20); } else if (type.equals("hmac-sha1-96")) { mac = new HMAC(new SHA1(), key, 12); } else if (type.equals("hmac-md5")) { mac = new HMAC(new MD5(), key, 16); } else if (type.equals("hmac-md5-96")) { mac = new HMAC(new MD5(), key, 12); } else throw new IllegalArgumentException("Unkown algorithm " + type); size = mac.getDigestLength(); } public final void initMac(int seq) { mac.reset(); mac.update((byte) (seq >> 24)); mac.update((byte) (seq >> 16)); mac.update((byte) (seq >> 8)); mac.update((byte) (seq)); } public final void update(byte[] packetdata, int off, int len) { mac.update(packetdata, off, len); } public final void getMac(byte[] out, int off) { mac.digest(out, off); } public final int size() { return size; } }
1030365071-xuechao
src/com/trilead/ssh2/crypto/digest/MAC.java
Java
asf20
1,822
package com.trilead.ssh2.crypto.digest; /** * HMAC. * * @author Christian Plattner, plattner@trilead.com * @version $Id: HMAC.java,v 1.1 2007/10/15 12:49:57 cplattne Exp $ */ public final class HMAC implements Digest { Digest md; byte[] k_xor_ipad; byte[] k_xor_opad; byte[] tmp; int size; public HMAC(Digest md, byte[] key, int size) { this.md = md; this.size = size; tmp = new byte[md.getDigestLength()]; final int BLOCKSIZE = 64; k_xor_ipad = new byte[BLOCKSIZE]; k_xor_opad = new byte[BLOCKSIZE]; if (key.length > BLOCKSIZE) { md.reset(); md.update(key); md.digest(tmp); key = tmp; } System.arraycopy(key, 0, k_xor_ipad, 0, key.length); System.arraycopy(key, 0, k_xor_opad, 0, key.length); for (int i = 0; i < BLOCKSIZE; i++) { k_xor_ipad[i] ^= 0x36; k_xor_opad[i] ^= 0x5C; } md.update(k_xor_ipad); } public final int getDigestLength() { return size; } public final void update(byte b) { md.update(b); } public final void update(byte[] b) { md.update(b); } public final void update(byte[] b, int off, int len) { md.update(b, off, len); } public final void reset() { md.reset(); md.update(k_xor_ipad); } public final void digest(byte[] out) { digest(out, 0); } public final void digest(byte[] out, int off) { md.digest(tmp); md.update(k_xor_opad); md.update(tmp); md.digest(tmp); System.arraycopy(tmp, 0, out, off, size); md.update(k_xor_ipad); } }
1030365071-xuechao
src/com/trilead/ssh2/crypto/digest/HMAC.java
Java
asf20
1,578
package com.trilead.ssh2.crypto.digest; /** * MD5. Based on the example code in RFC 1321. Optimized (...a little). * * @author Christian Plattner, plattner@trilead.com * @version $Id: MD5.java,v 1.1 2007/10/15 12:49:57 cplattne Exp $ */ /* * The following disclaimer has been copied from RFC 1321: * * Copyright (C) 1991-2, RSA Data Security, Inc. Created 1991. All rights * reserved. * * License to copy and use this software is granted provided that it is * identified as the "RSA Data Security, Inc. MD5 Message-Digest Algorithm" in * all material mentioning or referencing this software or this function. * * License is also granted to make and use derivative works provided that such * works are identified as "derived from the RSA Data Security, Inc. MD5 * Message-Digest Algorithm" in all material mentioning or referencing the * derived work. * * RSA Data Security, Inc. makes no representations concerning either the * merchantability of this software or the suitability of this software for any * particular purpose. It is provided "as is" without express or implied * warranty of any kind. * * These notices must be retained in any copies of any part of this * documentation and/or software. * */ public final class MD5 implements Digest { private int state0, state1, state2, state3; private long count; private final byte[] block = new byte[64]; private final int x[] = new int[16]; private static final byte[] padding = new byte[] { (byte) 128, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; public MD5() { reset(); } private static final int FF(int a, int b, int c, int d, int x, int s, int ac) { a += ((b & c) | ((~b) & d)) + x + ac; return ((a << s) | (a >>> (32 - s))) + b; } private static final int GG(int a, int b, int c, int d, int x, int s, int ac) { a += ((b & d) | (c & (~d))) + x + ac; return ((a << s) | (a >>> (32 - s))) + b; } private static final int HH(int a, int b, int c, int d, int x, int s, int ac) { a += (b ^ c ^ d) + x + ac; return ((a << s) | (a >>> (32 - s))) + b; } private static final int II(int a, int b, int c, int d, int x, int s, int ac) { a += (c ^ (b | (~d))) + x + ac; return ((a << s) | (a >>> (32 - s))) + b; } private static final void encode(byte[] dst, int dstoff, int word) { dst[dstoff] = (byte) (word); dst[dstoff + 1] = (byte) (word >> 8); dst[dstoff + 2] = (byte) (word >> 16); dst[dstoff + 3] = (byte) (word >> 24); } private final void transform(byte[] src, int pos) { int a = state0; int b = state1; int c = state2; int d = state3; for (int i = 0; i < 16; i++, pos += 4) { x[i] = (src[pos] & 0xff) | ((src[pos + 1] & 0xff) << 8) | ((src[pos + 2] & 0xff) << 16) | ((src[pos + 3] & 0xff) << 24); } /* Round 1 */ a = FF(a, b, c, d, x[0], 7, 0xd76aa478); /* 1 */ d = FF(d, a, b, c, x[1], 12, 0xe8c7b756); /* 2 */ c = FF(c, d, a, b, x[2], 17, 0x242070db); /* 3 */ b = FF(b, c, d, a, x[3], 22, 0xc1bdceee); /* 4 */ a = FF(a, b, c, d, x[4], 7, 0xf57c0faf); /* 5 */ d = FF(d, a, b, c, x[5], 12, 0x4787c62a); /* 6 */ c = FF(c, d, a, b, x[6], 17, 0xa8304613); /* 7 */ b = FF(b, c, d, a, x[7], 22, 0xfd469501); /* 8 */ a = FF(a, b, c, d, x[8], 7, 0x698098d8); /* 9 */ d = FF(d, a, b, c, x[9], 12, 0x8b44f7af); /* 10 */ c = FF(c, d, a, b, x[10], 17, 0xffff5bb1); /* 11 */ b = FF(b, c, d, a, x[11], 22, 0x895cd7be); /* 12 */ a = FF(a, b, c, d, x[12], 7, 0x6b901122); /* 13 */ d = FF(d, a, b, c, x[13], 12, 0xfd987193); /* 14 */ c = FF(c, d, a, b, x[14], 17, 0xa679438e); /* 15 */ b = FF(b, c, d, a, x[15], 22, 0x49b40821); /* 16 */ /* Round 2 */ a = GG(a, b, c, d, x[1], 5, 0xf61e2562); /* 17 */ d = GG(d, a, b, c, x[6], 9, 0xc040b340); /* 18 */ c = GG(c, d, a, b, x[11], 14, 0x265e5a51); /* 19 */ b = GG(b, c, d, a, x[0], 20, 0xe9b6c7aa); /* 20 */ a = GG(a, b, c, d, x[5], 5, 0xd62f105d); /* 21 */ d = GG(d, a, b, c, x[10], 9, 0x2441453); /* 22 */ c = GG(c, d, a, b, x[15], 14, 0xd8a1e681); /* 23 */ b = GG(b, c, d, a, x[4], 20, 0xe7d3fbc8); /* 24 */ a = GG(a, b, c, d, x[9], 5, 0x21e1cde6); /* 25 */ d = GG(d, a, b, c, x[14], 9, 0xc33707d6); /* 26 */ c = GG(c, d, a, b, x[3], 14, 0xf4d50d87); /* 27 */ b = GG(b, c, d, a, x[8], 20, 0x455a14ed); /* 28 */ a = GG(a, b, c, d, x[13], 5, 0xa9e3e905); /* 29 */ d = GG(d, a, b, c, x[2], 9, 0xfcefa3f8); /* 30 */ c = GG(c, d, a, b, x[7], 14, 0x676f02d9); /* 31 */ b = GG(b, c, d, a, x[12], 20, 0x8d2a4c8a); /* 32 */ /* Round 3 */ a = HH(a, b, c, d, x[5], 4, 0xfffa3942); /* 33 */ d = HH(d, a, b, c, x[8], 11, 0x8771f681); /* 34 */ c = HH(c, d, a, b, x[11], 16, 0x6d9d6122); /* 35 */ b = HH(b, c, d, a, x[14], 23, 0xfde5380c); /* 36 */ a = HH(a, b, c, d, x[1], 4, 0xa4beea44); /* 37 */ d = HH(d, a, b, c, x[4], 11, 0x4bdecfa9); /* 38 */ c = HH(c, d, a, b, x[7], 16, 0xf6bb4b60); /* 39 */ b = HH(b, c, d, a, x[10], 23, 0xbebfbc70); /* 40 */ a = HH(a, b, c, d, x[13], 4, 0x289b7ec6); /* 41 */ d = HH(d, a, b, c, x[0], 11, 0xeaa127fa); /* 42 */ c = HH(c, d, a, b, x[3], 16, 0xd4ef3085); /* 43 */ b = HH(b, c, d, a, x[6], 23, 0x4881d05); /* 44 */ a = HH(a, b, c, d, x[9], 4, 0xd9d4d039); /* 45 */ d = HH(d, a, b, c, x[12], 11, 0xe6db99e5); /* 46 */ c = HH(c, d, a, b, x[15], 16, 0x1fa27cf8); /* 47 */ b = HH(b, c, d, a, x[2], 23, 0xc4ac5665); /* 48 */ /* Round 4 */ a = II(a, b, c, d, x[0], 6, 0xf4292244); /* 49 */ d = II(d, a, b, c, x[7], 10, 0x432aff97); /* 50 */ c = II(c, d, a, b, x[14], 15, 0xab9423a7); /* 51 */ b = II(b, c, d, a, x[5], 21, 0xfc93a039); /* 52 */ a = II(a, b, c, d, x[12], 6, 0x655b59c3); /* 53 */ d = II(d, a, b, c, x[3], 10, 0x8f0ccc92); /* 54 */ c = II(c, d, a, b, x[10], 15, 0xffeff47d); /* 55 */ b = II(b, c, d, a, x[1], 21, 0x85845dd1); /* 56 */ a = II(a, b, c, d, x[8], 6, 0x6fa87e4f); /* 57 */ d = II(d, a, b, c, x[15], 10, 0xfe2ce6e0); /* 58 */ c = II(c, d, a, b, x[6], 15, 0xa3014314); /* 59 */ b = II(b, c, d, a, x[13], 21, 0x4e0811a1); /* 60 */ a = II(a, b, c, d, x[4], 6, 0xf7537e82); /* 61 */ d = II(d, a, b, c, x[11], 10, 0xbd3af235); /* 62 */ c = II(c, d, a, b, x[2], 15, 0x2ad7d2bb); /* 63 */ b = II(b, c, d, a, x[9], 21, 0xeb86d391); /* 64 */ state0 += a; state1 += b; state2 += c; state3 += d; } public final void reset() { count = 0; state0 = 0x67452301; state1 = 0xefcdab89; state2 = 0x98badcfe; state3 = 0x10325476; /* Clear traces in memory... */ for (int i = 0; i < 16; i++) x[i] = 0; } public final void update(byte b) { final int space = 64 - ((int) (count & 0x3f)); count++; block[64 - space] = b; if (space == 1) transform(block, 0); } public final void update(byte[] buff, int pos, int len) { int space = 64 - ((int) (count & 0x3f)); count += len; while (len > 0) { if (len < space) { System.arraycopy(buff, pos, block, 64 - space, len); break; } if (space == 64) { transform(buff, pos); } else { System.arraycopy(buff, pos, block, 64 - space, space); transform(block, 0); } pos += space; len -= space; space = 64; } } public final void update(byte[] b) { update(b, 0, b.length); } public final void digest(byte[] dst, int pos) { byte[] bits = new byte[8]; encode(bits, 0, (int) (count << 3)); encode(bits, 4, (int) (count >> 29)); int idx = (int) count & 0x3f; int padLen = (idx < 56) ? (56 - idx) : (120 - idx); update(padding, 0, padLen); update(bits, 0, 8); encode(dst, pos, state0); encode(dst, pos + 4, state1); encode(dst, pos + 8, state2); encode(dst, pos + 12, state3); reset(); } public final void digest(byte[] dst) { digest(dst, 0); } public final int getDigestLength() { return 16; } }
1030365071-xuechao
src/com/trilead/ssh2/crypto/digest/MD5.java
Java
asf20
8,195
package com.trilead.ssh2.crypto.digest; /** * SHA-1 implementation based on FIPS PUB 180-1. * Highly optimized. * <p> * (http://www.itl.nist.gov/fipspubs/fip180-1.htm) * * @author Christian Plattner, plattner@trilead.com * @version $Id: SHA1.java,v 1.1 2007/10/15 12:49:57 cplattne Exp $ */ public final class SHA1 implements Digest { private int H0, H1, H2, H3, H4; private final int[] w = new int[80]; private int currentPos; private long currentLen; public SHA1() { reset(); } public final int getDigestLength() { return 20; } public final void reset() { H0 = 0x67452301; H1 = 0xEFCDAB89; H2 = 0x98BADCFE; H3 = 0x10325476; H4 = 0xC3D2E1F0; currentPos = 0; currentLen = 0; /* In case of complete paranoia, we should also wipe out the * information contained in the w[] array */ } public final void update(byte b[]) { update(b, 0, b.length); } public final void update(byte b[], int off, int len) { if (len >= 4) { int idx = currentPos >> 2; switch (currentPos & 3) { case 0: w[idx] = (((b[off++] & 0xff) << 24) | ((b[off++] & 0xff) << 16) | ((b[off++] & 0xff) << 8) | (b[off++] & 0xff)); len -= 4; currentPos += 4; currentLen += 32; if (currentPos == 64) { perform(); currentPos = 0; } break; case 1: w[idx] = (w[idx] << 24) | (((b[off++] & 0xff) << 16) | ((b[off++] & 0xff) << 8) | (b[off++] & 0xff)); len -= 3; currentPos += 3; currentLen += 24; if (currentPos == 64) { perform(); currentPos = 0; } break; case 2: w[idx] = (w[idx] << 16) | (((b[off++] & 0xff) << 8) | (b[off++] & 0xff)); len -= 2; currentPos += 2; currentLen += 16; if (currentPos == 64) { perform(); currentPos = 0; } break; case 3: w[idx] = (w[idx] << 8) | (b[off++] & 0xff); len--; currentPos++; currentLen += 8; if (currentPos == 64) { perform(); currentPos = 0; } break; } /* Now currentPos is a multiple of 4 - this is the place to be...*/ while (len >= 8) { w[currentPos >> 2] = ((b[off++] & 0xff) << 24) | ((b[off++] & 0xff) << 16) | ((b[off++] & 0xff) << 8) | (b[off++] & 0xff); currentPos += 4; if (currentPos == 64) { perform(); currentPos = 0; } w[currentPos >> 2] = ((b[off++] & 0xff) << 24) | ((b[off++] & 0xff) << 16) | ((b[off++] & 0xff) << 8) | (b[off++] & 0xff); currentPos += 4; if (currentPos == 64) { perform(); currentPos = 0; } currentLen += 64; len -= 8; } while (len < 0) //(len >= 4) { w[currentPos >> 2] = ((b[off++] & 0xff) << 24) | ((b[off++] & 0xff) << 16) | ((b[off++] & 0xff) << 8) | (b[off++] & 0xff); len -= 4; currentPos += 4; currentLen += 32; if (currentPos == 64) { perform(); currentPos = 0; } } } /* Remaining bytes (1-3) */ while (len > 0) { /* Here is room for further improvements */ int idx = currentPos >> 2; w[idx] = (w[idx] << 8) | (b[off++] & 0xff); currentLen += 8; currentPos++; if (currentPos == 64) { perform(); currentPos = 0; } len--; } } public final void update(byte b) { int idx = currentPos >> 2; w[idx] = (w[idx] << 8) | (b & 0xff); currentLen += 8; currentPos++; if (currentPos == 64) { perform(); currentPos = 0; } } private final void putInt(byte[] b, int pos, int val) { b[pos] = (byte) (val >> 24); b[pos + 1] = (byte) (val >> 16); b[pos + 2] = (byte) (val >> 8); b[pos + 3] = (byte) val; } public final void digest(byte[] out) { digest(out, 0); } public final void digest(byte[] out, int off) { /* Pad with a '1' and 7-31 zero bits... */ int idx = currentPos >> 2; w[idx] = ((w[idx] << 8) | (0x80)) << ((3 - (currentPos & 3)) << 3); currentPos = (currentPos & ~3) + 4; if (currentPos == 64) { currentPos = 0; perform(); } else if (currentPos == 60) { currentPos = 0; w[15] = 0; perform(); } /* Now currentPos is a multiple of 4 and we can do the remaining * padding much more efficiently, furthermore we are sure * that currentPos <= 56. */ for (int i = currentPos >> 2; i < 14; i++) w[i] = 0; w[14] = (int) (currentLen >> 32); w[15] = (int) currentLen; perform(); putInt(out, off, H0); putInt(out, off + 4, H1); putInt(out, off + 8, H2); putInt(out, off + 12, H3); putInt(out, off + 16, H4); reset(); } private final void perform() { for (int t = 16; t < 80; t++) { int x = w[t - 3] ^ w[t - 8] ^ w[t - 14] ^ w[t - 16]; w[t] = ((x << 1) | (x >>> 31)); } int A = H0; int B = H1; int C = H2; int D = H3; int E = H4; /* Here we use variable substitution and loop unrolling * * === Original step: * * T = s5(A) + f(B,C,D) + E + w[0] + K; * E = D; D = C; C = s30(B); B = A; A = T; * * === Rewritten step: * * T = s5(A + f(B,C,D) + E + w[0] + K; * B = s30(B); * E = D; D = C; C = B; B = A; A = T; * * === Let's rewrite things, introducing new variables: * * E0 = E; D0 = D; C0 = C; B0 = B; A0 = A; * * T = s5(A0) + f(B0,C0,D0) + E0 + w[0] + K; * B0 = s30(B0); * E1 = D0; D1 = C0; C1 = B0; B1 = A0; A1 = T; * * T = s5(A1) + f(B1,C1,D1) + E1 + w[1] + K; * B1 = s30(B1); * E2 = D1; D2 = C1; C2 = B1; B2 = A1; A2 = T; * * E = E2; D = E2; C = C2; B = B2; A = A2; * * === No need for 'T', we can write into 'Ex' instead since * after the calculation of 'T' nobody is interested * in 'Ex' anymore. * * E0 = E; D0 = D; C0 = C; B0 = B; A0 = A; * * E0 = E0 + s5(A0) + f(B0,C0,D0) + w[0] + K; * B0 = s30(B0); * E1 = D0; D1 = C0; C1 = B0; B1 = A0; A1 = E0; * * E1 = E1 + s5(A1) + f(B1,C1,D1) + w[1] + K; * B1 = s30(B1); * E2 = D1; D2 = C1; C2 = B1; B2 = A1; A2 = E1; * * E = Ex; D = Ex; C = Cx; B = Bx; A = Ax; * * === Further optimization: get rid of the swap operations * Idea: instead of swapping the variables, swap the names of * the used variables in the next step: * * E0 = E; D0 = d; C0 = C; B0 = B; A0 = A; * * E0 = E0 + s5(A0) + f(B0,C0,D0) + w[0] + K; * B0 = s30(B0); * // E1 = D0; D1 = C0; C1 = B0; B1 = A0; A1 = E0; * * D0 = D0 + s5(E0) + f(A0,B0,C0) + w[1] + K; * A0 = s30(A0); * E2 = C0; D2 = B0; C2 = A0; B2 = E0; A2 = D0; * * E = E2; D = D2; C = C2; B = B2; A = A2; * * === OK, let's do this several times, also, directly * use A (instead of A0) and B,C,D,E. * * E = E + s5(A) + f(B,C,D) + w[0] + K; * B = s30(B); * // E1 = D; D1 = C; C1 = B; B1 = A; A1 = E; * * D = D + s5(E) + f(A,B,C) + w[1] + K; * A = s30(A); * // E2 = C; D2 = B; C2 = A; B2 = E; A2 = D; * * C = C + s5(D) + f(E,A,B) + w[2] + K; * E = s30(E); * // E3 = B; D3 = A; C3 = E; B3 = D; A3 = C; * * B = B + s5(C) + f(D,E,A) + w[3] + K; * D = s30(D); * // E4 = A; D4 = E; C4 = D; B4 = C; A4 = B; * * A = A + s5(B) + f(C,D,E) + w[4] + K; * C = s30(C); * // E5 = E; D5 = D; C5 = C; B5 = B; A5 = A; * * //E = E5; D = D5; C = C5; B = B5; A = A5; * * === Very nice, after 5 steps each variable * has the same contents as after 5 steps with * the original algorithm! * * We therefore can easily unroll each interval, * as the number of steps in each interval is a * multiple of 5 (20 steps per interval). */ E += ((A << 5) | (A >>> 27)) + ((B & C) | ((~B) & D)) + w[0] + 0x5A827999; B = ((B << 30) | (B >>> 2)); D += ((E << 5) | (E >>> 27)) + ((A & B) | ((~A) & C)) + w[1] + 0x5A827999; A = ((A << 30) | (A >>> 2)); C += ((D << 5) | (D >>> 27)) + ((E & A) | ((~E) & B)) + w[2] + 0x5A827999; E = ((E << 30) | (E >>> 2)); B += ((C << 5) | (C >>> 27)) + ((D & E) | ((~D) & A)) + w[3] + 0x5A827999; D = ((D << 30) | (D >>> 2)); A += ((B << 5) | (B >>> 27)) + ((C & D) | ((~C) & E)) + w[4] + 0x5A827999; C = ((C << 30) | (C >>> 2)); E += ((A << 5) | (A >>> 27)) + ((B & C) | ((~B) & D)) + w[5] + 0x5A827999; B = ((B << 30) | (B >>> 2)); D += ((E << 5) | (E >>> 27)) + ((A & B) | ((~A) & C)) + w[6] + 0x5A827999; A = ((A << 30) | (A >>> 2)); C += ((D << 5) | (D >>> 27)) + ((E & A) | ((~E) & B)) + w[7] + 0x5A827999; E = ((E << 30) | (E >>> 2)); B += ((C << 5) | (C >>> 27)) + ((D & E) | ((~D) & A)) + w[8] + 0x5A827999; D = ((D << 30) | (D >>> 2)); A += ((B << 5) | (B >>> 27)) + ((C & D) | ((~C) & E)) + w[9] + 0x5A827999; C = ((C << 30) | (C >>> 2)); E += ((A << 5) | (A >>> 27)) + ((B & C) | ((~B) & D)) + w[10] + 0x5A827999; B = ((B << 30) | (B >>> 2)); D += ((E << 5) | (E >>> 27)) + ((A & B) | ((~A) & C)) + w[11] + 0x5A827999; A = ((A << 30) | (A >>> 2)); C += ((D << 5) | (D >>> 27)) + ((E & A) | ((~E) & B)) + w[12] + 0x5A827999; E = ((E << 30) | (E >>> 2)); B += ((C << 5) | (C >>> 27)) + ((D & E) | ((~D) & A)) + w[13] + 0x5A827999; D = ((D << 30) | (D >>> 2)); A += ((B << 5) | (B >>> 27)) + ((C & D) | ((~C) & E)) + w[14] + 0x5A827999; C = ((C << 30) | (C >>> 2)); E += ((A << 5) | (A >>> 27)) + ((B & C) | ((~B) & D)) + w[15] + 0x5A827999; B = ((B << 30) | (B >>> 2)); D += ((E << 5) | (E >>> 27)) + ((A & B) | ((~A) & C)) + w[16] + 0x5A827999; A = ((A << 30) | (A >>> 2)); C += ((D << 5) | (D >>> 27)) + ((E & A) | ((~E) & B)) + w[17] + 0x5A827999; E = ((E << 30) | (E >>> 2)); B += ((C << 5) | (C >>> 27)) + ((D & E) | ((~D) & A)) + w[18] + 0x5A827999; D = ((D << 30) | (D >>> 2)); A += ((B << 5) | (B >>> 27)) + ((C & D) | ((~C) & E)) + w[19] + 0x5A827999; C = ((C << 30) | (C >>> 2)); E += ((A << 5) | (A >>> 27)) + (B ^ C ^ D) + w[20] + 0x6ED9EBA1; B = ((B << 30) | (B >>> 2)); D += ((E << 5) | (E >>> 27)) + (A ^ B ^ C) + w[21] + 0x6ED9EBA1; A = ((A << 30) | (A >>> 2)); C += ((D << 5) | (D >>> 27)) + (E ^ A ^ B) + w[22] + 0x6ED9EBA1; E = ((E << 30) | (E >>> 2)); B += ((C << 5) | (C >>> 27)) + (D ^ E ^ A) + w[23] + 0x6ED9EBA1; D = ((D << 30) | (D >>> 2)); A += ((B << 5) | (B >>> 27)) + (C ^ D ^ E) + w[24] + 0x6ED9EBA1; C = ((C << 30) | (C >>> 2)); E += ((A << 5) | (A >>> 27)) + (B ^ C ^ D) + w[25] + 0x6ED9EBA1; B = ((B << 30) | (B >>> 2)); D += ((E << 5) | (E >>> 27)) + (A ^ B ^ C) + w[26] + 0x6ED9EBA1; A = ((A << 30) | (A >>> 2)); C += ((D << 5) | (D >>> 27)) + (E ^ A ^ B) + w[27] + 0x6ED9EBA1; E = ((E << 30) | (E >>> 2)); B += ((C << 5) | (C >>> 27)) + (D ^ E ^ A) + w[28] + 0x6ED9EBA1; D = ((D << 30) | (D >>> 2)); A += ((B << 5) | (B >>> 27)) + (C ^ D ^ E) + w[29] + 0x6ED9EBA1; C = ((C << 30) | (C >>> 2)); E += ((A << 5) | (A >>> 27)) + (B ^ C ^ D) + w[30] + 0x6ED9EBA1; B = ((B << 30) | (B >>> 2)); D += ((E << 5) | (E >>> 27)) + (A ^ B ^ C) + w[31] + 0x6ED9EBA1; A = ((A << 30) | (A >>> 2)); C += ((D << 5) | (D >>> 27)) + (E ^ A ^ B) + w[32] + 0x6ED9EBA1; E = ((E << 30) | (E >>> 2)); B += ((C << 5) | (C >>> 27)) + (D ^ E ^ A) + w[33] + 0x6ED9EBA1; D = ((D << 30) | (D >>> 2)); A += ((B << 5) | (B >>> 27)) + (C ^ D ^ E) + w[34] + 0x6ED9EBA1; C = ((C << 30) | (C >>> 2)); E += ((A << 5) | (A >>> 27)) + (B ^ C ^ D) + w[35] + 0x6ED9EBA1; B = ((B << 30) | (B >>> 2)); D += ((E << 5) | (E >>> 27)) + (A ^ B ^ C) + w[36] + 0x6ED9EBA1; A = ((A << 30) | (A >>> 2)); C += ((D << 5) | (D >>> 27)) + (E ^ A ^ B) + w[37] + 0x6ED9EBA1; E = ((E << 30) | (E >>> 2)); B += ((C << 5) | (C >>> 27)) + (D ^ E ^ A) + w[38] + 0x6ED9EBA1; D = ((D << 30) | (D >>> 2)); A += ((B << 5) | (B >>> 27)) + (C ^ D ^ E) + w[39] + 0x6ED9EBA1; C = ((C << 30) | (C >>> 2)); E += ((A << 5) | (A >>> 27)) + ((B & C) | (B & D) | (C & D)) + w[40] + 0x8F1BBCDC; B = ((B << 30) | (B >>> 2)); D += ((E << 5) | (E >>> 27)) + ((A & B) | (A & C) | (B & C)) + w[41] + 0x8F1BBCDC; A = ((A << 30) | (A >>> 2)); C += ((D << 5) | (D >>> 27)) + ((E & A) | (E & B) | (A & B)) + w[42] + 0x8F1BBCDC; E = ((E << 30) | (E >>> 2)); B += ((C << 5) | (C >>> 27)) + ((D & E) | (D & A) | (E & A)) + w[43] + 0x8F1BBCDC; D = ((D << 30) | (D >>> 2)); A += ((B << 5) | (B >>> 27)) + ((C & D) | (C & E) | (D & E)) + w[44] + 0x8F1BBCDC; C = ((C << 30) | (C >>> 2)); E += ((A << 5) | (A >>> 27)) + ((B & C) | (B & D) | (C & D)) + w[45] + 0x8F1BBCDC; B = ((B << 30) | (B >>> 2)); D += ((E << 5) | (E >>> 27)) + ((A & B) | (A & C) | (B & C)) + w[46] + 0x8F1BBCDC; A = ((A << 30) | (A >>> 2)); C += ((D << 5) | (D >>> 27)) + ((E & A) | (E & B) | (A & B)) + w[47] + 0x8F1BBCDC; E = ((E << 30) | (E >>> 2)); B += ((C << 5) | (C >>> 27)) + ((D & E) | (D & A) | (E & A)) + w[48] + 0x8F1BBCDC; D = ((D << 30) | (D >>> 2)); A += ((B << 5) | (B >>> 27)) + ((C & D) | (C & E) | (D & E)) + w[49] + 0x8F1BBCDC; C = ((C << 30) | (C >>> 2)); E += ((A << 5) | (A >>> 27)) + ((B & C) | (B & D) | (C & D)) + w[50] + 0x8F1BBCDC; B = ((B << 30) | (B >>> 2)); D += ((E << 5) | (E >>> 27)) + ((A & B) | (A & C) | (B & C)) + w[51] + 0x8F1BBCDC; A = ((A << 30) | (A >>> 2)); C += ((D << 5) | (D >>> 27)) + ((E & A) | (E & B) | (A & B)) + w[52] + 0x8F1BBCDC; E = ((E << 30) | (E >>> 2)); B += ((C << 5) | (C >>> 27)) + ((D & E) | (D & A) | (E & A)) + w[53] + 0x8F1BBCDC; D = ((D << 30) | (D >>> 2)); A += ((B << 5) | (B >>> 27)) + ((C & D) | (C & E) | (D & E)) + w[54] + 0x8F1BBCDC; C = ((C << 30) | (C >>> 2)); E = E + ((A << 5) | (A >>> 27)) + ((B & C) | (B & D) | (C & D)) + w[55] + 0x8F1BBCDC; B = ((B << 30) | (B >>> 2)); D += ((E << 5) | (E >>> 27)) + ((A & B) | (A & C) | (B & C)) + w[56] + 0x8F1BBCDC; A = ((A << 30) | (A >>> 2)); C += ((D << 5) | (D >>> 27)) + ((E & A) | (E & B) | (A & B)) + w[57] + 0x8F1BBCDC; E = ((E << 30) | (E >>> 2)); B += ((C << 5) | (C >>> 27)) + ((D & E) | (D & A) | (E & A)) + w[58] + 0x8F1BBCDC; D = ((D << 30) | (D >>> 2)); A += ((B << 5) | (B >>> 27)) + ((C & D) | (C & E) | (D & E)) + w[59] + 0x8F1BBCDC; C = ((C << 30) | (C >>> 2)); E += ((A << 5) | (A >>> 27)) + (B ^ C ^ D) + w[60] + 0xCA62C1D6; B = ((B << 30) | (B >>> 2)); D += ((E << 5) | (E >>> 27)) + (A ^ B ^ C) + w[61] + 0xCA62C1D6; A = ((A << 30) | (A >>> 2)); C += ((D << 5) | (D >>> 27)) + (E ^ A ^ B) + w[62] + 0xCA62C1D6; E = ((E << 30) | (E >>> 2)); B += ((C << 5) | (C >>> 27)) + (D ^ E ^ A) + w[63] + 0xCA62C1D6; D = ((D << 30) | (D >>> 2)); A += ((B << 5) | (B >>> 27)) + (C ^ D ^ E) + w[64] + 0xCA62C1D6; C = ((C << 30) | (C >>> 2)); E += ((A << 5) | (A >>> 27)) + (B ^ C ^ D) + w[65] + 0xCA62C1D6; B = ((B << 30) | (B >>> 2)); D += ((E << 5) | (E >>> 27)) + (A ^ B ^ C) + w[66] + 0xCA62C1D6; A = ((A << 30) | (A >>> 2)); C += ((D << 5) | (D >>> 27)) + (E ^ A ^ B) + w[67] + 0xCA62C1D6; E = ((E << 30) | (E >>> 2)); B += ((C << 5) | (C >>> 27)) + (D ^ E ^ A) + w[68] + 0xCA62C1D6; D = ((D << 30) | (D >>> 2)); A += ((B << 5) | (B >>> 27)) + (C ^ D ^ E) + w[69] + 0xCA62C1D6; C = ((C << 30) | (C >>> 2)); E += ((A << 5) | (A >>> 27)) + (B ^ C ^ D) + w[70] + 0xCA62C1D6; B = ((B << 30) | (B >>> 2)); D += ((E << 5) | (E >>> 27)) + (A ^ B ^ C) + w[71] + 0xCA62C1D6; A = ((A << 30) | (A >>> 2)); C += ((D << 5) | (D >>> 27)) + (E ^ A ^ B) + w[72] + 0xCA62C1D6; E = ((E << 30) | (E >>> 2)); B += ((C << 5) | (C >>> 27)) + (D ^ E ^ A) + w[73] + 0xCA62C1D6; D = ((D << 30) | (D >>> 2)); A += ((B << 5) | (B >>> 27)) + (C ^ D ^ E) + w[74] + 0xCA62C1D6; C = ((C << 30) | (C >>> 2)); E += ((A << 5) | (A >>> 27)) + (B ^ C ^ D) + w[75] + 0xCA62C1D6; B = ((B << 30) | (B >>> 2)); D += ((E << 5) | (E >>> 27)) + (A ^ B ^ C) + w[76] + 0xCA62C1D6; A = ((A << 30) | (A >>> 2)); C += ((D << 5) | (D >>> 27)) + (E ^ A ^ B) + w[77] + 0xCA62C1D6; E = ((E << 30) | (E >>> 2)); B += ((C << 5) | (C >>> 27)) + (D ^ E ^ A) + w[78] + 0xCA62C1D6; D = ((D << 30) | (D >>> 2)); A += ((B << 5) | (B >>> 27)) + (C ^ D ^ E) + w[79] + 0xCA62C1D6; C = ((C << 30) | (C >>> 2)); H0 += A; H1 += B; H2 += C; H3 += D; H4 += E; // debug(80, H0, H1, H2, H3, H4); } private static final String toHexString(byte[] b) { final String hexChar = "0123456789ABCDEF"; StringBuffer sb = new StringBuffer(); for (int i = 0; i < b.length; i++) { sb.append(hexChar.charAt((b[i] >> 4) & 0x0f)); sb.append(hexChar.charAt(b[i] & 0x0f)); } return sb.toString(); } public static void main(String[] args) { SHA1 sha = new SHA1(); byte[] dig1 = new byte[20]; byte[] dig2 = new byte[20]; byte[] dig3 = new byte[20]; /* * We do not specify a charset name for getBytes(), since we assume that * the JVM's default encoder maps the _used_ ASCII characters exactly as * getBytes("US-ASCII") would do. (Ah, yes, too lazy to catch the * exception that can be thrown by getBytes("US-ASCII")). Note: This has * no effect on the SHA-1 implementation, this is just for the following * test code. */ sha.update("abc".getBytes()); sha.digest(dig1); sha.update("abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq".getBytes()); sha.digest(dig2); for (int i = 0; i < 1000000; i++) sha.update((byte) 'a'); sha.digest(dig3); String dig1_res = toHexString(dig1); String dig2_res = toHexString(dig2); String dig3_res = toHexString(dig3); String dig1_ref = "A9993E364706816ABA3E25717850C26C9CD0D89D"; String dig2_ref = "84983E441C3BD26EBAAE4AA1F95129E5E54670F1"; String dig3_ref = "34AA973CD4C4DAA4F61EEB2BDBAD27316534016F"; if (dig1_res.equals(dig1_ref)) System.out.println("SHA-1 Test 1 OK."); else System.out.println("SHA-1 Test 1 FAILED."); if (dig2_res.equals(dig2_ref)) System.out.println("SHA-1 Test 2 OK."); else System.out.println("SHA-1 Test 2 FAILED."); if (dig3_res.equals(dig3_ref)) System.out.println("SHA-1 Test 3 OK."); else System.out.println("SHA-1 Test 3 FAILED."); if (dig3_res.equals(dig3_ref)) System.out.println("SHA-1 Test 3 OK."); else System.out.println("SHA-1 Test 3 FAILED."); } }
1030365071-xuechao
src/com/trilead/ssh2/crypto/digest/SHA1.java
Java
asf20
18,717
package com.trilead.ssh2.crypto.digest; /** * Digest. * * @author Christian Plattner, plattner@trilead.com * @version $Id: Digest.java,v 1.1 2007/10/15 12:49:57 cplattne Exp $ */ public interface Digest { public int getDigestLength(); public void update(byte b); public void update(byte[] b); public void update(byte b[], int off, int len); public void reset(); public void digest(byte[] out); public void digest(byte[] out, int off); }
1030365071-xuechao
src/com/trilead/ssh2/crypto/digest/Digest.java
Java
asf20
483
package com.trilead.ssh2.crypto; import java.io.CharArrayWriter; import java.io.IOException; /** * Basic Base64 Support. * * @author Christian Plattner, plattner@trilead.com * @version $Id: Base64.java,v 1.1 2007/10/15 12:49:56 cplattne Exp $ */ public class Base64 { static final char[] alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".toCharArray(); public static char[] encode(byte[] content) { CharArrayWriter cw = new CharArrayWriter((4 * content.length) / 3); int idx = 0; int x = 0; for (int i = 0; i < content.length; i++) { if (idx == 0) x = (content[i] & 0xff) << 16; else if (idx == 1) x = x | ((content[i] & 0xff) << 8); else x = x | (content[i] & 0xff); idx++; if (idx == 3) { cw.write(alphabet[x >> 18]); cw.write(alphabet[(x >> 12) & 0x3f]); cw.write(alphabet[(x >> 6) & 0x3f]); cw.write(alphabet[x & 0x3f]); idx = 0; } } if (idx == 1) { cw.write(alphabet[x >> 18]); cw.write(alphabet[(x >> 12) & 0x3f]); cw.write('='); cw.write('='); } if (idx == 2) { cw.write(alphabet[x >> 18]); cw.write(alphabet[(x >> 12) & 0x3f]); cw.write(alphabet[(x >> 6) & 0x3f]); cw.write('='); } return cw.toCharArray(); } public static byte[] decode(char[] message) throws IOException { byte buff[] = new byte[4]; byte dest[] = new byte[message.length]; int bpos = 0; int destpos = 0; for (int i = 0; i < message.length; i++) { int c = message[i]; if ((c == '\n') || (c == '\r') || (c == ' ') || (c == '\t')) continue; if ((c >= 'A') && (c <= 'Z')) { buff[bpos++] = (byte) (c - 'A'); } else if ((c >= 'a') && (c <= 'z')) { buff[bpos++] = (byte) ((c - 'a') + 26); } else if ((c >= '0') && (c <= '9')) { buff[bpos++] = (byte) ((c - '0') + 52); } else if (c == '+') { buff[bpos++] = 62; } else if (c == '/') { buff[bpos++] = 63; } else if (c == '=') { buff[bpos++] = 64; } else { throw new IOException("Illegal char in base64 code."); } if (bpos == 4) { bpos = 0; if (buff[0] == 64) break; if (buff[1] == 64) throw new IOException("Unexpected '=' in base64 code."); if (buff[2] == 64) { int v = (((buff[0] & 0x3f) << 6) | ((buff[1] & 0x3f))); dest[destpos++] = (byte) (v >> 4); break; } else if (buff[3] == 64) { int v = (((buff[0] & 0x3f) << 12) | ((buff[1] & 0x3f) << 6) | ((buff[2] & 0x3f))); dest[destpos++] = (byte) (v >> 10); dest[destpos++] = (byte) (v >> 2); break; } else { int v = (((buff[0] & 0x3f) << 18) | ((buff[1] & 0x3f) << 12) | ((buff[2] & 0x3f) << 6) | ((buff[3] & 0x3f))); dest[destpos++] = (byte) (v >> 16); dest[destpos++] = (byte) (v >> 8); dest[destpos++] = (byte) (v); } } } byte[] res = new byte[destpos]; System.arraycopy(dest, 0, res, 0, destpos); return res; } }
1030365071-xuechao
src/com/trilead/ssh2/crypto/Base64.java
Java
asf20
3,149
package com.trilead.ssh2.crypto; import java.io.IOException; import java.math.BigInteger; /** * SimpleDERReader. * * @author Christian Plattner, plattner@trilead.com * @version $Id: SimpleDERReader.java,v 1.1 2007/10/15 12:49:56 cplattne Exp $ */ public class SimpleDERReader { byte[] buffer; int pos; int count; public SimpleDERReader(byte[] b) { resetInput(b); } public SimpleDERReader(byte[] b, int off, int len) { resetInput(b, off, len); } public void resetInput(byte[] b) { resetInput(b, 0, b.length); } public void resetInput(byte[] b, int off, int len) { buffer = b; pos = off; count = len; } private byte readByte() throws IOException { if (count <= 0) throw new IOException("DER byte array: out of data"); count--; return buffer[pos++]; } private byte[] readBytes(int len) throws IOException { if (len > count) throw new IOException("DER byte array: out of data"); byte[] b = new byte[len]; System.arraycopy(buffer, pos, b, 0, len); pos += len; count -= len; return b; } public int available() { return count; } private int readLength() throws IOException { int len = readByte() & 0xff; if ((len & 0x80) == 0) return len; int remain = len & 0x7F; if (remain == 0) return -1; len = 0; while (remain > 0) { len = len << 8; len = len | (readByte() & 0xff); remain--; } return len; } public int ignoreNextObject() throws IOException { int type = readByte() & 0xff; int len = readLength(); if ((len < 0) || len > available()) throw new IOException("Illegal len in DER object (" + len + ")"); readBytes(len); return type; } public BigInteger readInt() throws IOException { int type = readByte() & 0xff; if (type != 0x02) throw new IOException("Expected DER Integer, but found type " + type); int len = readLength(); if ((len < 0) || len > available()) throw new IOException("Illegal len in DER object (" + len + ")"); byte[] b = readBytes(len); BigInteger bi = new BigInteger(b); return bi; } public byte[] readSequenceAsByteArray() throws IOException { int type = readByte() & 0xff; if (type != 0x30) throw new IOException("Expected DER Sequence, but found type " + type); int len = readLength(); if ((len < 0) || len > available()) throw new IOException("Illegal len in DER object (" + len + ")"); byte[] b = readBytes(len); return b; } public byte[] readOctetString() throws IOException { int type = readByte() & 0xff; if (type != 0x04) throw new IOException("Expected DER Octetstring, but found type " + type); int len = readLength(); if ((len < 0) || len > available()) throw new IOException("Illegal len in DER object (" + len + ")"); byte[] b = readBytes(len); return b; } }
1030365071-xuechao
src/com/trilead/ssh2/crypto/SimpleDERReader.java
Java
asf20
3,005
package com.trilead.ssh2.crypto; import java.io.BufferedReader; import java.io.CharArrayReader; import java.io.IOException; import java.math.BigInteger; import com.trilead.ssh2.crypto.cipher.AES; import com.trilead.ssh2.crypto.cipher.BlockCipher; import com.trilead.ssh2.crypto.cipher.CBCMode; import com.trilead.ssh2.crypto.cipher.DES; import com.trilead.ssh2.crypto.cipher.DESede; import com.trilead.ssh2.crypto.digest.MD5; import com.trilead.ssh2.signature.DSAPrivateKey; import com.trilead.ssh2.signature.RSAPrivateKey; /** * PEM Support. * * @author Christian Plattner, plattner@trilead.com * @version $Id: PEMDecoder.java,v 1.2 2008/04/01 12:38:09 cplattne Exp $ */ public class PEMDecoder { public static final int PEM_RSA_PRIVATE_KEY = 1; public static final int PEM_DSA_PRIVATE_KEY = 2; private static final int hexToInt(char c) { if ((c >= 'a') && (c <= 'f')) { return (c - 'a') + 10; } if ((c >= 'A') && (c <= 'F')) { return (c - 'A') + 10; } if ((c >= '0') && (c <= '9')) { return (c - '0'); } throw new IllegalArgumentException("Need hex char"); } private static byte[] hexToByteArray(String hex) { if (hex == null) throw new IllegalArgumentException("null argument"); if ((hex.length() % 2) != 0) throw new IllegalArgumentException("Uneven string length in hex encoding."); byte decoded[] = new byte[hex.length() / 2]; for (int i = 0; i < decoded.length; i++) { int hi = hexToInt(hex.charAt(i * 2)); int lo = hexToInt(hex.charAt((i * 2) + 1)); decoded[i] = (byte) (hi * 16 + lo); } return decoded; } private static byte[] generateKeyFromPasswordSaltWithMD5(byte[] password, byte[] salt, int keyLen) throws IOException { if (salt.length < 8) throw new IllegalArgumentException("Salt needs to be at least 8 bytes for key generation."); MD5 md5 = new MD5(); byte[] key = new byte[keyLen]; byte[] tmp = new byte[md5.getDigestLength()]; while (true) { md5.update(password, 0, password.length); md5.update(salt, 0, 8); // ARGH we only use the first 8 bytes of the // salt in this step. // This took me two hours until I got AES-xxx running. int copy = (keyLen < tmp.length) ? keyLen : tmp.length; md5.digest(tmp, 0); System.arraycopy(tmp, 0, key, key.length - keyLen, copy); keyLen -= copy; if (keyLen == 0) return key; md5.update(tmp, 0, tmp.length); } } private static byte[] removePadding(byte[] buff, int blockSize) throws IOException { /* Removes RFC 1423/PKCS #7 padding */ int rfc_1423_padding = buff[buff.length - 1] & 0xff; if ((rfc_1423_padding < 1) || (rfc_1423_padding > blockSize)) throw new IOException("Decrypted PEM has wrong padding, did you specify the correct password?"); for (int i = 2; i <= rfc_1423_padding; i++) { if (buff[buff.length - i] != rfc_1423_padding) throw new IOException("Decrypted PEM has wrong padding, did you specify the correct password?"); } byte[] tmp = new byte[buff.length - rfc_1423_padding]; System.arraycopy(buff, 0, tmp, 0, buff.length - rfc_1423_padding); return tmp; } public static final PEMStructure parsePEM(char[] pem) throws IOException { PEMStructure ps = new PEMStructure(); String line = null; BufferedReader br = new BufferedReader(new CharArrayReader(pem)); String endLine = null; while (true) { line = br.readLine(); if (line == null) throw new IOException("Invalid PEM structure, '-----BEGIN...' missing"); line = line.trim(); if (line.startsWith("-----BEGIN DSA PRIVATE KEY-----")) { endLine = "-----END DSA PRIVATE KEY-----"; ps.pemType = PEM_DSA_PRIVATE_KEY; break; } if (line.startsWith("-----BEGIN RSA PRIVATE KEY-----")) { endLine = "-----END RSA PRIVATE KEY-----"; ps.pemType = PEM_RSA_PRIVATE_KEY; break; } } while (true) { line = br.readLine(); if (line == null) throw new IOException("Invalid PEM structure, " + endLine + " missing"); line = line.trim(); int sem_idx = line.indexOf(':'); if (sem_idx == -1) break; String name = line.substring(0, sem_idx + 1); String value = line.substring(sem_idx + 1); String values[] = value.split(","); for (int i = 0; i < values.length; i++) values[i] = values[i].trim(); // Proc-Type: 4,ENCRYPTED // DEK-Info: DES-EDE3-CBC,579B6BE3E5C60483 if ("Proc-Type:".equals(name)) { ps.procType = values; continue; } if ("DEK-Info:".equals(name)) { ps.dekInfo = values; continue; } /* Ignore line */ } StringBuffer keyData = new StringBuffer(); while (true) { if (line == null) throw new IOException("Invalid PEM structure, " + endLine + " missing"); line = line.trim(); if (line.startsWith(endLine)) break; keyData.append(line); line = br.readLine(); } char[] pem_chars = new char[keyData.length()]; keyData.getChars(0, pem_chars.length, pem_chars, 0); ps.data = Base64.decode(pem_chars); if (ps.data.length == 0) throw new IOException("Invalid PEM structure, no data available"); return ps; } private static final void decryptPEM(PEMStructure ps, byte[] pw) throws IOException { if (ps.dekInfo == null) throw new IOException("Broken PEM, no mode and salt given, but encryption enabled"); if (ps.dekInfo.length != 2) throw new IOException("Broken PEM, DEK-Info is incomplete!"); String algo = ps.dekInfo[0]; byte[] salt = hexToByteArray(ps.dekInfo[1]); BlockCipher bc = null; if (algo.equals("DES-EDE3-CBC")) { DESede des3 = new DESede(); des3.init(false, generateKeyFromPasswordSaltWithMD5(pw, salt, 24)); bc = new CBCMode(des3, salt, false); } else if (algo.equals("DES-CBC")) { DES des = new DES(); des.init(false, generateKeyFromPasswordSaltWithMD5(pw, salt, 8)); bc = new CBCMode(des, salt, false); } else if (algo.equals("AES-128-CBC")) { AES aes = new AES(); aes.init(false, generateKeyFromPasswordSaltWithMD5(pw, salt, 16)); bc = new CBCMode(aes, salt, false); } else if (algo.equals("AES-192-CBC")) { AES aes = new AES(); aes.init(false, generateKeyFromPasswordSaltWithMD5(pw, salt, 24)); bc = new CBCMode(aes, salt, false); } else if (algo.equals("AES-256-CBC")) { AES aes = new AES(); aes.init(false, generateKeyFromPasswordSaltWithMD5(pw, salt, 32)); bc = new CBCMode(aes, salt, false); } else { throw new IOException("Cannot decrypt PEM structure, unknown cipher " + algo); } if ((ps.data.length % bc.getBlockSize()) != 0) throw new IOException("Invalid PEM structure, size of encrypted block is not a multiple of " + bc.getBlockSize()); /* Now decrypt the content */ byte[] dz = new byte[ps.data.length]; for (int i = 0; i < ps.data.length / bc.getBlockSize(); i++) { bc.transformBlock(ps.data, i * bc.getBlockSize(), dz, i * bc.getBlockSize()); } /* Now check and remove RFC 1423/PKCS #7 padding */ dz = removePadding(dz, bc.getBlockSize()); ps.data = dz; ps.dekInfo = null; ps.procType = null; } public static final boolean isPEMEncrypted(PEMStructure ps) throws IOException { if (ps.procType == null) return false; if (ps.procType.length != 2) throw new IOException("Unknown Proc-Type field."); if ("4".equals(ps.procType[0]) == false) throw new IOException("Unknown Proc-Type field (" + ps.procType[0] + ")"); if ("ENCRYPTED".equals(ps.procType[1])) return true; return false; } public static Object decode(char[] pem, String password) throws IOException { PEMStructure ps = parsePEM(pem); if (isPEMEncrypted(ps)) { if (password == null) throw new IOException("PEM is encrypted, but no password was specified"); decryptPEM(ps, password.getBytes("ISO-8859-1")); } if (ps.pemType == PEM_DSA_PRIVATE_KEY) { SimpleDERReader dr = new SimpleDERReader(ps.data); byte[] seq = dr.readSequenceAsByteArray(); if (dr.available() != 0) throw new IOException("Padding in DSA PRIVATE KEY DER stream."); dr.resetInput(seq); BigInteger version = dr.readInt(); if (version.compareTo(BigInteger.ZERO) != 0) throw new IOException("Wrong version (" + version + ") in DSA PRIVATE KEY DER stream."); BigInteger p = dr.readInt(); BigInteger q = dr.readInt(); BigInteger g = dr.readInt(); BigInteger y = dr.readInt(); BigInteger x = dr.readInt(); if (dr.available() != 0) throw new IOException("Padding in DSA PRIVATE KEY DER stream."); return new DSAPrivateKey(p, q, g, y, x); } if (ps.pemType == PEM_RSA_PRIVATE_KEY) { SimpleDERReader dr = new SimpleDERReader(ps.data); byte[] seq = dr.readSequenceAsByteArray(); if (dr.available() != 0) throw new IOException("Padding in RSA PRIVATE KEY DER stream."); dr.resetInput(seq); BigInteger version = dr.readInt(); if ((version.compareTo(BigInteger.ZERO) != 0) && (version.compareTo(BigInteger.ONE) != 0)) throw new IOException("Wrong version (" + version + ") in RSA PRIVATE KEY DER stream."); BigInteger n = dr.readInt(); BigInteger e = dr.readInt(); BigInteger d = dr.readInt(); return new RSAPrivateKey(d, e, n); } throw new IOException("PEM problem: it is of unknown type"); } }
1030365071-xuechao
src/com/trilead/ssh2/crypto/PEMDecoder.java
Java
asf20
9,657
package com.trilead.ssh2.crypto; import com.trilead.ssh2.compression.CompressionFactory; import com.trilead.ssh2.crypto.cipher.BlockCipherFactory; import com.trilead.ssh2.crypto.digest.MAC; import com.trilead.ssh2.transport.KexManager; /** * CryptoWishList. * * @author Christian Plattner, plattner@trilead.com * @version $Id: CryptoWishList.java,v 1.1 2007/10/15 12:49:56 cplattne Exp $ */ public class CryptoWishList { public String[] kexAlgorithms = KexManager.getDefaultKexAlgorithmList(); public String[] serverHostKeyAlgorithms = KexManager.getDefaultServerHostkeyAlgorithmList(); public String[] c2s_enc_algos = BlockCipherFactory.getDefaultCipherList(); public String[] s2c_enc_algos = BlockCipherFactory.getDefaultCipherList(); public String[] c2s_mac_algos = MAC.getMacList(); public String[] s2c_mac_algos = MAC.getMacList(); public String[] c2s_comp_algos = CompressionFactory.getDefaultCompressorList(); public String[] s2c_comp_algos = CompressionFactory.getDefaultCompressorList(); }
1030365071-xuechao
src/com/trilead/ssh2/crypto/CryptoWishList.java
Java
asf20
1,043
package com.trilead.ssh2.crypto.dh; import java.math.BigInteger; import java.security.SecureRandom; import com.trilead.ssh2.DHGexParameters; import com.trilead.ssh2.crypto.digest.HashForSSH2Types; /** * DhGroupExchange. * * @author Christian Plattner, plattner@trilead.com * @version $Id: DhGroupExchange.java,v 1.1 2007/10/15 12:49:57 cplattne Exp $ */ public class DhGroupExchange { /* Given by the standard */ private BigInteger p; private BigInteger g; /* Client public and private */ private BigInteger e; private BigInteger x; /* Server public */ private BigInteger f; /* Shared secret */ private BigInteger k; public DhGroupExchange(BigInteger p, BigInteger g) { this.p = p; this.g = g; } public void init(SecureRandom rnd) { k = null; x = new BigInteger(p.bitLength() - 1, rnd); e = g.modPow(x, p); } /** * @return Returns the e. */ public BigInteger getE() { if (e == null) throw new IllegalStateException("Not initialized!"); return e; } /** * @return Returns the shared secret k. */ public BigInteger getK() { if (k == null) throw new IllegalStateException("Shared secret not yet known, need f first!"); return k; } /** * Sets f and calculates the shared secret. */ public void setF(BigInteger f) { if (e == null) throw new IllegalStateException("Not initialized!"); BigInteger zero = BigInteger.valueOf(0); if (zero.compareTo(f) >= 0 || p.compareTo(f) <= 0) throw new IllegalArgumentException("Invalid f specified!"); this.f = f; this.k = f.modPow(x, p); } public byte[] calculateH(byte[] clientversion, byte[] serverversion, byte[] clientKexPayload, byte[] serverKexPayload, byte[] hostKey, DHGexParameters para) { HashForSSH2Types hash = new HashForSSH2Types("SHA1"); hash.updateByteString(clientversion); hash.updateByteString(serverversion); hash.updateByteString(clientKexPayload); hash.updateByteString(serverKexPayload); hash.updateByteString(hostKey); if (para.getMin_group_len() > 0) hash.updateUINT32(para.getMin_group_len()); hash.updateUINT32(para.getPref_group_len()); if (para.getMax_group_len() > 0) hash.updateUINT32(para.getMax_group_len()); hash.updateBigInt(p); hash.updateBigInt(g); hash.updateBigInt(e); hash.updateBigInt(f); hash.updateBigInt(k); return hash.getDigest(); } }
1030365071-xuechao
src/com/trilead/ssh2/crypto/dh/DhGroupExchange.java
Java
asf20
2,477
package com.trilead.ssh2.crypto.dh; import java.io.UnsupportedEncodingException; import java.math.BigInteger; import java.security.SecureRandom; import com.trilead.ssh2.crypto.digest.HashForSSH2Types; import com.trilead.ssh2.log.Logger; /** * DhExchange. * * @author Christian Plattner, plattner@trilead.com * @version $Id: DhExchange.java,v 1.2 2008/04/01 12:38:09 cplattne Exp $ */ public class DhExchange { private static final Logger log = Logger.getLogger(DhExchange.class); /* Given by the standard */ static final BigInteger p1, p14; static final BigInteger g; BigInteger p; /* Client public and private */ BigInteger e; BigInteger x; /* Server public */ BigInteger f; /* Shared secret */ BigInteger k; static { final String p1_string = "17976931348623159077083915679378745319786029604875" + "60117064444236841971802161585193689478337958649255415021805654859805036464" + "40548199239100050792877003355816639229553136239076508735759914822574862575" + "00742530207744771258955095793777842444242661733472762929938766870920560605" + "0270810842907692932019128194467627007"; final String p14_string = "FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD129" + "024E088A67CC74020BBEA63B139B22514A08798E3404DDEF9519B3CD3A431B302B0" + "A6DF25F14374FE1356D6D51C245E485B576625E7EC6F44C42E9A637ED6B0BFF5CB" + "6F406B7EDEE386BFB5A899FA5AE9F24117C4B1FE649286651ECE45B3DC2007CB8A" + "163BF0598DA48361C55D39A69163FA8FD24CF5F83655D23DCA3AD961C62F356208" + "552BB9ED529077096966D670C354E4ABC9804F1746C08CA18217C32905E462E36C" + "E3BE39E772C180E86039B2783A2EC07A28FB5C55DF06F4C52C9DE2BCBF69558171" + "83995497CEA956AE515D2261898FA051015728E5A8AACAA68FFFFFFFFFFFFFFFF"; p1 = new BigInteger(p1_string); p14 = new BigInteger(p14_string, 16); g = new BigInteger("2"); } public DhExchange() { } public void init(int group, SecureRandom rnd) { k = null; if (group == 1) p = p1; else if (group == 14) p = p14; else throw new IllegalArgumentException("Unknown DH group " + group); x = new BigInteger(p.bitLength() - 1, rnd); e = g.modPow(x, p); } /** * @return Returns the e. * @throws IllegalStateException */ public BigInteger getE() { if (e == null) throw new IllegalStateException("DhDsaExchange not initialized!"); return e; } /** * @return Returns the shared secret k. * @throws IllegalStateException */ public BigInteger getK() { if (k == null) throw new IllegalStateException("Shared secret not yet known, need f first!"); return k; } /** * @param f */ public void setF(BigInteger f) { if (e == null) throw new IllegalStateException("DhDsaExchange not initialized!"); BigInteger zero = BigInteger.valueOf(0); if (zero.compareTo(f) >= 0 || p.compareTo(f) <= 0) throw new IllegalArgumentException("Invalid f specified!"); this.f = f; this.k = f.modPow(x, p); } public byte[] calculateH(byte[] clientversion, byte[] serverversion, byte[] clientKexPayload, byte[] serverKexPayload, byte[] hostKey) throws UnsupportedEncodingException { HashForSSH2Types hash = new HashForSSH2Types("SHA1"); if (log.isEnabled()) { log.log(90, "Client: '" + new String(clientversion, "ISO-8859-1") + "'"); log.log(90, "Server: '" + new String(serverversion, "ISO-8859-1") + "'"); } hash.updateByteString(clientversion); hash.updateByteString(serverversion); hash.updateByteString(clientKexPayload); hash.updateByteString(serverKexPayload); hash.updateByteString(hostKey); hash.updateBigInt(e); hash.updateBigInt(f); hash.updateBigInt(k); return hash.getDigest(); } }
1030365071-xuechao
src/com/trilead/ssh2/crypto/dh/DhExchange.java
Java
asf20
3,808
package com.trilead.ssh2.crypto; /** * Parsed PEM structure. * * @author Christian Plattner, plattner@trilead.com * @version $Id: PEMStructure.java,v 1.1 2007/10/15 12:49:56 cplattne Exp $ */ public class PEMStructure { public int pemType; String dekInfo[]; String procType[]; public byte[] data; }
1030365071-xuechao
src/com/trilead/ssh2/crypto/PEMStructure.java
Java
asf20
327
package com.trilead.ssh2.crypto; import java.math.BigInteger; import com.trilead.ssh2.crypto.digest.HashForSSH2Types; /** * Establishes key material for iv/key/mac (both directions). * * @author Christian Plattner, plattner@trilead.com * @version $Id: KeyMaterial.java,v 1.1 2007/10/15 12:49:56 cplattne Exp $ */ public class KeyMaterial { public byte[] initial_iv_client_to_server; public byte[] initial_iv_server_to_client; public byte[] enc_key_client_to_server; public byte[] enc_key_server_to_client; public byte[] integrity_key_client_to_server; public byte[] integrity_key_server_to_client; private static byte[] calculateKey(HashForSSH2Types sh, BigInteger K, byte[] H, byte type, byte[] SessionID, int keyLength) { byte[] res = new byte[keyLength]; int dglen = sh.getDigestLength(); int numRounds = (keyLength + dglen - 1) / dglen; byte[][] tmp = new byte[numRounds][]; sh.reset(); sh.updateBigInt(K); sh.updateBytes(H); sh.updateByte(type); sh.updateBytes(SessionID); tmp[0] = sh.getDigest(); int off = 0; int produced = Math.min(dglen, keyLength); System.arraycopy(tmp[0], 0, res, off, produced); keyLength -= produced; off += produced; for (int i = 1; i < numRounds; i++) { sh.updateBigInt(K); sh.updateBytes(H); for (int j = 0; j < i; j++) sh.updateBytes(tmp[j]); tmp[i] = sh.getDigest(); produced = Math.min(dglen, keyLength); System.arraycopy(tmp[i], 0, res, off, produced); keyLength -= produced; off += produced; } return res; } public static KeyMaterial create(String hashType, byte[] H, BigInteger K, byte[] SessionID, int keyLengthCS, int blockSizeCS, int macLengthCS, int keyLengthSC, int blockSizeSC, int macLengthSC) throws IllegalArgumentException { KeyMaterial km = new KeyMaterial(); HashForSSH2Types sh = new HashForSSH2Types(hashType); km.initial_iv_client_to_server = calculateKey(sh, K, H, (byte) 'A', SessionID, blockSizeCS); km.initial_iv_server_to_client = calculateKey(sh, K, H, (byte) 'B', SessionID, blockSizeSC); km.enc_key_client_to_server = calculateKey(sh, K, H, (byte) 'C', SessionID, keyLengthCS); km.enc_key_server_to_client = calculateKey(sh, K, H, (byte) 'D', SessionID, keyLengthSC); km.integrity_key_client_to_server = calculateKey(sh, K, H, (byte) 'E', SessionID, macLengthCS); km.integrity_key_server_to_client = calculateKey(sh, K, H, (byte) 'F', SessionID, macLengthSC); return km; } }
1030365071-xuechao
src/com/trilead/ssh2/crypto/KeyMaterial.java
Java
asf20
2,566
package com.trilead.ssh2; /** * A <code>SFTPv3DirectoryEntry</code> as returned by {@link SFTPv3Client#ls(String)}. * * @author Christian Plattner, plattner@trilead.com * @version $Id: SFTPv3DirectoryEntry.java,v 1.1 2007/10/15 12:49:56 cplattne Exp $ */ public class SFTPv3DirectoryEntry { /** * A relative name within the directory, without any path components. */ public String filename; /** * An expanded format for the file name, similar to what is returned by * "ls -l" on Un*x systems. * <p> * The format of this field is unspecified by the SFTP v3 protocol. * It MUST be suitable for use in the output of a directory listing * command (in fact, the recommended operation for a directory listing * command is to simply display this data). However, clients SHOULD NOT * attempt to parse the longname field for file attributes; they SHOULD * use the attrs field instead. * <p> * The recommended format for the longname field is as follows:<br> * <code>-rwxr-xr-x 1 mjos staff 348911 Mar 25 14:29 t-filexfer</code> */ public String longEntry; /** * The attributes of this entry. */ public SFTPv3FileAttributes attributes; }
1030365071-xuechao
src/com/trilead/ssh2/SFTPv3DirectoryEntry.java
Java
asf20
1,230
package com.trilead.ssh2.util; import java.io.PrintWriter; import java.io.StringWriter; import java.util.Collections; import java.util.LinkedList; import com.trilead.ssh2.log.Logger; /** * TimeoutService (beta). Here you can register a timeout. * <p> * Implemented having large scale programs in mind: if you open many concurrent SSH connections * that rely on timeouts, then there will be only one timeout thread. Once all timeouts * have expired/are cancelled, the thread will (sooner or later) exit. * Only after new timeouts arrive a new thread (singleton) will be instantiated. * * @author Christian Plattner, plattner@trilead.com * @version $Id: TimeoutService.java,v 1.1 2007/10/15 12:49:57 cplattne Exp $ */ public class TimeoutService { private static final Logger log = Logger.getLogger(TimeoutService.class); public static class TimeoutToken implements Comparable { private long runTime; private Runnable handler; private TimeoutToken(long runTime, Runnable handler) { this.runTime = runTime; this.handler = handler; } public int compareTo(Object o) { TimeoutToken t = (TimeoutToken) o; if (runTime > t.runTime) return 1; if (runTime == t.runTime) return 0; return -1; } } private static class TimeoutThread extends Thread { public void run() { synchronized (todolist) { while (true) { if (todolist.size() == 0) { timeoutThread = null; return; } long now = System.currentTimeMillis(); TimeoutToken tt = (TimeoutToken) todolist.getFirst(); if (tt.runTime > now) { /* Not ready yet, sleep a little bit */ try { todolist.wait(tt.runTime - now); } catch (InterruptedException e) { } /* We cannot simply go on, since it could be that the token * was removed (cancelled) or another one has been inserted in * the meantime. */ continue; } todolist.removeFirst(); try { tt.handler.run(); } catch (Exception e) { StringWriter sw = new StringWriter(); e.printStackTrace(new PrintWriter(sw)); log.log(20, "Exeception in Timeout handler:" + e.getMessage() + "(" + sw.toString() + ")"); } } } } } /* The list object is also used for locking purposes */ private static final LinkedList todolist = new LinkedList(); private static Thread timeoutThread = null; /** * It is assumed that the passed handler will not execute for a long time. * * @param runTime * @param handler * @return a TimeoutToken that can be used to cancel the timeout. */ public static final TimeoutToken addTimeoutHandler(long runTime, Runnable handler) { TimeoutToken token = new TimeoutToken(runTime, handler); synchronized (todolist) { todolist.add(token); Collections.sort(todolist); if (timeoutThread != null) timeoutThread.interrupt(); else { timeoutThread = new TimeoutThread(); timeoutThread.setDaemon(true); timeoutThread.start(); } } return token; } public static final void cancelTimeoutHandler(TimeoutToken token) { synchronized (todolist) { todolist.remove(token); if (timeoutThread != null) timeoutThread.interrupt(); } } }
1030365071-xuechao
src/com/trilead/ssh2/util/TimeoutService.java
Java
asf20
3,443
package com.trilead.ssh2.util; /** * Tokenizer. Why? Because StringTokenizer is not available in J2ME. * * @author Christian Plattner, plattner@trilead.com * @version $Id: Tokenizer.java,v 1.1 2007/10/15 12:49:57 cplattne Exp $ */ public class Tokenizer { /** * Exists because StringTokenizer is not available in J2ME. * Returns an array with at least 1 entry. * * @param source must be non-null * @param delimiter * @return an array of Strings */ public static String[] parseTokens(String source, char delimiter) { int numtoken = 1; for (int i = 0; i < source.length(); i++) { if (source.charAt(i) == delimiter) numtoken++; } String list[] = new String[numtoken]; int nextfield = 0; for (int i = 0; i < numtoken; i++) { if (nextfield >= source.length()) { list[i] = ""; } else { int idx = source.indexOf(delimiter, nextfield); if (idx == -1) idx = source.length(); list[i] = source.substring(nextfield, idx); nextfield = idx + 1; } } return list; } }
1030365071-xuechao
src/com/trilead/ssh2/util/Tokenizer.java
Java
asf20
1,104
/* -*-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 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); } 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=(int)(q<read?read-q-1:end-q);} // process input based on current state while(true){ switch (mode){ case TYPE: while(k<(3)){ if(n!=0){ r=Z_OK; } else{ bitb=b; bitk=k; z.avail_in=n; z.total_in+=p-z.next_in_index;z.next_in_index=p; write=q; return inflate_flush(z,r); }; n--; b|=(z.next_in[p++]&0xff)<<k; k+=8; } t = (int)(b & 7); last = t & 1; switch (t >>> 1){ case 0: // stored {b>>>=(3);k-=(3);} t = k & 7; // go to byte boundary {b>>>=(t);k-=(t);} mode = LENS; // get length of stored block break; case 1: // fixed { 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=(int)(q<read?read-q-1:end-q); } if(m==0){ write=q; r=inflate_flush(z,r); q=write;m=(int)(q<read?read-q-1:end-q); if(q==end&&read!=0){ q=0; m=(int)(q<read?read-q-1:end-q); } if(m==0){ bitb=b; bitk=k; z.avail_in=n;z.total_in+=p-z.next_in_index;z.next_in_index=p; write=q; return inflate_flush(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=(int)(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=(int)(q<read?read-q-1:end-q); if (read != write){ bitb=b; bitk=k; z.avail_in=n;z.total_in+=p-z.next_in_index;z.next_in_index=p; write=q; return inflate_flush(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 free(ZStream z){ reset(z, null); window=null; hufts=null; //ZFREE(z, s); } void set_dictionary(byte[] d, int start, int n){ System.arraycopy(d, start, window, 0, n); read = write = n; } // Returns true if inflate is currently at the end of a block generated // by Z_SYNC_FLUSH or Z_FULL_FLUSH. int sync_point(){ return mode == LENS ? 1 : 0; } // copy as much as possible from the sliding window to the output area int inflate_flush(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 = (int)((q <= write ? write : end) - q); if (n > z.avail_out) n = z.avail_out; if (n!=0 && r == Z_BUF_ERROR) r = Z_OK; // update counters z.avail_out -= n; z.total_out += n; // update check information if(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; } }
1030365071-xuechao
src/com/jcraft/jzlib/InfBlocks.java
Java
asf20
15,158
/* -*-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; } }
1030365071-xuechao
src/com/jcraft/jzlib/StaticTree.java
Java
asf20
6,164
/* -*-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"; public static String version(){return version;} // 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; }
1030365071-xuechao
src/com/jcraft/jzlib/JZlib.java
Java
asf20
2,803
/* -*-mode:java; c-basic-offset:2; -*- */ /* Copyright (c) 2000,2001,2002,2003 ymnk, JCraft,Inc. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. The names of the authors may not be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JCRAFT, INC. OR ANY CONTRIBUTORS TO THIS SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /* * This program is based on zlib-1.1.3, so all credit should go authors * Jean-loup Gailly(jloup@gzip.org) and Mark Adler(madler@alumni.caltech.edu) * and contributors of zlib. */ package com.jcraft.jzlib; final class Tree{ static final private int MAX_BITS=15; static final private int BL_CODES=19; static final private int D_CODES=30; static final private int LITERALS=256; static final private int LENGTH_CODES=29; static final private int L_CODES=(LITERALS+1+LENGTH_CODES); static final private int HEAP_SIZE=(2*L_CODES+1); // Bit length codes must not exceed MAX_BL_BITS bits static final int MAX_BL_BITS=7; // end of block literal code static final int END_BLOCK=256; // repeat previous bit length 3-6 times (2 bits of repeat count) static final int REP_3_6=16; // repeat a zero length 3-10 times (3 bits of repeat count) static final int REPZ_3_10=17; // repeat a zero length 11-138 times (7 bits of repeat count) static final int REPZ_11_138=18; // extra bits for each length code static final int[] extra_lbits={ 0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0 }; // extra bits for each distance code static final int[] extra_dbits={ 0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13 }; // extra bits for each bit length code static final int[] extra_blbits={ 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7 }; static final byte[] bl_order={ 16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15}; // The lengths of the bit length codes are sent in order of decreasing // probability, to avoid transmitting the lengths for unused bit // length codes. static final int Buf_size=8*2; // see definition of array dist_code below static final int DIST_CODE_LEN=512; static final byte[] _dist_code = { 0, 1, 2, 3, 4, 4, 5, 5, 6, 6, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 0, 0, 16, 17, 18, 18, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 22, 22, 22, 22, 22, 22, 22, 22, 23, 23, 23, 23, 23, 23, 23, 23, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29 }; static final byte[] _length_code={ 0, 1, 2, 3, 4, 5, 6, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 12, 12, 13, 13, 13, 13, 14, 14, 14, 14, 15, 15, 15, 15, 16, 16, 16, 16, 16, 16, 16, 16, 17, 17, 17, 17, 17, 17, 17, 17, 18, 18, 18, 18, 18, 18, 18, 18, 19, 19, 19, 19, 19, 19, 19, 19, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 28 }; static final int[] base_length = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 10, 12, 14, 16, 20, 24, 28, 32, 40, 48, 56, 64, 80, 96, 112, 128, 160, 192, 224, 0 }; static final int[] base_dist = { 0, 1, 2, 3, 4, 6, 8, 12, 16, 24, 32, 48, 64, 96, 128, 192, 256, 384, 512, 768, 1024, 1536, 2048, 3072, 4096, 6144, 8192, 12288, 16384, 24576 }; // Mapping from a distance to a distance code. dist is the distance - 1 and // must not have side effects. _dist_code[256] and _dist_code[257] are never // used. static int d_code(int dist){ return ((dist) < 256 ? _dist_code[dist] : _dist_code[256+((dist)>>>7)]); } short[] dyn_tree; // the dynamic tree int max_code; // largest code with non zero frequency StaticTree stat_desc; // the corresponding static tree // Compute the optimal bit lengths for a tree and update the total bit length // for the current block. // IN assertion: the fields freq and dad are set, heap[heap_max] and // above are the tree nodes sorted by increasing frequency. // OUT assertions: the field len is set to the optimal bit length, the // array bl_count contains the frequencies for each bit length. // The length opt_len is updated; static_len is also updated if stree is // not null. void gen_bitlen(Deflate s){ short[] tree = dyn_tree; short[] stree = stat_desc.static_tree; int[] extra = stat_desc.extra_bits; int base = stat_desc.extra_base; int max_length = stat_desc.max_length; int h; // heap index int n, m; // iterate over the tree elements int bits; // bit length int xbits; // extra bits short f; // frequency int overflow = 0; // number of elements with bit length too large for (bits = 0; bits <= MAX_BITS; bits++) s.bl_count[bits] = 0; // In a first pass, compute the optimal bit lengths (which may // overflow in the case of the bit length tree). tree[s.heap[s.heap_max]*2+1] = 0; // root of the heap for(h=s.heap_max+1; h<HEAP_SIZE; h++){ n = s.heap[h]; bits = tree[tree[n*2+1]*2+1] + 1; if (bits > max_length){ bits = max_length; overflow++; } tree[n*2+1] = (short)bits; // We overwrite tree[n*2+1] which is no longer needed if (n > max_code) continue; // not a leaf node s.bl_count[bits]++; xbits = 0; if (n >= base) xbits = extra[n-base]; f = tree[n*2]; s.opt_len += f * (bits + xbits); if (stree!=null) s.static_len += f * (stree[n*2+1] + xbits); } if (overflow == 0) return; // This happens for example on obj2 and pic of the Calgary corpus // Find the first bit length which could increase: do { bits = max_length-1; while(s.bl_count[bits]==0) bits--; s.bl_count[bits]--; // move one leaf down the tree s.bl_count[bits+1]+=2; // move one overflow item as its brother s.bl_count[max_length]--; // The brother of the overflow item also moves one step up, // but this does not affect bl_count[max_length] overflow -= 2; } while (overflow > 0); for (bits = max_length; bits != 0; bits--) { n = s.bl_count[bits]; while (n != 0) { m = s.heap[--h]; if (m > max_code) continue; if (tree[m*2+1] != bits) { s.opt_len += ((long)bits - (long)tree[m*2+1])*(long)tree[m*2]; tree[m*2+1] = (short)bits; } n--; } } } // Construct one Huffman tree and assigns the code bit strings and lengths. // Update the total bit length for the current block. // IN assertion: the field freq is set for all tree elements. // OUT assertions: the fields len and code are set to the optimal bit length // and corresponding code. The length opt_len is updated; static_len is // also updated if stree is not null. The field max_code is set. void build_tree(Deflate s){ short[] tree=dyn_tree; short[] stree=stat_desc.static_tree; int elems=stat_desc.elems; int n, m; // iterate over heap elements int max_code=-1; // largest code with non zero frequency int node; // new node being created // Construct the initial heap, with least frequent element in // heap[1]. The sons of heap[n] are heap[2*n] and heap[2*n+1]. // heap[0] is not used. s.heap_len = 0; s.heap_max = HEAP_SIZE; for(n=0; n<elems; n++) { if(tree[n*2] != 0) { s.heap[++s.heap_len] = max_code = n; s.depth[n] = 0; } else{ tree[n*2+1] = 0; } } // The pkzip format requires that at least one distance code exists, // and that at least one bit should be sent even if there is only one // possible code. So to avoid special checks later on we force at least // two codes of non zero frequency. while (s.heap_len < 2) { node = s.heap[++s.heap_len] = (max_code < 2 ? ++max_code : 0); tree[node*2] = 1; s.depth[node] = 0; s.opt_len--; if (stree!=null) s.static_len -= stree[node*2+1]; // node is 0 or 1 so it does not have extra bits } this.max_code = max_code; // The elements heap[heap_len/2+1 .. heap_len] are leaves of the tree, // establish sub-heaps of increasing lengths: for(n=s.heap_len/2;n>=1; n--) s.pqdownheap(tree, n); // Construct the Huffman tree by repeatedly combining the least two // frequent nodes. node=elems; // next internal node of the tree do{ // n = node of least frequency n=s.heap[1]; s.heap[1]=s.heap[s.heap_len--]; s.pqdownheap(tree, 1); m=s.heap[1]; // m = node of next least frequency s.heap[--s.heap_max] = n; // keep the nodes sorted by frequency s.heap[--s.heap_max] = m; // Create a new node father of n and m tree[node*2] = (short)(tree[n*2] + tree[m*2]); s.depth[node] = (byte)(Math.max(s.depth[n],s.depth[m])+1); tree[n*2+1] = tree[m*2+1] = (short)node; // and insert the new node in the heap s.heap[1] = node++; s.pqdownheap(tree, 1); } while(s.heap_len>=2); s.heap[--s.heap_max] = s.heap[1]; // At this point, the fields freq and dad are set. We can now // generate the bit lengths. gen_bitlen(s); // The field len is now set, we can generate the bit codes gen_codes(tree, max_code, s.bl_count); } // 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)); } } // 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; } }
1030365071-xuechao
src/com/jcraft/jzlib/Tree.java
Java
asf20
14,868
/* -*-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); } }
1030365071-xuechao
src/com/jcraft/jzlib/ZStreamException.java
Java
asf20
1,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; public final class Deflate{ 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 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 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; 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 // 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; // Window position at the beginning of the current output block. Gets // negative when the window is moved backwards. 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; // 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; // 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. 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; int last_lit; // running index in l_buf // 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 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 } 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; } // 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(); } 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; } // 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; } 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])); } // 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; } } } // 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 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 } // 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; } } } // 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_byte(byte c){ pending_buf[pending++]=c; } 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*/)); } final void send_code(int c, short[] tree){ int c2=c*2; send_bits((tree[c2]&0xffff), (tree[c2+1]&0xffff)); } void send_bits(int value, int length){ int len = length; if (bi_valid > (int)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; } } // 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; } // 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 += (int)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. } // 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]; } // 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); } // 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; } // 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); } 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(); } // 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 = (int)(strstart-max_start); strstart = (int)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; } // 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 } // 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(); } } // 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); } // 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; } 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 - (int)(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; } int deflateInit(ZStream strm, int level, int bits){ return deflateInit2(strm, level, Z_DEFLATED, bits, DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY); } int deflateInit(ZStream strm, int level){ return deflateInit(strm, level, MAX_WBITS); } 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 = (Deflate)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 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 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 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 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; } 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; } }
1030365071-xuechao
src/com/jcraft/jzlib/Deflate.java
Java
asf20
54,205
/* -*-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.*; 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; 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 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; } /*public int available() throws IOException { return inf.finished() ? 0 : 1; }*/ public int read() throws IOException { if(read(buf1, 0, 1)==-1) return(-1); return(buf1[0]&0xFF); } private boolean nomoreinput=false; 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 long skip(long n) throws IOException { int len=512; if(n<len) len=(int)n; byte[] tmp=new byte[len]; return((long)read(tmp)); } public int getFlushMode() { return(flush); } public void setFlushMode(int flush) { this.flush=flush; } /** * 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 close() throws IOException{ in.close(); } }
1030365071-xuechao
src/com/jcraft/jzlib/ZInputStream.java
Java
asf20
4,279
/* -*-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.*; 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; } public void write(int b) throws IOException { buf1[0]=(byte)b; write(buf1, 0, 1); } public void write(byte b[], int off, int len) throws IOException { if(len==0) return; 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); } public int getFlushMode() { return(flush); } public void setFlushMode(int flush) { this.flush=flush; } 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(); } public void end() { if(z==null) return; if(compress){ z.deflateEnd(); } else{ z.inflateEnd(); } z.free(); z=null; } public void close() throws IOException { try{ try{finish();} catch (IOException ignored) {} } finally{ end(); out.close(); out=null; } } /** * 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 flush() throws IOException { out.flush(); } }
1030365071-xuechao
src/com/jcraft/jzlib/ZOutputStream.java
Java
asf20
4,315
/* -*-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 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 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 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 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; } static private byte[] mark = {(byte)0, (byte)0, (byte)0xff, (byte)0xff}; 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(); } }
1030365071-xuechao
src/com/jcraft/jzlib/Inflate.java
Java
asf20
11,302
/* -*-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 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; } 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); } } } void free(ZStream z){ // ZFREE(z, c); } // Called with number of bytes left to write in window at least 258 // (the maximum string length) and number of input bytes available // at least ten. The ten bytes are six bytes for the longest length/ // distance pair plus four bytes for overloading the bit buffer. int inflate_fast(int bl, int bd, int[] tl, int tl_index, int[] td, int td_index, InfBlocks s, ZStream z){ int t; // temporary pointer int[] tp; // temporary pointer int tp_index; // temporary pointer int e; // extra bits or operation int b; // bit buffer int k; // bits in bit buffer int p; // input data pointer int n; // bytes available there int q; // output window write pointer int m; // bytes to end of window or read pointer int ml; // mask for literal/length tree int md; // mask for distance tree int c; // bytes to copy int d; // distance back to copy from int r; // copy source pointer int tp_index_t_3; // (tp_index+t)*3 // load input, output, bit values p=z.next_in_index;n=z.avail_in;b=s.bitb;k=s.bitk; q=s.write;m=q<s.read?s.read-q-1:s.end-q; // initialize masks ml = inflate_mask[bl]; md = inflate_mask[bd]; // do until not enough input or output space for fast loop do { // assume called with m >= 258 && n >= 10 // get literal/length code while(k<(20)){ // max bits for literal/length code n--; b|=(z.next_in[p++]&0xff)<<k;k+=8; } t= b&ml; tp=tl; tp_index=tl_index; tp_index_t_3=(tp_index+t)*3; if ((e = tp[tp_index_t_3]) == 0){ b>>=(tp[tp_index_t_3+1]); k-=(tp[tp_index_t_3+1]); s.window[q++] = (byte)tp[tp_index_t_3+2]; m--; continue; } do { b>>=(tp[tp_index_t_3+1]); k-=(tp[tp_index_t_3+1]); if((e&16)!=0){ e &= 15; c = tp[tp_index_t_3+2] + ((int)b & inflate_mask[e]); b>>=e; k-=e; // decode distance base of block to copy while(k<(15)){ // max bits for distance code n--; b|=(z.next_in[p++]&0xff)<<k;k+=8; } t= b&md; tp=td; tp_index=td_index; tp_index_t_3=(tp_index+t)*3; e = tp[tp_index_t_3]; do { b>>=(tp[tp_index_t_3+1]); k-=(tp[tp_index_t_3+1]); if((e&16)!=0){ // get extra bits to add to distance base e &= 15; while(k<(e)){ // get extra bits (up to 13) n--; b|=(z.next_in[p++]&0xff)<<k;k+=8; } d = tp[tp_index_t_3+2] + (b&inflate_mask[e]); b>>=(e); k-=(e); // do the copy m -= c; if (q >= d){ // offset before dest // just copy r=q-d; if(q-r>0 && 2>(q-r)){ s.window[q++]=s.window[r++]; // minimum count is three, s.window[q++]=s.window[r++]; // so unroll loop a little c-=2; } else{ System.arraycopy(s.window, r, s.window, q, 2); q+=2; r+=2; c-=2; } } else{ // else offset after destination r=q-d; do{ r+=s.end; // force pointer in window }while(r<0); // covers invalid distances e=s.end-r; if(c>e){ // if source crosses, c-=e; // wrapped copy if(q-r>0 && e>(q-r)){ do{s.window[q++] = s.window[r++];} while(--e!=0); } else{ System.arraycopy(s.window, r, s.window, q, e); q+=e; r+=e; e=0; } r = 0; // copy rest from start of window } } // copy all or what's left if(q-r>0 && c>(q-r)){ do{s.window[q++] = s.window[r++];} while(--c!=0); } else{ System.arraycopy(s.window, r, s.window, q, c); q+=c; r+=c; c=0; } break; } else if((e&64)==0){ t+=tp[tp_index_t_3+2]; t+=(b&inflate_mask[e]); tp_index_t_3=(tp_index+t)*3; e=tp[tp_index_t_3]; } else{ z.msg = "invalid distance code"; c=z.avail_in-n;c=(k>>3)<c?k>>3:c;n+=c;p-=c;k-=c<<3; s.bitb=b;s.bitk=k; z.avail_in=n;z.total_in+=p-z.next_in_index;z.next_in_index=p; s.write=q; return Z_DATA_ERROR; } } while(true); break; } if((e&64)==0){ t+=tp[tp_index_t_3+2]; t+=(b&inflate_mask[e]); tp_index_t_3=(tp_index+t)*3; if((e=tp[tp_index_t_3])==0){ b>>=(tp[tp_index_t_3+1]); k-=(tp[tp_index_t_3+1]); s.window[q++]=(byte)tp[tp_index_t_3+2]; m--; break; } } else if((e&32)!=0){ c=z.avail_in-n;c=(k>>3)<c?k>>3:c;n+=c;p-=c;k-=c<<3; s.bitb=b;s.bitk=k; z.avail_in=n;z.total_in+=p-z.next_in_index;z.next_in_index=p; s.write=q; return Z_STREAM_END; } else{ z.msg="invalid literal/length code"; c=z.avail_in-n;c=(k>>3)<c?k>>3:c;n+=c;p-=c;k-=c<<3; s.bitb=b;s.bitk=k; z.avail_in=n;z.total_in+=p-z.next_in_index;z.next_in_index=p; s.write=q; return Z_DATA_ERROR; } } while(true); } while(m>=258 && n>= 10); // not enough input or output--restore pointers and return c=z.avail_in-n;c=(k>>3)<c?k>>3:c;n+=c;p-=c;k-=c<<3; s.bitb=b;s.bitk=k; z.avail_in=n;z.total_in+=p-z.next_in_index;z.next_in_index=p; s.write=q; return Z_OK; } }
1030365071-xuechao
src/com/jcraft/jzlib/InfCodes.java
Java
asf20
16,042
/* -*-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 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 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 inflateSync(){ if(istate == null) return Z_STREAM_ERROR; return istate.inflateSync(this); } public int inflateSetDictionary(byte[] dictionary, int dictLength){ if(istate == null) return Z_STREAM_ERROR; return istate.inflateSetDictionary(this, dictionary, dictLength); } 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 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 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; } } // 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; } public void free(){ next_in=null; next_out=null; msg=null; _adler=null; } }
1030365071-xuechao
src/com/jcraft/jzlib/ZStream.java
Java
asf20
6,990
/* -*-mode:java; c-basic-offset:2; indent-tabs-mode:nil -*- */ /* Copyright (c) 2000,2001,2002,2003 ymnk, JCraft,Inc. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. The names of the authors may not be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JCRAFT, INC. OR ANY CONTRIBUTORS TO THIS SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /* * This program is based on zlib-1.1.3, so all credit should go authors * Jean-loup Gailly(jloup@gzip.org) and Mark Adler(madler@alumni.caltech.edu) * and contributors of zlib. */ package com.jcraft.jzlib; final class InfTree{ static final private int MANY=1440; static final private int Z_OK=0; static final private int Z_STREAM_END=1; static final private int Z_NEED_DICT=2; static final private int Z_ERRNO=-1; static final private int Z_STREAM_ERROR=-2; static final private int Z_DATA_ERROR=-3; static final private int Z_MEM_ERROR=-4; static final private int Z_BUF_ERROR=-5; static final private int Z_VERSION_ERROR=-6; static final int fixed_bl = 9; static final int fixed_bd = 5; static final int[] fixed_tl = { 96,7,256, 0,8,80, 0,8,16, 84,8,115, 82,7,31, 0,8,112, 0,8,48, 0,9,192, 80,7,10, 0,8,96, 0,8,32, 0,9,160, 0,8,0, 0,8,128, 0,8,64, 0,9,224, 80,7,6, 0,8,88, 0,8,24, 0,9,144, 83,7,59, 0,8,120, 0,8,56, 0,9,208, 81,7,17, 0,8,104, 0,8,40, 0,9,176, 0,8,8, 0,8,136, 0,8,72, 0,9,240, 80,7,4, 0,8,84, 0,8,20, 85,8,227, 83,7,43, 0,8,116, 0,8,52, 0,9,200, 81,7,13, 0,8,100, 0,8,36, 0,9,168, 0,8,4, 0,8,132, 0,8,68, 0,9,232, 80,7,8, 0,8,92, 0,8,28, 0,9,152, 84,7,83, 0,8,124, 0,8,60, 0,9,216, 82,7,23, 0,8,108, 0,8,44, 0,9,184, 0,8,12, 0,8,140, 0,8,76, 0,9,248, 80,7,3, 0,8,82, 0,8,18, 85,8,163, 83,7,35, 0,8,114, 0,8,50, 0,9,196, 81,7,11, 0,8,98, 0,8,34, 0,9,164, 0,8,2, 0,8,130, 0,8,66, 0,9,228, 80,7,7, 0,8,90, 0,8,26, 0,9,148, 84,7,67, 0,8,122, 0,8,58, 0,9,212, 82,7,19, 0,8,106, 0,8,42, 0,9,180, 0,8,10, 0,8,138, 0,8,74, 0,9,244, 80,7,5, 0,8,86, 0,8,22, 192,8,0, 83,7,51, 0,8,118, 0,8,54, 0,9,204, 81,7,15, 0,8,102, 0,8,38, 0,9,172, 0,8,6, 0,8,134, 0,8,70, 0,9,236, 80,7,9, 0,8,94, 0,8,30, 0,9,156, 84,7,99, 0,8,126, 0,8,62, 0,9,220, 82,7,27, 0,8,110, 0,8,46, 0,9,188, 0,8,14, 0,8,142, 0,8,78, 0,9,252, 96,7,256, 0,8,81, 0,8,17, 85,8,131, 82,7,31, 0,8,113, 0,8,49, 0,9,194, 80,7,10, 0,8,97, 0,8,33, 0,9,162, 0,8,1, 0,8,129, 0,8,65, 0,9,226, 80,7,6, 0,8,89, 0,8,25, 0,9,146, 83,7,59, 0,8,121, 0,8,57, 0,9,210, 81,7,17, 0,8,105, 0,8,41, 0,9,178, 0,8,9, 0,8,137, 0,8,73, 0,9,242, 80,7,4, 0,8,85, 0,8,21, 80,8,258, 83,7,43, 0,8,117, 0,8,53, 0,9,202, 81,7,13, 0,8,101, 0,8,37, 0,9,170, 0,8,5, 0,8,133, 0,8,69, 0,9,234, 80,7,8, 0,8,93, 0,8,29, 0,9,154, 84,7,83, 0,8,125, 0,8,61, 0,9,218, 82,7,23, 0,8,109, 0,8,45, 0,9,186, 0,8,13, 0,8,141, 0,8,77, 0,9,250, 80,7,3, 0,8,83, 0,8,19, 85,8,195, 83,7,35, 0,8,115, 0,8,51, 0,9,198, 81,7,11, 0,8,99, 0,8,35, 0,9,166, 0,8,3, 0,8,131, 0,8,67, 0,9,230, 80,7,7, 0,8,91, 0,8,27, 0,9,150, 84,7,67, 0,8,123, 0,8,59, 0,9,214, 82,7,19, 0,8,107, 0,8,43, 0,9,182, 0,8,11, 0,8,139, 0,8,75, 0,9,246, 80,7,5, 0,8,87, 0,8,23, 192,8,0, 83,7,51, 0,8,119, 0,8,55, 0,9,206, 81,7,15, 0,8,103, 0,8,39, 0,9,174, 0,8,7, 0,8,135, 0,8,71, 0,9,238, 80,7,9, 0,8,95, 0,8,31, 0,9,158, 84,7,99, 0,8,127, 0,8,63, 0,9,222, 82,7,27, 0,8,111, 0,8,47, 0,9,190, 0,8,15, 0,8,143, 0,8,79, 0,9,254, 96,7,256, 0,8,80, 0,8,16, 84,8,115, 82,7,31, 0,8,112, 0,8,48, 0,9,193, 80,7,10, 0,8,96, 0,8,32, 0,9,161, 0,8,0, 0,8,128, 0,8,64, 0,9,225, 80,7,6, 0,8,88, 0,8,24, 0,9,145, 83,7,59, 0,8,120, 0,8,56, 0,9,209, 81,7,17, 0,8,104, 0,8,40, 0,9,177, 0,8,8, 0,8,136, 0,8,72, 0,9,241, 80,7,4, 0,8,84, 0,8,20, 85,8,227, 83,7,43, 0,8,116, 0,8,52, 0,9,201, 81,7,13, 0,8,100, 0,8,36, 0,9,169, 0,8,4, 0,8,132, 0,8,68, 0,9,233, 80,7,8, 0,8,92, 0,8,28, 0,9,153, 84,7,83, 0,8,124, 0,8,60, 0,9,217, 82,7,23, 0,8,108, 0,8,44, 0,9,185, 0,8,12, 0,8,140, 0,8,76, 0,9,249, 80,7,3, 0,8,82, 0,8,18, 85,8,163, 83,7,35, 0,8,114, 0,8,50, 0,9,197, 81,7,11, 0,8,98, 0,8,34, 0,9,165, 0,8,2, 0,8,130, 0,8,66, 0,9,229, 80,7,7, 0,8,90, 0,8,26, 0,9,149, 84,7,67, 0,8,122, 0,8,58, 0,9,213, 82,7,19, 0,8,106, 0,8,42, 0,9,181, 0,8,10, 0,8,138, 0,8,74, 0,9,245, 80,7,5, 0,8,86, 0,8,22, 192,8,0, 83,7,51, 0,8,118, 0,8,54, 0,9,205, 81,7,15, 0,8,102, 0,8,38, 0,9,173, 0,8,6, 0,8,134, 0,8,70, 0,9,237, 80,7,9, 0,8,94, 0,8,30, 0,9,157, 84,7,99, 0,8,126, 0,8,62, 0,9,221, 82,7,27, 0,8,110, 0,8,46, 0,9,189, 0,8,14, 0,8,142, 0,8,78, 0,9,253, 96,7,256, 0,8,81, 0,8,17, 85,8,131, 82,7,31, 0,8,113, 0,8,49, 0,9,195, 80,7,10, 0,8,97, 0,8,33, 0,9,163, 0,8,1, 0,8,129, 0,8,65, 0,9,227, 80,7,6, 0,8,89, 0,8,25, 0,9,147, 83,7,59, 0,8,121, 0,8,57, 0,9,211, 81,7,17, 0,8,105, 0,8,41, 0,9,179, 0,8,9, 0,8,137, 0,8,73, 0,9,243, 80,7,4, 0,8,85, 0,8,21, 80,8,258, 83,7,43, 0,8,117, 0,8,53, 0,9,203, 81,7,13, 0,8,101, 0,8,37, 0,9,171, 0,8,5, 0,8,133, 0,8,69, 0,9,235, 80,7,8, 0,8,93, 0,8,29, 0,9,155, 84,7,83, 0,8,125, 0,8,61, 0,9,219, 82,7,23, 0,8,109, 0,8,45, 0,9,187, 0,8,13, 0,8,141, 0,8,77, 0,9,251, 80,7,3, 0,8,83, 0,8,19, 85,8,195, 83,7,35, 0,8,115, 0,8,51, 0,9,199, 81,7,11, 0,8,99, 0,8,35, 0,9,167, 0,8,3, 0,8,131, 0,8,67, 0,9,231, 80,7,7, 0,8,91, 0,8,27, 0,9,151, 84,7,67, 0,8,123, 0,8,59, 0,9,215, 82,7,19, 0,8,107, 0,8,43, 0,9,183, 0,8,11, 0,8,139, 0,8,75, 0,9,247, 80,7,5, 0,8,87, 0,8,23, 192,8,0, 83,7,51, 0,8,119, 0,8,55, 0,9,207, 81,7,15, 0,8,103, 0,8,39, 0,9,175, 0,8,7, 0,8,135, 0,8,71, 0,9,239, 80,7,9, 0,8,95, 0,8,31, 0,9,159, 84,7,99, 0,8,127, 0,8,63, 0,9,223, 82,7,27, 0,8,111, 0,8,47, 0,9,191, 0,8,15, 0,8,143, 0,8,79, 0,9,255 }; static final int[] fixed_td = { 80,5,1, 87,5,257, 83,5,17, 91,5,4097, 81,5,5, 89,5,1025, 85,5,65, 93,5,16385, 80,5,3, 88,5,513, 84,5,33, 92,5,8193, 82,5,9, 90,5,2049, 86,5,129, 192,5,24577, 80,5,2, 87,5,385, 83,5,25, 91,5,6145, 81,5,7, 89,5,1537, 85,5,97, 93,5,24577, 80,5,4, 88,5,769, 84,5,49, 92,5,12289, 82,5,13, 90,5,3073, 86,5,193, 192,5,24577 }; // Tables for deflate from PKZIP's appnote.txt. static final int[] cplens = { // Copy lengths for literal codes 257..285 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31, 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0 }; // see note #13 above about 258 static final int[] cplext = { // Extra bits for literal codes 257..285 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 0, 112, 112 // 112==invalid }; static final int[] cpdist = { // Copy offsets for distance codes 0..29 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193, 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145, 8193, 12289, 16385, 24577 }; static final int[] cpdext = { // Extra bits for distance codes 0, 0, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13}; // If BMAX needs to be larger than 16, then h and x[] should be uLong. static final int BMAX=15; // maximum bit length of any code int[] hn = null; // hufts used in space int[] v = null; // work area for huft_build int[] c = null; // bit length count table int[] r = null; // table entry for structure assignment int[] u = null; // table stack int[] x = null; // bit offsets, then code stack private int huft_build(int[] b, // code lengths in bits (all assumed <= BMAX) int bindex, int n, // number of codes (assumed <= 288) int s, // number of simple-valued codes (0..s-1) int[] d, // list of base values for non-simple codes int[] e, // list of extra bits for non-simple codes int[] t, // result: starting table int[] m, // maximum lookup bits, returns actual int[] hp,// space for trees int[] hn,// hufts used in space int[] v // working area: values in order of bit length ){ // Given a list of code lengths and a maximum table size, make a set of // tables to decode that set of codes. Return Z_OK on success, Z_BUF_ERROR // if the given code set is incomplete (the tables are still built in this // case), Z_DATA_ERROR if the input is invalid (an over-subscribed set of // lengths), or Z_MEM_ERROR if not enough memory. int a; // counter for codes of length k int f; // i repeats in table every f entries int g; // maximum code length int h; // table level int i; // counter, current code int j; // counter int k; // number of bits in current code int l; // bits per table (returned in m) int mask; // (1 << w) - 1, to avoid cc -O bug on HP int p; // pointer into c[], b[], or v[] int q; // points to current table int w; // bits before this table == (l * h) int xp; // pointer into x int y; // number of dummy codes added int z; // number of entries in current table // Generate counts for each bit length p = 0; i = n; do { c[b[bindex+p]]++; p++; i--; // assume all entries <= BMAX }while(i!=0); if(c[0] == n){ // null input--all zero length codes t[0] = -1; m[0] = 0; return Z_OK; } // Find minimum and maximum length, bound *m by those l = m[0]; for (j = 1; j <= BMAX; j++) if(c[j]!=0) break; k = j; // minimum code length if(l < j){ l = j; } for (i = BMAX; i!=0; i--){ if(c[i]!=0) break; } g = i; // maximum code length if(l > i){ l = i; } m[0] = l; // Adjust last length count to fill out codes, if needed for (y = 1 << j; j < i; j++, y <<= 1){ if ((y -= c[j]) < 0){ return Z_DATA_ERROR; } } if ((y -= c[i]) < 0){ return Z_DATA_ERROR; } c[i] += y; // Generate starting offsets into the value table for each length x[1] = j = 0; p = 1; xp = 2; while (--i!=0) { // note that i == g from above x[xp] = (j += c[p]); xp++; p++; } // Make a table of values in order of bit lengths i = 0; p = 0; do { if ((j = b[bindex+p]) != 0){ v[x[j]++] = i; } p++; } while (++i < n); n = x[g]; // set n to length of v // Generate the Huffman codes and for each, make the table entries x[0] = i = 0; // first Huffman code is zero p = 0; // grab values in bit order h = -1; // no tables yet--level -1 w = -l; // bits decoded == (l * h) u[0] = 0; // just to keep compilers happy q = 0; // ditto z = 0; // ditto // go through the bit lengths (k already is bits in shortest code) for (; k <= g; k++){ a = c[k]; while (a--!=0){ // here i is the Huffman code of length k bits for value *p // make tables up to required level while (k > w + l){ h++; w += l; // previous table always l bits // compute minimum size table less than or equal to l bits z = g - w; z = (z > l) ? l : z; // table size upper limit if((f=1<<(j=k-w))>a+1){ // try a k-w bit table // too few codes for k-w bit table f -= a + 1; // deduct codes from patterns left xp = k; if(j < z){ while (++j < z){ // try smaller tables up to z bits if((f <<= 1) <= c[++xp]) break; // enough codes to use up j bits f -= c[xp]; // else deduct codes from patterns } } } z = 1 << j; // table entries for j-bit table // allocate new table if (hn[0] + z > MANY){ // (note: doesn't matter for fixed) return Z_DATA_ERROR; // overflow of MANY } u[h] = q = /*hp+*/ hn[0]; // DEBUG hn[0] += z; // connect to last table, if there is one if(h!=0){ x[h]=i; // save pattern for backing up r[0]=(byte)j; // bits in this table r[1]=(byte)l; // bits to dump before this table j=i>>>(w - l); r[2] = (int)(q - u[h-1] - j); // offset to this table System.arraycopy(r, 0, hp, (u[h-1]+j)*3, 3); // connect to last table } else{ t[0] = q; // first table is returned result } } // set up table entry in r r[1] = (byte)(k - w); if (p >= n){ r[0] = 128 + 64; // out of values--invalid code } else if (v[p] < s){ r[0] = (byte)(v[p] < 256 ? 0 : 32 + 64); // 256 is end-of-block r[2] = v[p++]; // simple code is just the value } else{ r[0]=(byte)(e[v[p]-s]+16+64); // non-simple--look up in lists r[2]=d[v[p++] - s]; } // fill code-like entries with r f=1<<(k-w); for (j=i>>>w;j<z;j+=f){ System.arraycopy(r, 0, hp, (q+j)*3, 3); } // backwards increment the k-bit code i for (j = 1 << (k - 1); (i & j)!=0; j >>>= 1){ i ^= j; } i ^= j; // backup over finished tables mask = (1 << w) - 1; // needed on HP, cc -O bug while ((i & mask) != x[h]){ h--; // don't need to update q w -= l; mask = (1 << w) - 1; } } } // Return Z_BUF_ERROR if we were given an incomplete table return y != 0 && g != 1 ? Z_BUF_ERROR : Z_OK; } int inflate_trees_bits(int[] c, // 19 code lengths int[] bb, // bits tree desired/actual depth int[] tb, // bits tree result int[] hp, // space for trees ZStream z // for messages ){ int result; initWorkArea(19); hn[0]=0; result = huft_build(c, 0, 19, 19, null, null, tb, bb, hp, hn, v); if(result == Z_DATA_ERROR){ z.msg = "oversubscribed dynamic bit lengths tree"; } else if(result == Z_BUF_ERROR || bb[0] == 0){ z.msg = "incomplete dynamic bit lengths tree"; result = Z_DATA_ERROR; } return result; } int inflate_trees_dynamic(int nl, // number of literal/length codes int nd, // number of distance codes int[] c, // that many (total) code lengths int[] bl, // literal desired/actual bit depth int[] bd, // distance desired/actual bit depth int[] tl, // literal/length tree result int[] td, // distance tree result int[] hp, // space for trees ZStream z // for messages ){ int result; // build literal/length tree initWorkArea(288); hn[0]=0; result = huft_build(c, 0, nl, 257, cplens, cplext, tl, bl, hp, hn, v); if (result != Z_OK || bl[0] == 0){ if(result == Z_DATA_ERROR){ z.msg = "oversubscribed literal/length tree"; } else if (result != Z_MEM_ERROR){ z.msg = "incomplete literal/length tree"; result = Z_DATA_ERROR; } return result; } // build distance tree initWorkArea(288); result = huft_build(c, nl, nd, 0, cpdist, cpdext, td, bd, hp, hn, v); if (result != Z_OK || (bd[0] == 0 && nl > 257)){ if (result == Z_DATA_ERROR){ z.msg = "oversubscribed distance tree"; } else if (result == Z_BUF_ERROR) { z.msg = "incomplete distance tree"; result = Z_DATA_ERROR; } else if (result != Z_MEM_ERROR){ z.msg = "empty distance tree with lengths"; result = Z_DATA_ERROR; } return result; } return Z_OK; } static int inflate_trees_fixed(int[] bl, //literal desired/actual bit depth int[] bd, //distance desired/actual bit depth int[][] tl,//literal/length tree result int[][] td,//distance tree result ZStream z //for memory allocation ){ bl[0]=fixed_bl; bd[0]=fixed_bd; tl[0]=fixed_tl; td[0]=fixed_td; return Z_OK; } private void initWorkArea(int vsize){ if(hn==null){ hn=new int[1]; v=new int[vsize]; c=new int[BMAX+1]; r=new int[3]; u=new int[BMAX]; x=new int[BMAX+1]; } if(v.length<vsize){ v=new int[vsize]; } for(int i=0; i<vsize; i++){v[i]=0;} for(int i=0; i<BMAX+1; i++){c[i]=0;} for(int i=0; i<3; i++){r[i]=0;} // 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); } }
1030365071-xuechao
src/com/jcraft/jzlib/InfTree.java
Java
asf20
19,238
/* -*-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(); } */ }
1030365071-xuechao
src/com/jcraft/jzlib/Adler32.java
Java
asf20
3,289
#!/usr/bin/perl # # ConnectBot: simple, powerful, open-source SSH client for Android # Copyright 2011 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. # use strict; use warnings; use Getopt::Long; use Pod::Usage; use LWP::UserAgent; #use LWP::Debug qw(+); use HTTP::Cookies; use HTML::Form; use Data::Dumper; use IO::File; use XML::LibXML; use Locale::Language; use Locale::Country; my %config = ( 'url' => undef, 'username' => undef, 'password' => undef, 'build' => undef, 'branch' => undef, ); my $baseUrl; my $fileRegex; sub setupUA() { my $ua = LWP::UserAgent->new; push @{ $ua->requests_redirectable }, 'POST'; $ua->cookie_jar(HTTP::Cookies->new); return $ua; } sub getLoginToken($) { my $ua = shift; my $response = $ua->get("https://www.google.com/accounts/Login"); my @forms = HTML::Form->parse($response->content, $response->base); my $f = shift @forms; $f->param('Email', $config{'username'}); $f->param('Passwd', $config{'password'}); my $req = $f->click(); $response = $ua->request($req); if (not $response->is_success) { print "Got the error " . $response->status_line . "\n"; die "cannot login"; } } sub uploadFile($$) { my $ua = shift; my $targetFile = shift; # Go to package upload my $response = $ua->get($baseUrl . "entry"); my @forms = HTML::Form->parse($response->content, $response->base); my $f = $forms[$#forms]; my $summary = $config{'appname'} . " " . $config{'branch'} . " development snapshot"; if (defined($config{'build'})) { $summary .= " " . $config{'build'}; } $f->param('summary', $summary); $f->param('file', $targetFile); $f->param('label', 'Type-Installer', 'Featured'); my $req = $f->click('btn'); $response = $ua->request($req); return ($response->code eq "302"); } sub unfeature($$) { my $ua = shift; my $url = shift; print "unfeaturing $url\n"; my $response = $ua->get($url); if (not $response->is_success) { warn "couldn't reach $url"; return 0; } my @forms = HTML::Form->parse($response->content, $response->base); my $f = $forms[2]; my $i = 0; my $input = $f->find_input('label', 'text', $i++); while ($i != -1 and defined($input)) { if ($input->value eq 'Featured') { $input->value(''); $i = -1; } else { $input = $f->find_input('label', 'text', $i++); } } my $req = $f->click(); $response = $ua->request($req); if (not $response->is_success) { warn "unfeature: got the error " . $response->status_line . "\n"; return 0; } return 1; } sub deleteFile($$) { my $ua = shift; my $name = shift; my $url = $baseUrl . "delete?name=" . $name; my $response = $ua->get($url); if (not $response->is_success) { warn "deleteFile: couldn't reach $url"; return 0; } my @forms = HTML::Form->parse($response->content, $response->base); my $f = $forms[2]; my $req = $f->click('delete'); $response = $ua->request($req); if (not $response->is_success) { warn "deleteFile: got the error " . $response->status_line . "\n"; return 0; } print "Deleted $name\n"; return 1; } sub fixFeatured($) { my $ua = shift; my $response = $ua->get($baseUrl . 'list?q=label:Featured'); my $parser = XML::LibXML->new(); $parser->recover(1); my $doc = $parser->parse_html_string($response->content); my $root = $doc->getDocumentElement; my @nodes = $root->findnodes('//table[@id="resultstable"]//td[contains(@class, "col_1") and a[@class="label" and contains(@href, "Featured")]]/a[1]/@href'); foreach my $node (@nodes) { my $href = $node->findvalue('.'); next if ($href !~ $fileRegex); unfeature($ua, $baseUrl . $href) if ($2 ne $config{'build'} and $1 eq $config{'branch'}); } } sub deleteUndownloaded($$) { my $ua = shift; my $threshhold = shift; my $offset = 0; my $parser = XML::LibXML->new(); $parser->recover(1); my @toDelete = (); while (1) { my $response = $ua->get($baseUrl . 'list?start=' . $offset); my $doc = $parser->parse_html_string($response->content); my $root = $doc->getDocumentElement; my @nodes = $root->findnodes('//div[contains(., "Your search did not generate any results.")]'); last if $#nodes > -1; @nodes = $root->findnodes('//table[@id="resultstable"]//tr[@id="headingrow"]/th[starts-with(normalize-space(a), "DownloadCount")]/@class'); die 'Could not find DownloadCount header column' if ($#nodes == -1); my $downloadCountClass = $nodes[0]->findvalue('.'); @nodes = $root->findnodes('//table[@id="resultstable"]//td[contains(@class, "col_1") and not(a[@class="label" and contains(@href, "Featured")]) and ../td[contains(@class, "'.$downloadCountClass.'") and normalize-space(.) <= "'.$threshhold.'"]]/a[1]/@href'); foreach my $node (@nodes) { my $href = $node->findvalue('.'); next if ($href !~ $fileRegex); if ($href =~ /detail\?name=([^&]+)&/) { push @toDelete, $1; print "Pushing on $1\n"; } } $offset += 100; } #foreach my $href (@toDelete) { # deleteFile($ua, $href); #} } pod2usage(1) if ($#ARGV < 0); GetOptions(\%config, 'appname=s', 'username=s', 'password=s', 'build=s', 'branch=s', ); my $projectName = lc($config{'appname'}); $baseUrl = 'http://code.google.com/p/' . $projectName . '/downloads/'; $fileRegex = qr/$config{'appname'}-git-([a-z]*)-([0-9_-]*)(-[a-zA-Z]*)?\.apk/; my $ua = setupUA(); getLoginToken($ua); my $file = shift @ARGV; uploadFile($ua, $file); fixFeatured($ua); deleteUndownloaded($ua, 10); __END__ =head1 NAME google-code-upload.pl - Upload builds to Google Code =head1 SYNOPSIS google-code-upload.pl [options] <file> =head1 OPTIONS =over 8 =item B<--username> Username which has permission to uplaod files. =item B<--password> Password for user matching the username. =item B<--appname> Name used for the project's name (lowercase) and for matching existing files in download. =item B<--build> Build identifier (e.g., 2011-08-01-0001) =item B<--branch> Branch that this build belongs to. Optional. =back =head1 DESCRIPTION B<This program> uploads builds to a Google Code website, features the new uploads, and unfeatures any old uploades. =head1 AUTHOR Kenny Root =head1 COPYRIGHT and LICENSE Copyright 2011 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. =cut
1030365071-xuechao
tools/google-code-upload.pl
Perl
asf20
7,224
LOCAL_PATH := $(call my-dir) include $(CLEAR_VARS) LOCAL_MODULE := com_google_ase_Exec LOCAL_CFLAGS := -Werror LOCAL_SRC_FILES := com_google_ase_Exec.cpp LOCAL_LDLIBS := -llog include $(BUILD_SHARED_LIBRARY)
1030365071-xuechao
jni/Exec/Android.mk
Makefile
asf20
220
/* * Copyright (C) 2007 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "com_google_ase_Exec.h" #include <errno.h> #include <fcntl.h> #include <stdlib.h> #include <sys/ioctl.h> #include <sys/types.h> #include <sys/wait.h> #include <termios.h> #include <unistd.h> #include "android/log.h" #define LOG_TAG "Exec" #define LOG(...) __android_log_print(ANDROID_LOG_ERROR, LOG_TAG, __VA_ARGS__) void JNU_ThrowByName(JNIEnv* env, const char* name, const char* msg) { jclass clazz = env->FindClass(name); if (clazz != NULL) { env->ThrowNew(clazz, msg); } env->DeleteLocalRef(clazz); } char* JNU_GetStringNativeChars(JNIEnv* env, jstring jstr) { if (jstr == NULL) { return NULL; } jbyteArray bytes = 0; jthrowable exc; char* result = 0; if (env->EnsureLocalCapacity(2) < 0) { return 0; /* out of memory error */ } jclass Class_java_lang_String = env->FindClass("java/lang/String"); jmethodID MID_String_getBytes = env->GetMethodID( Class_java_lang_String, "getBytes", "()[B"); bytes = (jbyteArray) env->CallObjectMethod(jstr, MID_String_getBytes); exc = env->ExceptionOccurred(); if (!exc) { jint len = env->GetArrayLength(bytes); result = (char*) malloc(len + 1); if (result == 0) { JNU_ThrowByName(env, "java/lang/OutOfMemoryError", 0); env->DeleteLocalRef(bytes); return 0; } env->GetByteArrayRegion(bytes, 0, len, (jbyte*) result); result[len] = 0; /* NULL-terminate */ } else { env->DeleteLocalRef(exc); } env->DeleteLocalRef(bytes); return result; } int jniGetFDFromFileDescriptor(JNIEnv* env, jobject fileDescriptor) { jclass Class_java_io_FileDescriptor = env->FindClass("java/io/FileDescriptor"); jfieldID descriptor = env->GetFieldID(Class_java_io_FileDescriptor, "descriptor", "I"); return env->GetIntField(fileDescriptor, descriptor); } static int create_subprocess( const char* cmd, const char* arg0, const char* arg1, int* pProcessId) { char* devname; int ptm; pid_t pid; ptm = open("/dev/ptmx", O_RDWR); // | O_NOCTTY); if(ptm < 0){ LOG("[ cannot open /dev/ptmx - %s ]\n", strerror(errno)); return -1; } fcntl(ptm, F_SETFD, FD_CLOEXEC); if(grantpt(ptm) || unlockpt(ptm) || ((devname = (char*) ptsname(ptm)) == 0)){ LOG("[ trouble with /dev/ptmx - %s ]\n", strerror(errno)); return -1; } pid = fork(); if(pid < 0) { LOG("- fork failed: %s -\n", strerror(errno)); return -1; } if(pid == 0){ int pts; setsid(); pts = open(devname, O_RDWR); if(pts < 0) exit(-1); dup2(pts, 0); dup2(pts, 1); dup2(pts, 2); close(ptm); execl(cmd, cmd, arg0, arg1, NULL); exit(-1); } else { *pProcessId = (int) pid; return ptm; } } JNIEXPORT jobject JNICALL Java_com_google_ase_Exec_createSubprocess( JNIEnv* env, jclass clazz, jstring cmd, jstring arg0, jstring arg1, jintArray processIdArray) { char* cmd_8 = JNU_GetStringNativeChars(env, cmd); char* arg0_8 = JNU_GetStringNativeChars(env, arg0); char* arg1_8 = JNU_GetStringNativeChars(env, arg1); int procId; int ptm = create_subprocess(cmd_8, arg0_8, arg1_8, &procId); if (processIdArray) { int procIdLen = env->GetArrayLength(processIdArray); if (procIdLen > 0) { jboolean isCopy; int* pProcId = (int*) env->GetPrimitiveArrayCritical(processIdArray, &isCopy); if (pProcId) { *pProcId = procId; env->ReleasePrimitiveArrayCritical(processIdArray, pProcId, 0); } } } jclass Class_java_io_FileDescriptor = env->FindClass("java/io/FileDescriptor"); jmethodID init = env->GetMethodID(Class_java_io_FileDescriptor, "<init>", "()V"); jobject result = env->NewObject(Class_java_io_FileDescriptor, init); if (!result) { LOG("Couldn't create a FileDescriptor."); } else { jfieldID descriptor = env->GetFieldID(Class_java_io_FileDescriptor, "descriptor", "I"); env->SetIntField(result, descriptor, ptm); } return result; } JNIEXPORT void Java_com_google_ase_Exec_setPtyWindowSize( JNIEnv* env, jclass clazz, jobject fileDescriptor, jint row, jint col, jint xpixel, jint ypixel) { int fd; struct winsize sz; fd = jniGetFDFromFileDescriptor(env, fileDescriptor); if (env->ExceptionOccurred() != NULL) { return; } sz.ws_row = row; sz.ws_col = col; sz.ws_xpixel = xpixel; sz.ws_ypixel = ypixel; ioctl(fd, TIOCSWINSZ, &sz); } JNIEXPORT jint Java_com_google_ase_Exec_waitFor(JNIEnv* env, jclass clazz, jint procId) { int status; waitpid(procId, &status, 0); int result = 0; if (WIFEXITED(status)) { result = WEXITSTATUS(status); } return result; }
1030365071-xuechao
jni/Exec/com_google_ase_Exec.cpp
C++
asf20
5,383
# Build both ARMv5TE and x86-32 machine code. APP_ABI := armeabi x86
1030365071-xuechao
jni/Application.mk
Makefile
asf20
69
include $(call all-subdir-makefiles)
1030365071-xuechao
jni/Android.mk
Makefile
asf20
37
<html> <body style="background-color: #000; color: #fff"> <p>Gestures in ConnectBot allow a user to do several things for which there&#x27;s no keyboard equivalent. If the gestures seem backward, then imagine that you&#x27;re grabbing the text and moving it with your finger.</p> <h1><a name="Page_Up_/_Page_Down" />Page Up / Page Down</h1> <p>Swiping your finger up and down on the left third of the screen will send a page up and page down key to the remote host. Many programs map this to scrolling back into history such as irssi or tinyfugue.</p> <p><img src="http://connectbot.googlecode.com/svn/trunk/www/gesture-pgup.png" /> Page Up gesture</p> <p><img src="http://connectbot.googlecode.com/svn/trunk/www/gesture-pgdn.png" /> Page Down gesture</p> <h1><a name="Scroll_back_/_Scroll_forward" />Scroll back / Scroll forward</h1> <p>Swiping your finger up on the right side of the screen allows you to scroll backward and forward in the local terminal buffer history.</p> <p><img src="http://connectbot.googlecode.com/svn/trunk/www/gesture-scrollback.png" /> Scroll back gesture</p> <p><img src="http://connectbot.googlecode.com/svn/trunk/www/gesture-scrollforward.png" /> Scroll forward gesture</p> <h1><a name="Switching_hosts" />Switching hosts</h1> <p>Swiping your finger from one side of the screen to the other will switch between currently connected hosts.</p> <p><img src="http://connectbot.googlecode.com/svn/trunk/www/gesture-hostprev.png" /> Previous host gesture</p> <p><img src="http://connectbot.googlecode.com/svn/trunk/www/gesture-hostnext.png" /> Next host gesture</p> </body> </html>
1030365071-xuechao
assets/help/ScreenGestures.html
HTML
asf20
1,613
<html> <body style="background-color: #000; color: #fff"> <p><img src="http://connectbot.googlecode.com/svn/trunk/www/keyboard.jpg" /></p> <p>Here are some keyboard shortcuts available when a <strong>hardware keyboard</strong> is present. If you&#x27;re using a phone where the main input type is a <strong>virtual keyboard</strong>, please see the VirtualKeyboard help topic. </p> <p><strong>Note:</strong> the side that <strong>shift</strong>, <strong>alt</strong>, <strong>slash</strong>, and <strong>tab</strong> uses can be changed in preferences between left, right, and disabled.</p> <ul> <li>Control key (CTRL)</li> <blockquote>Pressing once on the trackball will toggle on <strong>control</strong> for the next character typed. The cursor will indicate this state with a &lt; symbol. Note that pressing the trackball again will send an <strong>escape</strong> key.</blockquote> </ul> <ul> <li>Escape (ESC)</li> <blockquote>Pressing twice on the trackball will send <strong>escape</strong> key. Note that some other terminal emulators map pressing <strong>ALT-<i>key</i></strong> to <strong>escape + <i>key</i></strong>.</blockquote> </ul> <ul> <li>Shift</li> <blockquote>Pressing the <strong>shift</strong> (up arrow) key once will make the next key typed its uppercase variant according to the keyboard layout. This state is indicated with an outline of a triangle on the top of the cursor. Pressing it twice will turn on <strong>shift lock</strong> which is indicated by a solid triangle on the top of the cursor.</blockquote> </ul> <ul> <li>Alt</li> <blockquote>Pressing the <strong>Alt</strong> key once will make the next key typed its symbol as indicated on the keyboard. This state is indicated with the outline of a triangle on the bottom of the cursor. Pressing it twice will turn on <strong>alt lock</strong> which is indicated by a solid triangle on the bottom of the cursor.</blockquote> </ul> <ul> <li>Slash (opposite side Alt)</li> <blockquote>The opposite side <strong>alt</strong> key can be used as a shortcut for the forward slash / character. This aids in quickly typing directories on the G1.</blockquote> </ul> <ul> <li>Tab (opposite side Shift)</li> <blockquote>The opposite side <strong>shift</strong> key can be used as a shortcut for the <strong>tab</strong> key (CTRL-i) for quick completion in many shells.</blockquote> </ul> <ul> <li>Function keys (F1 through F10)</li> <blockquote>Hold down the shift key and press numbers 1 through 10 to send F1 through F10 respectively.</blockquote> </ul> </body> </html>
1030365071-xuechao
assets/help/PhysicalKeyboard.html
HTML
asf20
2,582
<html> <body style="background-color: #000; color: #fff"> <p><img src="http://connectbot.googlecode.com/svn/trunk/www/magic-cb-screen.png" width="100%" /></p> <h2>Caveats</h2> <p>Since ConnectBot doesn&#x27;t use any of the normal TextView widgets, Android&#x27;s IME structure isn&#x27;t designed to directly support it.</p> <p>The best way to use Android with a virtual keyboard is in <strong>Portrait</strong> mode. By default, ConnectBot is set to use <strong>Portrait</strong> mode when no hardware keyboard is present. To change this setting, go to <strong>Preferences</strong> from the <strong>Host List</strong>.</p> <p>In <strong>Landscape</strong> mode, the Android virtual keyboard (or other IMEs) will take up the entire screen. Android provides no way for ConnectBot to resize the terminal view in <strong>Landscape</strong>. However, you may use a <i>work-around</i>: <strong>Force Resize</strong> to fit above the virtual keyboard if desired.</p> <p>On devices without a hardware keyboard, you may press and hold the <strong>MENU</strong> button to bring up the virtual keyboard. NOTE: This applies to any program on the Android platform; it is not ConnectBot specific.</p> <h2>How to Enter Control, Alt, Escape, and Function Keys</h2> <p>You can enter any key combination with ConnectBot and the virtual keyboard, but you must know how keys are mapped on a normal console. For instance, usually combinations of ALT+letter on a PC keyboard are actually mapped to sending, sequentially, ESC key then the letter.</p> <p>Note there are also screen gestures: see the ScreenGestures help topic.</a> for <strong>Page Up</strong> and <strong>Page Down</strong>.</p> <ul> <li>Trackball: 1 press is <strong>CTRL</strong>, 2 presses sends <strong>ESC</strong> </li> <li><strong>Tab key</strong> = <strong>CTRL + i</strong></li> <li><strong>Function key</strong> = <strong>CTRL + number</strong> </li> </ul> <h2>Examples</h2> <ul> <li><strong>ESC</strong> = Press the trackball twice.</li> <li><strong>ALT + Right Arrow</strong> = Press trackball twice then move trackball to right.</li> <li><strong>CTRL + A</strong> = Press trackball once then tap the &quot;A&quot; key on the soft keyboard.</li> <li><strong>F3</strong> = Press trackball once then tap the &quot;3&quot; key on the soft keyboard.</li> </ul> </body> </html>
1030365071-xuechao
assets/help/VirtualKeyboard.html
HTML
asf20
2,345
<html> <body style="background-color: #000; color: #fff"> <h2>Helpful hints</h2> <p>When you have multiple sessions open, you can 'pan' between them by swiping your finger left-to-right or right-to-left over the screen.</p> <p>Long-press on your Android desktop to create direct shortcuts to frequently-used SSH hosts.</p> <p>Slide your finger up/down on the right-half of the terminal screen to look at the scrollback history. Slide up/down on the left-half to send the page up/down keys.</p> </body> </html>
1030365071-xuechao
assets/help/Hints.html
HTML
asf20
515
<!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> <meta http-equiv='Content-Type' content='text/html; charset=utf-8' /> <title>管理员 - 歪伯乐微招聘 - 微博招聘、求职、简历信息,一站聚合、管理、定制</title> <link rel="icon" href="favicon_big.png" sizes="48x48"> <link rel="shortcut icon" href="/favicon.ico" /> <link href="css/themes/base/jquery.ui.all.css" rel="Stylesheet" type="text/css" /> <link href="css/share.css" rel="stylesheet" type="text/css" /> <link href="css/admin.css" rel="stylesheet" type="text/css" /> <script src="script/jquery-1.5.1.js" type="text/javascript"></script> <script src="script/jquery.cookie.js" type="text/javascript"></script> <script src="script/ui/jquery.ui.core.js" type="text/javascript"></script> <script src="script/ui/jquery.ui.widget.js" type="text/javascript"></script> <script src="script/ui/jquery.ui.mouse.js" type="text/javascript"></script> <script src="script/ui/jquery.ui.draggable.js" type="text/javascript"></script> <script src="script/ui/jquery.ui.resizable.js" type="text/javascript"></script> <script src="script/ui/jquery.ui.position.js" type="text/javascript"></script> <script src="script/ui/jquery.ui.dialog.js" type="text/javascript"></script> <script src="script/admin.js" type="text/javascript"></script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-22822126-1']); _gaq.push(['_setDomainName', '.ybole.com']); _gaq.push(['_trackPageview']); $(function () { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); }); </script> </head> <body> <div id="delete-dialog" title="提示"> <p> 确定删除这条信息吗?</p> </div> <div id="header"> <div class="left" id="links"> <a class="left" href="/">歪伯乐招聘网</a> <a class="left" href="http://t.sina.com.cn/2020566725">歪伯乐招聘官方微博</a> <a class="left last">我的微博</a> </div> <div class="right" id="infos"> <a class="left selected logined" id="name" href="/">admin</a><a class="left logined" href="logout/">退出</a> </div> </div> <div id="logo-search"> <a id="logo" class="left" href="/">测试版</a> </div> <div id="manager-title" class="inner"> <span class="left manager-title">管理中心</span> <span class="left manager-title-tag">管理员</span> </div> <div id="manager-content" class="inner"> <div id="content-left" class="left"> <div id="manager-control"> <a class="manager-control left manager-control-choose" onclick="ShowNormal(0)">管理中心</a> <a class="manager-control left" onclick="ShowFeedback(0)">意见管理</a> <a class="manager-control left" onclick="ShowHot()">热门企业管理</a> </div> <a id="jobs-publish-button" class="publish-button jobs left"></a><a id="recruitment-publish-button" class="publish-button recruitment left"></a> </div> <div id="content-middle" class="left"> <div id="blogs"> <div id="blogsinner"> </div> <div id="pages"> </div> </div> </div> <div id="content-right" class="left"> </div> </div> <div class="clear"> </div> <div id="footer" class="inner"> <div id="footerlinks"> <a href="/help">网站帮助</a> | <a href="/feedback">意见反馈</a> | <a>联系我们</a></div> <div id="copyright"> CopyRight © 2011-2012 <a>歪伯乐招聘网</a> Co. All Right Reserved. 鄂ICP证100111号<br /> Powered by:GNG</div> </div> </body> </html>
0f523140-f3b3-4653-89b0-eb08c39940ad
trunk/src/html/admin.html
HTML
gpl3
4,350
<?php include_once('common.inc.php'); func_register(array( 'user' => array( 'callback' => 'deal_user', ), 'profile' => array( 'callback' => 'profile_show', ), )); function theme_user($data) { include_once("theme.inc.php"); $content = ''; foreach($data as $r) { if(strstr($r['source'], '<')) $source = str_replace("<a ", '<a class="left microblog-item-position"', $r['source']); else $source = '<a class="left microblog-item-position">'.$r['source'].'</a>'; $content .= '<div class="item" id="'.$r['tweet_id'].'"> <div class="item-delete"> <a class="right"></a> </div> <div class="left item-pic"> <img alt="" width="50" height="50" src="'.$r['profile_image_url'].'"> </div> <div class="left item-content"> <div class="item-blog"> <a class="item-blog-name" target="_blank" href="'.BASE_URL.'profile/'.$r['post_screenname'].'">'.$r['post_screenname'].'</a>:'.$r['content'].' </div> <div class="item-other"> <span class="left item-time">'.time_tran($r['post_datetime']).'</span>'.$source.' <a class="right item-control last delete"> 删除</a> </div> </div> <div class="clear"> </div> </div>'; } echo $content; } function get_user_tweets($key, $site, $num, $page, $count = false) { connect_db(); if($count) { $limit = ""; $select = "COUNT(*)"; } else { if(!$page) $page = "0"; $select = "*"; $page = intval($page) * $num; $limit = " LIMIT $page , $num"; } if(!$key) { include_once("login.inc.php"); user_ensure_authenticated(); $key = get_current_user_id(); } if($site) $view = "SELECT $select from tweets WHERE deleted = 0 AND user_site_id = '$key' AND site_id = '$site' ORDER BY post_datetime DESC$limit"; else $view = "SELECT $select from tweets, (SELECT user_site_id, site_id FROM accountbindings WHERE user_id = '$key') AS ac WHERE tweets.deleted = 0 AND tweets.user_site_id = ac.user_site_id AND tweets.site_id = ac.site_id ORDER BY tweets.post_datetime DESC$limit"; $list = mysql_query($view); $result = array(); $i = 0; while($row = mysql_fetch_array($list)) $result[$i++] = $row; return $result; } function user_count() { $args = func_get_args(); $user = $args[2]; $site = get_post('site_id'); $data = get_user_tweets($user, $site, 10, "", true); echo $data[0][0]; } function user_show() { $args = func_get_args(); $user = $args[2]; $page = get_post('page'); $site = get_post('site_id'); $data = get_user_tweets($user, $site, 10, $page); theme('user', $data); } function user_info() { include_once("login.inc.php"); user_ensure_authenticated(); show_credentials(); } function user_set_role() { user_ensure_authenticated(); $id = get_current_user_id(); $args = func_get_args(); $key = $args[2]; if($key == "" or ($key != "1" and $key != "2")) die("Invalid argument!"); connect_db(); $view = "SELECT role_id FROM userinfo WHERE user_id='$id'"; $list = mysql_query($view); $row = mysql_fetch_array($list); $role = $row['role_id']; if($role != -1) die('Role already set!'); $view = "UPDATE userinfo SET role_id=".$key." WHERE user_id='".$id."'"; $list = mysql_query($view) or die("Update error!"); $GLOBALS['user']['role'] = $key; save_cookie(); } function user_role_show() { user_ensure_authenticated(); echo $GLOBALS['user']['role']; } function user_role() { user_role_show(); } function deal_user($query) { $key = (string) $query[1]; if(!$key) $key = "show"; $function = 'user_'.$key; if (!function_exists($function)) die("Invalid Argument!"); return call_user_func_array($function, $query); } function profile_show($query) { /*$args = func_get_args(); $key = $args[2];*/ $key = (string) $query[1]; if(!$key) die("Invalid Argument!"); header('Location: http://t.sina.com.cn/n/'.$key); } /*function deal_profile($query) { $key = (string) $query[1]; if(!$key) $key = "show"; $function = 'profile_'.$key; if (!function_exists($function)) die("Invalid Argument!"); return call_user_func_array($function, $query); }*/ ?>
0f523140-f3b3-4653-89b0-eb08c39940ad
trunk/src/html/user.inc.php
PHP
gpl3
5,040
<!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> <meta http-equiv='Content-Type' content='text/html; charset=utf-8' /> <meta name="keywords" content="免费发布微博招聘、求职信息,免费定制微职位、微简历" /> <meta name="google-site-verification" content="u38PD1jd9z3R0dAL6Syq-FDaxSZ_qzL6mrxhp-yEhw4" /> <title>首页 - 歪伯乐微招聘 - 微博招聘、求职、简历信息、一站聚合、定制</title> <link rel="icon" href="favicon_big.png" sizes="48x48"> <link rel="shortcut icon" href="/favicon.ico" /> <link href="css/themes/base/jquery.ui.all.css" rel="Stylesheet" type="text/css" /> <link href="css/share.css" rel="stylesheet" type="text/css" /> <link href="css/default.css" rel="stylesheet" type="text/css" /> <script src="script/jquery-1.5.1.js" type="text/javascript"></script> <script src="script/jquery.query-2.1.7.js" type="text/javascript"></script> <script src="script/jquery.cookie.js" type="text/javascript"></script> <script src="script/ui/jquery.ui.core.js" type="text/javascript"></script> <script src="script/ui/jquery.ui.widget.js" type="text/javascript"></script> <script src="script/ui/jquery.ui.mouse.js" type="text/javascript"></script> <script src="script/ui/jquery.ui.draggable.js" type="text/javascript"></script> <script src="script/ui/jquery.ui.resizable.js" type="text/javascript"></script> <script src="script/ui/jquery.ui.position.js" type="text/javascript"></script> <script src="script/ui/jquery.ui.dialog.js" type="text/javascript"></script> <script src="script/share.js" type="text/javascript"></script> <script src="script/DMshare.js" type="text/javascript"></script> <script src="script/default.js" type="text/javascript"></script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-20911105-2']); _gaq.push(['_setDomainName', '.ybole.com']); _gaq.push(['_trackPageview']); $(function () { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); }); </script> </head> <body> <div id="header"> <div class="left" id="links"> <a class="left" href="/">歪伯乐招聘网</a> <a class="left" href="http://t.sina.com.cn/2020566725"> 歪伯乐招聘官方微博</a> <a class="left last">我的微博</a> </div> <div class="right" id="infos"> <a class="left selected logined" id="name" href="/"></a><a class="left orange logined" href="/manager" id="manager-center">管理中心</a> <a class="left logined jobs" id="jobs-publish-quick"> 发布求职信息</a><a class="left logined recruitment" id="recruitment-publish-quick">发布招聘信息</a><a class="left logined admin" href="/admin">管理员入口</a> <a class="left logined" href="logout/"> 退出</a> <a class="left logouted" id="sina-login" href="login/"></a> </div> </div> <div id="logo-search"> <a id="logo" class="left" href="/">测试版</a> <div id="search-bar" class="left"> <a class="left sort" id="sort">全部分类</a><a class="left sort" id="sort-triangle">&#9660;</a> <input class="left" id="search-text" type="text" value="职位关键字,如:北京 产品经理 阿里巴巴" /> <a class="left" id="search-button"></a> </div> </div> <div id="company" class="inner"> <span class="left company-name">热门企业:</span> <div class="left" id="companies"> <div id="companies-inner"> <a class="company-name">新浪</a><a class="company-name">腾讯</a><a class="company-name">百度</a><a class="company-name">淘宝</a><a class="company-name">搜狐</a><a class="company-name">创新工场</a><a class="company-name">凡客</a><a class="company-name">海辉软件</a><a class="company-name">奇艺</a><a class="company-name">联想</a><a class="company-name">华为</a><a class="company-name">街旁</a><a class="company-name">中兴</a><a class="company-name">Tom</a><a class="company-name">网龙</a><a class="company-name">网易</a><a class="company-name">戴尔</a><a class="company-name">人民网</a><a class="company-name">米聊</a><a class="company-name last">金山</a></div> </div> <div class="left" id="company-control"> <a class="left company-control" id="company-control-left">◀</a> <a class="left company-control" id="company-control-right">▶</a> </div> </div> <div id="content" class="inner"> <div id="left" class="left"> <div id="blank"> </div> <div class="left-title left-title-first logined"> <span class="left-title-text left" id="concern-title">我的关注</span> <a class="right left-title-pic" id="concern-pic"></a> </div> <div id="concern" class="logined"> </div> <div class="left-title logined"> <span class="left left-title-text">搜索历史</span> <a class="right left-title-pic" id="history-pic"> </a> </div> <div id="history" class="logined"> </div> <div id="hot"> </div> </div> <div id="right" class="left"> <div id="radio"> </div> <div id="microblogs"> <div id="search-result-outer"> <div id="search-result"> <div class="left"> </div> <a id="search-result-rss" class="right"></a><a id="search-result-concern" class="right search-result-concern"> </a> </div> </div> <div id="fresh-outer"> <div id="fresh"> </div> </div> <div id="fresh-blogs" style="display: none; border-bottom: 1px #dedede solid"> </div> <div id="blogs"> </div> <div id="flower" style="text-align: center; display: none;"> <img src="images/loading.gif" alt="" />正在加载中... </div> <div id="pages"> </div> </div> </div> </div> <div class="clear"> </div> <div id="footer" class="inner"> <div id="footerlinks"> <a href="/help">网站帮助</a> | <a href="/feedback">意见反馈</a> | <a>联系我们</a></div> <div id="copyright"> CopyRight © 2011-2012 <a>歪伯乐招聘网</a> Co. All Right Reserved. 鄂ICP证100111号<br /> Powered by:GNG</div> </div> <div id="sorts" class="absolute"> <div id="sorts-tag"> <a id="sorts-name" class="left">全部分类</a> <a id="sorts-triangle" class="left">&#9660;</a> </div> <div id="sorts-content"> </div> </div> <div id="cover"> </div> <div id="role-choose" class="absolute role-jobs"> <a id="role-jobs" class="absolute"></a><a id="role-recruitment" class="absolute"> </a><a id="role-confirm" class="absolute"></a> </div> <div id="jobs-publish" class="absolute"> <div id="jobs-publish-title"> <span class="left">发布求职信息</span> <a class="right"></a> </div> <div id="jobs-publish-content"> <div id="jobs-publish-remain"> 还可输入136个字</div> <div id="jobs-publish-text"> <textarea>#求职#</textarea> </div> <div id="jobs-publish-tags-hot"> </div> <div id="jobs-publish-confirm"> <a class="right"></a><span class="right">本信息将同步发送到新浪微博</span> </div> </div> </div> <div id="recruitment-publish" class="absolute"> <div id="recruitment-publish-title"> <span class="left">发布招聘信息</span> <a class="right"></a> </div> <div id="recruitment-publish-content"> <div id="recruitment-publish-remain"> 还可输入136个字</div> <div id="recruitment-publish-text"> <textarea>#招聘#</textarea> </div> <div id="recruitment-publish-tags-hot"> </div> <div id="recruitment-publish-confirm"> <a class="right"></a><span class="right">本信息将同步发送到新浪微博</span> </div> </div> </div> <div id="backTop" class="absolute"> <a>▲回到顶部</a> </div> <div id="published-info" title="发布成功"> <p> 信息发布成功!本信息已同步发布到新浪微博。</p> <p> 您发布的信息将在一段时间之后显示在网站中,请不要重复发布。</p> </div> <div id="error-info" title="错误"> <p id="errormsg"> </p> </div> <div id="msgBox_noresume"> <div class="bg"> <div class="lt"> </div> <div class="md"> <div class="boxcontent"> <div class="title"> <img src="images/ico_resume.gif" alt=""> 申请职位 <a onclick="HideNoresume()"> <div class="btn_cross"> X</div> </a> </div> <div class="content"> 填写一份完善的简历能让微博招聘者快速<br /> 全面地了解您,大大增加您的录取概率! </div> <a href="/manager?type=profile"> <div class="msgBtn"> </div> </a> </div> </div> <div class="rt"> </div> </div> </div> <div id="msgBox_resume"> <div class="bg"> <div class="lt"> </div> <div class="md"> <div class="boxcontent"> <div class="title"> <img src="images/ico_resume.gif" alt=""> 申请职位 <a onclick="HideResume()"> <div class="btn_cross"> X</div> </a> </div> <div class="info"> <span class="left"></span><span class="right">还可输入115个字</span></div> <div class="content"> <textarea cols="60" rows="4" onkeydown="UpdateApply(this)" onkeyup="UpdateApply(this)"></textarea> <div class="mdline"> </div> <input type="radio" value="defult" checked="checked"><a target="_blank">默认简历</a>(<span>*</span>系统将自动为您附上您的简历) </div> <a onclick="ApplyJob()"> <div class="msgBtn"> </div> </a> </div> </div> <div class="rt"> </div> </div> </div> <div id="manager-tips" class="absolute"> <a class="right" onclick="CloseMTips()"></a> </div> <div id="concern-tips" class="absolute"> <a class="right" onclick="CloseCTips()"></a> </div> <div id="apply-tips" class="absolute"> <a class="right" onclick="CloseATips()"></a> </div> </body> </html>
0f523140-f3b3-4653-89b0-eb08c39940ad
trunk/src/html/default-bak.html
HTML
gpl3
12,704
<?php include_once('common.inc.php'); func_register(array( 'hot' => array( 'callback' => 'deal_hot', ), )); function get_tags($id) { include_once("common.inc.php"); connect_db(); $view = "SELECT tags.name from tags, (SELECT * FROM tag_relationship WHERE tweet_id='$id') as r WHERE r.tag_id=tags.tag_id ORDER BY tags.count DESC"; $list = mysql_query($view); $result = array(); $i = 0; while($row = mysql_fetch_array($list)) { $result[$i++] = $row[0]; if($i == 7) break; } if($i == 0) return false; return $result; } function get_hot($num) { include_once("common.inc.php"); connect_db(); $view = "SELECT tags.name,tags.count,tags.tag_group,tg.tag_group_name from tags,(SELECT * FROM tag_group) AS tg WHERE tg.tag_group = tags.tag_group ORDER BY tags.count DESC"; $list = mysql_query($view); $result = array(); $i = 0; $g = array(); $j = 0; while($row = mysql_fetch_array($list)) { $ok = true; foreach($g as $_g) if($_g == $row['tag_group']) { $ok = false; break; } if(!$ok) continue; if($row['tag_group']!=0) $name = $row['tag_group_name']; else $name = $row['name']; $row2 = array( 'name' => $name, 'count' => $row['count'], ); $result[$i++] = $row2; if($i == $num) break; if($row['tag_group']!=0) $g[$j++] = $row['tag_group']; } return $result; } function hot_tag() { $args = func_get_args(); $key = $args[2]; if($key == "0" or $key == "") { $content = '<div class="left-title"> <span class="left left-title-text">热门职位</span> <span class="right left-title-time">截止至'.date('Y.n.j').'</span> </div> <div id="hot-content">'; $num = 20; } elseif($key == "1") { $content = '<span id="jobs-publish-tags-hot-title" class="left">热门标签</span>'; $num = 10; } elseif($key == "2") { $content = '<span id="recruitment-publish-tags-hot-title" class="left">热门标签</span>'; $num = 10; } elseif($key == "3") { $content = ''; $num = 9; } else die("Invalid argument!"); $hots = get_hot($num); foreach($hots as $h) if($key == "1") $content .= '<a class="left jobs-publish-tags-hot-item" title="'.$h['name'].'">'.$h['name'].'</a>'; elseif($key == "2") $content .= '<a class="left recruitment-publish-tags-hot-item" title="'.$h['name'].'">'.$h['name'].'</a>'; elseif($key == "3") $content .= '<a onclick="HotClick(\''.$h['name'].'\')">'.$h['name'].'('.$h['count'].')</a>'; else $content .= '<a class="left hot-content-item" onclick="HotClick(\''.$h['name'].'\')">'.$h['name'].'('.$h['count'].')</a>'; if($key == "0" or $key == "") $content .= '</div>'; echo $content; } function hot_editgroup() { include_once('login.inc.php'); user_ensure_admin(); connect_db(); $view = "SELECT * FROM tags"; $list = mysql_query($view); $content = '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html><head><meta http-equiv="Content-Type" content="text/html; charset=utf-8" /></head><body><form action="/hot/groupupdate" method="post"><table>'; while($row = mysql_fetch_array($list)) $content .= "<tr><td>".$row['name']."</td><td><input type='text' name='".$row["tag_id"]."' value='".$row['tag_group']."' /></td></tr>"; $content .= "<input type='submit' value='修改' /></form></table></body></html>"; echo $content; } function hot_groupupdate() { include_once('login.inc.php'); user_ensure_admin(); connect_db(); $view = "SELECT tag_id FROM tags"; $list = mysql_query($view); $set = array(); while($row = mysql_fetch_array($list)) $set[$row['tag_id']] = get_post($row['tag_id']); foreach($set as $tag_id => $tag_group) { $view = "UPDATE tags SET tag_group='$tag_group' WHERE tag_id='$tag_id'"; $list = mysql_query($view); } header("Location: ".BASE_URL."hot/editgroup"); } function hot_editname() { include_once('login.inc.php'); user_ensure_admin(); connect_db(); $view = "SELECT DISTINCT tag_group FROM tags WHERE tag_group != 0 ORDER BY tag_group"; $list = mysql_query($view); $content = '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html><head><meta http-equiv="Content-Type" content="text/html; charset=utf-8" /></head><body><form action="/hot/nameupdate" method="post"><table>'; $set = array(); while($row = mysql_fetch_array($list)) $set[] = $row['tag_group']; foreach($set as $tag_group) { $view = "SELECT tag_group_name FROM tag_group WHERE tag_group = '$tag_group'"; $list = mysql_query($view); $row = mysql_fetch_array($list); $content .= "<tr><td>$tag_group</td><td><input type='text' name='$tag_group' value='".$row['tag_group_name']."' /></td></tr>"; } $content .= "<input type='submit' value='修改' /></form></table></body></html>"; echo $content; } function hot_nameupdate() { include_once('login.inc.php'); user_ensure_admin(); connect_db(); $view = "SELECT DISTINCT tag_group FROM tags WHERE tag_group != 0"; $list = mysql_query($view); $set = array(); while($row = mysql_fetch_array($list)) $set[$row['tag_group']] = get_post($row['tag_group']); foreach($set as $tag_group => $tag_group_name) { $view = "UPDATE tag_group SET tag_group_name='$tag_group_name' WHERE tag_group='$tag_group'"; $list = mysql_query($view); } header("Location: ".BASE_URL."hot/editname"); } function deal_hot($query) { $key = (string) $query[1]; if(!$key) die("Invalid Argument!"); $function = 'hot_'.$key; if (!function_exists($function)) die("Invalid Argument!"); return call_user_func_array($function, $query); } ?>
0f523140-f3b3-4653-89b0-eb08c39940ad
trunk/src/html/hot.inc.php
PHP
gpl3
6,549
<?php class UUID { public static function v4() { return sprintf('%04x%04x-%04x-%04x-%04x-%04x%04x%04x', // 32 bits for "time_low" mt_rand(0, 0xffff), mt_rand(0, 0xffff), // 16 bits for "time_mid" mt_rand(0, 0xffff), // 16 bits for "time_hi_and_version", // four most significant bits holds version number 4 mt_rand(0, 0x0fff) | 0x4000, // 16 bits, 8 bits for "clk_seq_hi_res", // 8 bits for "clk_seq_low", // two most significant bits holds zero and one for variant DCE1.1 mt_rand(0, 0x3fff) | 0x8000, // 48 bits for "node" mt_rand(0, 0xffff), mt_rand(0, 0xffff), mt_rand(0, 0xffff) ); } public static function is_valid($uuid) { return preg_match('/^\{?[0-9a-f]{8}\-?[0-9a-f]{4}\-?[0-9a-f]{4}\-?'. '[0-9a-f]{4}\-?[0-9a-f]{12}\}?$/i', $uuid) === 1; } } // Usage // Named-based UUID. // $v3uuid = UUID::v3('1546058f-5a25-4334-85ae-e68f2a44bbaf', 'SomeRandomString'); // $v5uuid = UUID::v5('1546058f-5a25-4334-85ae-e68f2a44bbaf', 'SomeRandomString'); // Pseudo-random UUID // $v4uuid = UUID::v4(); ?>
0f523140-f3b3-4653-89b0-eb08c39940ad
trunk/src/html/uuid.inc.php
PHP
gpl3
1,127
Ybole - Python backend ... Coming soon!
0f523140-f3b3-4653-89b0-eb08c39940ad
trunk/src/html/pybackend/views/home.tpl
Smarty
gpl3
40
#coding:utf8 from bottle import route, run, debug, template, request, validate, error, response, redirect from y_common import * from weibopy.auth import WebOAuthHandler from weibopy import oauth @route('/login') def login(): redirect('/sina/login') @route('/sina/login') def sina_login(): auth = WebOAuthHandler(sina_consumer_key, sina_consumer_secret) auth_url = auth.get_authorization_url_with_callback(baseurl + "/sina/callback/") redirect(auth_url) @route('/sina/callback/:request_token') def sina_callback(request_token): oauth_verifier = request.GET.get('oauth_verifier', None) auth = WebOAuthHandler(sina_consumer_key, sina_consumer_secret, oauth.OAuthToken.from_string(request_token)) token = auth.get_access_token(oauth_verifier) response.set_cookie("ybole_auth", token, secret = gng_secret) redirect('/')
0f523140-f3b3-4653-89b0-eb08c39940ad
trunk/src/html/pybackend/y_login.py
Python
gpl3
863
from bottle import route, run, debug, template, request, validate, error, response, redirect @route('/apply/sent') @route('/apply/sent/show') def apply_sent_show(): return template('home') @route('/apply/sent/add/:tweet_id') def apply_sent_add(tweet_id): return template('home') @route('/apply/sent/exist/:tweet_id') def apply_sent_exist(tweet_id): return template('home') @route('/apply/sent/count') def apply_sent_count(): return template('home') @route('/apply/sent/delete/:tweet_id') def apply_sent_delete(tweet_id): return template('home')
0f523140-f3b3-4653-89b0-eb08c39940ad
trunk/src/html/pybackend/y_apply.py
Python
gpl3
574
from bottle import route, run, debug, template, request, validate, error, response, redirect @route('/') @route('/home') def home(): return template('home') #return 'Ybole - Python backend ... Coming soon!'
0f523140-f3b3-4653-89b0-eb08c39940ad
trunk/src/html/pybackend/y_home.py
Python
gpl3
216
from bottle import route, run, debug, template, request, validate, error, response, redirect @route('/admin/') def admin(): return template("home") @route('/admin/tag') def admin_tag(): return template("home") @route('/admin/tag/edit') def admin_tag(): return template("home")
0f523140-f3b3-4653-89b0-eb08c39940ad
trunk/src/html/pybackend/y_admin.py
Python
gpl3
292
import re, base64, json baseurl = "http://www.ybole.com:81" gng_secret = "HUSTGNGisVeryGelivable" sina_consumer_key= "961495784" sina_consumer_secret ="47d9d806a1dc04cc758be6f7213465bc" def htmlEncode(str): """ Returns the HTML encoded version of the given string. This is useful to display a plain ASCII text string on a web page.""" htmlCodes = [ ['&', '&amp;'], ['<', '&lt;'], ['>', '&gt;'], ['"', '&quot;'], ] for orig, repl in htmlCodes: str = str.replace(orig, repl) return str def jsonencode(x): data = dict(x) return json.dumps(data)
0f523140-f3b3-4653-89b0-eb08c39940ad
trunk/src/html/pybackend/y_common.py
Python
gpl3
623
#coding:utf8 # Copyright 2009-2010 Joshua Roesslein # See LICENSE for details. from urllib2 import Request, urlopen import base64 from weibopy import oauth from weibopy.error import WeibopError from weibopy.api import API class AuthHandler(object): def apply_auth(self, url, method, headers, parameters): """Apply authentication headers to request""" raise NotImplementedError def get_username(self): """Return the username of the authenticated user""" raise NotImplementedError class BasicAuthHandler(AuthHandler): def __init__(self, username, password): self.username = username self._b64up = base64.b64encode('%s:%s' % (username, password)) def apply_auth(self, url, method, headers, parameters): headers['Authorization'] = 'Basic %s' % self._b64up def get_username(self): return self.username class OAuthHandler(AuthHandler): """OAuth authentication handler""" OAUTH_HOST = 'api.t.sina.com.cn' OAUTH_ROOT = '/oauth/' def __init__(self, consumer_key, consumer_secret, callback=None, secure=False): self._consumer = oauth.OAuthConsumer(consumer_key, consumer_secret) self._sigmethod = oauth.OAuthSignatureMethod_HMAC_SHA1() self.request_token = None self.access_token = None self.callback = callback self.username = None self.secure = secure def _get_oauth_url(self, endpoint): if self.secure: prefix = 'https://' else: prefix = 'http://' return prefix + self.OAUTH_HOST + self.OAUTH_ROOT + endpoint def apply_auth(self, url, method, headers, parameters): request = oauth.OAuthRequest.from_consumer_and_token( self._consumer, http_url=url, http_method=method, token=self.access_token, parameters=parameters ) request.sign_request(self._sigmethod, self._consumer, self.access_token) headers.update(request.to_header()) def _get_request_token(self): try: url = self._get_oauth_url('request_token') request = oauth.OAuthRequest.from_consumer_and_token( self._consumer, http_url=url, callback=self.callback ) request.sign_request(self._sigmethod, self._consumer, None) resp = urlopen(Request(url, headers=request.to_header())) return oauth.OAuthToken.from_string(resp.read()) except Exception, e: raise WeibopError(e) def set_request_token(self, key, secret): self.request_token = oauth.OAuthToken(key, secret) def set_access_token(self, key, secret): self.access_token = oauth.OAuthToken(key, secret) def get_authorization_url(self, signin_with_twitter=False): """Get the authorization URL to redirect the user""" try: # get the request token self.request_token = self._get_request_token() # build auth request and return as url if signin_with_twitter: url = self._get_oauth_url('authenticate') else: url = self._get_oauth_url('authorize') request = oauth.OAuthRequest.from_token_and_callback( token=self.request_token, http_url=url ) return request.to_url() except Exception, e: raise WeibopError(e) def get_access_token(self, verifier=None): """ After user has authorized the request token, get access token with user supplied verifier. """ try: url = self._get_oauth_url('access_token') # build request request = oauth.OAuthRequest.from_consumer_and_token( self._consumer, token=self.request_token, http_url=url, verifier=str(verifier) ) request.sign_request(self._sigmethod, self._consumer, self.request_token) # send request resp = urlopen(Request(url, headers=request.to_header())) self.access_token = oauth.OAuthToken.from_string(resp.read()) #print 'Access token key: '+ str(self.access_token.key) #print 'Access token secret: '+ str(self.access_token.secret) return self.access_token except Exception, e: raise WeibopError(e) def setToken(self, token, tokenSecret): self.access_token = oauth.OAuthToken(token, tokenSecret) def get_username(self): if self.username is None: api = API(self) user = api.verify_credentials() if user: self.username = user.screen_name else: raise WeibopError("Unable to get username, invalid oauth token!") return self.username class WebOAuthHandler(OAuthHandler): """继承自OAuthHandler,提供Web应用方法。""" def __init__(self, consumer_key, consumer_secret, access_token=None): OAuthHandler.__init__(self, consumer_key, consumer_secret) if access_token is not None: self.set_access_token(access_token.key, access_token.secret) self.api = API(self) def get_authorization_url_with_callback(self, callback, signin_with_twitter=False): """Get the authorization URL to redirect the user""" try: # get the request token self.request_token = self._get_request_token() # build auth request and return as url if signin_with_twitter: url = self._get_oauth_url('authenticate') else: url = self._get_oauth_url('authorize') request = oauth.OAuthRequest.from_token_and_callback( token=self.request_token, callback=callback+oauth.OAuthToken.to_string(self.request_token), http_url=url ) return request.to_url() except Exception, e: raise WeibopError(e)
0f523140-f3b3-4653-89b0-eb08c39940ad
trunk/src/html/pybackend/weibopy/auth.py
Python
gpl3
6,080
# Copyright 2009-2010 Joshua Roesslein # See LICENSE for details. class WeibopError(Exception): """Weibopy exception""" def __init__(self, reason): try: self.reason = reason.encode('utf-8') except: self.reason = reason def __str__(self): return self.reason
0f523140-f3b3-4653-89b0-eb08c39940ad
trunk/src/html/pybackend/weibopy/error.py
Python
gpl3
322
# Copyright 2009-2010 Joshua Roesslein # See LICENSE for details. from weibopy.utils import parse_datetime, parse_html_value, parse_a_href, \ parse_search_datetime, unescape_html class ResultSet(list): """A list like object that holds results from a Twitter API query.""" class Model(object): def __init__(self, api=None): self._api = api def __getstate__(self): # pickle pickle = dict(self.__dict__) del pickle['_api'] # do not pickle the API reference return pickle @classmethod def parse(cls, api, json): """Parse a JSON object into a model instance.""" raise NotImplementedError @classmethod def parse_list(cls, api, json_list): """Parse a list of JSON objects into a result set of model instances.""" results = ResultSet() for obj in json_list: results.append(cls.parse(api, obj)) return results class Status(Model): @classmethod def parse(cls, api, json): status = cls(api) for k, v in json.items(): if k == 'user': user = User.parse(api, v) setattr(status, 'author', user) setattr(status, 'user', user) # DEPRECIATED elif k == 'screen_name': setattr(status, k, v) elif k == 'created_at': setattr(status, k, parse_datetime(v)) elif k == 'source': if '<' in v: setattr(status, k, parse_html_value(v)) setattr(status, 'source_url', parse_a_href(v)) else: setattr(status, k, v) elif k == 'retweeted_status': setattr(status, k, User.parse(api, v)) elif k == 'geo': setattr(status, k, Geo.parse(api, v)) else: setattr(status, k, v) return status def destroy(self): return self._api.destroy_status(self.id) def retweet(self): return self._api.retweet(self.id) def retweets(self): return self._api.retweets(self.id) def favorite(self): return self._api.create_favorite(self.id) class Geo(Model): @classmethod def parse(cls, api, json): geo = cls(api) if json is not None: for k, v in json.items(): setattr(geo, k, v) return geo class Comments(Model): @classmethod def parse(cls, api, json): comments = cls(api) for k, v in json.items(): if k == 'user': user = User.parse(api, v) setattr(comments, 'author', user) setattr(comments, 'user', user) elif k == 'status': status = Status.parse(api, v) setattr(comments, 'user', status) elif k == 'created_at': setattr(comments, k, parse_datetime(v)) elif k == 'reply_comment': setattr(comments, k, User.parse(api, v)) else: setattr(comments, k, v) return comments def destroy(self): return self._api.destroy_status(self.id) def retweet(self): return self._api.retweet(self.id) def retweets(self): return self._api.retweets(self.id) def favorite(self): return self._api.create_favorite(self.id) class User(Model): @classmethod def parse(cls, api, json): user = cls(api) for k, v in json.items(): if k == 'created_at': setattr(user, k, parse_datetime(v)) elif k == 'status': setattr(user, k, Status.parse(api, v)) elif k == 'screen_name': setattr(user, k, v) elif k == 'following': # twitter sets this to null if it is false if v is True: setattr(user, k, True) else: setattr(user, k, False) else: setattr(user, k, v) return user @classmethod def parse_list(cls, api, json_list): if isinstance(json_list, list): item_list = json_list else: item_list = json_list['users'] results = ResultSet() for obj in item_list: results.append(cls.parse(api, obj)) return results def timeline(self, **kargs): return self._api.user_timeline(user_id=self.id, **kargs) def friends(self, **kargs): return self._api.friends(user_id=self.id, **kargs) def followers(self, **kargs): return self._api.followers(user_id=self.id, **kargs) def follow(self): self._api.create_friendship(user_id=self.id) self.following = True def unfollow(self): self._api.destroy_friendship(user_id=self.id) self.following = False def lists_memberships(self, *args, **kargs): return self._api.lists_memberships(user=self.screen_name, *args, **kargs) def lists_subscriptions(self, *args, **kargs): return self._api.lists_subscriptions(user=self.screen_name, *args, **kargs) def lists(self, *args, **kargs): return self._api.lists(user=self.screen_name, *args, **kargs) def followers_ids(self, *args, **kargs): return self._api.followers_ids(user_id=self.id, *args, **kargs) class DirectMessage(Model): @classmethod def parse(cls, api, json): dm = cls(api) for k, v in json.items(): if k == 'sender' or k == 'recipient': setattr(dm, k, User.parse(api, v)) elif k == 'created_at': setattr(dm, k, parse_datetime(v)) else: setattr(dm, k, v) return dm class Friendship(Model): @classmethod def parse(cls, api, json): source = cls(api) for k, v in json['source'].items(): setattr(source, k, v) # parse target target = cls(api) for k, v in json['target'].items(): setattr(target, k, v) return source, target class SavedSearch(Model): @classmethod def parse(cls, api, json): ss = cls(api) for k, v in json.items(): if k == 'created_at': setattr(ss, k, parse_datetime(v)) else: setattr(ss, k, v) return ss def destroy(self): return self._api.destroy_saved_search(self.id) class SearchResult(Model): @classmethod def parse(cls, api, json): result = cls() for k, v in json.items(): if k == 'created_at': setattr(result, k, parse_search_datetime(v)) elif k == 'source': setattr(result, k, parse_html_value(unescape_html(v))) else: setattr(result, k, v) return result @classmethod def parse_list(cls, api, json_list, result_set=None): results = ResultSet() results.max_id = json_list.get('max_id') results.since_id = json_list.get('since_id') results.refresh_url = json_list.get('refresh_url') results.next_page = json_list.get('next_page') results.results_per_page = json_list.get('results_per_page') results.page = json_list.get('page') results.completed_in = json_list.get('completed_in') results.query = json_list.get('query') for obj in json_list['results']: results.append(cls.parse(api, obj)) return results class List(Model): @classmethod def parse(cls, api, json): lst = List(api) for k,v in json.items(): if k == 'user': setattr(lst, k, User.parse(api, v)) else: setattr(lst, k, v) return lst @classmethod def parse_list(cls, api, json_list, result_set=None): results = ResultSet() for obj in json_list['lists']: results.append(cls.parse(api, obj)) return results def update(self, **kargs): return self._api.update_list(self.slug, **kargs) def destroy(self): return self._api.destroy_list(self.slug) def timeline(self, **kargs): return self._api.list_timeline(self.user.screen_name, self.slug, **kargs) def add_member(self, id): return self._api.add_list_member(self.slug, id) def remove_member(self, id): return self._api.remove_list_member(self.slug, id) def members(self, **kargs): return self._api.list_members(self.user.screen_name, self.slug, **kargs) def is_member(self, id): return self._api.is_list_member(self.user.screen_name, self.slug, id) def subscribe(self): return self._api.subscribe_list(self.user.screen_name, self.slug) def unsubscribe(self): return self._api.unsubscribe_list(self.user.screen_name, self.slug) def subscribers(self, **kargs): return self._api.list_subscribers(self.user.screen_name, self.slug, **kargs) def is_subscribed(self, id): return self._api.is_subscribed_list(self.user.screen_name, self.slug, id) class JSONModel(Model): @classmethod def parse(cls, api, json): lst = JSONModel(api) for k,v in json.items(): setattr(lst, k, v) return lst class IDSModel(Model): @classmethod def parse(cls, api, json): ids = IDSModel(api) for k, v in json.items(): setattr(ids, k, v) return ids class Counts(Model): @classmethod def parse(cls, api, json): ids = Counts(api) for k, v in json.items(): setattr(ids, k, v) return ids class ModelFactory(object): """ Used by parsers for creating instances of models. You may subclass this factory to add your own extended models. """ status = Status comments = Comments user = User direct_message = DirectMessage friendship = Friendship saved_search = SavedSearch search_result = SearchResult list = List json = JSONModel ids_list = IDSModel counts = Counts
0f523140-f3b3-4653-89b0-eb08c39940ad
trunk/src/html/pybackend/weibopy/models.py
Python
gpl3
10,222
""" The MIT License Copyright (c) 2007 Leah Culver Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. """ import cgi import urllib import time import random import urlparse import hmac import binascii VERSION = '1.0' # Hi Blaine! HTTP_METHOD = 'GET' SIGNATURE_METHOD = 'PLAINTEXT' class OAuthError(RuntimeError): """Generic exception class.""" def __init__(self, message='OAuth error occured.'): self.message = message def build_authenticate_header(realm=''): """Optional WWW-Authenticate header (401 error)""" return {'WWW-Authenticate': 'OAuth realm="%s"' % realm} def escape(s): """Escape a URL including any /.""" return urllib.quote(s, safe='~') def _utf8_str(s): """Convert unicode to utf-8.""" if isinstance(s, unicode): return s.encode("utf-8") else: return str(s) def generate_timestamp(): """Get seconds since epoch (UTC).""" return int(time.time()) def generate_nonce(length=8): """Generate pseudorandom number.""" return ''.join([str(random.randint(0, 9)) for i in range(length)]) def generate_verifier(length=8): """Generate pseudorandom number.""" return ''.join([str(random.randint(0, 9)) for i in range(length)]) class OAuthConsumer(object): """Consumer of OAuth authentication. OAuthConsumer is a data type that represents the identity of the Consumer via its shared secret with the Service Provider. """ key = None secret = None def __init__(self, key, secret): self.key = key self.secret = secret class OAuthToken(object): """OAuthToken is a data type that represents an End User via either an access or request token. key -- the token secret -- the token secret """ key = None secret = None callback = None callback_confirmed = None verifier = None def __init__(self, key, secret): self.key = key self.secret = secret def set_callback(self, callback): self.callback = callback self.callback_confirmed = 'true' def set_verifier(self, verifier=None): if verifier is not None: self.verifier = verifier else: self.verifier = generate_verifier() def get_callback_url(self): if self.callback and self.verifier: # Append the oauth_verifier. parts = urlparse.urlparse(self.callback) scheme, netloc, path, params, query, fragment = parts[:6] if query: query = '%s&oauth_verifier=%s' % (query, self.verifier) else: query = 'oauth_verifier=%s' % self.verifier return urlparse.urlunparse((scheme, netloc, path, params, query, fragment)) return self.callback def to_string(self): data = { 'oauth_token': self.key, 'oauth_token_secret': self.secret, } if self.callback_confirmed is not None: data['oauth_callback_confirmed'] = self.callback_confirmed return urllib.urlencode(data) def from_string(s): """ Returns a token from something like: oauth_token_secret=xxx&oauth_token=xxx """ params = cgi.parse_qs(s, keep_blank_values=False) key = params['oauth_token'][0] secret = params['oauth_token_secret'][0] token = OAuthToken(key, secret) try: token.callback_confirmed = params['oauth_callback_confirmed'][0] except KeyError: pass # 1.0, no callback confirmed. return token from_string = staticmethod(from_string) def __str__(self): return self.to_string() class OAuthRequest(object): """OAuthRequest represents the request and can be serialized. OAuth parameters: - oauth_consumer_key - oauth_token - oauth_signature_method - oauth_signature - oauth_timestamp - oauth_nonce - oauth_version - oauth_verifier ... any additional parameters, as defined by the Service Provider. """ parameters = None # OAuth parameters. http_method = HTTP_METHOD http_url = None version = VERSION def __init__(self, http_method=HTTP_METHOD, http_url=None, parameters=None): self.http_method = http_method self.http_url = http_url self.parameters = parameters or {} def set_parameter(self, parameter, value): self.parameters[parameter] = value def get_parameter(self, parameter): try: return self.parameters[parameter] except: raise OAuthError('Parameter not found: %s' % parameter) def _get_timestamp_nonce(self): return self.get_parameter('oauth_timestamp'), self.get_parameter( 'oauth_nonce') def get_nonoauth_parameters(self): """Get any non-OAuth parameters.""" parameters = {} for k, v in self.parameters.iteritems(): # Ignore oauth parameters. if k.find('oauth_') < 0: parameters[k] = v return parameters def to_header(self, realm=''): """Serialize as a header for an HTTPAuth request.""" auth_header = 'OAuth realm="%s"' % realm # Add the oauth parameters. if self.parameters: for k, v in self.parameters.iteritems(): if k[:6] == 'oauth_': auth_header += ', %s="%s"' % (k, escape(str(v))) return {'Authorization': auth_header} def to_postdata(self): """Serialize as post data for a POST request.""" return '&'.join(['%s=%s' % (escape(str(k)), escape(str(v))) \ for k, v in self.parameters.iteritems()]) def to_url(self): """Serialize as a URL for a GET request.""" return '%s?%s' % (self.get_normalized_http_url(), self.to_postdata()) def get_normalized_parameters(self): """Return a string that contains the parameters that must be signed.""" params = self.parameters try: # Exclude the signature if it exists. del params['oauth_signature'] except: pass # Escape key values before sorting. key_values = [(escape(_utf8_str(k)), escape(_utf8_str(v))) \ for k,v in params.items()] # Sort lexicographically, first after key, then after value. key_values.sort() # Combine key value pairs into a string. return '&'.join(['%s=%s' % (k, v) for k, v in key_values]) def get_normalized_http_method(self): """Uppercases the http method.""" return self.http_method.upper() def get_normalized_http_url(self): """Parses the URL and rebuilds it to be scheme://host/path.""" parts = urlparse.urlparse(self.http_url) scheme, netloc, path = parts[:3] # Exclude default port numbers. if scheme == 'http' and netloc[-3:] == ':80': netloc = netloc[:-3] elif scheme == 'https' and netloc[-4:] == ':443': netloc = netloc[:-4] return '%s://%s%s' % (scheme, netloc, path) def sign_request(self, signature_method, consumer, token): """Set the signature parameter to the result of build_signature.""" # Set the signature method. self.set_parameter('oauth_signature_method', signature_method.get_name()) # Set the signature. self.set_parameter('oauth_signature',self.build_signature(signature_method, consumer, token)) def build_signature(self, signature_method, consumer, token): """Calls the build signature method within the signature method.""" return signature_method.build_signature(self, consumer, token) def from_request(http_method, http_url, headers=None, parameters=None, query_string=None): """Combines multiple parameter sources.""" if parameters is None: parameters = {} # Headers if headers and 'Authorization' in headers: auth_header = headers['Authorization'] # Check that the authorization header is OAuth. if auth_header[:6] == 'OAuth ': auth_header = auth_header[6:] try: # Get the parameters from the header. header_params = OAuthRequest._split_header(auth_header) parameters.update(header_params) except: raise OAuthError('Unable to parse OAuth parameters from ' 'Authorization header.') # GET or POST query string. if query_string: query_params = OAuthRequest._split_url_string(query_string) parameters.update(query_params) # URL parameters. param_str = urlparse.urlparse(http_url)[4] # query url_params = OAuthRequest._split_url_string(param_str) parameters.update(url_params) if parameters: return OAuthRequest(http_method, http_url, parameters) return None from_request = staticmethod(from_request) def from_consumer_and_token(oauth_consumer, token=None, callback=None, verifier=None, http_method=HTTP_METHOD, http_url=None, parameters=None): if not parameters: parameters = {} defaults = { 'oauth_consumer_key': oauth_consumer.key, 'oauth_timestamp': generate_timestamp(), 'oauth_nonce': generate_nonce(), 'oauth_version': OAuthRequest.version, } defaults.update(parameters) parameters = defaults if token: parameters['oauth_token'] = token.key if token.callback: parameters['oauth_callback'] = token.callback # 1.0a support for verifier. if verifier: parameters['oauth_verifier'] = verifier elif callback: # 1.0a support for callback in the request token request. parameters['oauth_callback'] = callback return OAuthRequest(http_method, http_url, parameters) from_consumer_and_token = staticmethod(from_consumer_and_token) def from_token_and_callback(token, callback=None, http_method=HTTP_METHOD, http_url=None, parameters=None): if not parameters: parameters = {} parameters['oauth_token'] = token.key if callback: parameters['oauth_callback'] = callback return OAuthRequest(http_method, http_url, parameters) from_token_and_callback = staticmethod(from_token_and_callback) def _split_header(header): """Turn Authorization: header into parameters.""" params = {} parts = header.split(',') for param in parts: # Ignore realm parameter. if param.find('realm') > -1: continue # Remove whitespace. param = param.strip() # Split key-value. param_parts = param.split('=', 1) # Remove quotes and unescape the value. params[param_parts[0]] = urllib.unquote(param_parts[1].strip('\"')) return params _split_header = staticmethod(_split_header) def _split_url_string(param_str): """Turn URL string into parameters.""" parameters = cgi.parse_qs(param_str, keep_blank_values=False) for k, v in parameters.iteritems(): parameters[k] = urllib.unquote(v[0]) return parameters _split_url_string = staticmethod(_split_url_string) class OAuthServer(object): """A worker to check the validity of a request against a data store.""" timestamp_threshold = 300 # In seconds, five minutes. version = VERSION signature_methods = None data_store = None def __init__(self, data_store=None, signature_methods=None): self.data_store = data_store self.signature_methods = signature_methods or {} def set_data_store(self, data_store): self.data_store = data_store def get_data_store(self): return self.data_store def add_signature_method(self, signature_method): self.signature_methods[signature_method.get_name()] = signature_method return self.signature_methods def fetch_request_token(self, oauth_request): """Processes a request_token request and returns the request token on success. """ try: # Get the request token for authorization. token = self._get_token(oauth_request, 'request') except OAuthError: # No token required for the initial token request. version = self._get_version(oauth_request) consumer = self._get_consumer(oauth_request) try: callback = self.get_callback(oauth_request) except OAuthError: callback = None # 1.0, no callback specified. self._check_signature(oauth_request, consumer, None) # Fetch a new token. token = self.data_store.fetch_request_token(consumer, callback) return token def fetch_access_token(self, oauth_request): """Processes an access_token request and returns the access token on success. """ version = self._get_version(oauth_request) consumer = self._get_consumer(oauth_request) try: verifier = self._get_verifier(oauth_request) except OAuthError: verifier = None # Get the request token. token = self._get_token(oauth_request, 'request') self._check_signature(oauth_request, consumer, token) new_token = self.data_store.fetch_access_token(consumer, token, verifier) return new_token def verify_request(self, oauth_request): """Verifies an api call and checks all the parameters.""" # -> consumer and token version = self._get_version(oauth_request) consumer = self._get_consumer(oauth_request) # Get the access token. token = self._get_token(oauth_request, 'access') self._check_signature(oauth_request, consumer, token) parameters = oauth_request.get_nonoauth_parameters() return consumer, token, parameters def authorize_token(self, token, user): """Authorize a request token.""" return self.data_store.authorize_request_token(token, user) def get_callback(self, oauth_request): """Get the callback URL.""" return oauth_request.get_parameter('oauth_callback') def build_authenticate_header(self, realm=''): """Optional support for the authenticate header.""" return {'WWW-Authenticate': 'OAuth realm="%s"' % realm} def _get_version(self, oauth_request): """Verify the correct version request for this server.""" try: version = oauth_request.get_parameter('oauth_version') except: version = VERSION if version and version != self.version: raise OAuthError('OAuth version %s not supported.' % str(version)) return version def _get_signature_method(self, oauth_request): """Figure out the signature with some defaults.""" try: signature_method = oauth_request.get_parameter( 'oauth_signature_method') except: signature_method = SIGNATURE_METHOD try: # Get the signature method object. signature_method = self.signature_methods[signature_method] except: signature_method_names = ', '.join(self.signature_methods.keys()) raise OAuthError('Signature method %s not supported try one of the ' 'following: %s' % (signature_method, signature_method_names)) return signature_method def _get_consumer(self, oauth_request): consumer_key = oauth_request.get_parameter('oauth_consumer_key') consumer = self.data_store.lookup_consumer(consumer_key) if not consumer: raise OAuthError('Invalid consumer.') return consumer def _get_token(self, oauth_request, token_type='access'): """Try to find the token for the provided request token key.""" token_field = oauth_request.get_parameter('oauth_token') token = self.data_store.lookup_token(token_type, token_field) if not token: raise OAuthError('Invalid %s token: %s' % (token_type, token_field)) return token def _get_verifier(self, oauth_request): return oauth_request.get_parameter('oauth_verifier') def _check_signature(self, oauth_request, consumer, token): timestamp, nonce = oauth_request._get_timestamp_nonce() self._check_timestamp(timestamp) self._check_nonce(consumer, token, nonce) signature_method = self._get_signature_method(oauth_request) try: signature = oauth_request.get_parameter('oauth_signature') except: raise OAuthError('Missing signature.') # Validate the signature. valid_sig = signature_method.check_signature(oauth_request, consumer, token, signature) if not valid_sig: key, base = signature_method.build_signature_base_string( oauth_request, consumer, token) raise OAuthError('Invalid signature. Expected signature base ' 'string: %s' % base) built = signature_method.build_signature(oauth_request, consumer, token) def _check_timestamp(self, timestamp): """Verify that timestamp is recentish.""" timestamp = int(timestamp) now = int(time.time()) lapsed = abs(now - timestamp) if lapsed > self.timestamp_threshold: raise OAuthError('Expired timestamp: given %d and now %s has a ' 'greater difference than threshold %d' % (timestamp, now, self.timestamp_threshold)) def _check_nonce(self, consumer, token, nonce): """Verify that the nonce is uniqueish.""" nonce = self.data_store.lookup_nonce(consumer, token, nonce) if nonce: raise OAuthError('Nonce already used: %s' % str(nonce)) class OAuthClient(object): """OAuthClient is a worker to attempt to execute a request.""" consumer = None token = None def __init__(self, oauth_consumer, oauth_token): self.consumer = oauth_consumer self.token = oauth_token def get_consumer(self): return self.consumer def get_token(self): return self.token def fetch_request_token(self, oauth_request): """-> OAuthToken.""" raise NotImplementedError def fetch_access_token(self, oauth_request): """-> OAuthToken.""" raise NotImplementedError def access_resource(self, oauth_request): """-> Some protected resource.""" raise NotImplementedError class OAuthDataStore(object): """A database abstraction used to lookup consumers and tokens.""" def lookup_consumer(self, key): """-> OAuthConsumer.""" raise NotImplementedError def lookup_token(self, oauth_consumer, token_type, token_token): """-> OAuthToken.""" raise NotImplementedError def lookup_nonce(self, oauth_consumer, oauth_token, nonce): """-> OAuthToken.""" raise NotImplementedError def fetch_request_token(self, oauth_consumer, oauth_callback): """-> OAuthToken.""" raise NotImplementedError def fetch_access_token(self, oauth_consumer, oauth_token, oauth_verifier): """-> OAuthToken.""" raise NotImplementedError def authorize_request_token(self, oauth_token, user): """-> OAuthToken.""" raise NotImplementedError class OAuthSignatureMethod(object): """A strategy class that implements a signature method.""" def get_name(self): """-> str.""" raise NotImplementedError def build_signature_base_string(self, oauth_request, oauth_consumer, oauth_token): """-> str key, str raw.""" raise NotImplementedError def build_signature(self, oauth_request, oauth_consumer, oauth_token): """-> str.""" raise NotImplementedError def check_signature(self, oauth_request, consumer, token, signature): built = self.build_signature(oauth_request, consumer, token) return built == signature class OAuthSignatureMethod_HMAC_SHA1(OAuthSignatureMethod): def get_name(self): return 'HMAC-SHA1' def build_signature_base_string(self, oauth_request, consumer, token): sig = ( escape(oauth_request.get_normalized_http_method()), escape(oauth_request.get_normalized_http_url()), escape(oauth_request.get_normalized_parameters()), ) key = '%s&' % escape(consumer.secret) if token: key += escape(token.secret) #print "OAuth base string:" + str(sig) raw = '&'.join(sig) return key, raw def build_signature(self, oauth_request, consumer, token): """Builds the base signature string.""" key, raw = self.build_signature_base_string(oauth_request, consumer, token) # HMAC object. try: import hashlib # 2.5 hashed = hmac.new(key, raw, hashlib.sha1) except: import sha # Deprecated hashed = hmac.new(key, raw, sha) # Calculate the digest base 64. return binascii.b2a_base64(hashed.digest())[:-1] class OAuthSignatureMethod_PLAINTEXT(OAuthSignatureMethod): def get_name(self): return 'PLAINTEXT' def build_signature_base_string(self, oauth_request, consumer, token): """Concatenates the consumer key and secret.""" sig = '%s&' % escape(consumer.secret) if token: sig = sig + escape(token.secret) return sig, sig def build_signature(self, oauth_request, consumer, token): key, raw = self.build_signature_base_string(oauth_request, consumer, token) return key
0f523140-f3b3-4653-89b0-eb08c39940ad
trunk/src/html/pybackend/weibopy/oauth.py
Python
gpl3
23,187
# Copyright 2009-2010 Joshua Roesslein # See LICENSE for details. from weibopy.models import ModelFactory from weibopy.utils import import_simplejson from weibopy.error import WeibopError class Parser(object): def parse(self, method, payload): """ Parse the response payload and return the result. Returns a tuple that contains the result data and the cursors (or None if not present). """ raise NotImplementedError def parse_error(self, method, payload): """ Parse the error message from payload. If unable to parse the message, throw an exception and default error message will be used. """ raise NotImplementedError class JSONParser(Parser): payload_format = 'json' def __init__(self): self.json_lib = import_simplejson() def parse(self, method, payload): try: json = self.json_lib.loads(payload) except Exception, e: print "Failed to parse JSON payload:"+ str(payload) raise WeibopError('Failed to parse JSON payload: %s' % e) #if isinstance(json, dict) and 'previous_cursor' in json and 'next_cursor' in json: # cursors = json['previous_cursor'], json['next_cursor'] # return json, cursors #else: return json def parse_error(self, method, payload): return self.json_lib.loads(payload) class ModelParser(JSONParser): def __init__(self, model_factory=None): JSONParser.__init__(self) self.model_factory = model_factory or ModelFactory def parse(self, method, payload): try: if method.payload_type is None: return model = getattr(self.model_factory, method.payload_type) except AttributeError: raise WeibopError('No model for this payload type: %s' % method.payload_type) json = JSONParser.parse(self, method, payload) if isinstance(json, tuple): json, cursors = json else: cursors = None if method.payload_list: result = model.parse_list(method.api, json) else: result = model.parse(method.api, json) if cursors: return result, cursors else: return result
0f523140-f3b3-4653-89b0-eb08c39940ad
trunk/src/html/pybackend/weibopy/parsers.py
Python
gpl3
2,316
# Copyright 2010 Joshua Roesslein # See LICENSE for details. from datetime import datetime import time import htmlentitydefs import re def parse_datetime(str): # We must parse datetime this way to work in python 2.4 #return datetime(*(time.strptime(str, '%a %b %d %H:%M:%S +0800 %Y')[0:6])) #Changed by Felix Yan try: a = time.strptime(str, '%a %b %d %H:%M:%S +0800 %Y')[0:6] except: print "Error: " + str a = "" if len(a)<6: raise ValueError else: return datetime(*a) def parse_html_value(html): return html[html.find('>')+1:html.rfind('<')] def parse_a_href(atag): start = atag.find('"') + 1 end = atag.find('"', start) return atag[start:end] def parse_search_datetime(str): # python 2.4 return datetime(*(time.strptime(str, '%a, %d %b %Y %H:%M:%S +0000')[0:6])) def unescape_html(text): """Created by Fredrik Lundh (http://effbot.org/zone/re-sub.htm#unescape-html)""" def fixup(m): text = m.group(0) if text[:2] == "&#": # character reference try: if text[:3] == "&#x": return unichr(int(text[3:-1], 16)) else: return unichr(int(text[2:-1])) except ValueError: pass else: # named entity try: text = unichr(htmlentitydefs.name2codepoint[text[1:-1]]) except KeyError: pass return text # leave as is return re.sub("&#?\w+;", fixup, text) def convert_to_utf8_str(arg): # written by Michael Norton (http://docondev.blogspot.com/) if isinstance(arg, unicode): arg = arg.encode('utf-8') elif not isinstance(arg, str): arg = str(arg) return arg def import_simplejson(): try: import simplejson as json except ImportError: try: import json # Python 2.6+ except ImportError: try: from django.utils import simplejson as json # Google App Engine except ImportError: raise ImportError, "Can't load a json library" return json
0f523140-f3b3-4653-89b0-eb08c39940ad
trunk/src/html/pybackend/weibopy/utils.py
Python
gpl3
2,209
# Copyright 2009-2010 Joshua Roesslein # See LICENSE for details. import httplib import urllib import time import re from weibopy.error import WeibopError from weibopy.utils import convert_to_utf8_str re_path_template = re.compile('{\w+}') def bind_api(**config): class APIMethod(object): path = config['path'] payload_type = config.get('payload_type', None) payload_list = config.get('payload_list', False) allowed_param = config.get('allowed_param', []) method = config.get('method', 'GET') require_auth = config.get('require_auth', False) search_api = config.get('search_api', False) def __init__(self, api, args, kargs): # If authentication is required and no credentials # are provided, throw an error. if self.require_auth and not api.auth: raise WeibopError('Authentication required!') self.api = api self.post_data = kargs.pop('post_data', None) self.retry_count = kargs.pop('retry_count', api.retry_count) self.retry_delay = kargs.pop('retry_delay', api.retry_delay) self.retry_errors = kargs.pop('retry_errors', api.retry_errors) self.headers = kargs.pop('headers', {}) self.build_parameters(args, kargs) # Pick correct URL root to use if self.search_api: self.api_root = api.search_root else: self.api_root = api.api_root # Perform any path variable substitution self.build_path() if api.secure: self.scheme = 'https://' else: self.scheme = 'http://' if self.search_api: self.host = api.search_host else: self.host = api.host # Manually set Host header to fix an issue in python 2.5 # or older where Host is set including the 443 port. # This causes Twitter to issue 301 redirect. # See Issue http://github.com/joshthecoder/tweepy/issues/#issue/12 self.headers['Host'] = self.host def build_parameters(self, args, kargs): self.parameters = {} for idx, arg in enumerate(args): try: self.parameters[self.allowed_param[idx]] = convert_to_utf8_str(arg) except IndexError: raise WeibopError('Too many parameters supplied!') for k, arg in kargs.items(): if arg is None: continue if k in self.parameters: raise WeibopError('Multiple values for parameter %s supplied!' % k) self.parameters[k] = convert_to_utf8_str(arg) def build_path(self): for variable in re_path_template.findall(self.path): name = variable.strip('{}') if name == 'user' and self.api.auth: value = self.api.auth.get_username() else: try: value = urllib.quote(self.parameters[name]) except KeyError: raise WeibopError('No parameter value found for path variable: %s' % name) del self.parameters[name] self.path = self.path.replace(variable, value) def execute(self): # Build the request URL url = self.api_root + self.path if self.api.source is not None: self.parameters.setdefault('source',self.api.source) if len(self.parameters): if self.method == 'GET': url = '%s?%s' % (url, urllib.urlencode(self.parameters)) else: self.headers.setdefault("User-Agent","python") if self.post_data is None: self.headers.setdefault("Accept","text/html") self.headers.setdefault("Content-Type","application/x-www-form-urlencoded") self.post_data = urllib.urlencode(self.parameters) # Query the cache if one is available # and this request uses a GET method. if self.api.cache and self.method == 'GET': cache_result = self.api.cache.get(url) # if cache result found and not expired, return it if cache_result: # must restore api reference if isinstance(cache_result, list): for result in cache_result: result._api = self.api else: cache_result._api = self.api return cache_result #urllib.urlencode(self.parameters) # Continue attempting request until successful # or maximum number of retries is reached. sTime = time.time() retries_performed = 0 while retries_performed < self.retry_count + 1: # Open connection # FIXME: add timeout if self.api.secure: conn = httplib.HTTPSConnection(self.host) else: conn = httplib.HTTPConnection(self.host) # Apply authentication if self.api.auth: self.api.auth.apply_auth( self.scheme + self.host + url, self.method, self.headers, self.parameters ) # Execute request try: conn.request(self.method, url, headers=self.headers, body=self.post_data) resp = conn.getresponse() except Exception, e: raise WeibopError('Failed to send request: %s' % e + "url=" + str(url) +",self.headers="+ str(self.headers)) # Exit request loop if non-retry error code if self.retry_errors: if resp.status not in self.retry_errors: break else: if resp.status == 200: break # Sleep before retrying request again time.sleep(self.retry_delay) retries_performed += 1 # If an error was returned, throw an exception body = resp.read() self.api.last_response = resp if self.api.log is not None: requestUrl = "URL:http://"+ self.host + url eTime = '%.0f' % ((time.time() - sTime) * 1000) postData = "" if self.post_data is not None: postData = ",post:"+ self.post_data[0:500] self.api.log.debug(requestUrl +",time:"+ str(eTime)+ postData+",result:"+ body ) if resp.status != 200: try: json = self.api.parser.parse_error(self, body) error_code = json['error_code'] error = json['error'] error_msg = 'error_code:' + error_code +','+ error except Exception: error_msg = "Twitter error response: status code = %s" % resp.status raise WeibopError(error_msg) # Parse the response payload result = self.api.parser.parse(self, body) conn.close() # Store result into cache if one is available. if self.api.cache and self.method == 'GET' and result: self.api.cache.store(url, result) return result def _call(api, *args, **kargs): method = APIMethod(api, args, kargs) return method.execute() # Set pagination mode if 'cursor' in APIMethod.allowed_param: _call.pagination_mode = 'cursor' elif 'page' in APIMethod.allowed_param: _call.pagination_mode = 'page' return _call
0f523140-f3b3-4653-89b0-eb08c39940ad
trunk/src/html/pybackend/weibopy/binder.py
Python
gpl3
8,100
# Copyright 2009-2010 Joshua Roesslein # See LICENSE for details. """ weibo API library """ __version__ = '1.5' __author__ = 'Joshua Roesslein' __license__ = 'MIT' from weibopy.models import Status, User, DirectMessage, Friendship, SavedSearch, SearchResult, ModelFactory, IDSModel from weibopy.error import WeibopError from weibopy.api import API from weibopy.cache import Cache, MemoryCache, FileCache from weibopy.auth import BasicAuthHandler, OAuthHandler from weibopy.streaming import Stream, StreamListener from weibopy.cursor import Cursor # Global, unauthenticated instance of API api = API() def debug(enable=True, level=1): import httplib httplib.HTTPConnection.debuglevel = level
0f523140-f3b3-4653-89b0-eb08c39940ad
trunk/src/html/pybackend/weibopy/__init__.py
Python
gpl3
706
# Copyright 2009-2010 Joshua Roesslein # See LICENSE for details. import httplib from socket import timeout from threading import Thread from time import sleep import urllib from weibopy.auth import BasicAuthHandler from weibopy.models import Status from weibopy.api import API from weibopy.error import WeibopError from weibopy.utils import import_simplejson json = import_simplejson() STREAM_VERSION = 1 class StreamListener(object): def __init__(self, api=None): self.api = api or API() def on_data(self, data): """Called when raw data is received from connection. Override this method if you wish to manually handle the stream data. Return False to stop stream and close connection. """ if 'in_reply_to_status_id' in data: status = Status.parse(self.api, json.loads(data)) if self.on_status(status) is False: return False elif 'delete' in data: delete = json.loads(data)['delete']['status'] if self.on_delete(delete['id'], delete['user_id']) is False: return False elif 'limit' in data: if self.on_limit(json.loads(data)['limit']['track']) is False: return False def on_status(self, status): """Called when a new status arrives""" return def on_delete(self, status_id, user_id): """Called when a delete notice arrives for a status""" return def on_limit(self, track): """Called when a limitation notice arrvies""" return def on_error(self, status_code): """Called when a non-200 status code is returned""" return False def on_timeout(self): """Called when stream connection times out""" return class Stream(object): host = 'stream.twitter.com' def __init__(self, username, password, listener, timeout=5.0, retry_count = None, retry_time = 10.0, snooze_time = 5.0, buffer_size=1500, headers=None): self.auth = BasicAuthHandler(username, password) self.running = False self.timeout = timeout self.retry_count = retry_count self.retry_time = retry_time self.snooze_time = snooze_time self.buffer_size = buffer_size self.listener = listener self.api = API() self.headers = headers or {} self.body = None def _run(self): # setup self.auth.apply_auth(None, None, self.headers, None) # enter loop error_counter = 0 conn = None while self.running: if self.retry_count and error_counter > self.retry_count: # quit if error count greater than retry count break try: conn = httplib.HTTPConnection(self.host) conn.connect() conn.sock.settimeout(self.timeout) conn.request('POST', self.url, self.body, headers=self.headers) resp = conn.getresponse() if resp.status != 200: if self.listener.on_error(resp.status) is False: break error_counter += 1 sleep(self.retry_time) else: error_counter = 0 self._read_loop(resp) except timeout: if self.listener.on_timeout() == False: break if self.running is False: break conn.close() sleep(self.snooze_time) except Exception: # any other exception is fatal, so kill loop break # cleanup self.running = False if conn: conn.close() def _read_loop(self, resp): data = '' while self.running: if resp.isclosed(): break # read length length = '' while True: c = resp.read(1) if c == '\n': break length += c length = length.strip() if length.isdigit(): length = int(length) else: continue # read data and pass into listener data = resp.read(length) if self.listener.on_data(data) is False: self.running = False def _start(self, async): self.running = True if async: Thread(target=self._run).start() else: self._run() def firehose(self, count=None, async=False): if self.running: raise WeibopError('Stream object already connected!') self.url = '/%i/statuses/firehose.json?delimited=length' % STREAM_VERSION if count: self.url += '&count=%s' % count self._start(async) def retweet(self, async=False): if self.running: raise WeibopError('Stream object already connected!') self.url = '/%i/statuses/retweet.json?delimited=length' % STREAM_VERSION self._start(async) def sample(self, count=None, async=False): if self.running: raise WeibopError('Stream object already connected!') self.url = '/%i/statuses/sample.json?delimited=length' % STREAM_VERSION if count: self.url += '&count=%s' % count self._start(async) def filter(self, follow=None, track=None, async=False): params = {} self.headers['Content-type'] = "application/x-www-form-urlencoded" if self.running: raise WeibopError('Stream object already connected!') self.url = '/%i/statuses/filter.json?delimited=length' % STREAM_VERSION if follow: params['follow'] = ','.join(map(str, follow)) if track: params['track'] = ','.join(map(str, track)) self.body = urllib.urlencode(params) self._start(async) def disconnect(self): if self.running is False: return self.running = False
0f523140-f3b3-4653-89b0-eb08c39940ad
trunk/src/html/pybackend/weibopy/streaming.py
Python
gpl3
6,143
# Copyright 2009-2010 Joshua Roesslein # See LICENSE for details. import os import mimetypes from weibopy.binder import bind_api from weibopy.error import WeibopError from weibopy.parsers import ModelParser class API(object): """Twitter API""" def __init__(self, auth_handler=None, host='api.t.sina.com.cn', search_host='api.t.sina.com.cn', cache=None, secure=False, api_root='', search_root='', retry_count=0, retry_delay=0, retry_errors=None,source=None, parser=None, log = None): self.auth = auth_handler self.host = host if source == None: if auth_handler != None: self.source = self.auth._consumer.key else: self.source = source self.search_host = search_host self.api_root = api_root self.search_root = search_root self.cache = cache self.secure = secure self.retry_count = retry_count self.retry_delay = retry_delay self.retry_errors = retry_errors self.parser = parser or ModelParser() self.log = log """ statuses/public_timeline """ public_timeline = bind_api( path = '/statuses/public_timeline.json', payload_type = 'status', payload_list = True, allowed_param = [] ) """ statuses/home_timeline """ home_timeline = bind_api( path = '/statuses/home_timeline.json', payload_type = 'status', payload_list = True, allowed_param = ['since_id', 'max_id', 'count', 'page'], require_auth = True ) """ statuses/friends_timeline """ friends_timeline = bind_api( path = '/statuses/friends_timeline.json', payload_type = 'status', payload_list = True, allowed_param = ['since_id', 'max_id', 'count', 'page'], require_auth = True ) """ statuses/comment """ comment = bind_api( path = '/statuses/comment.json', method = 'POST', payload_type = 'comments', allowed_param = ['id', 'cid', 'comment'], require_auth = True ) """ statuses/comment_destroy """ comment_destroy = bind_api( path = '/statuses/comment_destroy/{id}.json', method = 'POST', payload_type = 'comments', allowed_param = ['id'], require_auth = True ) """ statuses/comments_timeline """ comments = bind_api( path = '/statuses/comments.json', payload_type = 'comments', payload_list = True, allowed_param = ['id', 'count', 'page'], require_auth = True ) """ statuses/comments_timeline """ comments_timeline = bind_api( path = '/statuses/comments_timeline.json', payload_type = 'comments', payload_list = True, allowed_param = ['since_id', 'max_id', 'count', 'page'], require_auth = True ) """ statuses/comments_by_me """ comments_by_me = bind_api( path = '/statuses/comments_by_me.json', payload_type = 'comments', payload_list = True, allowed_param = ['since_id', 'max_id', 'count', 'page'], require_auth = True ) """ statuses/user_timeline """ user_timeline = bind_api( path = '/statuses/user_timeline.json', payload_type = 'status', payload_list = True, allowed_param = ['id', 'user_id', 'screen_name', 'since_id', 'max_id', 'count', 'page'] ) """ statuses/mentions """ mentions = bind_api( path = '/statuses/mentions.json', payload_type = 'status', payload_list = True, allowed_param = ['since_id', 'max_id', 'count', 'page'], require_auth = True ) """ statuses/counts """ counts = bind_api( path = '/statuses/counts.json', payload_type = 'counts', payload_list = True, allowed_param = ['ids'], require_auth = True ) """ statuses/unread """ unread = bind_api( path = '/statuses/unread.json', payload_type = 'counts' ) """ statuses/retweeted_by_me """ retweeted_by_me = bind_api( path = '/statuses/retweeted_by_me.json', payload_type = 'status', payload_list = True, allowed_param = ['since_id', 'max_id', 'count', 'page'], require_auth = True ) """ statuses/retweeted_to_me """ retweeted_to_me = bind_api( path = '/statuses/retweeted_to_me.json', payload_type = 'status', payload_list = True, allowed_param = ['since_id', 'max_id', 'count', 'page'], require_auth = True ) """ statuses/retweets_of_me """ retweets_of_me = bind_api( path = '/statuses/retweets_of_me.json', payload_type = 'status', payload_list = True, allowed_param = ['since_id', 'max_id', 'count', 'page'], require_auth = True ) """ statuses/show """ get_status = bind_api( path = '/statuses/show.json', payload_type = 'status', allowed_param = ['id'] ) """ statuses/update """ update_status = bind_api( path = '/statuses/update.json', method = 'POST', payload_type = 'status', allowed_param = ['status', 'lat', 'long', 'source'], require_auth = True ) """ statuses/upload """ def upload(self, filename, status, lat=None, long=None, source=None): if source is None: source=self.source headers, post_data = API._pack_image(filename, 1024, source=source, status=status, lat=lat, long=long, contentname="pic") args = [status] allowed_param = ['status'] if lat is not None: args.append(lat) allowed_param.append('lat') if long is not None: args.append(long) allowed_param.append('long') if source is not None: args.append(source) allowed_param.append('source') return bind_api( path = '/statuses/upload.json', method = 'POST', payload_type = 'status', require_auth = True, allowed_param = allowed_param )(self, *args, post_data=post_data, headers=headers) """ statuses/reply """ reply = bind_api( path = '/statuses/reply.json', method = 'POST', payload_type = 'status', allowed_param = ['id', 'cid','comment'], require_auth = True ) """ statuses/repost """ repost = bind_api( path = '/statuses/repost.json', method = 'POST', payload_type = 'status', allowed_param = ['id', 'status'], require_auth = True ) """ statuses/destroy """ destroy_status = bind_api( path = '/statuses/destroy/{id}.json', method = 'DELETE', payload_type = 'status', allowed_param = ['id'], require_auth = True ) """ statuses/retweet """ retweet = bind_api( path = '/statuses/retweet/{id}.json', method = 'POST', payload_type = 'status', allowed_param = ['id'], require_auth = True ) """ statuses/retweets """ retweets = bind_api( path = '/statuses/retweets/{id}.json', payload_type = 'status', payload_list = True, allowed_param = ['id', 'count'], require_auth = True ) """ users/show """ get_user = bind_api( path = '/users/show.json', payload_type = 'user', allowed_param = ['id', 'user_id', 'screen_name'] ) """ Get the authenticated user """ def me(self): return self.get_user(screen_name=self.auth.get_username()) """ users/search """ search_users = bind_api( path = '/users/search.json', payload_type = 'user', payload_list = True, require_auth = True, allowed_param = ['q', 'per_page', 'page'] ) """ statuses/friends """ friends = bind_api( path = '/statuses/friends.json', payload_type = 'user', payload_list = True, allowed_param = ['id', 'user_id', 'screen_name', 'page', 'cursor'] ) """ statuses/followers """ followers = bind_api( path = '/statuses/followers.json', payload_type = 'user', payload_list = True, allowed_param = ['id', 'user_id', 'screen_name', 'page', 'cursor'] ) """ direct_messages """ direct_messages = bind_api( path = '/direct_messages.json', payload_type = 'direct_message', payload_list = True, allowed_param = ['since_id', 'max_id', 'count', 'page'], require_auth = True ) """ direct_messages/sent """ sent_direct_messages = bind_api( path = '/direct_messages/sent.json', payload_type = 'direct_message', payload_list = True, allowed_param = ['since_id', 'max_id', 'count', 'page'], require_auth = True ) """ direct_messages/new """ new_direct_message = bind_api( path = '/direct_messages/new.json', method = 'POST', payload_type = 'direct_message', allowed_param = ['id', 'screen_name', 'user_id', 'text'], require_auth = True ) """ direct_messages/destroy """ destroy_direct_message = bind_api( path = '/direct_messages/destroy/{id}.json', method = 'DELETE', payload_type = 'direct_message', allowed_param = ['id'], require_auth = True ) """ friendships/create """ create_friendship = bind_api( path = '/friendships/create.json', method = 'POST', payload_type = 'user', allowed_param = ['id', 'user_id', 'screen_name', 'follow'], require_auth = True ) """ friendships/destroy """ destroy_friendship = bind_api( path = '/friendships/destroy.json', method = 'DELETE', payload_type = 'user', allowed_param = ['id', 'user_id', 'screen_name'], require_auth = True ) """ friendships/exists """ exists_friendship = bind_api( path = '/friendships/exists.json', payload_type = 'json', allowed_param = ['user_a', 'user_b'] ) """ friendships/show """ show_friendship = bind_api( path = '/friendships/show.json', payload_type = 'friendship', allowed_param = ['source_id', 'source_screen_name', 'target_id', 'target_screen_name'] ) """ friends/ids """ friends_ids = bind_api( path = '/friends/ids.json', payload_type = 'user', allowed_param = ['id', 'user_id', 'screen_name', 'cursor', 'count'], require_auth = True ) """ followers/ids """ followers_ids = bind_api( path = '/followers/ids.json', payload_type = 'json', allowed_param = ['id', 'page'], ) """ account/verify_credentials """ def verify_credentials(self): try: return bind_api( path = '/account/verify_credentials.json', payload_type = 'user', require_auth = True )(self) except WeibopError: return False """ account/rate_limit_status """ rate_limit_status = bind_api( path = '/account/rate_limit_status.json', payload_type = 'json' ) """ account/update_delivery_device """ set_delivery_device = bind_api( path = '/account/update_delivery_device.json', method = 'POST', allowed_param = ['device'], payload_type = 'user', require_auth = True ) """ account/update_profile_colors """ update_profile_colors = bind_api( path = '/account/update_profile_colors.json', method = 'POST', payload_type = 'user', allowed_param = ['profile_background_color', 'profile_text_color', 'profile_link_color', 'profile_sidebar_fill_color', 'profile_sidebar_border_color'], require_auth = True ) """ account/update_profile_image """ def update_profile_image(self, filename): headers, post_data = API._pack_image(filename=filename, max_size=700, source=self.source) return bind_api( path = '/account/update_profile_image.json', method = 'POST', payload_type = 'user', require_auth = True )(self, post_data=post_data, headers=headers) """ account/update_profile_background_image """ def update_profile_background_image(self, filename, *args, **kargs): headers, post_data = API._pack_image(filename, 800) bind_api( path = '/account/update_profile_background_image.json', method = 'POST', payload_type = 'user', allowed_param = ['tile'], require_auth = True )(self, post_data=post_data, headers=headers) """ account/update_profile """ update_profile = bind_api( path = '/account/update_profile.json', method = 'POST', payload_type = 'user', allowed_param = ['name', 'url', 'location', 'description'], require_auth = True ) """ favorites """ favorites = bind_api( path = '/favorites/{id}.json', payload_type = 'status', payload_list = True, allowed_param = ['id', 'page'] ) """ favorites/create """ create_favorite = bind_api( path = '/favorites/create/{id}.json', method = 'POST', payload_type = 'status', allowed_param = ['id'], require_auth = True ) """ favorites/destroy """ destroy_favorite = bind_api( path = '/favorites/destroy/{id}.json', method = 'DELETE', payload_type = 'status', allowed_param = ['id'], require_auth = True ) """ notifications/follow """ enable_notifications = bind_api( path = '/notifications/follow.json', method = 'POST', payload_type = 'user', allowed_param = ['id', 'user_id', 'screen_name'], require_auth = True ) """ notifications/leave """ disable_notifications = bind_api( path = '/notifications/leave.json', method = 'POST', payload_type = 'user', allowed_param = ['id', 'user_id', 'screen_name'], require_auth = True ) """ blocks/create """ create_block = bind_api( path = '/blocks/create.json', method = 'POST', payload_type = 'user', allowed_param = ['id', 'user_id', 'screen_name'], require_auth = True ) """ blocks/destroy """ destroy_block = bind_api( path = '/blocks/destroy.json', method = 'DELETE', payload_type = 'user', allowed_param = ['id', 'user_id', 'screen_name'], require_auth = True ) """ blocks/exists """ def exists_block(self, *args, **kargs): try: bind_api( path = '/blocks/exists.json', allowed_param = ['id', 'user_id', 'screen_name'], require_auth = True )(self, *args, **kargs) except WeibopError: return False return True """ blocks/blocking """ blocks = bind_api( path = '/blocks/blocking.json', payload_type = 'user', payload_list = True, allowed_param = ['page'], require_auth = True ) """ blocks/blocking/ids """ blocks_ids = bind_api( path = '/blocks/blocking/ids.json', payload_type = 'json', require_auth = True ) """ statuses/repost """ report_spam = bind_api( path = '/report_spam.json', method = 'POST', payload_type = 'user', allowed_param = ['id', 'user_id', 'screen_name'], require_auth = True ) """ saved_searches """ saved_searches = bind_api( path = '/saved_searches.json', payload_type = 'saved_search', payload_list = True, require_auth = True ) """ saved_searches/show """ get_saved_search = bind_api( path = '/saved_searches/show/{id}.json', payload_type = 'saved_search', allowed_param = ['id'], require_auth = True ) """ saved_searches/create """ create_saved_search = bind_api( path = '/saved_searches/create.json', method = 'POST', payload_type = 'saved_search', allowed_param = ['query'], require_auth = True ) """ saved_searches/destroy """ destroy_saved_search = bind_api( path = '/saved_searches/destroy/{id}.json', method = 'DELETE', payload_type = 'saved_search', allowed_param = ['id'], require_auth = True ) """ help/test """ def test(self): try: bind_api( path = '/help/test.json', )(self) except WeibopError: return False return True def create_list(self, *args, **kargs): return bind_api( path = '/%s/lists.json' % self.auth.get_username(), method = 'POST', payload_type = 'list', allowed_param = ['name', 'mode', 'description'], require_auth = True )(self, *args, **kargs) def destroy_list(self, slug): return bind_api( path = '/%s/lists/%s.json' % (self.auth.get_username(), slug), method = 'DELETE', payload_type = 'list', require_auth = True )(self) def update_list(self, slug, *args, **kargs): return bind_api( path = '/%s/lists/%s.json' % (self.auth.get_username(), slug), method = 'POST', payload_type = 'list', allowed_param = ['name', 'mode', 'description'], require_auth = True )(self, *args, **kargs) lists = bind_api( path = '/{user}/lists.json', payload_type = 'list', payload_list = True, allowed_param = ['user', 'cursor'], require_auth = True ) lists_memberships = bind_api( path = '/{user}/lists/memberships.json', payload_type = 'list', payload_list = True, allowed_param = ['user', 'cursor'], require_auth = True ) lists_subscriptions = bind_api( path = '/{user}/lists/subscriptions.json', payload_type = 'list', payload_list = True, allowed_param = ['user', 'cursor'], require_auth = True ) list_timeline = bind_api( path = '/{owner}/lists/{slug}/statuses.json', payload_type = 'status', payload_list = True, allowed_param = ['owner', 'slug', 'since_id', 'max_id', 'count', 'page'] ) get_list = bind_api( path = '/{owner}/lists/{slug}.json', payload_type = 'list', allowed_param = ['owner', 'slug'] ) def add_list_member(self, slug, *args, **kargs): return bind_api( path = '/%s/%s/members.json' % (self.auth.get_username(), slug), method = 'POST', payload_type = 'list', allowed_param = ['id'], require_auth = True )(self, *args, **kargs) def remove_list_member(self, slug, *args, **kargs): return bind_api( path = '/%s/%s/members.json' % (self.auth.get_username(), slug), method = 'DELETE', payload_type = 'list', allowed_param = ['id'], require_auth = True )(self, *args, **kargs) list_members = bind_api( path = '/{owner}/{slug}/members.json', payload_type = 'user', payload_list = True, allowed_param = ['owner', 'slug', 'cursor'] ) def is_list_member(self, owner, slug, user_id): try: return bind_api( path = '/%s/%s/members/%s.json' % (owner, slug, user_id), payload_type = 'user' )(self) except WeibopError: return False subscribe_list = bind_api( path = '/{owner}/{slug}/subscribers.json', method = 'POST', payload_type = 'list', allowed_param = ['owner', 'slug'], require_auth = True ) unsubscribe_list = bind_api( path = '/{owner}/{slug}/subscribers.json', method = 'DELETE', payload_type = 'list', allowed_param = ['owner', 'slug'], require_auth = True ) list_subscribers = bind_api( path = '/{owner}/{slug}/subscribers.json', payload_type = 'user', payload_list = True, allowed_param = ['owner', 'slug', 'cursor'] ) def is_subscribed_list(self, owner, slug, user_id): try: return bind_api( path = '/%s/%s/subscribers/%s.json' % (owner, slug, user_id), payload_type = 'user' )(self) except WeibopError: return False """ trends/available """ trends_available = bind_api( path = '/trends/available.json', payload_type = 'json', allowed_param = ['lat', 'long'] ) """ trends/location """ trends_location = bind_api( path = '/trends/{woeid}.json', payload_type = 'json', allowed_param = ['woeid'] ) """ search """ search = bind_api( search_api = True, path = '/search.json', payload_type = 'search_result', payload_list = True, allowed_param = ['q', 'lang', 'locale', 'rpp', 'page', 'since_id', 'geocode', 'show_user'] ) search.pagination_mode = 'page' """ trends """ trends = bind_api( search_api = True, path = '/trends.json', payload_type = 'json' ) """ trends/current """ trends_current = bind_api( search_api = True, path = '/trends/current.json', payload_type = 'json', allowed_param = ['exclude'] ) """ trends/daily """ trends_daily = bind_api( search_api = True, path = '/trends/daily.json', payload_type = 'json', allowed_param = ['date', 'exclude'] ) """ trends/weekly """ trends_weekly = bind_api( search_api = True, path = '/trends/weekly.json', payload_type = 'json', allowed_param = ['date', 'exclude'] ) """ Internal use only """ @staticmethod def _pack_image(filename, max_size, source=None, status=None, lat=None, long=None, contentname="image"): """Pack image from file into multipart-formdata post body""" # image must be less than 700kb in size try: if os.path.getsize(filename) > (max_size * 1024): raise WeibopError('File is too big, must be less than 700kb.') #except os.error, e: except os.error: raise WeibopError('Unable to access file') # image must be gif, jpeg, or png file_type = mimetypes.guess_type(filename) if file_type is None: raise WeibopError('Could not determine file type') file_type = file_type[0] if file_type not in ['image/gif', 'image/jpeg', 'image/png']: raise WeibopError('Invalid file type for image: %s' % file_type) # build the mulitpart-formdata body fp = open(filename, 'rb') BOUNDARY = 'Tw3ePy' body = [] if status is not None: body.append('--' + BOUNDARY) body.append('Content-Disposition: form-data; name="status"') body.append('Content-Type: text/plain; charset=US-ASCII') body.append('Content-Transfer-Encoding: 8bit') body.append('') body.append(status) if source is not None: body.append('--' + BOUNDARY) body.append('Content-Disposition: form-data; name="source"') body.append('Content-Type: text/plain; charset=US-ASCII') body.append('Content-Transfer-Encoding: 8bit') body.append('') body.append(source) if lat is not None: body.append('--' + BOUNDARY) body.append('Content-Disposition: form-data; name="lat"') body.append('Content-Type: text/plain; charset=US-ASCII') body.append('Content-Transfer-Encoding: 8bit') body.append('') body.append(lat) if long is not None: body.append('--' + BOUNDARY) body.append('Content-Disposition: form-data; name="long"') body.append('Content-Type: text/plain; charset=US-ASCII') body.append('Content-Transfer-Encoding: 8bit') body.append('') body.append(long) body.append('--' + BOUNDARY) body.append('Content-Disposition: form-data; name="'+ contentname +'"; filename="%s"' % filename) body.append('Content-Type: %s' % file_type) body.append('Content-Transfer-Encoding: binary') body.append('') body.append(fp.read()) body.append('--' + BOUNDARY + '--') body.append('') fp.close() body.append('--' + BOUNDARY + '--') body.append('') body = '\r\n'.join(body) # build headers headers = { 'Content-Type': 'multipart/form-data; boundary=Tw3ePy', 'Content-Length': len(body) } return headers, body
0f523140-f3b3-4653-89b0-eb08c39940ad
trunk/src/html/pybackend/weibopy/api.py
Python
gpl3
25,468
# Copyright 2009-2010 Joshua Roesslein # See LICENSE for details. from weibopy.error import WeibopError class Cursor(object): """Pagination helper class""" def __init__(self, method, *args, **kargs): if hasattr(method, 'pagination_mode'): if method.pagination_mode == 'cursor': self.iterator = CursorIterator(method, args, kargs) else: self.iterator = PageIterator(method, args, kargs) else: raise WeibopError('This method does not perform pagination') def pages(self, limit=0): """Return iterator for pages""" if limit > 0: self.iterator.limit = limit return self.iterator def items(self, limit=0): """Return iterator for items in each page""" i = ItemIterator(self.iterator) i.limit = limit return i class BaseIterator(object): def __init__(self, method, args, kargs): self.method = method self.args = args self.kargs = kargs self.limit = 0 def next(self): raise NotImplementedError def prev(self): raise NotImplementedError def __iter__(self): return self class CursorIterator(BaseIterator): def __init__(self, method, args, kargs): BaseIterator.__init__(self, method, args, kargs) self.next_cursor = -1 self.prev_cursor = 0 self.count = 0 def next(self): if self.next_cursor == 0 or (self.limit and self.count == self.limit): raise StopIteration data, cursors = self.method( cursor=self.next_cursor, *self.args, **self.kargs ) self.prev_cursor, self.next_cursor = cursors if len(data) == 0: raise StopIteration self.count += 1 return data def prev(self): if self.prev_cursor == 0: raise WeibopError('Can not page back more, at first page') data, self.next_cursor, self.prev_cursor = self.method( cursor=self.prev_cursor, *self.args, **self.kargs ) self.count -= 1 return data class PageIterator(BaseIterator): def __init__(self, method, args, kargs): BaseIterator.__init__(self, method, args, kargs) self.current_page = 0 def next(self): self.current_page += 1 items = self.method(page=self.current_page, *self.args, **self.kargs) if len(items) == 0 or (self.limit > 0 and self.current_page > self.limit): raise StopIteration return items def prev(self): if (self.current_page == 1): raise WeibopError('Can not page back more, at first page') self.current_page -= 1 return self.method(page=self.current_page, *self.args, **self.kargs) class ItemIterator(BaseIterator): def __init__(self, page_iterator): self.page_iterator = page_iterator self.limit = 0 self.current_page = None self.page_index = -1 self.count = 0 def next(self): if self.limit > 0 and self.count == self.limit: raise StopIteration if self.current_page is None or self.page_index == len(self.current_page) - 1: # Reached end of current page, get the next page... self.current_page = self.page_iterator.next() self.page_index = -1 self.page_index += 1 self.count += 1 return self.current_page[self.page_index] def prev(self): if self.current_page is None: raise WeibopError('Can not go back more, at first page') if self.page_index == 0: # At the beginning of the current page, move to next... self.current_page = self.page_iterator.prev() self.page_index = len(self.current_page) if self.page_index == 0: raise WeibopError('No more items') self.page_index -= 1 self.count -= 1 return self.current_page[self.page_index]
0f523140-f3b3-4653-89b0-eb08c39940ad
trunk/src/html/pybackend/weibopy/cursor.py
Python
gpl3
4,026
# Copyright 2009-2010 Joshua Roesslein # See LICENSE for details. import time import threading import os import cPickle as pickle try: import hashlib except ImportError: # python 2.4 import md5 as hashlib try: import fcntl except ImportError: # Probably on a windows system # TODO: use win32file pass class Cache(object): """Cache interface""" def __init__(self, timeout=60): """Initialize the cache timeout: number of seconds to keep a cached entry """ self.timeout = timeout def store(self, key, value): """Add new record to cache key: entry key value: data of entry """ raise NotImplementedError def get(self, key, timeout=None): """Get cached entry if exists and not expired key: which entry to get timeout: override timeout with this value [optional] """ raise NotImplementedError def count(self): """Get count of entries currently stored in cache""" raise NotImplementedError def cleanup(self): """Delete any expired entries in cache.""" raise NotImplementedError def flush(self): """Delete all cached entries""" raise NotImplementedError class MemoryCache(Cache): """In-memory cache""" def __init__(self, timeout=60): Cache.__init__(self, timeout) self._entries = {} self.lock = threading.Lock() def __getstate__(self): # pickle return {'entries': self._entries, 'timeout': self.timeout} def __setstate__(self, state): # unpickle self.lock = threading.Lock() self._entries = state['entries'] self.timeout = state['timeout'] def _is_expired(self, entry, timeout): return timeout > 0 and (time.time() - entry[0]) >= timeout def store(self, key, value): self.lock.acquire() self._entries[key] = (time.time(), value) self.lock.release() def get(self, key, timeout=None): self.lock.acquire() try: # check to see if we have this key entry = self._entries.get(key) if not entry: # no hit, return nothing return None # use provided timeout in arguments if provided # otherwise use the one provided during init. if timeout is None: timeout = self.timeout # make sure entry is not expired if self._is_expired(entry, timeout): # entry expired, delete and return nothing del self._entries[key] return None # entry found and not expired, return it return entry[1] finally: self.lock.release() def count(self): return len(self._entries) def cleanup(self): self.lock.acquire() try: for k, v in self._entries.items(): if self._is_expired(v, self.timeout): del self._entries[k] finally: self.lock.release() def flush(self): self.lock.acquire() self._entries.clear() self.lock.release() class FileCache(Cache): """File-based cache""" # locks used to make cache thread-safe cache_locks = {} def __init__(self, cache_dir, timeout=60): Cache.__init__(self, timeout) if os.path.exists(cache_dir) is False: os.mkdir(cache_dir) self.cache_dir = cache_dir if cache_dir in FileCache.cache_locks: self.lock = FileCache.cache_locks[cache_dir] else: self.lock = threading.Lock() FileCache.cache_locks[cache_dir] = self.lock if os.name == 'posix': self._lock_file = self._lock_file_posix self._unlock_file = self._unlock_file_posix elif os.name == 'nt': self._lock_file = self._lock_file_win32 self._unlock_file = self._unlock_file_win32 else: print 'Warning! FileCache locking not supported on this system!' self._lock_file = self._lock_file_dummy self._unlock_file = self._unlock_file_dummy def _get_path(self, key): md5 = hashlib.md5() md5.update(key) return os.path.join(self.cache_dir, md5.hexdigest()) def _lock_file_dummy(self, path, exclusive=True): return None def _unlock_file_dummy(self, lock): return def _lock_file_posix(self, path, exclusive=True): lock_path = path + '.lock' if exclusive is True: f_lock = open(lock_path, 'w') fcntl.lockf(f_lock, fcntl.LOCK_EX) else: f_lock = open(lock_path, 'r') fcntl.lockf(f_lock, fcntl.LOCK_SH) if os.path.exists(lock_path) is False: f_lock.close() return None return f_lock def _unlock_file_posix(self, lock): lock.close() def _lock_file_win32(self, path, exclusive=True): # TODO: implement return None def _unlock_file_win32(self, lock): # TODO: implement return def _delete_file(self, path): os.remove(path) if os.path.exists(path + '.lock'): os.remove(path + '.lock') def store(self, key, value): path = self._get_path(key) self.lock.acquire() try: # acquire lock and open file f_lock = self._lock_file(path) datafile = open(path, 'wb') # write data pickle.dump((time.time(), value), datafile) # close and unlock file datafile.close() self._unlock_file(f_lock) finally: self.lock.release() def get(self, key, timeout=None): return self._get(self._get_path(key), timeout) def _get(self, path, timeout): if os.path.exists(path) is False: # no record return None self.lock.acquire() try: # acquire lock and open f_lock = self._lock_file(path, False) datafile = open(path, 'rb') # read pickled object created_time, value = pickle.load(datafile) datafile.close() # check if value is expired if timeout is None: timeout = self.timeout if timeout > 0 and (time.time() - created_time) >= timeout: # expired! delete from cache value = None self._delete_file(path) # unlock and return result self._unlock_file(f_lock) return value finally: self.lock.release() def count(self): c = 0 for entry in os.listdir(self.cache_dir): if entry.endswith('.lock'): continue c += 1 return c def cleanup(self): for entry in os.listdir(self.cache_dir): if entry.endswith('.lock'): continue self._get(os.path.join(self.cache_dir, entry), None) def flush(self): for entry in os.listdir(self.cache_dir): if entry.endswith('.lock'): continue self._delete_file(os.path.join(self.cache_dir, entry))
0f523140-f3b3-4653-89b0-eb08c39940ad
trunk/src/html/pybackend/weibopy/cache.py
Python
gpl3
7,372
#coding:utf8 import os, sys from bottle import route, run, debug, template, request, validate, error, response, redirect # only needed when you run Bottle on mod_wsgi from bottle import default_app from y_home import * from y_apply import * from y_admin import * from y_login import * #reload(sys) #sys.setdefaultencoding('utf-8') debug(True) def main(): run(reloader=True); if __name__ == "__main__": # Interactive mode main() else: # Mod WSGI launch os.chdir(os.path.dirname(__file__)) application = default_app()
0f523140-f3b3-4653-89b0-eb08c39940ad
trunk/src/html/pybackend/index.py
Python
gpl3
544
# -*- coding: utf-8 -*- """ Bottle is a fast and simple micro-framework for small web applications. It offers request dispatching (Routes) with url parameter support, templates, a built-in HTTP Server and adapters for many third party WSGI/HTTP-server and template engines - all in a single file and with no dependencies other than the Python Standard Library. Homepage and documentation: http://bottle.paws.de/ Licence (MIT) ------------- Copyright (c) 2009, Marcel Hellkamp. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. Example ------- This is an example:: from bottle import route, run, request, response, static_file, abort @route('/') def hello_world(): return 'Hello World!' @route('/hello/:name') def hello_name(name): return 'Hello %s!' % name @route('/hello', method='POST') def hello_post(): name = request.POST['name'] return 'Hello %s!' % name @route('/static/:filename#.*#') def static(filename): return static_file(filename, root='/path/to/static/files/') run(host='localhost', port=8080) """ from __future__ import with_statement __author__ = 'Marcel Hellkamp' __version__ = '0.8.5' __license__ = 'MIT' import base64 import cgi import email.utils import functools import hmac import inspect import itertools import mimetypes import os import re import subprocess import sys import thread import threading import time import tokenize import tempfile from Cookie import SimpleCookie from tempfile import TemporaryFile from traceback import format_exc from urllib import quote as urlquote from urlparse import urlunsplit, urljoin try: from collections import MutableMapping as DictMixin except ImportError: # pragma: no cover from UserDict import DictMixin try: from urlparse import parse_qs except ImportError: # pragma: no cover from cgi import parse_qs try: import cPickle as pickle except ImportError: # pragma: no cover import pickle try: try: from json import dumps as json_dumps except ImportError: # pragma: no cover from simplejson import dumps as json_dumps except ImportError: # pragma: no cover json_dumps = None if sys.version_info >= (3,0,0): # pragma: no cover # See Request.POST from io import BytesIO from io import TextIOWrapper class NCTextIOWrapper(TextIOWrapper): ''' Garbage collecting an io.TextIOWrapper(buffer) instance closes the wrapped buffer. This subclass keeps it open. ''' def close(self): pass StringType = bytes def touni(x, enc='utf8'): # Convert anything to unicode (py3) return str(x, encoding=enc) if isinstance(x, bytes) else str(x) else: from StringIO import StringIO as BytesIO from types import StringType NCTextIOWrapper = None def touni(x, enc='utf8'): # Convert anything to unicode (py2) return x if isinstance(x, unicode) else unicode(str(x), encoding=enc) def tob(data, enc='utf8'): # Convert strings to bytes (py2 and py3) return data.encode(enc) if isinstance(data, unicode) else data # Background compatibility import warnings def depr(message, critical=False): if critical: raise DeprecationWarning(message) warnings.warn(message, DeprecationWarning, stacklevel=3) # Exceptions and Events class BottleException(Exception): """ A base class for exceptions used by bottle. """ pass class HTTPResponse(BottleException): """ Used to break execution and immediately finish the response """ def __init__(self, output='', status=200, header=None): super(BottleException, self).__init__("HTTP Response %d" % status) self.status = int(status) self.output = output self.headers = HeaderDict(header) if header else None def apply(self, response): if self.headers: for key, value in self.headers.iterallitems(): response.headers[key] = value response.status = self.status class HTTPError(HTTPResponse): """ Used to generate an error page """ def __init__(self, code=500, output='Unknown Error', exception=None, traceback=None, header=None): super(HTTPError, self).__init__(output, code, header) self.exception = exception self.traceback = traceback def __repr__(self): return ''.join(ERROR_PAGE_TEMPLATE.render(e=self)) # Routing class RouteError(BottleException): """ This is a base class for all routing related exceptions """ class RouteSyntaxError(RouteError): """ The route parser found something not supported by this router """ class RouteBuildError(RouteError): """ The route could not been build """ class Route(object): ''' Represents a single route and can parse the dynamic route syntax ''' syntax = re.compile(r'(.*?)(?<!\\):([a-zA-Z_]+)?(?:#(.*?)#)?') default = '[^/]+' def __init__(self, route, target=None, name=None, static=False): """ Create a Route. The route string may contain `:key`, `:key#regexp#` or `:#regexp#` tokens for each dynamic part of the route. These can be escaped with a backslash infront of the `:` and are compleately ignored if static is true. A name may be used to refer to this route later (depends on Router) """ self.route = route self.target = target self.name = name if static: self.route = self.route.replace(':','\\:') self._tokens = None def tokens(self): """ Return a list of (type, value) tokens. """ if not self._tokens: self._tokens = list(self.tokenise(self.route)) return self._tokens @classmethod def tokenise(cls, route): ''' Split a string into an iterator of (type, value) tokens. ''' match = None for match in cls.syntax.finditer(route): pre, name, rex = match.groups() if pre: yield ('TXT', pre.replace('\\:',':')) if rex and name: yield ('VAR', (rex, name)) elif name: yield ('VAR', (cls.default, name)) elif rex: yield ('ANON', rex) if not match: yield ('TXT', route.replace('\\:',':')) elif match.end() < len(route): yield ('TXT', route[match.end():].replace('\\:',':')) def group_re(self): ''' Return a regexp pattern with named groups ''' out = '' for token, data in self.tokens(): if token == 'TXT': out += re.escape(data) elif token == 'VAR': out += '(?P<%s>%s)' % (data[1], data[0]) elif token == 'ANON': out += '(?:%s)' % data return out def flat_re(self): ''' Return a regexp pattern with non-grouping parentheses ''' rf = lambda m: m.group(0) if len(m.group(1)) % 2 else m.group(1) + '(?:' return re.sub(r'(\\*)(\(\?P<[^>]*>|\((?!\?))', rf, self.group_re()) def format_str(self): ''' Return a format string with named fields. ''' out, i = '', 0 for token, value in self.tokens(): if token == 'TXT': out += value.replace('%','%%') elif token == 'ANON': out += '%%(anon%d)s' % i; i+=1 elif token == 'VAR': out += '%%(%s)s' % value[1] return out @property def static(self): return not self.is_dynamic() def is_dynamic(self): ''' Return true if the route contains dynamic parts ''' for token, value in self.tokens(): if token != 'TXT': return True return False def __repr__(self): return "<Route(%s) />" % repr(self.route) def __eq__(self, other): return self.route == other.route class Router(object): ''' A route associates a string (e.g. URL) with an object (e.g. function) Some dynamic routes may extract parts of the string and provide them as a dictionary. This router matches a string against multiple routes and returns the associated object along with the extracted data. ''' def __init__(self): self.routes = [] # List of all installed routes self.named = {} # Cache for named routes and their format strings self.static = {} # Cache for static routes self.dynamic = [] # Search structure for dynamic routes def add(self, route, target=None, **ka): """ Add a route->target pair or a :class:`Route` object to the Router. Return the Route object. See :class:`Route` for details. """ if not isinstance(route, Route): route = Route(route, target, **ka) if self.get_route(route): return RouteError('Route %s is not uniqe.' % route) self.routes.append(route) return route def get_route(self, route, target=None, **ka): ''' Get a route from the router by specifying either the same parameters as in :meth:`add` or comparing to an instance of :class:`Route`. Note that not all parameters are considered by the compare function. ''' if not isinstance(route, Route): route = Route(route, **ka) for known in self.routes: if route == known: return known return None def match(self, uri): ''' Match an URI and return a (target, urlargs) tuple ''' if uri in self.static: return self.static[uri], {} for combined, subroutes in self.dynamic: match = combined.match(uri) if not match: continue target, args_re = subroutes[match.lastindex - 1] args = args_re.match(uri).groupdict() if args_re else {} return target, args return None, {} def build(self, _name, **args): ''' Build an URI out of a named route and values for te wildcards. ''' try: return self.named[_name] % args except KeyError: raise RouteBuildError("No route found with name '%s'." % _name) def compile(self): ''' Build the search structures. Call this before actually using the router.''' self.named = {} self.static = {} self.dynamic = [] for route in self.routes: if route.name: self.named[route.name] = route.format_str() if route.static: self.static[route.route] = route.target continue gpatt = route.group_re() fpatt = route.flat_re() try: gregexp = re.compile('^(%s)$' % gpatt) if '(?P' in gpatt else None combined = '%s|(^%s$)' % (self.dynamic[-1][0].pattern, fpatt) self.dynamic[-1] = (re.compile(combined), self.dynamic[-1][1]) self.dynamic[-1][1].append((route.target, gregexp)) except (AssertionError, IndexError), e: # AssertionError: Too many groups self.dynamic.append((re.compile('(^%s$)'%fpatt),[(route.target, gregexp)])) except re.error, e: raise RouteSyntaxError("Could not add Route: %s (%s)" % (route, e)) def __eq__(self, other): return self.routes == other.routes # WSGI abstraction: Application, Request and Response objects class Bottle(object): """ WSGI application """ def __init__(self, catchall=True, autojson=True, config=None): """ Create a new bottle instance. You usually don't do that. Use `bottle.app.push()` instead. """ self.routes = Router() self.mounts = {} self.error_handler = {} self.catchall = catchall self.config = config or {} self.serve = True self.castfilter = [] if autojson and json_dumps: self.add_filter(dict, dict2json) def optimize(self, *a, **ka): depr("Bottle.optimize() is obsolete.") def mount(self, app, script_path): ''' Mount a Bottle application to a specific URL prefix ''' if not isinstance(app, Bottle): raise TypeError('Only Bottle instances are supported for now.') script_path = '/'.join(filter(None, script_path.split('/'))) path_depth = script_path.count('/') + 1 if not script_path: raise TypeError('Empty script_path. Perhaps you want a merge()?') for other in self.mounts: if other.startswith(script_path): raise TypeError('Conflict with existing mount: %s' % other) @self.route('/%s/:#.*#' % script_path, method="ANY") def mountpoint(): request.path_shift(path_depth) return app.handle(request.path, request.method) self.mounts[script_path] = app def add_filter(self, ftype, func): ''' Register a new output filter. Whenever bottle hits a handler output matching `ftype`, `func` is applied to it. ''' if not isinstance(ftype, type): raise TypeError("Expected type object, got %s" % type(ftype)) self.castfilter = [(t, f) for (t, f) in self.castfilter if t != ftype] self.castfilter.append((ftype, func)) self.castfilter.sort() def match_url(self, path, method='GET'): """ Find a callback bound to a path and a specific HTTP method. Return (callback, param) tuple or raise HTTPError. method: HEAD falls back to GET. All methods fall back to ANY. """ path, method = path.strip().lstrip('/'), method.upper() callbacks, args = self.routes.match(path) if not callbacks: raise HTTPError(404, "Not found: " + path) if method in callbacks: return callbacks[method], args if method == 'HEAD' and 'GET' in callbacks: return callbacks['GET'], args if 'ANY' in callbacks: return callbacks['ANY'], args allow = [m for m in callbacks if m != 'ANY'] if 'GET' in allow and 'HEAD' not in allow: allow.append('HEAD') raise HTTPError(405, "Method not allowed.", header=[('Allow',",".join(allow))]) def get_url(self, routename, **kargs): """ Return a string that matches a named route """ scriptname = request.environ.get('SCRIPT_NAME', '').strip('/') + '/' location = self.routes.build(routename, **kargs).lstrip('/') return urljoin(urljoin('/', scriptname), location) def route(self, path=None, method='GET', **kargs): """ Decorator: bind a function to a GET request path. If the path parameter is None, the signature of the decorated function is used to generate the paths. See yieldroutes() for details. The method parameter (default: GET) specifies the HTTP request method to listen to. You can specify a list of methods too. """ def wrapper(callback): routes = [path] if path else yieldroutes(callback) methods = method.split(';') if isinstance(method, str) else method for r in routes: for m in methods: r, m = r.strip().lstrip('/'), m.strip().upper() old = self.routes.get_route(r, **kargs) if old: old.target[m] = callback else: self.routes.add(r, {m: callback}, **kargs) self.routes.compile() return callback return wrapper def get(self, path=None, method='GET', **kargs): """ Decorator: Bind a function to a GET request path. See :meth:'route' for details. """ return self.route(path, method, **kargs) def post(self, path=None, method='POST', **kargs): """ Decorator: Bind a function to a POST request path. See :meth:'route' for details. """ return self.route(path, method, **kargs) def put(self, path=None, method='PUT', **kargs): """ Decorator: Bind a function to a PUT request path. See :meth:'route' for details. """ return self.route(path, method, **kargs) def delete(self, path=None, method='DELETE', **kargs): """ Decorator: Bind a function to a DELETE request path. See :meth:'route' for details. """ return self.route(path, method, **kargs) def error(self, code=500): """ Decorator: Registrer an output handler for a HTTP error code""" def wrapper(handler): self.error_handler[int(code)] = handler return handler return wrapper def handle(self, url, method): """ Execute the handler bound to the specified url and method and return its output. If catchall is true, exceptions are catched and returned as HTTPError(500) objects. """ if not self.serve: return HTTPError(503, "Server stopped") try: handler, args = self.match_url(url, method) return handler(**args) except HTTPResponse, e: return e except Exception, e: if isinstance(e, (KeyboardInterrupt, SystemExit, MemoryError))\ or not self.catchall: raise return HTTPError(500, 'Unhandled exception', e, format_exc(10)) def _cast(self, out, request, response, peek=None): """ Try to convert the parameter into something WSGI compatible and set correct HTTP headers when possible. Support: False, str, unicode, dict, HTTPResponse, HTTPError, file-like, iterable of strings and iterable of unicodes """ # Filtered types (recursive, because they may return anything) for testtype, filterfunc in self.castfilter: if isinstance(out, testtype): return self._cast(filterfunc(out), request, response) # Empty output is done here if not out: response.headers['Content-Length'] = 0 return [] # Join lists of byte or unicode strings. Mixed lists are NOT supported if isinstance(out, (tuple, list))\ and isinstance(out[0], (StringType, unicode)): out = out[0][0:0].join(out) # b'abc'[0:0] -> b'' # Encode unicode strings if isinstance(out, unicode): out = out.encode(response.charset) # Byte Strings are just returned if isinstance(out, StringType): response.headers['Content-Length'] = str(len(out)) return [out] # HTTPError or HTTPException (recursive, because they may wrap anything) if isinstance(out, HTTPError): out.apply(response) return self._cast(self.error_handler.get(out.status, repr)(out), request, response) if isinstance(out, HTTPResponse): out.apply(response) return self._cast(out.output, request, response) # File-like objects. if hasattr(out, 'read'): if 'wsgi.file_wrapper' in request.environ: return request.environ['wsgi.file_wrapper'](out) elif hasattr(out, 'close') or not hasattr(out, '__iter__'): return WSGIFileWrapper(out) # Handle Iterables. We peek into them to detect their inner type. try: out = iter(out) first = out.next() while not first: first = out.next() except StopIteration: return self._cast('', request, response) except HTTPResponse, e: first = e except Exception, e: first = HTTPError(500, 'Unhandled exception', e, format_exc(10)) if isinstance(e, (KeyboardInterrupt, SystemExit, MemoryError))\ or not self.catchall: raise # These are the inner types allowed in iterator or generator objects. if isinstance(first, HTTPResponse): return self._cast(first, request, response) if isinstance(first, StringType): return itertools.chain([first], out) if isinstance(first, unicode): return itertools.imap(lambda x: x.encode(response.charset), itertools.chain([first], out)) return self._cast(HTTPError(500, 'Unsupported response type: %s'\ % type(first)), request, response) def __call__(self, environ, start_response): """ The bottle WSGI-interface. """ try: environ['bottle.app'] = self request.bind(environ) response.bind(self) out = self.handle(request.path, request.method) out = self._cast(out, request, response) # rfc2616 section 4.3 if response.status in (100, 101, 204, 304) or request.method == 'HEAD': out = [] status = '%d %s' % (response.status, HTTP_CODES[response.status]) start_response(status, response.headerlist) return out except (KeyboardInterrupt, SystemExit, MemoryError): raise except Exception, e: if not self.catchall: raise err = '<h1>Critical error while processing request: %s</h1>' \ % environ.get('PATH_INFO', '/') if DEBUG: err += '<h2>Error:</h2>\n<pre>%s</pre>\n' % repr(e) err += '<h2>Traceback:</h2>\n<pre>%s</pre>\n' % format_exc(10) environ['wsgi.errors'].write(err) #TODO: wsgi.error should not get html start_response('500 INTERNAL SERVER ERROR', [('Content-Type', 'text/html')]) return [tob(err)] class Request(threading.local, DictMixin): """ Represents a single HTTP request using thread-local attributes. The Request object wraps a WSGI environment and can be used as such. """ def __init__(self, environ=None, config=None): """ Create a new Request instance. You usually don't do this but use the global `bottle.request` instance instead. """ self.bind(environ or {}, config) def bind(self, environ, config=None): """ Bind a new WSGI enviroment. This is done automatically for the global `bottle.request` instance on every request. """ self.environ = environ self.config = config or {} # These attributes are used anyway, so it is ok to compute them here self.path = '/' + environ.get('PATH_INFO', '/').lstrip('/') self.method = environ.get('REQUEST_METHOD', 'GET').upper() @property def _environ(self): depr("Request._environ renamed to Request.environ") return self.environ def copy(self): ''' Returns a copy of self ''' return Request(self.environ.copy(), self.config) def path_shift(self, shift=1): ''' Shift path fragments from PATH_INFO to SCRIPT_NAME and vice versa. :param shift: The number of path fragments to shift. May be negative to change the shift direction. (default: 1) ''' script_name = self.environ.get('SCRIPT_NAME','/') self['SCRIPT_NAME'], self.path = path_shift(script_name, self.path, shift) self['PATH_INFO'] = self.path def __getitem__(self, key): return self.environ[key] def __delitem__(self, key): self[key] = ""; del(self.environ[key]) def __iter__(self): return iter(self.environ) def __len__(self): return len(self.environ) def keys(self): return self.environ.keys() def __setitem__(self, key, value): """ Shortcut for Request.environ.__setitem__ """ self.environ[key] = value todelete = [] if key in ('PATH_INFO','REQUEST_METHOD'): self.bind(self.environ, self.config) elif key == 'wsgi.input': todelete = ('body','forms','files','params') elif key == 'QUERY_STRING': todelete = ('get','params') elif key.startswith('HTTP_'): todelete = ('headers', 'cookies') for key in todelete: if 'bottle.' + key in self.environ: del self.environ['bottle.' + key] @property def query_string(self): """ The content of the QUERY_STRING environment variable. """ return self.environ.get('QUERY_STRING', '') @property def fullpath(self): """ Request path including SCRIPT_NAME (if present) """ return self.environ.get('SCRIPT_NAME', '').rstrip('/') + self.path @property def url(self): """ Full URL as requested by the client (computed). This value is constructed out of different environment variables and includes scheme, host, port, scriptname, path and query string. """ scheme = self.environ.get('wsgi.url_scheme', 'http') host = self.environ.get('HTTP_X_FORWARDED_HOST', self.environ.get('HTTP_HOST', None)) if not host: host = self.environ.get('SERVER_NAME') port = self.environ.get('SERVER_PORT', '80') if scheme + port not in ('https443', 'http80'): host += ':' + port parts = (scheme, host, urlquote(self.fullpath), self.query_string, '') return urlunsplit(parts) @property def content_length(self): """ Content-Length header as an integer, -1 if not specified """ return int(self.environ.get('CONTENT_LENGTH','') or -1) @property def header(self): ''' :class:`HeaderDict` filled with request headers. HeaderDict keys are case insensitive str.title()d ''' if 'bottle.headers' not in self.environ: header = self.environ['bottle.headers'] = HeaderDict() for key, value in self.environ.iteritems(): if key.startswith('HTTP_'): key = key[5:].replace('_','-').title() header[key] = value return self.environ['bottle.headers'] @property def GET(self): """ The QUERY_STRING parsed into a MultiDict. Keys and values are strings. Multiple values per key are possible. See MultiDict for details. """ if 'bottle.get' not in self.environ: data = parse_qs(self.query_string, keep_blank_values=True) get = self.environ['bottle.get'] = MultiDict() for key, values in data.iteritems(): for value in values: get[key] = value return self.environ['bottle.get'] @property def POST(self): """ Property: The HTTP POST body parsed into a MultiDict. This supports urlencoded and multipart POST requests. Multipart is commonly used for file uploads and may result in some of the values being cgi.FieldStorage objects instead of strings. Multiple values per key are possible. See MultiDict for details. """ if 'bottle.post' not in self.environ: self.environ['bottle.post'] = MultiDict() self.environ['bottle.forms'] = MultiDict() self.environ['bottle.files'] = MultiDict() safe_env = {'QUERY_STRING':''} # Build a safe environment for cgi for key in ('REQUEST_METHOD', 'CONTENT_TYPE', 'CONTENT_LENGTH'): if key in self.environ: safe_env[key] = self.environ[key] if NCTextIOWrapper: fb = NCTextIOWrapper(self.body, encoding='ISO-8859-1', newline='\n') # TODO: Content-Length may be wrong now. Does cgi.FieldStorage # use it at all? I think not, because all tests pass. else: fb = self.body data = cgi.FieldStorage(fp=fb, environ=safe_env, keep_blank_values=True) for item in data.list or []: if item.filename: self.environ['bottle.post'][item.name] = item self.environ['bottle.files'][item.name] = item else: self.environ['bottle.post'][item.name] = item.value self.environ['bottle.forms'][item.name] = item.value return self.environ['bottle.post'] @property def forms(self): """ Property: HTTP POST form data parsed into a MultiDict. """ if 'bottle.forms' not in self.environ: self.POST return self.environ['bottle.forms'] @property def files(self): """ Property: HTTP POST file uploads parsed into a MultiDict. """ if 'bottle.files' not in self.environ: self.POST return self.environ['bottle.files'] @property def params(self): """ A combined MultiDict with POST and GET parameters. """ if 'bottle.params' not in self.environ: self.environ['bottle.params'] = MultiDict(self.GET) self.environ['bottle.params'].update(dict(self.forms)) return self.environ['bottle.params'] @property def body(self): """ The HTTP request body as a seekable buffer object. This property returns a copy of the `wsgi.input` stream and should be used instead of `environ['wsgi.input']`. """ if 'bottle.body' not in self.environ: maxread = max(0, self.content_length) stream = self.environ['wsgi.input'] body = BytesIO() if maxread < MEMFILE_MAX else TemporaryFile(mode='w+b') while maxread > 0: part = stream.read(min(maxread, MEMFILE_MAX)) if not part: #TODO: Wrong content_length. Error? Do nothing? break body.write(part) maxread -= len(part) self.environ['wsgi.input'] = body self.environ['bottle.body'] = body self.environ['bottle.body'].seek(0) return self.environ['bottle.body'] @property def auth(self): #TODO: Tests and docs. Add support for digest. namedtuple? """ HTTP authorisation data as a (user, passwd) tuple. (experimental) This implementation currently only supports basic auth and returns None on errors. """ return parse_auth(self.environ.get('HTTP_AUTHORIZATION','')) @property def COOKIES(self): """ Cookie information parsed into a dictionary. Secure cookies are NOT decoded automatically. See Request.get_cookie() for details. """ if 'bottle.cookies' not in self.environ: raw_dict = SimpleCookie(self.environ.get('HTTP_COOKIE','')) self.environ['bottle.cookies'] = {} for cookie in raw_dict.itervalues(): self.environ['bottle.cookies'][cookie.key] = cookie.value return self.environ['bottle.cookies'] def get_cookie(self, name, secret=None): """ Return the (decoded) value of a cookie. """ value = self.COOKIES.get(name) dec = cookie_decode(value, secret) if secret else None return dec or value @property def is_ajax(self): ''' True if the request was generated using XMLHttpRequest ''' #TODO: write tests return self.header.get('X-Requested-With') == 'XMLHttpRequest' class Response(threading.local): """ Represents a single HTTP response using thread-local attributes. """ def __init__(self, config=None): self.bind(config) def bind(self, config=None): """ Resets the Response object to its factory defaults. """ self._COOKIES = None self.status = 200 self.headers = HeaderDict() self.content_type = 'text/html; charset=UTF-8' self.config = config or {} @property def header(self): depr("Response.header renamed to Response.headers") return self.headers def copy(self): ''' Returns a copy of self ''' copy = Response(self.config) copy.status = self.status copy.headers = self.headers.copy() copy.content_type = self.content_type return copy def wsgiheader(self): ''' Returns a wsgi conform list of header/value pairs. ''' for c in self.COOKIES.values(): if c.OutputString() not in self.headers.getall('Set-Cookie'): self.headers.append('Set-Cookie', c.OutputString()) # rfc2616 section 10.2.3, 10.3.5 if self.status in (204, 304) and 'content-type' in self.headers: del self.headers['content-type'] if self.status == 304: for h in ('allow', 'content-encoding', 'content-language', 'content-length', 'content-md5', 'content-range', 'content-type', 'last-modified'): # + c-location, expires? if h in self.headers: del self.headers[h] return list(self.headers.iterallitems()) headerlist = property(wsgiheader) @property def charset(self): """ Return the charset specified in the content-type header. This defaults to `UTF-8`. """ if 'charset=' in self.content_type: return self.content_type.split('charset=')[-1].split(';')[0].strip() return 'UTF-8' @property def COOKIES(self): """ A dict-like SimpleCookie instance. Use Response.set_cookie() instead. """ if not self._COOKIES: self._COOKIES = SimpleCookie() return self._COOKIES def set_cookie(self, key, value, secret=None, **kargs): """ Add a new cookie with various options. If the cookie value is not a string, a secure cookie is created. Possible options are: expires, path, comment, domain, max_age, secure, version, httponly See http://de.wikipedia.org/wiki/HTTP-Cookie#Aufbau for details """ if not isinstance(value, basestring): if not secret: raise TypeError('Cookies must be strings when secret is not set') value = cookie_encode(value, secret).decode('ascii') #2to3 hack self.COOKIES[key] = value for k, v in kargs.iteritems(): self.COOKIES[key][k.replace('_', '-')] = v def get_content_type(self): """ Current 'Content-Type' header. """ return self.headers['Content-Type'] def set_content_type(self, value): self.headers['Content-Type'] = value content_type = property(get_content_type, set_content_type, None, get_content_type.__doc__) # Data Structures class MultiDict(DictMixin): """ A dict that remembers old values for each key """ # collections.MutableMapping would be better for Python >= 2.6 def __init__(self, *a, **k): self.dict = dict() for k, v in dict(*a, **k).iteritems(): self[k] = v def __len__(self): return len(self.dict) def __iter__(self): return iter(self.dict) def __contains__(self, key): return key in self.dict def __delitem__(self, key): del self.dict[key] def keys(self): return self.dict.keys() def __getitem__(self, key): return self.get(key, KeyError, -1) def __setitem__(self, key, value): self.append(key, value) def append(self, key, value): self.dict.setdefault(key, []).append(value) def replace(self, key, value): self.dict[key] = [value] def getall(self, key): return self.dict.get(key) or [] def get(self, key, default=None, index=-1): if key not in self.dict and default != KeyError: return [default][index] return self.dict[key][index] def iterallitems(self): for key, values in self.dict.iteritems(): for value in values: yield key, value class HeaderDict(MultiDict): """ Same as :class:`MultiDict`, but title()s the keys and overwrites by default. """ def __contains__(self, key): return MultiDict.__contains__(self, self.httpkey(key)) def __getitem__(self, key): return MultiDict.__getitem__(self, self.httpkey(key)) def __delitem__(self, key): return MultiDict.__delitem__(self, self.httpkey(key)) def __setitem__(self, key, value): self.replace(key, value) def get(self, key, default=None, index=-1): return MultiDict.get(self, self.httpkey(key), default, index) def append(self, key, value): return MultiDict.append(self, self.httpkey(key), str(value)) def replace(self, key, value): return MultiDict.replace(self, self.httpkey(key), str(value)) def getall(self, key): return MultiDict.getall(self, self.httpkey(key)) def httpkey(self, key): return str(key).replace('_','-').title() class AppStack(list): """ A stack implementation. """ def __call__(self): """ Return the current default app. """ return self[-1] def push(self, value=None): """ Add a new Bottle instance to the stack """ if not isinstance(value, Bottle): value = Bottle() self.append(value) return value class WSGIFileWrapper(object): def __init__(self, fp, buffer_size=1024*64): self.fp, self.buffer_size = fp, buffer_size for attr in ('fileno', 'close', 'read', 'readlines'): if hasattr(fp, attr): setattr(self, attr, getattr(fp, attr)) def __iter__(self): read, buff = self.fp.read, self.buffer_size while True: part = read(buff) if not part: break yield part # Module level functions # Output filter def dict2json(d): response.content_type = 'application/json' return json_dumps(d) def abort(code=500, text='Unknown Error: Appliction stopped.'): """ Aborts execution and causes a HTTP error. """ raise HTTPError(code, text) def redirect(url, code=303): """ Aborts execution and causes a 303 redirect """ scriptname = request.environ.get('SCRIPT_NAME', '').rstrip('/') + '/' location = urljoin(request.url, urljoin(scriptname, url)) raise HTTPResponse("", status=code, header=dict(Location=location)) def send_file(*a, **k): #BC 0.6.4 """ Raises the output of static_file(). (deprecated) """ raise static_file(*a, **k) def static_file(filename, root, guessmime=True, mimetype=None, download=False): """ Opens a file in a safe way and returns a HTTPError object with status code 200, 305, 401 or 404. Sets Content-Type, Content-Length and Last-Modified header. Obeys If-Modified-Since header and HEAD requests. """ root = os.path.abspath(root) + os.sep filename = os.path.abspath(os.path.join(root, filename.strip('/\\'))) header = dict() if not filename.startswith(root): return HTTPError(403, "Access denied.") if not os.path.exists(filename) or not os.path.isfile(filename): return HTTPError(404, "File does not exist.") if not os.access(filename, os.R_OK): return HTTPError(403, "You do not have permission to access this file.") if not mimetype and guessmime: header['Content-Type'] = mimetypes.guess_type(filename)[0] else: header['Content-Type'] = mimetype if mimetype else 'text/plain' if download == True: download = os.path.basename(filename) if download: header['Content-Disposition'] = 'attachment; filename="%s"' % download stats = os.stat(filename) lm = time.strftime("%a, %d %b %Y %H:%M:%S GMT", time.gmtime(stats.st_mtime)) header['Last-Modified'] = lm ims = request.environ.get('HTTP_IF_MODIFIED_SINCE') if ims: ims = ims.split(";")[0].strip() # IE sends "<date>; length=146" ims = parse_date(ims) if ims is not None and ims >= int(stats.st_mtime): header['Date'] = time.strftime("%a, %d %b %Y %H:%M:%S GMT", time.gmtime()) return HTTPResponse(status=304, header=header) header['Content-Length'] = stats.st_size if request.method == 'HEAD': return HTTPResponse('', header=header) else: return HTTPResponse(open(filename, 'rb'), header=header) # Utilities def debug(mode=True): """ Change the debug level. There is only one debug level supported at the moment.""" global DEBUG DEBUG = bool(mode) def parse_date(ims): """ Parse rfc1123, rfc850 and asctime timestamps and return UTC epoch. """ try: ts = email.utils.parsedate_tz(ims) return time.mktime(ts[:8] + (0,)) - (ts[9] or 0) - time.timezone except (TypeError, ValueError, IndexError): return None def parse_auth(header): """ Parse rfc2617 HTTP authentication header string (basic) and return (user,pass) tuple or None""" try: method, data = header.split(None, 1) if method.lower() == 'basic': name, pwd = base64.b64decode(data).split(':', 1) return name, pwd except (KeyError, ValueError, TypeError): return None def _lscmp(a, b): ''' Compares two strings in a cryptographically save way: Runtime is not affected by a common prefix. ''' return not sum(0 if x==y else 1 for x, y in zip(a, b)) and len(a) == len(b) def cookie_encode(data, key): ''' Encode and sign a pickle-able object. Return a string ''' msg = base64.b64encode(pickle.dumps(data, -1)) sig = base64.b64encode(hmac.new(key, msg).digest()) return tob('!') + sig + tob('?') + msg def cookie_decode(data, key): ''' Verify and decode an encoded string. Return an object or None''' data = tob(data) if cookie_is_encoded(data): sig, msg = data.split(tob('?'), 1) if _lscmp(sig[1:], base64.b64encode(hmac.new(key, msg).digest())): return pickle.loads(base64.b64decode(msg)) return None def cookie_is_encoded(data): ''' Return True if the argument looks like a encoded cookie.''' return bool(data.startswith(tob('!')) and tob('?') in data) def tonativefunc(enc='utf-8'): ''' Returns a function that turns everything into 'native' strings using enc ''' if sys.version_info >= (3,0,0): return lambda x: x.decode(enc) if isinstance(x, bytes) else str(x) return lambda x: x.encode(enc) if isinstance(x, unicode) else str(x) def yieldroutes(func): """ Return a generator for routes that match the signature (name, args) of the func parameter. This may yield more than one route if the function takes optional keyword arguments. The output is best described by example: a() -> '/a' b(x, y) -> '/b/:x/:y' c(x, y=5) -> '/c/:x' and '/c/:x/:y' d(x=5, y=6) -> '/d' and '/d/:x' and '/d/:x/:y' """ path = func.__name__.replace('__','/').lstrip('/') spec = inspect.getargspec(func) argc = len(spec[0]) - len(spec[3] or []) path += ('/:%s' * argc) % tuple(spec[0][:argc]) yield path for arg in spec[0][argc:]: path += '/:%s' % arg yield path def path_shift(script_name, path_info, shift=1): ''' Shift path fragments from PATH_INFO to SCRIPT_NAME and vice versa. :return: The modified paths. :param script_name: The SCRIPT_NAME path. :param script_name: The PATH_INFO path. :param shift: The number of path fragments to shift. May be negative to change ths shift direction. (default: 1) ''' if shift == 0: return script_name, path_info pathlist = path_info.strip('/').split('/') scriptlist = script_name.strip('/').split('/') if pathlist and pathlist[0] == '': pathlist = [] if scriptlist and scriptlist[0] == '': scriptlist = [] if shift > 0 and shift <= len(pathlist): moved = pathlist[:shift] scriptlist = scriptlist + moved pathlist = pathlist[shift:] elif shift < 0 and shift >= -len(scriptlist): moved = scriptlist[shift:] pathlist = moved + pathlist scriptlist = scriptlist[:shift] else: empty = 'SCRIPT_NAME' if shift < 0 else 'PATH_INFO' raise AssertionError("Cannot shift. Nothing left from %s" % empty) new_script_name = '/' + '/'.join(scriptlist) new_path_info = '/' + '/'.join(pathlist) if path_info.endswith('/') and pathlist: new_path_info += '/' return new_script_name, new_path_info # Decorators #TODO: Replace default_app() with app() def validate(**vkargs): """ Validates and manipulates keyword arguments by user defined callables. Handles ValueError and missing arguments by raising HTTPError(403). """ def decorator(func): def wrapper(**kargs): for key, value in vkargs.iteritems(): if key not in kargs: abort(403, 'Missing parameter: %s' % key) try: kargs[key] = value(kargs[key]) except ValueError: abort(403, 'Wrong parameter format for: %s' % key) return func(**kargs) return wrapper return decorator route = functools.wraps(Bottle.route)(lambda *a, **ka: app().route(*a, **ka)) get = functools.wraps(Bottle.get)(lambda *a, **ka: app().get(*a, **ka)) post = functools.wraps(Bottle.post)(lambda *a, **ka: app().post(*a, **ka)) put = functools.wraps(Bottle.put)(lambda *a, **ka: app().put(*a, **ka)) delete = functools.wraps(Bottle.delete)(lambda *a, **ka: app().delete(*a, **ka)) error = functools.wraps(Bottle.error)(lambda *a, **ka: app().error(*a, **ka)) url = functools.wraps(Bottle.get_url)(lambda *a, **ka: app().get_url(*a, **ka)) mount = functools.wraps(Bottle.mount)(lambda *a, **ka: app().mount(*a, **ka)) def default(): depr("The default() decorator is deprecated. Use @error(404) instead.") return error(404) # Server adapter class ServerAdapter(object): quiet = False def __init__(self, host='127.0.0.1', port=8080, **kargs): self.options = kargs self.host = host self.port = int(port) def run(self, handler): # pragma: no cover pass def __repr__(self): args = ', '.join(['%s=%s'%(k,repr(v)) for k, v in self.options.items()]) return "%s(%s)" % (self.__class__.__name__, args) class CGIServer(ServerAdapter): quiet = True def run(self, handler): # pragma: no cover from wsgiref.handlers import CGIHandler CGIHandler().run(handler) # Just ignore host and port here class FlupFCGIServer(ServerAdapter): def run(self, handler): # pragma: no cover import flup.server.fcgi flup.server.fcgi.WSGIServer(handler, bindAddress=(self.host, self.port)).run() class WSGIRefServer(ServerAdapter): def run(self, handler): # pragma: no cover from wsgiref.simple_server import make_server, WSGIRequestHandler if self.quiet: class QuietHandler(WSGIRequestHandler): def log_request(*args, **kw): pass self.options['handler_class'] = QuietHandler srv = make_server(self.host, self.port, handler, **self.options) srv.serve_forever() class CherryPyServer(ServerAdapter): def run(self, handler): # pragma: no cover from cherrypy import wsgiserver server = wsgiserver.CherryPyWSGIServer((self.host, self.port), handler) server.start() class PasteServer(ServerAdapter): def run(self, handler): # pragma: no cover from paste import httpserver from paste.translogger import TransLogger app = TransLogger(handler) httpserver.serve(app, host=self.host, port=str(self.port), **self.options) class FapwsServer(ServerAdapter): """ Extremly fast webserver using libev. See http://william-os4y.livejournal.com/ """ def run(self, handler): # pragma: no cover import fapws._evwsgi as evwsgi from fapws import base evwsgi.start(self.host, self.port) evwsgi.set_base_module(base) def app(environ, start_response): environ['wsgi.multiprocess'] = False return handler(environ, start_response) evwsgi.wsgi_cb(('',app)) evwsgi.run() class TornadoServer(ServerAdapter): """ Untested. As described here: http://github.com/facebook/tornado/blob/master/tornado/wsgi.py#L187 """ def run(self, handler): # pragma: no cover import tornado.wsgi import tornado.httpserver import tornado.ioloop container = tornado.wsgi.WSGIContainer(handler) server = tornado.httpserver.HTTPServer(container) server.listen(port=self.port) tornado.ioloop.IOLoop.instance().start() class AppEngineServer(ServerAdapter): """ Untested. """ quiet = True def run(self, handler): from google.appengine.ext.webapp import util util.run_wsgi_app(handler) class TwistedServer(ServerAdapter): """ Untested. """ def run(self, handler): from twisted.web import server, wsgi from twisted.python.threadpool import ThreadPool from twisted.internet import reactor thread_pool = ThreadPool() thread_pool.start() reactor.addSystemEventTrigger('after', 'shutdown', thread_pool.stop) factory = server.Site(wsgi.WSGIResource(reactor, thread_pool, handler)) reactor.listenTCP(self.port, factory, interface=self.host) reactor.run() class DieselServer(ServerAdapter): """ Untested. """ def run(self, handler): from diesel.protocols.wsgi import WSGIApplication app = WSGIApplication(handler, port=self.port) app.run() class GunicornServer(ServerAdapter): """ Untested. """ def run(self, handler): import gunicorn.arbiter gunicorn.arbiter.Arbiter((self.host, self.port), 4, handler).run() class EventletServer(ServerAdapter): """ Untested """ def run(self, handler): from eventlet import wsgi, listen wsgi.server(listen((self.host, self.port)), handler) class RocketServer(ServerAdapter): """ Untested. As requested in issue 63 http://github.com/defnull/bottle/issues/#issue/63 """ def run(self, handler): from rocket import Rocket server = Rocket((self.host, self.port), 'wsgi', { 'wsgi_app' : handler }) server.start() class AutoServer(ServerAdapter): """ Untested. """ adapters = [CherryPyServer, PasteServer, TwistedServer, WSGIRefServer] def run(self, handler): for sa in self.adapters: try: return sa(self.host, self.port, **self.options).run(handler) except ImportError: pass def run(app=None, server=WSGIRefServer, host='127.0.0.1', port=8080, interval=1, reloader=False, quiet=False, **kargs): """ Runs bottle as a web server. """ app = app if app else default_app() # Instantiate server, if it is a class instead of an instance if isinstance(server, type): server = server(host=host, port=port, **kargs) if not isinstance(server, ServerAdapter): raise RuntimeError("Server must be a subclass of WSGIAdapter") server.quiet = server.quiet or quiet if not server.quiet and not os.environ.get('BOTTLE_CHILD'): print "Bottle server starting up (using %s)..." % repr(server) print "Listening on http://%s:%d/" % (server.host, server.port) print "Use Ctrl-C to quit." print try: if reloader: interval = min(interval, 1) if os.environ.get('BOTTLE_CHILD'): _reloader_child(server, app, interval) else: _reloader_observer(server, app, interval) else: server.run(app) except KeyboardInterrupt: pass if not server.quiet and not os.environ.get('BOTTLE_CHILD'): print "Shutting down..." class FileCheckerThread(threading.Thread): ''' Thread that periodically checks for changed module files. ''' def __init__(self, lockfile, interval): threading.Thread.__init__(self) self.lockfile, self.interval = lockfile, interval #1: lockfile to old; 2: lockfile missing #3: module file changed; 5: external exit self.status = 0 def run(self): exists = os.path.exists mtime = lambda path: os.stat(path).st_mtime files = dict() for module in sys.modules.values(): try: path = inspect.getsourcefile(module) if path and exists(path): files[path] = mtime(path) except TypeError: pass while not self.status: for path, lmtime in files.iteritems(): if not exists(path) or mtime(path) > lmtime: self.status = 3 if not exists(self.lockfile): self.status = 2 elif mtime(self.lockfile) < time.time() - self.interval - 5: self.status = 1 if not self.status: time.sleep(self.interval) if self.status != 5: thread.interrupt_main() def _reloader_child(server, app, interval): ''' Start the server and check for modified files in a background thread. As soon as an update is detected, KeyboardInterrupt is thrown in the main thread to exit the server loop. The process exists with status code 3 to request a reload by the observer process. If the lockfile is not modified in 2*interval second or missing, we assume that the observer process died and exit with status code 1 or 2. ''' lockfile = os.environ.get('BOTTLE_LOCKFILE') bgcheck = FileCheckerThread(lockfile, interval) try: bgcheck.start() server.run(app) except KeyboardInterrupt, e: pass bgcheck.status, status = 5, bgcheck.status bgcheck.join() # bgcheck.status == 5 --> silent exit if status: sys.exit(status) def _reloader_observer(server, app, interval): ''' Start a child process with identical commandline arguments and restart it as long as it exists with status code 3. Also create a lockfile and touch it (update mtime) every interval seconds. ''' fd, lockfile = tempfile.mkstemp(prefix='bottle-reloader.', suffix='.lock') os.close(fd) # We only need this file to exist. We never write to it try: while os.path.exists(lockfile): args = [sys.executable] + sys.argv environ = os.environ.copy() environ['BOTTLE_CHILD'] = 'true' environ['BOTTLE_LOCKFILE'] = lockfile p = subprocess.Popen(args, env=environ) while p.poll() is None: # Busy wait... os.utime(lockfile, None) # I am alive! time.sleep(interval) if p.poll() != 3: if os.path.exists(lockfile): os.unlink(lockfile) sys.exit(p.poll()) elif not server.quiet: print "Reloading server..." except KeyboardInterrupt: pass if os.path.exists(lockfile): os.unlink(lockfile) # Templates class TemplateError(HTTPError): def __init__(self, message): HTTPError.__init__(self, 500, message) class BaseTemplate(object): """ Base class and minimal API for template adapters """ extentions = ['tpl','html','thtml','stpl'] settings = {} #used in prepare() defaults = {} #used in render() def __init__(self, source=None, name=None, lookup=[], encoding='utf8', **settings): """ Create a new template. If the source parameter (str or buffer) is missing, the name argument is used to guess a template filename. Subclasses can assume that self.source and/or self.filename are set. Both are strings. The lookup, encoding and settings parameters are stored as instance variables. The lookup parameter stores a list containing directory paths. The encoding parameter should be used to decode byte strings or files. The settings parameter contains a dict for engine-specific settings. """ self.name = name self.source = source.read() if hasattr(source, 'read') else source self.filename = source.filename if hasattr(source, 'filename') else None self.lookup = map(os.path.abspath, lookup) self.encoding = encoding self.settings = self.settings.copy() # Copy from class variable self.settings.update(settings) # Apply if not self.source and self.name: self.filename = self.search(self.name, self.lookup) if not self.filename: raise TemplateError('Template %s not found.' % repr(name)) if not self.source and not self.filename: raise TemplateError('No template specified.') self.prepare(**self.settings) @classmethod def search(cls, name, lookup=[]): """ Search name in all directories specified in lookup. First without, then with common extensions. Return first hit. """ if os.path.isfile(name): return name for spath in lookup: fname = os.path.join(spath, name) if os.path.isfile(fname): return fname for ext in cls.extentions: if os.path.isfile('%s.%s' % (fname, ext)): return '%s.%s' % (fname, ext) @classmethod def global_config(cls, key, *args): ''' This reads or sets the global settings stored in class.settings. ''' if args: cls.settings[key] = args[0] else: return cls.settings[key] def prepare(self, **options): """ Run preparations (parsing, caching, ...). It should be possible to call this again to refresh a template or to update settings. """ raise NotImplementedError def render(self, **args): """ Render the template with the specified local variables and return a single byte or unicode string. If it is a byte string, the encoding must match self.encoding. This method must be thread-safe! """ raise NotImplementedError class MakoTemplate(BaseTemplate): def prepare(self, **options): from mako.template import Template from mako.lookup import TemplateLookup options.update({'input_encoding':self.encoding}) #TODO: This is a hack... http://github.com/defnull/bottle/issues#issue/8 mylookup = TemplateLookup(directories=['.']+self.lookup, **options) if self.source: self.tpl = Template(self.source, lookup=mylookup) else: #mako cannot guess extentions. We can, but only at top level... name = self.name if not os.path.splitext(name)[1]: name += os.path.splitext(self.filename)[1] self.tpl = mylookup.get_template(name) def render(self, **args): _defaults = self.defaults.copy() _defaults.update(args) return self.tpl.render(**_defaults) class CheetahTemplate(BaseTemplate): def prepare(self, **options): from Cheetah.Template import Template self.context = threading.local() self.context.vars = {} options['searchList'] = [self.context.vars] if self.source: self.tpl = Template(source=self.source, **options) else: self.tpl = Template(file=self.filename, **options) def render(self, **args): self.context.vars.update(self.defaults) self.context.vars.update(args) out = str(self.tpl) self.context.vars.clear() return [out] class Jinja2Template(BaseTemplate): def prepare(self, filters=None, tests=None, **kwargs): from jinja2 import Environment, FunctionLoader if 'prefix' in kwargs: # TODO: to be removed after a while raise RuntimeError('The keyword argument `prefix` has been removed. ' 'Use the full jinja2 environment name line_statement_prefix instead.') self.env = Environment(loader=FunctionLoader(self.loader), **kwargs) if filters: self.env.filters.update(filters) if tests: self.env.tests.update(tests) if self.source: self.tpl = self.env.from_string(self.source) else: self.tpl = self.env.get_template(self.filename) def render(self, **args): _defaults = self.defaults.copy() _defaults.update(args) return self.tpl.render(**_defaults).encode("utf-8") def loader(self, name): fname = self.search(name, self.lookup) if fname: with open(fname, "rb") as f: return f.read().decode(self.encoding) class SimpleTemplate(BaseTemplate): blocks = ('if','elif','else','try','except','finally','for','while','with','def','class') dedent_blocks = ('elif', 'else', 'except', 'finally') def prepare(self, escape_func=cgi.escape, noescape=False): self.cache = {} if self.source: self.code = self.translate(self.source) self.co = compile(self.code, '<string>', 'exec') else: self.code = self.translate(open(self.filename).read()) self.co = compile(self.code, self.filename, 'exec') enc = self.encoding self._str = lambda x: touni(x, enc) self._escape = lambda x: escape_func(touni(x, enc)) if noescape: self._str, self._escape = self._escape, self._str def translate(self, template): stack = [] # Current Code indentation lineno = 0 # Current line of code ptrbuffer = [] # Buffer for printable strings and token tuple instances codebuffer = [] # Buffer for generated python code touni = functools.partial(unicode, encoding=self.encoding) multiline = dedent = False def yield_tokens(line): for i, part in enumerate(re.split(r'\{\{(.*?)\}\}', line)): if i % 2: if part.startswith('!'): yield 'RAW', part[1:] else: yield 'CMD', part else: yield 'TXT', part def split_comment(codeline): """ Removes comments from a line of code. """ line = codeline.splitlines()[0] try: tokens = list(tokenize.generate_tokens(iter(line).next)) except tokenize.TokenError: return line.rsplit('#',1) if '#' in line else (line, '') for token in tokens: if token[0] == tokenize.COMMENT: start, end = token[2][1], token[3][1] return codeline[:start] + codeline[end:], codeline[start:end] return line, '' def flush(): # Flush the ptrbuffer if not ptrbuffer: return cline = '' for line in ptrbuffer: for token, value in line: if token == 'TXT': cline += repr(value) elif token == 'RAW': cline += '_str(%s)' % value elif token == 'CMD': cline += '_escape(%s)' % value cline += ', ' cline = cline[:-2] + '\\\n' cline = cline[:-2] if cline[:-1].endswith('\\\\\\\\\\n'): cline = cline[:-7] + cline[-1] # 'nobr\\\\\n' --> 'nobr' cline = '_printlist([' + cline + '])' del ptrbuffer[:] # Do this before calling code() again code(cline) def code(stmt): for line in stmt.splitlines(): codebuffer.append(' ' * len(stack) + line.strip()) for line in template.splitlines(True): lineno += 1 line = line if isinstance(line, unicode)\ else unicode(line, encoding=self.encoding) if lineno <= 2: m = re.search(r"%.*coding[:=]\s*([-\w\.]+)", line) if m: self.encoding = m.group(1) if m: line = line.replace('coding','coding (removed)') if line.strip()[:2].count('%') == 1: line = line.split('%',1)[1].lstrip() # Full line following the % cline = split_comment(line)[0].strip() cmd = re.split(r'[^a-zA-Z0-9_]', cline)[0] flush() ##encodig (TODO: why?) if cmd in self.blocks or multiline: cmd = multiline or cmd dedent = cmd in self.dedent_blocks # "else:" if dedent and not oneline and not multiline: cmd = stack.pop() code(line) oneline = not cline.endswith(':') # "if 1: pass" multiline = cmd if cline.endswith('\\') else False if not oneline and not multiline: stack.append(cmd) elif cmd == 'end' and stack: code('#end(%s) %s' % (stack.pop(), line.strip()[3:])) elif cmd == 'include': p = cline.split(None, 2)[1:] if len(p) == 2: code("_=_include(%s, _stdout, %s)" % (repr(p[0]), p[1])) elif p: code("_=_include(%s, _stdout)" % repr(p[0])) else: # Empty %include -> reverse of %rebase code("_printlist(_base)") elif cmd == 'rebase': p = cline.split(None, 2)[1:] if len(p) == 2: code("globals()['_rebase']=(%s, dict(%s))" % (repr(p[0]), p[1])) elif p: code("globals()['_rebase']=(%s, {})" % repr(p[0])) else: code(line) else: # Line starting with text (not '%') or '%%' (escaped) if line.strip().startswith('%%'): line = line.replace('%%', '%', 1) ptrbuffer.append(yield_tokens(line)) flush() return '\n'.join(codebuffer) + '\n' def subtemplate(self, _name, _stdout, **args): if _name not in self.cache: self.cache[_name] = self.__class__(name=_name, lookup=self.lookup) return self.cache[_name].execute(_stdout, **args) def execute(self, _stdout, **args): env = self.defaults.copy() env.update({'_stdout': _stdout, '_printlist': _stdout.extend, '_include': self.subtemplate, '_str': self._str, '_escape': self._escape}) env.update(args) eval(self.co, env) if '_rebase' in env: subtpl, rargs = env['_rebase'] subtpl = self.__class__(name=subtpl, lookup=self.lookup) rargs['_base'] = _stdout[:] #copy stdout del _stdout[:] # clear stdout return subtpl.execute(_stdout, **rargs) return env def render(self, **args): """ Render the template using keyword arguments as local variables. """ stdout = [] self.execute(stdout, **args) return ''.join(stdout) def template(tpl, template_adapter=SimpleTemplate, **kwargs): ''' Get a rendered template as a string iterator. You can use a name, a filename or a template string as first parameter. ''' if tpl not in TEMPLATES or DEBUG: settings = kwargs.get('template_settings',{}) lookup = kwargs.get('template_lookup', TEMPLATE_PATH) if isinstance(tpl, template_adapter): TEMPLATES[tpl] = tpl if settings: TEMPLATES[tpl].prepare(**settings) elif "\n" in tpl or "{" in tpl or "%" in tpl or '$' in tpl: TEMPLATES[tpl] = template_adapter(source=tpl, lookup=lookup, **settings) else: TEMPLATES[tpl] = template_adapter(name=tpl, lookup=lookup, **settings) if not TEMPLATES[tpl]: abort(500, 'Template (%s) not found' % tpl) return TEMPLATES[tpl].render(**kwargs) mako_template = functools.partial(template, template_adapter=MakoTemplate) cheetah_template = functools.partial(template, template_adapter=CheetahTemplate) jinja2_template = functools.partial(template, template_adapter=Jinja2Template) def view(tpl_name, **defaults): ''' Decorator: renders a template for a handler. The handler can control its behavior like that: - return a dict of template vars to fill out the template - return something other than a dict and the view decorator will not process the template, but return the handler result as is. This includes returning a HTTPResponse(dict) to get, for instance, JSON with autojson or other castfilters ''' def decorator(func): @functools.wraps(func) def wrapper(*args, **kwargs): result = func(*args, **kwargs) if isinstance(result, (dict, DictMixin)): tplvars = defaults.copy() tplvars.update(result) return template(tpl_name, **tplvars) return result return wrapper return decorator mako_view = functools.partial(view, template_adapter=MakoTemplate) cheetah_view = functools.partial(view, template_adapter=CheetahTemplate) jinja2_view = functools.partial(view, template_adapter=Jinja2Template) # Modul initialization and configuration TEMPLATE_PATH = ['./', './views/'] TEMPLATES = {} DEBUG = False MEMFILE_MAX = 1024*100 HTTP_CODES = { 100: 'CONTINUE', 101: 'SWITCHING PROTOCOLS', 200: 'OK', 201: 'CREATED', 202: 'ACCEPTED', 203: 'NON-AUTHORITATIVE INFORMATION', 204: 'NO CONTENT', 205: 'RESET CONTENT', 206: 'PARTIAL CONTENT', 300: 'MULTIPLE CHOICES', 301: 'MOVED PERMANENTLY', 302: 'FOUND', 303: 'SEE OTHER', 304: 'NOT MODIFIED', 305: 'USE PROXY', 306: 'RESERVED', 307: 'TEMPORARY REDIRECT', 400: 'BAD REQUEST', 401: 'UNAUTHORIZED', 402: 'PAYMENT REQUIRED', 403: 'FORBIDDEN', 404: 'NOT FOUND', 405: 'METHOD NOT ALLOWED', 406: 'NOT ACCEPTABLE', 407: 'PROXY AUTHENTICATION REQUIRED', 408: 'REQUEST TIMEOUT', 409: 'CONFLICT', 410: 'GONE', 411: 'LENGTH REQUIRED', 412: 'PRECONDITION FAILED', 413: 'REQUEST ENTITY TOO LARGE', 414: 'REQUEST-URI TOO LONG', 415: 'UNSUPPORTED MEDIA TYPE', 416: 'REQUESTED RANGE NOT SATISFIABLE', 417: 'EXPECTATION FAILED', 500: 'INTERNAL SERVER ERROR', 501: 'NOT IMPLEMENTED', 502: 'BAD GATEWAY', 503: 'SERVICE UNAVAILABLE', 504: 'GATEWAY TIMEOUT', 505: 'HTTP VERSION NOT SUPPORTED', } """ A dict of known HTTP error and status codes """ ERROR_PAGE_TEMPLATE = SimpleTemplate(""" %try: %from bottle import DEBUG, HTTP_CODES, request %status_name = HTTP_CODES.get(e.status, 'Unknown').title() <!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN"> <html> <head> <title>Error {{e.status}}: {{status_name}}</title> <style type="text/css"> html {background-color: #eee; font-family: sans;} body {background-color: #fff; border: 1px solid #ddd; padding: 15px; margin: 15px;} pre {background-color: #eee; border: 1px solid #ddd; padding: 5px;} </style> </head> <body> <h1>Error {{e.status}}: {{status_name}}</h1> <p>Sorry, the requested URL <tt>{{request.url}}</tt> caused an error:</p> <pre>{{str(e.output)}}</pre> %if DEBUG and e.exception: <h2>Exception:</h2> <pre>{{repr(e.exception)}}</pre> %end %if DEBUG and e.traceback: <h2>Traceback:</h2> <pre>{{e.traceback}}</pre> %end </body> </html> %except ImportError: <b>ImportError:</b> Could not generate the error page. Please add bottle to sys.path %end """) """ The HTML template used for error messages """ request = Request() """ Whenever a page is requested, the :class:`Bottle` WSGI handler stores metadata about the current request into this instance of :class:`Request`. It is thread-safe and can be accessed from within handler functions. """ response = Response() """ The :class:`Bottle` WSGI handler uses metadata assigned to this instance of :class:`Response` to generate the WSGI response. """ local = threading.local() """ Thread-local namespace. Not used by Bottle, but could get handy """ # Initialize app stack (create first empty Bottle app) # BC: 0.6.4 and needed for run() app = default_app = AppStack() app.push()
0f523140-f3b3-4653-89b0-eb08c39940ad
trunk/src/html/pybackend/bottle.py
Python
gpl3
73,521
<!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> <meta http-equiv='Content-Type' content='text/html; charset=utf-8' /> <title>意见反馈 - 歪伯乐微招聘 - 微博招聘、求职、简历信息,一站聚合、管理、定制</title> <link rel="icon" href="favicon_big.png" sizes="48x48"> <link rel="shortcut icon" href="/favicon.ico" /> <link href="css/themes/base/jquery.ui.all.css" rel="Stylesheet" type="text/css" /> <link href="css/share.css" rel="stylesheet" type="text/css" /> <link href="css/help_feedback.css" rel="stylesheet" type="text/css" /> <link href="css/themes/base/jquery.ui.all.css" rel="stylesheet" type="text/css" /> <script src="script/jquery-1.5.1.js" type="text/javascript"></script> <script src="script/jquery.cookie.js" type="text/javascript"></script> <script src="script/ui/jquery.ui.core.js" type="text/javascript"></script> <script src="script/ui/jquery.ui.widget.js" type="text/javascript"></script> <script src="script/ui/jquery.ui.mouse.js" type="text/javascript"></script> <script src="script/ui/jquery.ui.draggable.js" type="text/javascript"></script> <script src="script/ui/jquery.ui.resizable.js" type="text/javascript"></script> <script src="script/ui/jquery.ui.position.js" type="text/javascript"></script> <script src="script/ui/jquery.ui.dialog.js" type="text/javascript"></script> <script src="script/share.js" type="text/javascript"></script> <script src="script/help_feedback.js" type="text/javascript"></script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-22822126-2']); _gaq.push(['_setDomainName', '.ybole.com']); _gaq.push(['_trackPageview']); $(function () { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); }); </script> </head> <body> <div id="header"> <div class="left" id="links"> <a class="left first" href="/">歪伯乐招聘网</a> <a class="left" href="http://t.sina.com.cn/2020566725"> 歪伯乐招聘官方微博</a> <a class="left logined" id="my-microbloging">我的微博</a> </div> <div class="right" id="infos"> <a class="left selected logined" id="name" href="/"></a><a class="left orange logined" href="/manager" id="manager-center">管理中心</a> <a class="left jobs" id="jobs-publish-quick"> 发布求职信息</a><a class="left recruitment" id="recruitment-publish-quick">发布招聘信息</a><a class="left admin" href="/admin">管理员入口</a> <a class="left logined" href="logout/">退出</a> <a class="left logouted" id="sina-login" href="login/"></a> </div> </div> <div id="logo-search"> <a id="logo" class="left" href="/">测试版</a> </div> <div id="content" class="inner"> <div class="left" id="content-left"> <div> <a href="/help">网站帮助</a></div> <div> <a href="/feedback" style="text-decoration: underline;">意见反馈</a></div> </div> <div class="left" id="content-middle"> <div class="left" id="inner-content"> <div> <p> <strong>联系反馈</strong></p> <p> 新浪微博账号:@歪伯乐</p> <p> 客服邮箱:support@yBole.com<br /> 媒体邮箱:media@yBole.com<br /> 合作邮箱:bd@yBole.com</p> <p> 歪伯乐是个新产品,存在很多的不足。<br /> 歪伯乐的成长,离不开热心用户和朋友们的关注与支持。<br /> 您的需求和批评,是歪伯乐发展的不竭动力。<br /> 请不吝赐教。</p> </div> <div> 请留下您宝贵的意见,我们会根据您的意见来不断完善歪伯乐招聘网! </div> <div> <span class="left">问题:</span> <input type="text" class="left" id="question" /> </div> <div> <span class="left">问题描述:</span> <textarea rows="5" id="description"></textarea> </div> <div> 请留下您的联系方式,方便我们及时与您沟通! </div> <div> <span class="left">邮箱:</span> <input type="text" class="left" id="email" /> </div> <div> <a class="left"></a> </div> </div> </div> </div> <div class="clear"> </div> <div id="footer" class="inner"> <div id="footerlinks"> <a href="/help">网站帮助</a> | <a href="/feedback">意见反馈</a> | <a>联系我们</a></div> <div id="copyright"> CopyRight © 2011-2012 <a>歪伯乐招聘网</a> Co. All Right Reserved. 鄂ICP证100111号<br /> Powered by:GNG</div> </div> <div id="cover"> </div> <div id="jobs-publish" class="absolute"> <div id="jobs-publish-title"> <span class="left">发布求职信息</span> <a class="right"></a> </div> <div id="jobs-publish-content"> <div id="jobs-publish-remain"> 还可输入136个字</div> <div id="jobs-publish-text"> <textarea>#求职#</textarea> </div> <div id="jobs-publish-tags-hot"> </div> <div id="jobs-publish-confirm"> <a class="right"></a><span class="right">本信息将同步发送到新浪微博</span> </div> </div> </div> <div id="recruitment-publish" class="absolute"> <div id="recruitment-publish-title"> <span class="left">发布招聘信息</span> <a class="right"></a> </div> <div id="recruitment-publish-content"> <div id="recruitment-publish-remain"> 还可输入136个字</div> <form action="tweet/post/2" name="postform" id="RecruitmentForm" method="post" enctype="multipart/form-data" target="hf"> <div id="recruitment-publish-text"> <textarea name="text">#招聘#</textarea> </div> <div id="recruitment-publish-tags-hot"> </div> <div id="recruitment-publish-file"><span class="left">上传图片</span><input type="file" name="upload" id="file" /></div> </form> <div id="recruitment-publish-confirm"> <a class="right"></a><span class="right">本信息将同步发送到新浪微博</span> </div> </div> </div> <div id="popBox_publishok" class="popBox popBoxwd1" style="display: none;"> <div class="boxtitle"> <div class="popboxicon"> <h4> 信息发布提示</h4> </div> </div> <div class="popBox_main"> <div class="line1"> <div class="popboxicon img_tip"> </div> <div class="font_tip"> 信息发布成功!</div> </div> <div class="line2"> <div class="font_tip2" style="line-height: 18px;"> 信息已同步到新浪微博,本信息将在稍后显示<br> 在本网站中,请不要重复发布。</div> </div> <div class="line3"> <a class="popboxicon btn_ikown" onclick="$('#popBox_publishok').hide();">好的,我知道了</a></div> </div> </div> <div id="feedback-info"> <p>感谢您的反馈!我们将认真对待您的意见和建议!</p> </div> <div id="LFlower" style="display: none; position: absolute; z-index: 3000;"></div> <iframe id="hf" name="hf" style="display:none;"></iframe> <div id="error-info" title="错误"> <p id="errormsg"> </p> </div> </body> </html>
0f523140-f3b3-4653-89b0-eb08c39940ad
trunk/src/html/feedback.html
HTML
gpl3
8,956
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>CKFinder User's Guide</title> </head> <frameset rows="50,*" bordercolor="#f5f5f5"> <frame src="files/header.html" noresize="1" frameborder="0" bordercolor="#f5f5f5"></frame> <frameset cols="200,*"> <frame src="files/toc.html" bordercolor="#f5f5f5"></frame> <frame src="files/001.html" name="CKDocsMain" bordercolor="#f5f5f5"></frame> </frameset> </frameset> </html>
0f523140-f3b3-4653-89b0-eb08c39940ad
trunk/src/html/ckfinder/help/en/index.html
HTML
gpl3
511
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>CKFinder User's Guide</title> <link href="other/help.css" type="text/css" rel="stylesheet" /> <script type="text/javascript" src="other/help.js"></script> </head> <body> <h1> Compatibility and System Requirements </h1> <p> CKFinder is a "web application". It means that it's made to run inside web browsers, making it easy to deploy and to use in any computer.</p> <p> Currently, the following browsers are required to CKFinder to run:</p> <ul> <li>Internet Explorer 6.0+</li> <li>Firefox 2.0+</li> <li>Safari 3+</li> <li>Google Chrome</li> <li>Opera 9.5+</li> <li>Camino 1.0+</li> </ul> <p> Some features are dependent of your browser settings. By default, it should be ready for CKFinder, but if you are experiencing problems with the <a href="012.html">Context Menu</a> or your <a href="008.html">Settings</a> are not being saved, be sure that your browser is configured to "<strong>allow scripts to replace context menus</strong>" ("allow scripts to receive right clicks") and that you have "<strong>cookies support enabled</strong>".</p> <p> Please contact your system administrator if you have any doubt.</p> </body> </html>
0f523140-f3b3-4653-89b0-eb08c39940ad
trunk/src/html/ckfinder/help/en/files/013.html
HTML
gpl3
1,330
<!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>CKFinder User's Guide</title> <link href="other/help.css" type="text/css" rel="stylesheet" /> <script type="text/javascript" src="other/help.js"></script> </head> <body> <h1> Welcome to CKFinder </h1> <p> <strong>CKFinder is a Collaborative Software</strong> that makes it easy to maintain and share files located on a central computer (the server).</p> <p> Whether you are new to CKFinder or an experienced user, it is well worth spending time browsing through the CKFinder documentation, to achieve complete knowledge about this simple but powerful software.</p> <h2> Legal notices </h2> <p> Your attention is drawn to the <a href="011.html" title="Link to Legal Notices">Legal Notices</a>. </p> </body> </html>
0f523140-f3b3-4653-89b0-eb08c39940ad
trunk/src/html/ckfinder/help/en/files/001.html
HTML
gpl3
951
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>CKFinder User's Guide</title> <link href="other/help.css" type="text/css" rel="stylesheet" /> <script type="text/javascript" src="other/help.js"></script> </head> <body> <h1> Help Button </h1> <p> Opens the "User's Guide" in a new window.</p> </body> </html>
0f523140-f3b3-4653-89b0-eb08c39940ad
trunk/src/html/ckfinder/help/en/files/009.html
HTML
gpl3
405
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>CKFinder User's Guide</title> <link href="other/help.css" type="text/css" rel="stylesheet" /> <script type="text/javascript" src="other/help.js"></script> </head> <body> <h1> CKFinder License </h1> <iframe src="../../../license.txt" style="width:800px;height:600px"></iframe> </body> </html>
0f523140-f3b3-4653-89b0-eb08c39940ad
trunk/src/html/ckfinder/help/en/files/license.html
HTML
gpl3
435
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>CKFinder User's Guide</title> <link href="other/help.css" type="text/css" rel="stylesheet" /> <script type="text/javascript" src="other/help.js"></script> </head> <body> <h1> CKFinder Interface Overview </h1> <p> The CKFinder interface has been designed to be clear, familiar to our end users, and easy to learn and use. Most features can be handled with a mouse click and context menus. </p> <p> The following is a screenshot of CKFinder: </p> <p style="text-align: center"> <img src="images/001.gif" alt="CKFinder Screenshot" height="402" width="609" /> </p> <ol> <li><a href="003.html">Folders Pane</a>: contains the "tree view" of the folders where you can navigate. Folders are ways to organize files better. </li> <li><a href="004.html">Files Pane</a>: lists the files available in the selected folder. </li> <li><a href="005.html">Toolbar</a>: a series of buttons that can be clicked to quickly execute specific functions. </li> <li><a href="010.html">Status Bar</a>: space used to display information regarding the select file, the total number of files in the folder, etc. </li> <li><a href="012.html">Context Menu</a>: a series of buttons that can be used to execute specific tasks in the object that has been clicked. The available options dynamically change, depending on which kind of object is clicked. </li> </ol> </body> </html>
0f523140-f3b3-4653-89b0-eb08c39940ad
trunk/src/html/ckfinder/help/en/files/002.html
HTML
gpl3
1,555
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>CKFinder User's Guide</title> <link href="other/help.css" type="text/css" rel="stylesheet" /> <script type="text/javascript" src="other/help.js"></script> </head> <body> <h1> Refresh Button </h1> <p > While working in a shared space like CKFinder, where dozens or even hundreds of users are working in the same files, it may happen that changes are done by others in the same folder you are working on, at the right moment that you have it opened. To reload the files list, just click the "Refresh" button.</p> <p style="text-align: center"> <img height="25" src="images/011.gif" width="258" />&nbsp;</p> <p> For example, suppose you have to create a page for a brand new product of your company. You open CKFinder to get the product picture to include in the company web site, but, when opening the "Products" folder, you can't find that picture. You take the phone and call "Beth", saying: "Hey Beth, the product picture is not at CKFinder!". Beth says, "Ops... just a minute". She opens CKFinder in her computer, uploads the picture file from her desktop and tells you: "It's there now, just refresh it". You click on Refresh and, voila! The file appears there for you. This is why CKFinder is also known as <strong>Collaborative Software.</strong></p> </body> </html>
0f523140-f3b3-4653-89b0-eb08c39940ad
trunk/src/html/ckfinder/help/en/files/007.html
HTML
gpl3
1,458
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>CKFinder User's Guide</title> <link href="other/help.css" type="text/css" rel="stylesheet" /> <script type="text/javascript" src="other/help.js"></script> </head> <body> <h1> Files Pane </h1> <p> The Files Pane lists all files available in the selected folder.</p> <h2> Different Views</h2> <p> The Files Pane may present two different views, depending on CKFinder settings (see "<a href="008.html">Settings</a>"). The following is a comparison of the "<strong>Thumbnails</strong>" and the "<strong>List</strong>" views for the same folder:</p> <p style="text-align: center"> <img src="images/007.gif" width="404" height="332" /> </p> <p style="text-align: center"> <img src="images/006.gif" width="404" height="332" /> </p> <h2> Basic Operations &nbsp;</h2> <h3> Selecting (Activating) a File</h3> <p> To select a file, making it the "active file" in CKFinder, simply click in the file. To make it easy to understand that the mouse is over the file, the file area will be colored. The selected file will have a different background color (generally blue). </p> <h2> Advanced Operations </h2> <p> Advanced operations may be achieved on a file by using its "<a href="012.html">Context Menu</a>". The following options are available: </p> <p style="text-align: center"> <img height="122" src="images/008.gif" width="82" /> </p> <p> <span class="info">Note:</span> Some context menu buttons may be disabled, depending on CKFinder settings enforced by your system administrator. </p> <div> <h3> Selecting Files </h3> </div> <p> To select a file, returning it to the hosting application, just click the "Select" option.</p> <h3> Viewing (previewing) Files</h3> <p> To preview a file in the browser, just click the "View" button. Not all kinds of files can be viewed on browsers, but this feature is quite useful for images, text and PDF files. In other cases, the browser will ask you to open the file with the proper application.</p> <div> <h3> Downloading Files</h3> <p> To download a file, just click the "Download" button. The browser will ask you for the place to save the downloaded file in your computer.</p> <h3> Renaming Files </h3> </div> <p> To rename a file, just click the "Rename" option in the context menu. A dialog box, containing the current file name, will appear, asking for the new name. Just type it and confirm. </p> <p> Not all characters can be used in folder and files names due to limitations in the systems where CKFinder runs. For instance, the following characters cannot be used on folders and files names: <strong>\</strong> <strong>/</strong> <strong>:</strong> <strong>*</strong> <strong>?</strong> <strong>"</strong> <strong>&lt;</strong> <strong> &gt;</strong> <strong>|</strong></p> <p> <span class="warning">Attention:</span> by renaming a file, links or media insertions available in other pages, which point to the renamed file, will be "broken", therefore not available anymore. So, be careful when using this feature.</p> <div> <h3> Deleting Files </h3> </div> <p> To delete a file, just click the "Delete" option in the context menu. A confirmation message will appear to ensure that this operation is desired. </p> <p> <span class="warning">Attention:</span> by deleting a file, links or media insertions available in other pages, which point to the deleted file, will be "broken", therefore not available anymore. So, be careful when using this feature.</p> </body> </html>
0f523140-f3b3-4653-89b0-eb08c39940ad
trunk/src/html/ckfinder/help/en/files/004.html
HTML
gpl3
3,801
window.onload = function() { var copyP = document.createElement( 'p' ) ; copyP.className = 'copyright' ; copyP.innerHTML = '&copy; 2007-2011 <a href="http://cksource.com" target="_blank">CKSource</a> - Frederico Knabben . All rights reserved.<br /><br />' ; document.body.appendChild( document.createElement( 'hr' ) ) ; document.body.appendChild( copyP ) ; window.top.SetActiveTopic( window.location.pathname ) ; }
0f523140-f3b3-4653-89b0-eb08c39940ad
trunk/src/html/ckfinder/help/en/files/other/help.js
JavaScript
gpl3
435
body { margin: 0px; font-family: Georgia, Trebuchet, Trebuchet MS, Verdana; } h1 { background-color: #f5f5f5; color: #696969; padding-left: 20px; padding-right: 20px; padding-top: 10px; padding-bottom: 10px; margin: 0px; margin-bottom: 40px; } p, ul, ol { margin-bottom: 30px; margin-top: 0px; margin-left: 40px; margin-right: 40px; } ol, ul { padding-left:40px; } h2 { margin-left: 20px; margin-bottom: 30px; margin-top: 0px; } h3 { margin-left: 40px; margin-bottom: 15px; margin-top: 0px; } hr { margin-top: 0px; } .info { font-weight: bold; } .warning { font-weight: bold; color: #ff0000; }
0f523140-f3b3-4653-89b0-eb08c39940ad
trunk/src/html/ckfinder/help/en/files/other/help.css
CSS
gpl3
687
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>CKFinder User's Guide</title> <link href="other/help.css" type="text/css" rel="stylesheet" /> <script type="text/javascript" src="other/help.js"></script> </head> <body> <h1> Settings Button </h1> <p> The "Settings" button, in the <a href="005.html">toolbar</a>, opens the "Settings Pane", where you can configure and customize CKFinder. Here is a screenshot of it:</p> <p style="text-align: center"> <img src="images/013.gif" height="190" width="404" /></p> <p> All settings are automatically saved by using browser "cookies". Cookies are small files containing private configuration information for specific web sites.</p> <p> To close the Settings Pane, just click in the "Close" button, or click "Settings" again in the toolbar.</p> <h2> Configuration Options</h2> <p> All configuration options are related to the <a href="004.html">Files Pane</a>. They are used to control how to display information in that pane. The Files Pane will react immediately to changes in the Settings Pane.</p> <h3> View</h3> <p> Controls the view mode in the <a href="004.html">Files Pane</a>:</p> <ul> <li>The "<strong>Thumbnails</strong>" mode will display each file as a "box". For images, a small preview of it (called thumbnail) will be displayed inside the box. For other files, an icon will be available instead.</li> </ul> <ul> <li>The "<strong>List</strong>" mode will display all files as a list, one bellow the other. No image previews are available in this mode.</li> </ul> <h3> Display</h3> <p> Sets the amount of information available in the Files Pane. To exemplify, here is the thumbnail box when you have no options selected for Display, until having all options selected:</p> <p style="text-align:center"> <table align="center" cellpadding="0" cellspacing="0"> <tr> <td valign="top" style="padding-right: 10px"> <img src="images/014.gif" width="112" height="112" /></td> <td valign="top" style="padding-right: 10px; padding-left: 10px"> <img src="images/015.gif" width="112" height="128" /></td> <td valign="top" style="padding-right: 10px; padding-left: 10px"> <img src="images/016.gif" width="112" height="144" /></td> <td valign="top" style="padding-left: 10px"> <img src="images/017.gif" width="112" height="160" /></td> </tr> </table> </p> <h3> Sorting</h3> <p> Controls the order in which the files will be listed. If can be alphabetically by file name, by date of creation of the file with newer files first, or even by file size.</p> </body> </html>
0f523140-f3b3-4653-89b0-eb08c39940ad
trunk/src/html/ckfinder/help/en/files/008.html
HTML
gpl3
2,779
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>CKFinder User's Guide</title> <link href="other/help.css" type="text/css" rel="stylesheet" /> <script type="text/javascript" src="other/help.js"></script> <script type="text/javascript"> function CheckForm() { if ( document.getElementById( 'xSuggestion' ).value == '' ) { alert( 'Please type your suggestion text before sending' ) ; return false ; } document.getElementById( 'xSubmit' ).disabled = true ; document.getElementById( 'spamcheck' ).value = 9945 + 13671 ; return true ; } </script> </head> <body> <h1> Your Suggestions </h1> <p> Feel free to <a href="http://cksource.com/contact">send us your suggestions</a> about this documentation. We are always willing to improve it, offering you a better software every day.</p> </body> </html>
0f523140-f3b3-4653-89b0-eb08c39940ad
trunk/src/html/ckfinder/help/en/files/suggestions.html
HTML
gpl3
927
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>CKFinder User's Guide</title> <link href="other/help.css" type="text/css" rel="stylesheet" /> <script type="text/javascript" src="other/help.js"></script> </head> <body> <h1> Context Menu </h1> <p> The "Context Menu" is a series of buttons (called "menu") that can be used to execute specific tasks in the object that has been clicked. The available options dynamically change, depending on which kind of object is clicked.</p> <h2> Available Menus</h2> <p> The following are the menus that you may find while working on a standard CKFinder installation.</p> <h3> Folder Context Menu</h3> <p> It appears when clicking in a folder in the <a href="003.html">Folders Pane</a> with the mouse right button:</p> <p style="text-align: center"> <img src="images/004.gif" />&nbsp;</p> <h3> File Context Menu</h3> <p> It appears when clicking in a file in the <a href="004.html">Files Pane</a> with the mouse right button:</p> <p style="text-align: center"> <img src="images/008.gif" />&nbsp;</p> <h3> Empty Space Context Menu</h3> <p> It appears when clicking in the <a href="004.html">Files Pane</a>, but outside a file (in the background) with the mouse right button:</p> <p style="text-align: center"> <img src="images/020.gif" /></p> </body> </html>
0f523140-f3b3-4653-89b0-eb08c39940ad
trunk/src/html/ckfinder/help/en/files/012.html
HTML
gpl3
1,464
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>CKFinder User's Guide</title> <link href="other/help.css" type="text/css" rel="stylesheet" /> <script type="text/javascript" src="other/help.js"></script> </head> <body> <h1> Legal Notices </h1> <p> CKFinder, including this documentation, is Copyright &copy; 2007-2011 <a href="http://cksource.com" target="_blank">CKSource</a> - Frederico Knabben. All rights reserved. Please ensure that you have read and understood the <a href="license.html">CKFinder License</a>. </p> <p> The icons used in the toolbar and context menus have been designed by Mark James. Please check the following URL for more information:<br /> <a href="http://www.famfamfam.com/lab/icons/silk/">http://www.famfamfam.com/lab/icons/silk/</a></p> <h2> Trademarks </h2> <p> CKFinder, the CKFinder Logo, CKSource, CKEditor and FCKeditor are trademarks of <a href="http://cksource.com" target="_blank">CKSource</a> - Frederico Knabben.</p> </body> </html>
0f523140-f3b3-4653-89b0-eb08c39940ad
trunk/src/html/ckfinder/help/en/files/011.html
HTML
gpl3
1,101
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>CKFinder User's Guide</title> <link href="other/help.css" type="text/css" rel="stylesheet" /> <script type="text/javascript" src="other/help.js"></script> </head> <body> <h1> Folders Pane </h1> <p> The Folders Pane contains the "tree view" of the folders where you can navigate. Folders are ways to organize files better.</p> <p> It is called a "tree view" because you have the folders hierarchy represented like tree branches. It uses the same graphic representation found in many modern operating systems.</p> <h2> Basic Operations </h2> <h3> Opening a Folder </h3> <p> To open a folder, revealing its "children" folders, simply click in the plus sign (<img src="images/002.gif" height="9" width="9" />) in front of it. If the plus sign is not present, the folder doesn't have children folders to be displayed. </p> <p> See "Under Request Loading" below in this page to better understand how folders are load. </p> <h3> Closing a Folder </h3> <p> To close a folder, hiding its children folders, simply click in the minus sign (<img src="images/003.gif" height="9" width="9" />) in front of it. </p> <h3> Selecting a Folder </h3> <p> To select a folder, making it the "current folder" in CKFinder, simply click in the folder name, or in its icon. The selected folder will have a different background color. </p> <h2> Advanced Operations </h2> <p> Advanced operations may be achieved on a folder by using its "<a href="012.html">Context Menu</a>". The following options are available: </p> <p style="text-align: center"> <img src="images/004.gif" width="104" height="75" />&nbsp;</p> <p> <span class="info">Note:</span> Some context menu buttons may be disabled, depending on CKFinder settings enforced by your system administrator. </p> <div> <h3> Creating Folders </h3> </div> <p> To create a child folder inside an existing folder, just click the "New Subfolder" option in the context menu. A dialog box will appear, asking for the new folder name. Just type it and confirm. </p> <p> Not all characters can be used in folder and files names due to limitations in the systems where CKFinder runs. For instance, the following characters cannot be used on folders and files names: <strong>\</strong> <strong>/</strong> <strong>:</strong> <strong>*</strong> <strong>?</strong> <strong>&quot;</strong> <strong>&lt;</strong> <strong>&gt;</strong> <strong>|</strong></p> <div> <h3> Renaming Folders </h3> </div> <p> To rename a folder, just click the "Rename" option in the context menu. A dialog box, containing the current folder name, will appear, asking for the new folder name. Just type it and confirm. </p> <p> Not all characters can be used in folder and files names due to limitations in the systems where CKFinder runs. For instance, the following characters cannot be used on folders and files names: <strong>\</strong> <strong>/</strong> <strong>:</strong> <strong>*</strong> <strong>?</strong> <strong>&quot;</strong> <strong>&lt;</strong> <strong>&gt;</strong> <strong>|</strong></p> <p> <span class="warning">Attention:</span> by renaming a folder, links or media insertions available in other pages, which point to files or folders inside the renamed folder, will be "broken", therefore not available anymore. So, be careful when using this feature.</p> <div> <h3> Deleting Folders </h3> </div> <p> To delete a folder, including its contents, just click the "Delete" option in the context menu. A confirmation message will appear to ensure that this operation is desired. </p> <p> <span class="warning">Attention:</span> by deleting a folder, links or media insertions available in other pages, which point to files or folders inside the deleted folder, will be "broken", therefore not available anymore. So, be careful when using this feature.</p> <div> <h2> "Under Request" Loading </h2> </div> <p> The most important difference between CKFinder and the folders tree found in operating systems, is that, in CKFinder, the folders are loaded "under request". It means that it doesn't load the entire folders tree at startup, but loads a small subset of them when "opening" the folder. This is a requirement on advanced web applications like CKFinder.</p> <p> To indicate that folders are being loaded, the "Loading..." label may appear when opening a folder: </p> <p style="text-align: center"> <img src="images/005.gif" width="150" height="78" />&nbsp;</p> <p> The label will automatically disappear once the folders load is completed. Once loaded, the label should not appear anymore for that folder. </p> </body> </html>
0f523140-f3b3-4653-89b0-eb08c39940ad
trunk/src/html/ckfinder/help/en/files/003.html
HTML
gpl3
5,003
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>CKFinder User's Guide</title> <style type="text/css"> body { margin: 0px; font-family: Trebuchet, Trebuchet MS, Arial; } a { text-decoration: none ; } a:hover { text-decoration: underline ; } ul { list-style-type: none; padding-left: 20px; margin:0px; } li { white-space: nowrap; padding-left:2px; padding-right:2px; } .toc { background-color: #696969; color: #f5f5f5; margin: 0px; font-weight: bold; text-align: center; } .contents { padding: 10px; } .active { color: highlighttext; background-color: highlight; } </style> <script type="text/javascript"> window.onload = function() { for ( var i = 0 ; i < document.links.length ; i++ ) { var link = document.links[i] ; link.target = 'CKDocsMain' ; link.innerHTML = '&nbsp;' + link.innerHTML + '&nbsp;' ; } } var lastLink = null ; window.top.SetActiveTopic = function( topicUrl ) { var pageName = topicUrl.match( /(?:^|\/|\\)([^\\\/]+)$/ )[1] ; if ( lastLink ) lastLink.className = '' ; for ( var i = 0 ; i < document.links.length ; i++ ) { var link = document.links[i] ; if ( link.href.match( /(?:^|\/|\\)([^\\\/]+)$/ )[1] == pageName ) { lastLink = link ; link.className = 'active' ; return ; } } } </script> </head> <body> <p class="toc"> &nbsp;Table of Contents </p> <div class="contents"> <ul style="padding-left: 0px;"> <li><a href="001.html">Welcome</a></li> <li><a href="002.html">CKFinder Interface</a> <ul> <li><a href="003.html">Folders Pane</a></li> <li><a href="004.html">Files Pane</a></li> <li><a href="005.html">Toolbar</a> <ul> <li><a href="006.html">Upload</a></li> <li><a href="007.html">Refresh</a></li> <li><a href="008.html">Settings</a></li> <li><a href="009.html">Help</a></li> </ul> </li> <li><a href="010.html">Status Bar</a></li> <li><a href="012.html">Context Menu</a></li> </ul> </li> <li><a href="013.html">Compatibility and System Requirements</a></li> <li><a href="011.html">Legal Notices</a></li> <li><a href="suggestions.html">Suggestions?</a></li> </ul> </div> </body> </html>
0f523140-f3b3-4653-89b0-eb08c39940ad
trunk/src/html/ckfinder/help/en/files/toc.html
HTML
gpl3
2,369
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>CKFinder User's Guide</title> <style type="text/css"> body { margin: 0px; font-family: Trebuchet, Trebuchet MS, Verdana; background-color: #696969; color: #f5f5f5; padding-left: 20px; padding-right: 20px; overflow: hidden; } a { color: #f5f5f5; text-decoration: none ; } a:hover { text-decoration: underline ; } </style> </head> <body> <table width="100%" height="100%" border="0" cellpadding="0" cellspacing="0"> <tr> <td valign="middle"> <h2 style="margin: 0px; padding: 0px;"> CKFinder User's Guide</h2> </td> <td align="right" valign="middle"> <a href="http://ckfinder.com" target="_blank">Visit the CKFinder Web Site</a></td> </tr> </table> </body> </html>
0f523140-f3b3-4653-89b0-eb08c39940ad
trunk/src/html/ckfinder/help/en/files/header.html
HTML
gpl3
877
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>CKFinder User's Guide</title> <link href="other/help.css" type="text/css" rel="stylesheet" /> <script type="text/javascript" src="other/help.js"></script> </head> <body> <h1> Toolbar </h1> <p> The Toolbar is a dedicated area at the top of the CKFinder interface. It contains a series of buttons that can be clicked to quickly execute specific functions.&nbsp; Here is a screenshot of it: </p> <p style="text-align: center"> <img src="images/009.gif" height="25" width="258" /> </p> <h2> Toolbar Buttons</h2> <p> The following is the list of buttons available in the standard toolbar:</p> <ul> <li><a href="006.html">Upload</a>: Opens the "Upload Pane", which can be used to add new files to the current folder.</li> <li><a href="007.html">Refresh</a>: Reloads the list of files in the <a href="004.html"> Files Pane</a>.</li> <li><a href="008.html">Settings</a>: Opens the "Settings Pane", were you can configure and personalize CKFinder.</li> <li><a href="009.html">Help</a>: Opens this User's Guide.</li> </ul> </body> </html>
0f523140-f3b3-4653-89b0-eb08c39940ad
trunk/src/html/ckfinder/help/en/files/005.html
HTML
gpl3
1,228
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>CKFinder User's Guide</title> <link href="other/help.css" type="text/css" rel="stylesheet" /> <script type="text/javascript" src="other/help.js"></script> </head> <body> <h1> Status Bar </h1> <p> The "Status Bar" is a small space used to display information regarding the select file, the total number of files in the folder, etc. It can be found at the very button of the CKFinder interface. </p> <p> If <strong>a file is selected</strong> in CKFinder, the Status Bar will display detailed information about that file, containing the file name, its size and the data of its last modification. For example:</p> <p style="text-align: center"> <img src="images/018.gif" height="17" width="221" />&nbsp;</p> <p> If <strong>no files are selected</strong> instead, the total number of files in the current folder is displayed. For example:</p> <p style="text-align: center"> <img src="images/019.gif" height="17" width="221" />&nbsp;</p> </body> </html>
0f523140-f3b3-4653-89b0-eb08c39940ad
trunk/src/html/ckfinder/help/en/files/010.html
HTML
gpl3
1,132
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>CKFinder User's Guide</title> <link href="other/help.css" type="text/css" rel="stylesheet" /> <script type="text/javascript" src="other/help.js"></script> </head> <body> <h1> Upload Button </h1> <p> The upload* button, in the <a href="005.html">toolbar</a>, opens the "Upload Pane", which can be used to add new files to the current folder. Here is a screenshot of it:</p> <p style="text-align: center"> <img height="153" src="images/012.gif" width="404" />&nbsp;</p> <p> To close the Upload Pane, just click in the "Cancel" button, or click "Upload" again in the toolbar.</p> <p> * "<strong>Upload</strong>" is a technical term. It means the action of transferring a file from your local computer to a central computer (also known as server).</p> <h2> Upload Steps</h2> <ol> <li>Select the file from your computer by using the "Browse..." button. The text in the button may vary from browsers, but it will always be right after the "Select the file to upload" field.</li> <li>Click the "Upload Selected File" button. A message will appear, indicating that the upload is in progress.</li> <li>Wait for the upload to terminate. Once completed, the Upload Pane will close automatically, and the uploaded file will be selected in the <a href="004.html">Files Pane</a>.</li> </ol> <h2> Upload Messages</h2> <p> The following are messages that may appear when uploading files:</p> <h3> A file with the same name is already available. The uploaded file has been renamed to "filename(1).ext"</h3> <p> Indicates that the uploaded file name is already in use by another file in the same folder. To avoid conflict, a progressive number, the "(1)", has been appended to the original name.</p> <h3> Invalid file</h3> <p> The uploaded file has not been accepted. </p> <p> The most common cause for this messages is that CKFinder has been configured to not accept the kind of file you are trying to upload, based on its extension. This is a security restriction. Another cause of it may be that the file size is too big for your system. In this case the server must be configured to accept bigger files. </p> <h3>Upload cancelled for security reasons. The file contains HTML like data.</h3> <p>The uploaded file contains HTML code. For security reasons, only files with selected extensions are allowed to contain HTML code.</p> <p> Please contact your system administrator to have more information regarding the accepted file types and their size limits.</p> </body> </html>
0f523140-f3b3-4653-89b0-eb08c39940ad
trunk/src/html/ckfinder/help/en/files/006.html
HTML
gpl3
2,742
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Frameset//EN" "http://www.w3.org/TR/html4/frameset.dtd"> <html lang="es"> <head> <title>Gu&iacute;a para el usuario de CKFinder</title> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <style type="text/css"> frame {border-color:#f5f5f5} </style> </head> <frameset rows="50,*"> <frame src="files/header.html" noresize frameborder="0"> <frameset cols="200,*"> <frame src="files/toc.html"> <frame src="files/001.html" name="CKDocsMain"> </frameset> </frameset> </html>
0f523140-f3b3-4653-89b0-eb08c39940ad
trunk/src/html/ckfinder/help/es/index.html
HTML
gpl3
569
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html lang="es"> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Guía del usuario de CKFinder</title> <link href="other/help.css" type="text/css" rel="stylesheet"> <script type="text/javascript" src="other/help.js"></script> </head> <body> <h1> Compatibilidad y Requerimientos del Sistema</h1> <p> CKFinder es una aplicaci&oacute;n &quot;Web&quot;, esto significa que est&aacute; hecha para ser ejecutada dentro de un navegador siendo m&aacute;s f&aacute;cil distribuir y usar en cualquier ordenador.</p> <p> Actualmente cualquiera de los siguientes navegadores se requieren para ejecutar CKFinder:</p> <ul> <li>Internet Explorer 6.0+</li> <li>Firefox 2.0+</li> <li>Safari 3+</li> <li>Google Chrome</li> <li>Opera 9.5+</li> <li>Camino 1.0+</li> </ul> <p>Algunas caracter&iacute;sticas dependen para su funcionamiento de ajustes propios del navegador de internet. Por defecto CKFinder deber&iacute;a funcionar correctamente, sin embargo si experimienta alg&uacute;n problema con el <a href="012.html">Men&uacute; contextual</a> o quiz&aacute; sus <a href="008.html">Ajustes</a> no est&aacute;n siendo guardados, asegurese que su navegador est&aacute; configurado para &quot;Permitir a los scripts reemplazar men&uacute;s contextuales&quot; (&quot;Permitir a los scripts recibir clicks con el bot&oacute;n derecho&quot;) y adem&aacute;s tener habilitado el &quot;Soporte para cookies&quot;. </p> <p>Por favor contacte a su administrador en caso de que tenga alguna duda.</p> </body> </html>
0f523140-f3b3-4653-89b0-eb08c39940ad
trunk/src/html/ckfinder/help/es/files/013.html
HTML
gpl3
1,685