Initial project's source code check-in.
This commit is contained in:
commit
b03b0b373f
4573 changed files with 981205 additions and 0 deletions
685
WebsitePanel/Sources/WebsitePanel.Server.Utils/BsdDES.cs
Normal file
685
WebsitePanel/Sources/WebsitePanel.Server.Utils/BsdDES.cs
Normal file
|
@ -0,0 +1,685 @@
|
|||
// Copyright (c) 2011, Outercurve Foundation.
|
||||
// All rights reserved.
|
||||
//
|
||||
// Redistribution and use in source and binary forms, with or without modification,
|
||||
// are permitted provided that the following conditions are met:
|
||||
//
|
||||
// - Redistributions of source code must retain the above copyright notice, this
|
||||
// list of conditions and the following disclaimer.
|
||||
//
|
||||
// - 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.
|
||||
//
|
||||
// - Neither the name of the Outercurve Foundation nor the names of its
|
||||
// contributors may be used to endorse or promote products derived from this
|
||||
// software without specific prior written permission.
|
||||
//
|
||||
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
|
||||
// ANY EXPRESS 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 COPYRIGHT HOLDER OR CONTRIBUTORS 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.
|
||||
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Text;
|
||||
|
||||
namespace WebsitePanel.Server.Utils
|
||||
{
|
||||
/*
|
||||
* FreeSec: libcrypt for NetBSD
|
||||
*
|
||||
* Copyright (c) 1994 David Burren
|
||||
* All rights reserved.
|
||||
*
|
||||
* Adapted for FreeBSD-2.0 by Geoffrey M. Rehmet
|
||||
* this file should now *only* export crypt(), in order to make
|
||||
* binaries of libcrypt exportable from the USA
|
||||
*
|
||||
* Adapted for FreeBSD-4.0 by Mark R V Murray
|
||||
* this file should now *only* export crypt_des(), in order to make
|
||||
* a module that can be optionally included in libcrypt.
|
||||
*
|
||||
* 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. Neither the name of the author nor the names of other contributors
|
||||
* may be used to endorse or promote products derived from this software
|
||||
* without specific prior written permission.
|
||||
*
|
||||
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
|
||||
* ANY EXPRESS 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 AUTHOR OR CONTRIBUTORS 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.
|
||||
*/
|
||||
|
||||
public class BsdDES
|
||||
{
|
||||
byte[] IP = new byte[64] {
|
||||
58, 50, 42, 34, 26, 18, 10, 2, 60, 52, 44, 36, 28, 20, 12, 4,
|
||||
62, 54, 46, 38, 30, 22, 14, 6, 64, 56, 48, 40, 32, 24, 16, 8,
|
||||
57, 49, 41, 33, 25, 17, 9, 1, 59, 51, 43, 35, 27, 19, 11, 3,
|
||||
61, 53, 45, 37, 29, 21, 13, 5, 63, 55, 47, 39, 31, 23, 15, 7
|
||||
};
|
||||
|
||||
byte[] inv_key_perm = new byte[64];
|
||||
byte[] key_perm = new byte[56] {
|
||||
57, 49, 41, 33, 25, 17, 9, 1, 58, 50, 42, 34, 26, 18,
|
||||
10, 2, 59, 51, 43, 35, 27, 19, 11, 3, 60, 52, 44, 36,
|
||||
63, 55, 47, 39, 31, 23, 15, 7, 62, 54, 46, 38, 30, 22,
|
||||
14, 6, 61, 53, 45, 37, 29, 21, 13, 5, 28, 20, 12, 4
|
||||
};
|
||||
|
||||
byte[] key_shifts = new byte[16] {
|
||||
1, 1, 2, 2, 2, 2, 2, 2, 1, 2, 2, 2, 2, 2, 2, 1
|
||||
};
|
||||
|
||||
byte[] inv_comp_perm = new byte[56];
|
||||
byte[] comp_perm = new byte[48] {
|
||||
14, 17, 11, 24, 1, 5, 3, 28, 15, 6, 21, 10,
|
||||
23, 19, 12, 4, 26, 8, 16, 7, 27, 20, 13, 2,
|
||||
41, 52, 31, 37, 47, 55, 30, 40, 51, 45, 33, 48,
|
||||
44, 49, 39, 56, 34, 53, 46, 42, 50, 36, 29, 32
|
||||
};
|
||||
|
||||
/*
|
||||
* No E box is used, as it's replaced by some ANDs, shifts, and ORs.
|
||||
*/
|
||||
|
||||
byte[,] u_sbox = new byte[8, 64];
|
||||
byte[,] sbox = new byte[8, 64] {
|
||||
{
|
||||
14, 4, 13, 1, 2, 15, 11, 8, 3, 10, 6, 12, 5, 9, 0, 7,
|
||||
0, 15, 7, 4, 14, 2, 13, 1, 10, 6, 12, 11, 9, 5, 3, 8,
|
||||
4, 1, 14, 8, 13, 6, 2, 11, 15, 12, 9, 7, 3, 10, 5, 0,
|
||||
15, 12, 8, 2, 4, 9, 1, 7, 5, 11, 3, 14, 10, 0, 6, 13
|
||||
},
|
||||
{
|
||||
15, 1, 8, 14, 6, 11, 3, 4, 9, 7, 2, 13, 12, 0, 5, 10,
|
||||
3, 13, 4, 7, 15, 2, 8, 14, 12, 0, 1, 10, 6, 9, 11, 5,
|
||||
0, 14, 7, 11, 10, 4, 13, 1, 5, 8, 12, 6, 9, 3, 2, 15,
|
||||
13, 8, 10, 1, 3, 15, 4, 2, 11, 6, 7, 12, 0, 5, 14, 9
|
||||
},
|
||||
{
|
||||
10, 0, 9, 14, 6, 3, 15, 5, 1, 13, 12, 7, 11, 4, 2, 8,
|
||||
13, 7, 0, 9, 3, 4, 6, 10, 2, 8, 5, 14, 12, 11, 15, 1,
|
||||
13, 6, 4, 9, 8, 15, 3, 0, 11, 1, 2, 12, 5, 10, 14, 7,
|
||||
1, 10, 13, 0, 6, 9, 8, 7, 4, 15, 14, 3, 11, 5, 2, 12
|
||||
},
|
||||
{
|
||||
7, 13, 14, 3, 0, 6, 9, 10, 1, 2, 8, 5, 11, 12, 4, 15,
|
||||
13, 8, 11, 5, 6, 15, 0, 3, 4, 7, 2, 12, 1, 10, 14, 9,
|
||||
10, 6, 9, 0, 12, 11, 7, 13, 15, 1, 3, 14, 5, 2, 8, 4,
|
||||
3, 15, 0, 6, 10, 1, 13, 8, 9, 4, 5, 11, 12, 7, 2, 14
|
||||
},
|
||||
{
|
||||
2, 12, 4, 1, 7, 10, 11, 6, 8, 5, 3, 15, 13, 0, 14, 9,
|
||||
14, 11, 2, 12, 4, 7, 13, 1, 5, 0, 15, 10, 3, 9, 8, 6,
|
||||
4, 2, 1, 11, 10, 13, 7, 8, 15, 9, 12, 5, 6, 3, 0, 14,
|
||||
11, 8, 12, 7, 1, 14, 2, 13, 6, 15, 0, 9, 10, 4, 5, 3
|
||||
},
|
||||
{
|
||||
12, 1, 10, 15, 9, 2, 6, 8, 0, 13, 3, 4, 14, 7, 5, 11,
|
||||
10, 15, 4, 2, 7, 12, 9, 5, 6, 1, 13, 14, 0, 11, 3, 8,
|
||||
9, 14, 15, 5, 2, 8, 12, 3, 7, 0, 4, 10, 1, 13, 11, 6,
|
||||
4, 3, 2, 12, 9, 5, 15, 10, 11, 14, 1, 7, 6, 0, 8, 13
|
||||
},
|
||||
{
|
||||
4, 11, 2, 14, 15, 0, 8, 13, 3, 12, 9, 7, 5, 10, 6, 1,
|
||||
13, 0, 11, 7, 4, 9, 1, 10, 14, 3, 5, 12, 2, 15, 8, 6,
|
||||
1, 4, 11, 13, 12, 3, 7, 14, 10, 15, 6, 8, 0, 5, 9, 2,
|
||||
6, 11, 13, 8, 1, 4, 10, 7, 9, 5, 0, 15, 14, 2, 3, 12
|
||||
},
|
||||
{
|
||||
13, 2, 8, 4, 6, 15, 11, 1, 10, 9, 3, 14, 5, 0, 12, 7,
|
||||
1, 15, 13, 8, 10, 3, 7, 4, 12, 5, 6, 11, 0, 14, 9, 2,
|
||||
7, 11, 4, 1, 9, 12, 14, 2, 0, 6, 10, 13, 15, 3, 5, 8,
|
||||
2, 1, 14, 7, 4, 10, 8, 13, 15, 12, 9, 0, 3, 5, 6, 11
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
byte[] un_pbox = new byte[32];
|
||||
byte[] pbox = new byte[32] {
|
||||
16, 7, 20, 21, 29, 12, 28, 17, 1, 15, 23, 26, 5, 18, 31, 10,
|
||||
2, 8, 24, 14, 32, 27, 3, 9, 19, 13, 30, 6, 22, 11, 4, 25
|
||||
};
|
||||
|
||||
uint[] bits32 = new uint[32]
|
||||
{
|
||||
0x80000000, 0x40000000, 0x20000000, 0x10000000,
|
||||
0x08000000, 0x04000000, 0x02000000, 0x01000000,
|
||||
0x00800000, 0x00400000, 0x00200000, 0x00100000,
|
||||
0x00080000, 0x00040000, 0x00020000, 0x00010000,
|
||||
0x00008000, 0x00004000, 0x00002000, 0x00001000,
|
||||
0x00000800, 0x00000400, 0x00000200, 0x00000100,
|
||||
0x00000080, 0x00000040, 0x00000020, 0x00000010,
|
||||
0x00000008, 0x00000004, 0x00000002, 0x00000001
|
||||
};
|
||||
|
||||
byte[] bits8 = new byte[8] { 0x80, 0x40, 0x20, 0x10, 0x08, 0x04, 0x02, 0x01 };
|
||||
|
||||
byte[] ascii64 = System.Text.ASCIIEncoding.ASCII.GetBytes(
|
||||
"./0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz");
|
||||
/* 0000000000111111111122222222223333333333444444444455555555556666 */
|
||||
/* 0123456789012345678901234567890123456789012345678901234567890123 */
|
||||
|
||||
bool des_initialised = false;
|
||||
uint saltbits;
|
||||
uint old_salt;
|
||||
byte[] init_perm = new byte[64], final_perm = new byte[64];
|
||||
uint[] en_keysl = new uint[16], en_keysr = new uint[16];
|
||||
uint[] de_keysl = new uint[16], de_keysr = new uint[16];
|
||||
byte[,] m_sbox = new byte[4, 4096];
|
||||
uint[,] psbox = new uint[4, 256];
|
||||
uint[,] ip_maskl = new uint[8, 256], ip_maskr = new uint[8, 256];
|
||||
uint[,] fp_maskl = new uint[8, 256], fp_maskr = new uint[8, 256];
|
||||
uint[,] key_perm_maskl = new uint[8, 128], key_perm_maskr = new uint[8, 128];
|
||||
uint[,] comp_maskl = new uint[8, 128], comp_maskr = new uint[8, 128];
|
||||
uint old_rawkey0, old_rawkey1;
|
||||
|
||||
|
||||
|
||||
uint AsciiToBin(char ch)
|
||||
{
|
||||
if (ch > 'z')
|
||||
return 0;
|
||||
if (ch >= 'a')
|
||||
return (uint)(ch - 'a' + 38);
|
||||
if (ch > 'Z')
|
||||
return 0;
|
||||
if (ch >= 'A')
|
||||
return (uint)(ch - 'A' + 12);
|
||||
if (ch > '9')
|
||||
return (0);
|
||||
if (ch >= '.')
|
||||
return (uint)(ch - '.');
|
||||
return 0;
|
||||
}
|
||||
|
||||
void Init()
|
||||
{
|
||||
int inbit, obit;
|
||||
old_rawkey0 = old_rawkey1 = 0;
|
||||
saltbits = 0;
|
||||
old_salt = 0;
|
||||
const int bits28 = 4;
|
||||
const int bits24 = 8;
|
||||
|
||||
/*
|
||||
* Invert the S-boxes, reordering the input bits.
|
||||
*/
|
||||
for (int i = 0; i < 8; i++)
|
||||
for (int j = 0; j < 64; j++)
|
||||
{
|
||||
int b = (j & 0x20) | ((j & 1) << 4) | ((j >> 1) & 0xf);
|
||||
u_sbox[i, j] = sbox[i, b];
|
||||
}
|
||||
|
||||
/*
|
||||
* Convert the inverted S-boxes into 4 arrays of 8 bits.
|
||||
* Each will handle 12 bits of the S-box input.
|
||||
*/
|
||||
for (int b = 0; b < 4; b++)
|
||||
for (int i = 0; i < 64; i++)
|
||||
for (int j = 0; j < 64; j++)
|
||||
m_sbox[b, (i << 6) | j] =
|
||||
(byte)((u_sbox[(b << 1), i] << 4) |
|
||||
u_sbox[(b << 1) + 1, j]);
|
||||
|
||||
/*
|
||||
* Set up the initial & final permutations into a useful form, and
|
||||
* initialise the inverted key permutation.
|
||||
*/
|
||||
for (int i = 0; i < 64; i++)
|
||||
{
|
||||
init_perm[final_perm[i] = (byte)(IP[i] - 1)] = (byte)i;
|
||||
inv_key_perm[i] = 255;
|
||||
}
|
||||
|
||||
/*
|
||||
* Invert the key permutation and initialise the inverted key
|
||||
* compression permutation.
|
||||
*/
|
||||
for (int i = 0; i < 56; i++)
|
||||
{
|
||||
inv_key_perm[key_perm[i] - 1] = (byte)i;
|
||||
inv_comp_perm[i] = 255;
|
||||
}
|
||||
|
||||
/*
|
||||
* Invert the key compression permutation.
|
||||
*/
|
||||
for (int i = 0; i < 48; i++)
|
||||
{
|
||||
inv_comp_perm[comp_perm[i] - 1] = (byte)i;
|
||||
}
|
||||
|
||||
/*
|
||||
* Set up the OR-mask arrays for the initial and final permutations,
|
||||
* and for the key initial and compression permutations.
|
||||
*/
|
||||
for (int k = 0; k < 8; k++)
|
||||
{
|
||||
for (int i = 0; i < 256; i++)
|
||||
{
|
||||
ip_maskl[k, i] = 0;
|
||||
ip_maskr[k, i] = 0;
|
||||
fp_maskl[k, i] = 0;
|
||||
fp_maskr[k, i] = 0;
|
||||
for (int j = 0; j < 8; j++)
|
||||
{
|
||||
inbit = 8 * k + j;
|
||||
if ((i & bits8[j]) > 0)
|
||||
{
|
||||
if ((obit = init_perm[inbit]) < 32)
|
||||
ip_maskl[k, i] |= bits32[obit];
|
||||
else
|
||||
ip_maskr[k, i] |= bits32[obit - 32];
|
||||
if ((obit = final_perm[inbit]) < 32)
|
||||
fp_maskl[k, i] |= bits32[obit];
|
||||
else
|
||||
fp_maskr[k, i] |= bits32[obit - 32];
|
||||
}
|
||||
}
|
||||
}
|
||||
for (int i = 0; i < 128; i++)
|
||||
{
|
||||
key_perm_maskl[k, i] = 0;
|
||||
key_perm_maskr[k, i] = 0;
|
||||
for (int j = 0; j < 7; j++)
|
||||
{
|
||||
inbit = 8 * k + j;
|
||||
if ((i & bits8[j + 1]) > 0)
|
||||
{
|
||||
if ((obit = inv_key_perm[inbit]) == 255)
|
||||
continue;
|
||||
if (obit < 28)
|
||||
key_perm_maskl[k, i] |= bits32[obit + bits28];
|
||||
else
|
||||
key_perm_maskr[k, i] |= bits32[obit - 28 + bits28];
|
||||
}
|
||||
}
|
||||
comp_maskl[k, i] = 0;
|
||||
comp_maskr[k, i] = 0;
|
||||
for (int j = 0; j < 7; j++)
|
||||
{
|
||||
inbit = 7 * k + j;
|
||||
if ((i & bits8[j + 1]) > 0)
|
||||
{
|
||||
if ((obit = inv_comp_perm[inbit]) == 255)
|
||||
continue;
|
||||
if (obit < 24)
|
||||
comp_maskl[k, i] |= bits32[obit + bits24];
|
||||
else
|
||||
comp_maskr[k, i] |= bits32[obit - 24 + bits24];
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/*
|
||||
* Invert the P-box permutation, and convert into OR-masks for
|
||||
* handling the output of the S-box arrays setup above.
|
||||
*/
|
||||
for (int i = 0; i < 32; i++)
|
||||
un_pbox[pbox[i] - 1] = (byte)i;
|
||||
|
||||
for (int b = 0; b < 4; b++)
|
||||
for (int i = 0; i < 256; i++)
|
||||
{
|
||||
psbox[b, i] = 0;
|
||||
for (int j = 0; j < 8; j++)
|
||||
{
|
||||
if ((i & bits8[j]) > 0)
|
||||
psbox[b, i] |= bits32[un_pbox[8 * b + j]];
|
||||
}
|
||||
}
|
||||
|
||||
des_initialised = true;
|
||||
}
|
||||
|
||||
void SetupSalt(uint salt)
|
||||
{
|
||||
uint obit, saltbit;
|
||||
int i;
|
||||
|
||||
if (salt == old_salt)
|
||||
return;
|
||||
old_salt = salt;
|
||||
|
||||
saltbits = 0;
|
||||
saltbit = 1;
|
||||
obit = 0x800000;
|
||||
for (i = 0; i < 24; i++)
|
||||
{
|
||||
if ((salt & saltbit) > 0)
|
||||
saltbits |= obit;
|
||||
saltbit <<= 1;
|
||||
obit >>= 1;
|
||||
}
|
||||
}
|
||||
|
||||
int SetKey(byte[] key)
|
||||
{
|
||||
if (!des_initialised)
|
||||
Init();
|
||||
|
||||
uint rawkey0 = ntohl(BitConverter.ToUInt32(key, 0));
|
||||
uint rawkey1 = ntohl(BitConverter.ToUInt32(key, 4));
|
||||
|
||||
if ((rawkey0 | rawkey1) > 0
|
||||
&& rawkey0 == old_rawkey0
|
||||
&& rawkey1 == old_rawkey1)
|
||||
{
|
||||
/*
|
||||
* Already setup for this key.
|
||||
* This optimisation fails on a zero key (which is weak and
|
||||
* has bad parity anyway) in order to simplify the starting
|
||||
* conditions.
|
||||
*/
|
||||
return 0;
|
||||
}
|
||||
old_rawkey0 = rawkey0;
|
||||
old_rawkey1 = rawkey1;
|
||||
|
||||
/*
|
||||
* Do key permutation and split into two 28-bit subkeys.
|
||||
*/
|
||||
uint k0 = key_perm_maskl[0, rawkey0 >> 25]
|
||||
| key_perm_maskl[1, (rawkey0 >> 17) & 0x7f]
|
||||
| key_perm_maskl[2, (rawkey0 >> 9) & 0x7f]
|
||||
| key_perm_maskl[3, (rawkey0 >> 1) & 0x7f]
|
||||
| key_perm_maskl[4, rawkey1 >> 25]
|
||||
| key_perm_maskl[5, (rawkey1 >> 17) & 0x7f]
|
||||
| key_perm_maskl[6, (rawkey1 >> 9) & 0x7f]
|
||||
| key_perm_maskl[7, (rawkey1 >> 1) & 0x7f];
|
||||
uint k1 = key_perm_maskr[0, rawkey0 >> 25]
|
||||
| key_perm_maskr[1, (rawkey0 >> 17) & 0x7f]
|
||||
| key_perm_maskr[2, (rawkey0 >> 9) & 0x7f]
|
||||
| key_perm_maskr[3, (rawkey0 >> 1) & 0x7f]
|
||||
| key_perm_maskr[4, rawkey1 >> 25]
|
||||
| key_perm_maskr[5, (rawkey1 >> 17) & 0x7f]
|
||||
| key_perm_maskr[6, (rawkey1 >> 9) & 0x7f]
|
||||
| key_perm_maskr[7, (rawkey1 >> 1) & 0x7f];
|
||||
/*
|
||||
* Rotate subkeys and do compression permutation.
|
||||
*/
|
||||
int shifts = 0;
|
||||
for (int round = 0; round < 16; round++)
|
||||
{
|
||||
uint t0, t1;
|
||||
|
||||
shifts += key_shifts[round];
|
||||
|
||||
t0 = (k0 << shifts) | (k0 >> (28 - shifts));
|
||||
t1 = (k1 << shifts) | (k1 >> (28 - shifts));
|
||||
|
||||
de_keysl[15 - round] =
|
||||
en_keysl[round] = comp_maskl[0, (t0 >> 21) & 0x7f]
|
||||
| comp_maskl[1, (t0 >> 14) & 0x7f]
|
||||
| comp_maskl[2, (t0 >> 7) & 0x7f]
|
||||
| comp_maskl[3, t0 & 0x7f]
|
||||
| comp_maskl[4, (t1 >> 21) & 0x7f]
|
||||
| comp_maskl[5, (t1 >> 14) & 0x7f]
|
||||
| comp_maskl[6, (t1 >> 7) & 0x7f]
|
||||
| comp_maskl[7, t1 & 0x7f];
|
||||
|
||||
de_keysr[15 - round] =
|
||||
en_keysr[round] = comp_maskr[0, (t0 >> 21) & 0x7f]
|
||||
| comp_maskr[1, (t0 >> 14) & 0x7f]
|
||||
| comp_maskr[2, (t0 >> 7) & 0x7f]
|
||||
| comp_maskr[3, t0 & 0x7f]
|
||||
| comp_maskr[4, (t1 >> 21) & 0x7f]
|
||||
| comp_maskr[5, (t1 >> 14) & 0x7f]
|
||||
| comp_maskr[6, (t1 >> 7) & 0x7f]
|
||||
| comp_maskr[7, t1 & 0x7f];
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
int DoDes(uint l_in, uint r_in, out uint l_out, out uint r_out, int count)
|
||||
{
|
||||
/*
|
||||
* l_in, r_in, l_out, and r_out are in pseudo-"big-endian" format.
|
||||
*/
|
||||
uint l, r;
|
||||
uint[] kl1, kr1;
|
||||
int kl, kr;
|
||||
uint f, r48l, r48r;
|
||||
int round;
|
||||
|
||||
f = 0;
|
||||
l_out = r_out = 0;
|
||||
|
||||
if (count == 0)
|
||||
{
|
||||
return 1;
|
||||
}
|
||||
else if (count > 0)
|
||||
{
|
||||
/*
|
||||
* Encrypting
|
||||
*/
|
||||
kl1 = en_keysl;
|
||||
kr1 = en_keysr;
|
||||
}
|
||||
else
|
||||
{
|
||||
/*
|
||||
* Decrypting
|
||||
*/
|
||||
count = -count;
|
||||
kl1 = de_keysl;
|
||||
kr1 = de_keysr;
|
||||
}
|
||||
|
||||
/*
|
||||
* Do initial permutation (IP).
|
||||
*/
|
||||
l = ip_maskl[0, l_in >> 24]
|
||||
| ip_maskl[1, (l_in >> 16) & 0xff]
|
||||
| ip_maskl[2, (l_in >> 8) & 0xff]
|
||||
| ip_maskl[3, l_in & 0xff]
|
||||
| ip_maskl[4, r_in >> 24]
|
||||
| ip_maskl[5, (r_in >> 16) & 0xff]
|
||||
| ip_maskl[6, (r_in >> 8) & 0xff]
|
||||
| ip_maskl[7, r_in & 0xff];
|
||||
r = ip_maskr[0, l_in >> 24]
|
||||
| ip_maskr[1, (l_in >> 16) & 0xff]
|
||||
| ip_maskr[2, (l_in >> 8) & 0xff]
|
||||
| ip_maskr[3, l_in & 0xff]
|
||||
| ip_maskr[4, r_in >> 24]
|
||||
| ip_maskr[5, (r_in >> 16) & 0xff]
|
||||
| ip_maskr[6, (r_in >> 8) & 0xff]
|
||||
| ip_maskr[7, r_in & 0xff];
|
||||
|
||||
while (count-- > 0)
|
||||
{
|
||||
/*
|
||||
* Do each round.
|
||||
*/
|
||||
kl = 0;
|
||||
kr = 0;
|
||||
round = 16;
|
||||
while (round-- > 0)
|
||||
{
|
||||
/*
|
||||
* Expand R to 48 bits (simulate the E-box).
|
||||
*/
|
||||
r48l = ((r & 0x00000001) << 23)
|
||||
| ((r & 0xf8000000) >> 9)
|
||||
| ((r & 0x1f800000) >> 11)
|
||||
| ((r & 0x01f80000) >> 13)
|
||||
| ((r & 0x001f8000) >> 15);
|
||||
|
||||
r48r = ((r & 0x0001f800) << 7)
|
||||
| ((r & 0x00001f80) << 5)
|
||||
| ((r & 0x000001f8) << 3)
|
||||
| ((r & 0x0000001f) << 1)
|
||||
| ((r & 0x80000000) >> 31);
|
||||
/*
|
||||
* Do salting for crypt() and friends, and
|
||||
* XOR with the permuted key.
|
||||
*/
|
||||
f = (r48l ^ r48r) & saltbits;
|
||||
r48l ^= f ^ kl1[kl++];
|
||||
r48r ^= f ^ kr1[kr++];
|
||||
/*
|
||||
* Do sbox lookups (which shrink it back to 32 bits)
|
||||
* and do the pbox permutation at the same time.
|
||||
*/
|
||||
f = psbox[0, m_sbox[0, r48l >> 12]]
|
||||
| psbox[1, m_sbox[1, r48l & 0xfff]]
|
||||
| psbox[2, m_sbox[2, r48r >> 12]]
|
||||
| psbox[3, m_sbox[3, r48r & 0xfff]];
|
||||
/*
|
||||
* Now that we've permuted things, complete f().
|
||||
*/
|
||||
f ^= l;
|
||||
l = r;
|
||||
r = f;
|
||||
}
|
||||
r = l;
|
||||
l = f;
|
||||
}
|
||||
/*
|
||||
* Do final permutation (inverse of IP).
|
||||
*/
|
||||
l_out = fp_maskl[0, l >> 24]
|
||||
| fp_maskl[1, (l >> 16) & 0xff]
|
||||
| fp_maskl[2, (l >> 8) & 0xff]
|
||||
| fp_maskl[3, l & 0xff]
|
||||
| fp_maskl[4, r >> 24]
|
||||
| fp_maskl[5, (r >> 16) & 0xff]
|
||||
| fp_maskl[6, (r >> 8) & 0xff]
|
||||
| fp_maskl[7, r & 0xff];
|
||||
r_out = fp_maskr[0, l >> 24]
|
||||
| fp_maskr[1, (l >> 16) & 0xff]
|
||||
| fp_maskr[2, (l >> 8) & 0xff]
|
||||
| fp_maskr[3, l & 0xff]
|
||||
| fp_maskr[4, r >> 24]
|
||||
| fp_maskr[5, (r >> 16) & 0xff]
|
||||
| fp_maskr[6, (r >> 8) & 0xff]
|
||||
| fp_maskr[7, r & 0xff];
|
||||
return 0;
|
||||
}
|
||||
|
||||
public string Crypt(string key)
|
||||
{
|
||||
// salt chars
|
||||
string salt_chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789./";
|
||||
|
||||
// generate random salt - 2 symbols
|
||||
StringBuilder salt = new StringBuilder();
|
||||
Random rnd = new Random();
|
||||
for (int i = 0; i < 2; i++)
|
||||
salt.Append(salt_chars[rnd.Next(salt_chars.Length - 1)]);
|
||||
|
||||
// call crypt
|
||||
return Crypt(key, salt.ToString());
|
||||
}
|
||||
|
||||
public string Crypt(string key, string setting)
|
||||
{
|
||||
if (String.IsNullOrEmpty(setting) || setting.Length < 2)
|
||||
throw new ArgumentException("Salt must be at least 2 symbols", "setting");
|
||||
|
||||
uint salt, l, r0, r1;
|
||||
int count;
|
||||
|
||||
//u_char *p, *q;
|
||||
//static char output[21];
|
||||
byte[] output = new byte[13];
|
||||
|
||||
if (!des_initialised)
|
||||
Init();
|
||||
|
||||
/*
|
||||
* Copy the key, shifting each character up by one bit
|
||||
* and padding with zeros.
|
||||
*/
|
||||
byte[] key_bytes = System.Text.ASCIIEncoding.ASCII.GetBytes(key);
|
||||
byte[] setting_bytes = System.Text.ASCIIEncoding.ASCII.GetBytes(setting);
|
||||
byte[] keybuf = new byte[8];
|
||||
|
||||
for (int i = 0; i < keybuf.Length; i++)
|
||||
keybuf[i] = (i < key_bytes.Length) ? (byte)(key_bytes[i] << 1) : (byte)0;
|
||||
|
||||
if (SetKey(keybuf) != 0)
|
||||
return null;
|
||||
|
||||
/*
|
||||
* "old"-style:
|
||||
* setting - 2 bytes of salt
|
||||
* key - up to 8 characters
|
||||
*/
|
||||
count = 25;
|
||||
|
||||
salt = (AsciiToBin(setting[1]) << 6)
|
||||
| AsciiToBin(setting[0]);
|
||||
|
||||
output[0] = setting_bytes[0];
|
||||
/*
|
||||
* If the encrypted password that the salt was extracted from
|
||||
* is only 1 character long, the salt will be corrupted. We
|
||||
* need to ensure that the output string doesn't have an extra
|
||||
* NUL in it!
|
||||
*/
|
||||
output[1] = setting_bytes.Length > 1 ? setting_bytes[1] : output[0];
|
||||
|
||||
int p = 2;
|
||||
|
||||
SetupSalt(salt);
|
||||
/*
|
||||
* Do it.
|
||||
*/
|
||||
if (DoDes(0, 0, out r0, out r1, count) != 0)
|
||||
return null;
|
||||
/*
|
||||
* Now encode the result...
|
||||
*/
|
||||
l = (r0 >> 8);
|
||||
output[p++] = ascii64[(l >> 18) & 0x3f];
|
||||
output[p++] = ascii64[(l >> 12) & 0x3f];
|
||||
output[p++] = ascii64[(l >> 6) & 0x3f];
|
||||
output[p++] = ascii64[l & 0x3f];
|
||||
|
||||
l = (r0 << 16) | ((r1 >> 16) & 0xffff);
|
||||
output[p++] = ascii64[(l >> 18) & 0x3f];
|
||||
output[p++] = ascii64[(l >> 12) & 0x3f];
|
||||
output[p++] = ascii64[(l >> 6) & 0x3f];
|
||||
output[p++] = ascii64[l & 0x3f];
|
||||
|
||||
l = r1 << 2;
|
||||
output[p++] = ascii64[(l >> 12) & 0x3f];
|
||||
output[p++] = ascii64[(l >> 6) & 0x3f];
|
||||
output[p++] = ascii64[l & 0x3f];
|
||||
|
||||
return System.Text.ASCIIEncoding.ASCII.GetString(output);
|
||||
}
|
||||
|
||||
uint ntohl(uint n)
|
||||
{
|
||||
return ((n & 0xFF) << 24) | ((n & 0xFF00) << 8) | ((n & 0xFF0000) >> 8) | ((n & 0xFF000000) >> 24);
|
||||
}
|
||||
}
|
||||
}
|
216
WebsitePanel/Sources/WebsitePanel.Server.Utils/CRC32.cs
Normal file
216
WebsitePanel/Sources/WebsitePanel.Server.Utils/CRC32.cs
Normal file
|
@ -0,0 +1,216 @@
|
|||
// Copyright (c) 2011, Outercurve Foundation.
|
||||
// All rights reserved.
|
||||
//
|
||||
// Redistribution and use in source and binary forms, with or without modification,
|
||||
// are permitted provided that the following conditions are met:
|
||||
//
|
||||
// - Redistributions of source code must retain the above copyright notice, this
|
||||
// list of conditions and the following disclaimer.
|
||||
//
|
||||
// - 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.
|
||||
//
|
||||
// - Neither the name of the Outercurve Foundation nor the names of its
|
||||
// contributors may be used to endorse or promote products derived from this
|
||||
// software without specific prior written permission.
|
||||
//
|
||||
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
|
||||
// ANY EXPRESS 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 COPYRIGHT HOLDER OR CONTRIBUTORS 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.
|
||||
|
||||
using System;
|
||||
using System.Collections;
|
||||
using System.IO;
|
||||
using System.Security.Cryptography;
|
||||
|
||||
namespace WebsitePanel.Providers.Utils
|
||||
{
|
||||
public class CRC32 : HashAlgorithm
|
||||
{
|
||||
protected static uint AllOnes = 0xffffffff;
|
||||
protected static Hashtable cachedCRC32Tables;
|
||||
protected static bool autoCache;
|
||||
|
||||
protected uint[] crc32Table;
|
||||
private uint m_crc;
|
||||
|
||||
/// <summary>
|
||||
/// Returns the default polynomial (used in WinZip, Ethernet, etc)
|
||||
/// </summary>
|
||||
public static uint DefaultPolynomial
|
||||
{
|
||||
get { return 0x04C11DB7; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the auto-cache setting of this class.
|
||||
/// </summary>
|
||||
public static bool AutoCache
|
||||
{
|
||||
get { return autoCache; }
|
||||
set { autoCache = value; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Initialize the cache
|
||||
/// </summary>
|
||||
static CRC32()
|
||||
{
|
||||
cachedCRC32Tables = Hashtable.Synchronized(new Hashtable());
|
||||
autoCache = true;
|
||||
}
|
||||
|
||||
public static void ClearCache()
|
||||
{
|
||||
cachedCRC32Tables.Clear();
|
||||
}
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// Builds a crc32 table given a polynomial
|
||||
/// </summary>
|
||||
/// <param name="ulPolynomial"></param>
|
||||
/// <returns></returns>
|
||||
protected static uint[] BuildCRC32Table(uint ulPolynomial)
|
||||
{
|
||||
uint dwCrc;
|
||||
uint[] table = new uint[256];
|
||||
|
||||
// 256 values representing ASCII character codes.
|
||||
for (int i = 0; i < 256; i++)
|
||||
{
|
||||
dwCrc = (uint)i;
|
||||
for (int j = 8; j > 0; j--)
|
||||
{
|
||||
if ((dwCrc & 1) == 1)
|
||||
dwCrc = (dwCrc >> 1) ^ ulPolynomial;
|
||||
else
|
||||
dwCrc >>= 1;
|
||||
}
|
||||
table[i] = dwCrc;
|
||||
}
|
||||
|
||||
return table;
|
||||
}
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// Creates a CRC32 object using the DefaultPolynomial
|
||||
/// </summary>
|
||||
public CRC32()
|
||||
: this(DefaultPolynomial)
|
||||
{
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a CRC32 object using the specified Creates a CRC32 object
|
||||
/// </summary>
|
||||
public CRC32(uint aPolynomial)
|
||||
: this(aPolynomial, CRC32.AutoCache)
|
||||
{
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Construct the
|
||||
/// </summary>
|
||||
public CRC32(uint aPolynomial, bool cacheTable)
|
||||
{
|
||||
this.HashSizeValue = 32;
|
||||
|
||||
crc32Table = (uint[])cachedCRC32Tables[aPolynomial];
|
||||
if (crc32Table == null)
|
||||
{
|
||||
crc32Table = CRC32.BuildCRC32Table(aPolynomial);
|
||||
if (cacheTable)
|
||||
cachedCRC32Tables.Add(aPolynomial, crc32Table);
|
||||
}
|
||||
Initialize();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Initializes an implementation of HashAlgorithm.
|
||||
/// </summary>
|
||||
public override void Initialize()
|
||||
{
|
||||
m_crc = AllOnes;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <param name="buffer"></param>
|
||||
/// <param name="offset"></param>
|
||||
/// <param name="count"></param>
|
||||
protected override void HashCore(byte[] buffer, int offset, int count)
|
||||
{
|
||||
// Save the text in the buffer.
|
||||
for (int i = offset; i < count; i++)
|
||||
{
|
||||
ulong tabPtr = (m_crc & 0xFF) ^ buffer[i];
|
||||
m_crc >>= 8;
|
||||
m_crc ^= crc32Table[tabPtr];
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <returns></returns>
|
||||
protected override byte[] HashFinal()
|
||||
{
|
||||
byte[] finalHash = new byte[4];
|
||||
ulong finalCRC = m_crc ^ AllOnes;
|
||||
|
||||
finalHash[0] = (byte)((finalCRC >> 24) & 0xFF);
|
||||
finalHash[1] = (byte)((finalCRC >> 16) & 0xFF);
|
||||
finalHash[2] = (byte)((finalCRC >> 8) & 0xFF);
|
||||
finalHash[3] = (byte)((finalCRC >> 0) & 0xFF);
|
||||
|
||||
return finalHash;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Computes the hash value for the specified Stream.
|
||||
/// </summary>
|
||||
new public byte[] ComputeHash(Stream inputStream)
|
||||
{
|
||||
byte[] buffer = new byte[4096];
|
||||
int bytesRead;
|
||||
while ((bytesRead = inputStream.Read(buffer, 0, 4096)) > 0)
|
||||
{
|
||||
HashCore(buffer, 0, bytesRead);
|
||||
}
|
||||
return HashFinal();
|
||||
}
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// Overloaded. Computes the hash value for the input data.
|
||||
/// </summary>
|
||||
new public byte[] ComputeHash(byte[] buffer)
|
||||
{
|
||||
return ComputeHash(buffer, 0, buffer.Length);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Overloaded. Computes the hash value for the input data.
|
||||
/// </summary>
|
||||
/// <param name="buffer"></param>
|
||||
/// <param name="offset"></param>
|
||||
/// <param name="count"></param>
|
||||
/// <returns></returns>
|
||||
new public byte[] ComputeHash(byte[] buffer, int offset, int count)
|
||||
{
|
||||
HashCore(buffer, offset, count);
|
||||
return HashFinal();
|
||||
}
|
||||
}
|
||||
}
|
|
@ -0,0 +1,211 @@
|
|||
// Copyright (c) 2011, Outercurve Foundation.
|
||||
// All rights reserved.
|
||||
//
|
||||
// Redistribution and use in source and binary forms, with or without modification,
|
||||
// are permitted provided that the following conditions are met:
|
||||
//
|
||||
// - Redistributions of source code must retain the above copyright notice, this
|
||||
// list of conditions and the following disclaimer.
|
||||
//
|
||||
// - 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.
|
||||
//
|
||||
// - Neither the name of the Outercurve Foundation nor the names of its
|
||||
// contributors may be used to endorse or promote products derived from this
|
||||
// software without specific prior written permission.
|
||||
//
|
||||
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
|
||||
// ANY EXPRESS 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 COPYRIGHT HOLDER OR CONTRIBUTORS 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.
|
||||
|
||||
using System;
|
||||
using System.Diagnostics;
|
||||
using System.Collections.Generic;
|
||||
using System.Text;
|
||||
using System.Globalization;
|
||||
|
||||
namespace WebsitePanel.Server.Utils
|
||||
{
|
||||
public class EventLogTraceListener : TraceListener
|
||||
{
|
||||
private EventLog eventLog;
|
||||
private bool nameSet;
|
||||
|
||||
public EventLog EventLog
|
||||
{
|
||||
get
|
||||
{
|
||||
return this.eventLog;
|
||||
}
|
||||
set
|
||||
{
|
||||
this.eventLog = value;
|
||||
}
|
||||
}
|
||||
|
||||
public override string Name
|
||||
{
|
||||
get
|
||||
{
|
||||
if (!this.nameSet && (this.eventLog != null))
|
||||
{
|
||||
this.nameSet = true;
|
||||
base.Name = this.eventLog.Source;
|
||||
}
|
||||
return base.Name;
|
||||
}
|
||||
set
|
||||
{
|
||||
this.nameSet = true;
|
||||
base.Name = value;
|
||||
}
|
||||
}
|
||||
|
||||
public EventLogTraceListener(EventLog eventLog)
|
||||
: base((eventLog != null) ? eventLog.Source : string.Empty)
|
||||
{
|
||||
this.eventLog = eventLog;
|
||||
}
|
||||
|
||||
public EventLogTraceListener(string source)
|
||||
{
|
||||
if (!EventLog.SourceExists(source))
|
||||
{
|
||||
EventLog.CreateEventSource(source, source);
|
||||
}
|
||||
|
||||
this.eventLog = new EventLog();
|
||||
this.eventLog.Source = source;
|
||||
this.eventLog.ModifyOverflowPolicy(OverflowAction.OverwriteAsNeeded, 0);
|
||||
}
|
||||
|
||||
private EventInstance CreateEventInstance(TraceEventType severity, int id)
|
||||
{
|
||||
if (id > 0xffff)
|
||||
{
|
||||
id = 0xffff;
|
||||
}
|
||||
if (id < 0)
|
||||
{
|
||||
id = 0;
|
||||
}
|
||||
EventInstance instance1 = new EventInstance((long)id, 0);
|
||||
if ((severity == TraceEventType.Error) || (severity == TraceEventType.Critical))
|
||||
{
|
||||
instance1.EntryType = EventLogEntryType.Error;
|
||||
return instance1;
|
||||
}
|
||||
if (severity == TraceEventType.Warning)
|
||||
{
|
||||
instance1.EntryType = EventLogEntryType.Warning;
|
||||
return instance1;
|
||||
}
|
||||
instance1.EntryType = EventLogEntryType.Information;
|
||||
return instance1;
|
||||
}
|
||||
|
||||
public override void TraceData(TraceEventCache eventCache, string source, TraceEventType severity, int id, params object[] data)
|
||||
{
|
||||
if ((base.Filter == null) || base.Filter.ShouldTrace(eventCache, source, severity, id, null, null, null, data))
|
||||
{
|
||||
EventInstance instance1 = this.CreateEventInstance(severity, id);
|
||||
StringBuilder builder1 = new StringBuilder();
|
||||
if (data != null)
|
||||
{
|
||||
for (int num1 = 0; num1 < data.Length; num1++)
|
||||
{
|
||||
if (num1 != 0)
|
||||
{
|
||||
builder1.Append(", ");
|
||||
}
|
||||
if (data[num1] != null)
|
||||
{
|
||||
builder1.Append(data[num1].ToString());
|
||||
}
|
||||
}
|
||||
}
|
||||
this.eventLog.WriteEvent(instance1, new object[] { builder1.ToString() });
|
||||
}
|
||||
}
|
||||
|
||||
public override void TraceData(TraceEventCache eventCache, string source, TraceEventType severity, int id, object data)
|
||||
{
|
||||
if ((base.Filter == null) || base.Filter.ShouldTrace(eventCache, source, severity, id, null, null, data, null))
|
||||
{
|
||||
EventInstance instance1 = this.CreateEventInstance(severity, id);
|
||||
this.eventLog.WriteEvent(instance1, new object[] { data });
|
||||
}
|
||||
}
|
||||
|
||||
public override void TraceEvent(TraceEventCache eventCache, string source, TraceEventType severity, int id, string message)
|
||||
{
|
||||
if ((base.Filter == null) || base.Filter.ShouldTrace(eventCache, source, severity, id, message, null, null, null))
|
||||
{
|
||||
EventInstance instance1 = this.CreateEventInstance(severity, id);
|
||||
this.eventLog.WriteEvent(instance1, new object[] { message });
|
||||
}
|
||||
}
|
||||
|
||||
public override void TraceEvent(TraceEventCache eventCache, string source, TraceEventType severity, int id, string format, params object[] args)
|
||||
{
|
||||
if ((base.Filter == null) || base.Filter.ShouldTrace(eventCache, source, severity, id, format, args, null, null))
|
||||
{
|
||||
EventInstance instance1 = this.CreateEventInstance(severity, id);
|
||||
if (args == null)
|
||||
{
|
||||
this.eventLog.WriteEvent(instance1, new object[] { format });
|
||||
}
|
||||
else if (string.IsNullOrEmpty(format))
|
||||
{
|
||||
string[] textArray1 = new string[args.Length];
|
||||
for (int num1 = 0; num1 < args.Length; num1++)
|
||||
{
|
||||
textArray1[num1] = args[num1].ToString();
|
||||
}
|
||||
this.eventLog.WriteEvent(instance1, textArray1);
|
||||
}
|
||||
else
|
||||
{
|
||||
this.eventLog.WriteEvent(instance1, new object[] { string.Format(CultureInfo.InvariantCulture, format, args) });
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public override void Write(string message)
|
||||
{
|
||||
if (this.eventLog != null)
|
||||
{
|
||||
this.eventLog.WriteEntry(message);
|
||||
}
|
||||
}
|
||||
|
||||
public override void WriteLine(string message)
|
||||
{
|
||||
this.Write(message);
|
||||
}
|
||||
|
||||
public override void Close()
|
||||
{
|
||||
if (this.eventLog != null)
|
||||
{
|
||||
this.eventLog.Close();
|
||||
}
|
||||
}
|
||||
|
||||
protected override void Dispose(bool disposing)
|
||||
{
|
||||
if (disposing)
|
||||
{
|
||||
this.Close();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
951
WebsitePanel/Sources/WebsitePanel.Server.Utils/FileUtils.cs
Normal file
951
WebsitePanel/Sources/WebsitePanel.Server.Utils/FileUtils.cs
Normal file
|
@ -0,0 +1,951 @@
|
|||
// Copyright (c) 2011, Outercurve Foundation.
|
||||
// All rights reserved.
|
||||
//
|
||||
// Redistribution and use in source and binary forms, with or without modification,
|
||||
// are permitted provided that the following conditions are met:
|
||||
//
|
||||
// - Redistributions of source code must retain the above copyright notice, this
|
||||
// list of conditions and the following disclaimer.
|
||||
//
|
||||
// - 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.
|
||||
//
|
||||
// - Neither the name of the Outercurve Foundation nor the names of its
|
||||
// contributors may be used to endorse or promote products derived from this
|
||||
// software without specific prior written permission.
|
||||
//
|
||||
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
|
||||
// ANY EXPRESS 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 COPYRIGHT HOLDER OR CONTRIBUTORS 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.
|
||||
|
||||
using System;
|
||||
using System.IO;
|
||||
using System.Text;
|
||||
using System.Text.RegularExpressions;
|
||||
using System.Runtime.InteropServices;
|
||||
using System.Diagnostics;
|
||||
using System.Collections;
|
||||
using System.Collections.Generic;
|
||||
using System.Reflection;
|
||||
using Ionic.Zip;
|
||||
using WebsitePanel.Providers.OS;
|
||||
|
||||
|
||||
namespace WebsitePanel.Providers.Utils
|
||||
{
|
||||
/// <summary>
|
||||
/// Summary description for FileUtils.
|
||||
/// </summary>
|
||||
public class FileUtils
|
||||
{
|
||||
public static string EvaluateSystemVariables(string str)
|
||||
{
|
||||
if (String.IsNullOrEmpty(str))
|
||||
return str;
|
||||
|
||||
Regex re = new Regex("%(.+)%", RegexOptions.IgnoreCase);
|
||||
return re.Replace(str, new MatchEvaluator(EvaluateSystemVariable));
|
||||
}
|
||||
|
||||
public static string GetExecutablePathWithoutParameters(string path)
|
||||
{
|
||||
if (String.IsNullOrEmpty(path))
|
||||
return path;
|
||||
|
||||
int idx = -1;
|
||||
int exeIdx = path.ToLower().IndexOf(".exe");
|
||||
int dllIdx = path.ToLower().IndexOf(".dll");
|
||||
|
||||
if (exeIdx != -1)
|
||||
idx = exeIdx;
|
||||
|
||||
if (dllIdx != -1)
|
||||
idx = dllIdx;
|
||||
|
||||
if (exeIdx != -1 && dllIdx != -1)
|
||||
{
|
||||
idx = exeIdx;
|
||||
if (dllIdx < exeIdx)
|
||||
idx = dllIdx;
|
||||
}
|
||||
|
||||
string execPath = path;
|
||||
if (idx != -1)
|
||||
{
|
||||
execPath = path.Substring(0, idx + 4);
|
||||
if (execPath.StartsWith("\""))
|
||||
execPath = execPath.Substring(1);
|
||||
}
|
||||
|
||||
return execPath;
|
||||
}
|
||||
|
||||
public static string CorrectRelativePath(string relativePath)
|
||||
{
|
||||
// clean path
|
||||
string correctedPath = Regex.Replace(relativePath.Replace("/", "\\"),
|
||||
@"\.\\|\.\.|\\\\|\?|\:|\""|\<|\>|\||%|\$", "");
|
||||
if (correctedPath.StartsWith("\\"))
|
||||
correctedPath = correctedPath.Substring(1);
|
||||
return correctedPath;
|
||||
}
|
||||
|
||||
private static string EvaluateSystemVariable(Match match)
|
||||
{
|
||||
return Environment.GetEnvironmentVariable(match.Groups[1].Value);
|
||||
}
|
||||
|
||||
public static bool FileExists(string path)
|
||||
{
|
||||
return File.Exists(path);
|
||||
}
|
||||
|
||||
public static bool DirectoryExists(string path)
|
||||
{
|
||||
return Directory.Exists(path);
|
||||
}
|
||||
|
||||
public static string CreatePackageFolder(string initialPath)
|
||||
{
|
||||
// substitute vars
|
||||
initialPath = FileUtils.EvaluateSystemVariables(initialPath);
|
||||
|
||||
int i = 0;
|
||||
string path = null;
|
||||
while (true)
|
||||
{
|
||||
path = initialPath + ((i == 0) ? "" : i.ToString());
|
||||
if (!FileUtils.DirectoryExists(path))
|
||||
{
|
||||
// create directory
|
||||
FileUtils.CreateDirectory(path);
|
||||
break;
|
||||
}
|
||||
|
||||
i++;
|
||||
}
|
||||
|
||||
// Set permissions
|
||||
// We decided to inherit NTFS permissions from the parent folder to comply with with the native security schema in Windows,
|
||||
// when a user decides on his own how to implement security practices for NTFS permissions schema and harden the server.
|
||||
SecurityUtils.GrantNtfsPermissionsBySid(path, SystemSID.ADMINISTRATORS, NTFSPermission.FullControl, true, true);
|
||||
SecurityUtils.GrantNtfsPermissionsBySid(path, SystemSID.SYSTEM, NTFSPermission.FullControl, true, true);
|
||||
//
|
||||
return path;
|
||||
}
|
||||
|
||||
public static SystemFile GetFile(string path)
|
||||
{
|
||||
if (!File.Exists(path))
|
||||
return null;
|
||||
|
||||
FileInfo file = new FileInfo(path);
|
||||
return new SystemFile(file.Name, file.FullName, false, file.Length,
|
||||
file.CreationTime, file.LastWriteTime);
|
||||
}
|
||||
|
||||
public static SystemFile[] GetFiles(string path)
|
||||
{
|
||||
ArrayList items = new ArrayList();
|
||||
DirectoryInfo root = new DirectoryInfo(path);
|
||||
|
||||
// get directories
|
||||
DirectoryInfo[] dirs = root.GetDirectories();
|
||||
foreach (DirectoryInfo dir in dirs)
|
||||
{
|
||||
string fullName = System.IO.Path.Combine(path, dir.Name);
|
||||
SystemFile fi = new SystemFile(dir.Name, fullName, true, 0, dir.CreationTime, dir.LastWriteTime);
|
||||
items.Add(fi);
|
||||
|
||||
// check if the directory is empty
|
||||
fi.IsEmpty = (Directory.GetFileSystemEntries(fullName).Length == 0);
|
||||
}
|
||||
|
||||
// get files
|
||||
FileInfo[] files = root.GetFiles();
|
||||
foreach (FileInfo file in files)
|
||||
{
|
||||
string fullName = System.IO.Path.Combine(path, file.Name);
|
||||
SystemFile fi = new SystemFile(file.Name, fullName, false, file.Length, file.CreationTime, file.LastWriteTime);
|
||||
items.Add(fi);
|
||||
}
|
||||
|
||||
return (SystemFile[])items.ToArray(typeof(SystemFile));
|
||||
}
|
||||
|
||||
public static SystemFile[] GetFilesRecursive(string rootFolder, string path)
|
||||
{
|
||||
return GetFilesRecursiveByPattern(rootFolder, path, "*.*");
|
||||
}
|
||||
|
||||
public static SystemFile[] GetFilesRecursiveByPattern(string rootFolder, string path, string pattern)
|
||||
{
|
||||
// parse pattern
|
||||
string[] patterns = new string[] { pattern };
|
||||
if (pattern.IndexOf("|") != -1 || pattern.IndexOf(";") != -1)
|
||||
patterns = pattern.Split(new char[] { '|', ';' });
|
||||
|
||||
// get files
|
||||
ArrayList files = new ArrayList();
|
||||
foreach (string ptrn in patterns)
|
||||
GetFilesList(files, rootFolder, path, ptrn);
|
||||
return (SystemFile[])files.ToArray(typeof(SystemFile));
|
||||
}
|
||||
|
||||
private static void GetFilesList(ArrayList files, string rootFolder, string folder, string pattern)
|
||||
{
|
||||
string fullPath = System.IO.Path.Combine(rootFolder, folder);
|
||||
|
||||
// add files in the current folder
|
||||
FileInfo[] dirFiles = new DirectoryInfo(fullPath).GetFiles(pattern);
|
||||
foreach (FileInfo file in dirFiles)
|
||||
{
|
||||
SystemFile fi = new SystemFile(folder + "\\" + file.Name, file.Name, false, file.Length,
|
||||
file.CreationTime, file.LastWriteTime);
|
||||
files.Add(fi);
|
||||
}
|
||||
|
||||
// add children folders
|
||||
|
||||
DirectoryInfo[] dirs = new DirectoryInfo(fullPath).GetDirectories();
|
||||
foreach (DirectoryInfo dir in dirs)
|
||||
{
|
||||
GetFilesList(files, rootFolder, System.IO.Path.Combine(folder, dir.Name), pattern);
|
||||
}
|
||||
}
|
||||
|
||||
public static SystemFile[] GetDirectoriesRecursive(string rootFolder, string path)
|
||||
{
|
||||
ArrayList folders = new ArrayList();
|
||||
GetDirectoriesRecursive(folders, rootFolder, path);
|
||||
return (SystemFile[])folders.ToArray(typeof(SystemFile));
|
||||
}
|
||||
|
||||
private static void GetDirectoriesRecursive(ArrayList folders, string rootFolder, string folder)
|
||||
{
|
||||
// add the current folder
|
||||
SystemFile fi = new SystemFile("\\" + folder, folder, true, 0, DateTime.Now, DateTime.Now);
|
||||
folders.Add(fi);
|
||||
|
||||
// add children folders
|
||||
string fullPath = System.IO.Path.Combine(rootFolder, folder);
|
||||
DirectoryInfo dir = new DirectoryInfo(fullPath);
|
||||
fi.Created = dir.CreationTime;
|
||||
fi.Changed = dir.LastWriteTime;
|
||||
DirectoryInfo[] subDirs = dir.GetDirectories();
|
||||
foreach (DirectoryInfo subDir in subDirs)
|
||||
{
|
||||
GetDirectoriesRecursive(folders, rootFolder, System.IO.Path.Combine(folder, subDir.Name));
|
||||
}
|
||||
}
|
||||
|
||||
public static byte[] GetFileBinaryContent(string path)
|
||||
{
|
||||
if (!File.Exists(path))
|
||||
return null;
|
||||
|
||||
FileStream stream = new FileStream(path, FileMode.Open);
|
||||
if (stream == null)
|
||||
return null;
|
||||
|
||||
long length = stream.Length;
|
||||
byte[] content = new byte[length];
|
||||
stream.Read(content, 0, (int)length);
|
||||
stream.Close();
|
||||
return content;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Returns file contents trying to read according to file contents
|
||||
/// </summary>
|
||||
/// <param name="path">Path to the file.</param>
|
||||
/// <param name="encoding">Current file encoding.</param>
|
||||
/// <returns>Array of bytes.</returns>
|
||||
/// <remarks>
|
||||
/// It uses UTF8 by default, so in case incorrect or not supported encoding name
|
||||
/// UTF8 will be used to read file contents and convert it to the byte array.
|
||||
/// </remarks>
|
||||
public static byte[] GetFileBinaryContent(string path, string encoding)
|
||||
{
|
||||
if (!File.Exists(path))
|
||||
return null;
|
||||
|
||||
Encoding fileEncoding = GetEncodingByNameOrDefault(encoding, Encoding.UTF8);
|
||||
|
||||
string fileContent = String.Empty;
|
||||
using (StreamReader sr = new StreamReader(path, fileEncoding))
|
||||
{
|
||||
fileContent = sr.ReadToEnd();
|
||||
}
|
||||
|
||||
return fileEncoding.GetBytes(fileContent).Clone() as byte[];
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Returns <see cref="Encoding"/> from <paramref name="encoding"/> name specified.
|
||||
/// If cannot find <see cref="Encoding"/>, returns <paramref name="defaultEncoding"/>.
|
||||
/// </summary>
|
||||
/// <param name="encoding">The name of the encoding to return.</param>
|
||||
/// <param name="defaultEncoding"><see cref="Encoding"/> that will be returned if no <paramref name="encoding"/> will be found.</param>
|
||||
/// <returns>
|
||||
/// <see cref="Encoding"/> from the <paramref name="encoding"/> name specified,
|
||||
/// otherwise <paramref name="defaultEncoding"/>.
|
||||
/// </returns>
|
||||
private static Encoding GetEncodingByNameOrDefault(string encoding, Encoding defaultEncoding)
|
||||
{
|
||||
Encoding currentEncoding = defaultEncoding;
|
||||
|
||||
try
|
||||
{
|
||||
currentEncoding = Encoding.GetEncoding(encoding);
|
||||
}
|
||||
catch(ArgumentException)
|
||||
{
|
||||
// this encoding is either no supported or incorrect
|
||||
// set to default encoding
|
||||
currentEncoding = defaultEncoding;
|
||||
}
|
||||
|
||||
return currentEncoding;
|
||||
}
|
||||
|
||||
public static Stream GetFileBinaryContentStream(string path)
|
||||
{
|
||||
if (!File.Exists(path))
|
||||
return null;
|
||||
|
||||
return new FileStream(path, FileMode.Open);
|
||||
}
|
||||
|
||||
public static byte[] GetFileBinaryChunk(string path, int offset, int length)
|
||||
{
|
||||
if (!File.Exists(path))
|
||||
return null;
|
||||
|
||||
FileStream stream = new FileStream(path, FileMode.Open);
|
||||
if (stream == null)
|
||||
return null;
|
||||
|
||||
if (offset > 0)
|
||||
stream.Seek(offset, SeekOrigin.Begin);
|
||||
|
||||
byte[] content = new byte[length];
|
||||
int readBytes = stream.Read(content, 0, length);
|
||||
stream.Close();
|
||||
|
||||
if (readBytes < length)
|
||||
{
|
||||
byte[] lastContent = new byte[readBytes];
|
||||
if (readBytes > 0)
|
||||
{
|
||||
Array.Copy(content, 0, lastContent, 0, readBytes);
|
||||
}
|
||||
// avoiding of getting empty content
|
||||
if (lastContent.Length == 0)
|
||||
{
|
||||
lastContent = new byte[] { 1 };
|
||||
}
|
||||
return lastContent;
|
||||
}
|
||||
else
|
||||
{
|
||||
return content;
|
||||
}
|
||||
}
|
||||
|
||||
public static string GetFileTextContent(string path)
|
||||
{
|
||||
StreamReader reader = new StreamReader(path);
|
||||
string content = reader.ReadToEnd();
|
||||
reader.Close();
|
||||
return content;
|
||||
}
|
||||
|
||||
public static void UpdateFileBinaryContent(string path, byte[] content)
|
||||
{
|
||||
FileStream stream = new FileStream(path, FileMode.Create);
|
||||
stream.Write(content, 0, content.Length);
|
||||
stream.Close();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Updates file contents using encoding.
|
||||
/// </summary>
|
||||
/// <param name="path">Path to the file.</param>
|
||||
/// <param name="content">File contents.</param>
|
||||
/// <param name="encoding">Current file encoding.</param>
|
||||
/// <remarks>
|
||||
/// It uses UTF8 by default, so in case incorrect or not supported encoding name is submitted,
|
||||
/// then UTF8 will be used to convert bytes to file contents.
|
||||
/// </remarks>
|
||||
public static void UpdateFileBinaryContent(string path, byte[] content, string encoding)
|
||||
{
|
||||
Encoding fileEncoding = GetEncodingByNameOrDefault(encoding, Encoding.UTF8);
|
||||
|
||||
using (StreamWriter sw = new StreamWriter(File.Create(path), fileEncoding))
|
||||
{
|
||||
sw.Write(
|
||||
fileEncoding.GetString(content)
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
public static void AppendFileBinaryContent(string path, byte[] chunk)
|
||||
{
|
||||
FileStream stream = new FileStream(path, FileMode.Append, FileAccess.Write);
|
||||
stream.Write(chunk, 0, chunk.Length);
|
||||
stream.Close();
|
||||
}
|
||||
|
||||
public static void UpdateFileTextContent(string path, string content)
|
||||
{
|
||||
StreamWriter stream = new StreamWriter(path);
|
||||
stream.Write(content);
|
||||
stream.Close();
|
||||
}
|
||||
|
||||
public static void CreateFile(string path)
|
||||
{
|
||||
FileStream stream = File.Create(path);
|
||||
stream.Close();
|
||||
}
|
||||
|
||||
public static void ChangeFileAttributes(string path, DateTime createdTime, DateTime changedTime)
|
||||
{
|
||||
if (Directory.Exists(path))
|
||||
{
|
||||
Directory.SetCreationTime(path, createdTime);
|
||||
Directory.SetLastWriteTime(path, changedTime);
|
||||
}
|
||||
else if (File.Exists(path))
|
||||
{
|
||||
File.SetCreationTime(path, createdTime);
|
||||
File.SetLastWriteTime(path, changedTime);
|
||||
}
|
||||
}
|
||||
|
||||
public static void DeleteFile(string path)
|
||||
{
|
||||
if (File.Exists(path))
|
||||
File.Delete(path);
|
||||
else
|
||||
if (Directory.Exists(path))
|
||||
Directory.Delete(path, true);
|
||||
|
||||
}
|
||||
|
||||
public static void DeleteFiles(string[] files)
|
||||
{
|
||||
foreach (string file in files)
|
||||
DeleteFile(file);
|
||||
}
|
||||
|
||||
public static void DeleteEmptyDirectories(string[] directories)
|
||||
{
|
||||
foreach (string directory in directories)
|
||||
DeleteEmptyDirectoryRecursive(directory);
|
||||
}
|
||||
|
||||
private static bool DeleteEmptyDirectoryRecursive(string directory)
|
||||
{
|
||||
if (!Directory.Exists(directory))
|
||||
return true;
|
||||
|
||||
// iterate through child folders
|
||||
bool empty = true;
|
||||
string[] dirs = Directory.GetDirectories(directory);
|
||||
foreach (string dir in dirs)
|
||||
{
|
||||
if (!DeleteEmptyDirectoryRecursive(dir))
|
||||
empty = false;
|
||||
}
|
||||
|
||||
string[] files = Directory.GetFiles(directory);
|
||||
empty = empty && (files.Length == 0);
|
||||
|
||||
// try to delete directory
|
||||
if (empty)
|
||||
Directory.Delete(directory);
|
||||
|
||||
return empty;
|
||||
}
|
||||
|
||||
public static void MoveFile(string sourcePath, string destinationPath)
|
||||
{
|
||||
if (File.Exists(sourcePath))
|
||||
{
|
||||
File.Move(sourcePath, destinationPath);
|
||||
}
|
||||
else if (Directory.Exists(sourcePath))
|
||||
{
|
||||
Directory.Move(sourcePath, destinationPath);
|
||||
}
|
||||
else
|
||||
{
|
||||
throw new Exception("Specified file is not found!");
|
||||
}
|
||||
|
||||
// reset NTFS permissions on destination file/folder
|
||||
SecurityUtils.ResetNtfsPermissions(destinationPath);
|
||||
}
|
||||
|
||||
public static void CopyFile(string sourcePath, string destinationPath)
|
||||
{
|
||||
if (File.Exists(sourcePath))
|
||||
{
|
||||
File.Copy(sourcePath, destinationPath, true);
|
||||
}
|
||||
else if (Directory.Exists(sourcePath))
|
||||
{
|
||||
CopyDirectory(sourcePath, destinationPath);
|
||||
}
|
||||
else
|
||||
{
|
||||
throw new Exception("Specified file is not found!");
|
||||
}
|
||||
|
||||
// reset NTFS permissions on destination file/folder
|
||||
SecurityUtils.ResetNtfsPermissions(destinationPath);
|
||||
}
|
||||
|
||||
private static void CopyDirectory(string sourceDir, string destinationDir)
|
||||
{
|
||||
// create directory
|
||||
DirectoryInfo srcDir = new DirectoryInfo(sourceDir);
|
||||
if(!Directory.Exists(destinationDir))
|
||||
Directory.CreateDirectory(destinationDir);
|
||||
|
||||
// create subdirectories
|
||||
DirectoryInfo[] dirs = srcDir.GetDirectories();
|
||||
foreach (DirectoryInfo dir in dirs)
|
||||
{
|
||||
CopyDirectory(System.IO.Path.Combine(sourceDir, dir.Name),
|
||||
System.IO.Path.Combine(destinationDir, dir.Name));
|
||||
}
|
||||
|
||||
// copy files
|
||||
FileInfo[] files = srcDir.GetFiles();
|
||||
foreach (FileInfo file in files)
|
||||
{
|
||||
// copy file
|
||||
file.CopyTo(System.IO.Path.Combine(destinationDir, file.Name), true);
|
||||
}
|
||||
}
|
||||
|
||||
public static void CreateDirectory(string path)
|
||||
{
|
||||
if (!Directory.Exists(path))
|
||||
{
|
||||
// create directory structure
|
||||
Directory.CreateDirectory(path);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
public static void ZipFiles(string zipFile, string rootPath, string[] files)
|
||||
{
|
||||
using (ZipFile zip = new ZipFile())
|
||||
{
|
||||
//use unicode if necessary
|
||||
zip.UseUnicodeAsNecessary = true;
|
||||
zip.UseZip64WhenSaving = Zip64Option.AsNecessary;
|
||||
|
||||
//skip locked files
|
||||
zip.ZipErrorAction = ZipErrorAction.Skip;
|
||||
foreach (string file in files)
|
||||
{
|
||||
string fullPath = Path.Combine(rootPath, file);
|
||||
if (Directory.Exists(fullPath))
|
||||
{
|
||||
//add directory with the same directory name
|
||||
zip.AddDirectory(fullPath, file);
|
||||
}
|
||||
else if (File.Exists(fullPath))
|
||||
{
|
||||
//add file to the root folder
|
||||
zip.AddFile(fullPath, "");
|
||||
}
|
||||
}
|
||||
zip.Save(zipFile);
|
||||
}
|
||||
}
|
||||
|
||||
public static string[] UnzipFiles(string zipFile, string destFolder)
|
||||
{
|
||||
using (ZipFile zip = ZipFile.Read(zipFile))
|
||||
{
|
||||
foreach (ZipEntry e in zip)
|
||||
{
|
||||
// Remove Read-Only attribute from a zip entry
|
||||
if ((e.Attributes & FileAttributes.ReadOnly) == FileAttributes.ReadOnly)
|
||||
e.Attributes ^= FileAttributes.ReadOnly;
|
||||
//
|
||||
e.Extract(destFolder, ExtractExistingFileAction.OverwriteSilently);
|
||||
}
|
||||
}
|
||||
|
||||
List<string> files = new List<string>();
|
||||
foreach(SystemFile systemFile in GetFiles(destFolder))
|
||||
{
|
||||
files.Add(systemFile.FullName);
|
||||
}
|
||||
|
||||
return files.ToArray();
|
||||
}
|
||||
|
||||
private static void CreateDirectoriesStructure(string path)
|
||||
{
|
||||
string dir = System.IO.Path.GetDirectoryName(path);
|
||||
if (!Directory.Exists(dir))
|
||||
{
|
||||
// create directory structure
|
||||
Directory.CreateDirectory(dir);
|
||||
}
|
||||
}
|
||||
|
||||
public static string ExecuteSystemCommand(string cmd, string args)
|
||||
{
|
||||
return ExecuteSystemCommand(cmd, args, null);
|
||||
}
|
||||
|
||||
public static string ExecuteSystemCommand(string cmd, string args, string outputFile)
|
||||
{
|
||||
// launch system process
|
||||
ProcessStartInfo startInfo = new ProcessStartInfo(cmd, args);
|
||||
startInfo.WindowStyle = ProcessWindowStyle.Hidden;
|
||||
startInfo.RedirectStandardOutput = true;
|
||||
startInfo.UseShellExecute = false;
|
||||
startInfo.CreateNoWindow = true;
|
||||
|
||||
// get working directory from executable path
|
||||
startInfo.WorkingDirectory = Path.GetDirectoryName(cmd);
|
||||
Process proc = Process.Start(startInfo);
|
||||
|
||||
|
||||
// analyze results
|
||||
StreamReader reader = proc.StandardOutput;
|
||||
string results = "";
|
||||
if (!String.IsNullOrEmpty(outputFile))
|
||||
{
|
||||
// stream to writer
|
||||
StreamWriter writer = new StreamWriter(outputFile);
|
||||
int BUFFER_LENGTH = 2048;
|
||||
int readBytes = 0;
|
||||
char[] buffer = new char[BUFFER_LENGTH];
|
||||
while ((readBytes = reader.Read(buffer, 0, BUFFER_LENGTH)) > 0)
|
||||
{
|
||||
writer.Write(buffer, 0, readBytes);
|
||||
}
|
||||
writer.Close();
|
||||
}
|
||||
else
|
||||
{
|
||||
// return as string
|
||||
results = reader.ReadToEnd();
|
||||
}
|
||||
reader.Close();
|
||||
|
||||
return results;
|
||||
}
|
||||
|
||||
public static void ExecuteCmdCommand(string command)
|
||||
{
|
||||
ProcessStartInfo ProcessInfo;
|
||||
Process process;
|
||||
|
||||
ProcessInfo = new ProcessStartInfo("cmd.exe", "/C " + command);
|
||||
ProcessInfo.CreateNoWindow = true;
|
||||
ProcessInfo.UseShellExecute = false;
|
||||
process = Process.Start(ProcessInfo);
|
||||
if (process != null)
|
||||
{
|
||||
process.WaitForExit(500);
|
||||
process.Close();
|
||||
}
|
||||
}
|
||||
|
||||
public static void SaveStreamToFile(Stream stream, string path)
|
||||
{
|
||||
try
|
||||
{
|
||||
//Create a file to save to
|
||||
Stream toStream = File.Open(path, FileMode.Create, FileAccess.Write, FileShare.ReadWrite);
|
||||
|
||||
//use the binary reader & writer because
|
||||
//they can work with all formats
|
||||
//i.e images, text files ,avi,mp3..
|
||||
BinaryReader br = new BinaryReader(stream);
|
||||
BinaryWriter bw = new BinaryWriter(toStream);
|
||||
|
||||
//copy data from the FromStream to the outStream
|
||||
//convert from long to int
|
||||
bw.Write(br.ReadBytes((int)stream.Length));
|
||||
|
||||
//save
|
||||
bw.Flush();
|
||||
|
||||
//clean up
|
||||
bw.Close();
|
||||
br.Close();
|
||||
}
|
||||
//use Exception e as it can handle any exception
|
||||
catch
|
||||
{
|
||||
//code if u like
|
||||
}
|
||||
}
|
||||
|
||||
public static long CalculateFolderSize(string path)
|
||||
{
|
||||
int files = 0;
|
||||
int folders = 0;
|
||||
// check directory exists
|
||||
if (!Directory.Exists(path))
|
||||
return 0;
|
||||
// normalize path
|
||||
path = path.Replace("/", "\\");
|
||||
// remove trailing slash
|
||||
if (path.EndsWith(@"\"))
|
||||
path = path.Substring(0, path.Length - 1);
|
||||
// calculate folder size
|
||||
return CalculateFolderSize(path, out files, out folders);
|
||||
}
|
||||
|
||||
private static long CalculateFolderSize(string path, out int files, out int folders)
|
||||
{
|
||||
files = 0;
|
||||
folders = 0;
|
||||
|
||||
IntPtr INVALID_HANDLE_VALUE = new IntPtr(-1);
|
||||
long size = 0;
|
||||
FindData findData = new FindData();
|
||||
|
||||
IntPtr findHandle;
|
||||
|
||||
findHandle = path.StartsWith("\\\\")
|
||||
? Kernel32.FindFirstFile(path + @"\*", findData)
|
||||
: Kernel32.FindFirstFile(@"\\?\" + path + @"\*", findData);
|
||||
if (findHandle != INVALID_HANDLE_VALUE)
|
||||
{
|
||||
|
||||
do
|
||||
{
|
||||
if ((findData.fileAttributes & (int)FileAttributes.Directory) != 0)
|
||||
{
|
||||
|
||||
if (findData.fileName != "." && findData.fileName != "..")
|
||||
{
|
||||
folders++;
|
||||
|
||||
int subfiles, subfolders;
|
||||
string subdirectory = path + (path.EndsWith(@"\") ? "" : @"\") +
|
||||
findData.fileName;
|
||||
size += CalculateFolderSize(subdirectory, out subfiles, out subfolders);
|
||||
folders += subfolders;
|
||||
files += subfiles;
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
// File
|
||||
files++;
|
||||
|
||||
size += (long)findData.nFileSizeLow + (long)findData.nFileSizeHigh * 4294967296;
|
||||
}
|
||||
}
|
||||
while (Kernel32.FindNextFile(findHandle, findData));
|
||||
Kernel32.FindClose(findHandle);
|
||||
|
||||
}
|
||||
|
||||
return size;
|
||||
}
|
||||
|
||||
public static void CreateAccessDatabase(string databasePath)
|
||||
{
|
||||
if (String.IsNullOrEmpty(databasePath))
|
||||
throw new ArgumentException("databasePath");
|
||||
|
||||
string connectionString = String.Format("Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0};Jet OLEDB:Engine Type=5;Mode=Share Deny None;Jet OLEDB:Database Locking Mode=0",
|
||||
databasePath);
|
||||
|
||||
Type adoxType = Type.GetTypeFromProgID("ADOX.Catalog");
|
||||
object cat = Activator.CreateInstance(adoxType);
|
||||
adoxType.InvokeMember("Create", BindingFlags.Instance | BindingFlags.Public | BindingFlags.InvokeMethod,
|
||||
null, cat, new object[] { connectionString });
|
||||
object conn = adoxType.InvokeMember("ActiveConnection", BindingFlags.Instance | BindingFlags.Public | BindingFlags.GetProperty,
|
||||
null, cat, null);
|
||||
adoxType.InvokeMember("Close", BindingFlags.Instance | BindingFlags.Public | BindingFlags.InvokeMethod, null,
|
||||
conn, null);
|
||||
cat = null;
|
||||
}
|
||||
#region Advanced Delete
|
||||
/// <summary>
|
||||
/// Deletes the specified file.
|
||||
/// </summary>
|
||||
/// <param name="fileName">The name of the file to be deleted.</param>
|
||||
public static void DeleteFileAdvanced(string fileName)
|
||||
{
|
||||
int attempts = 0;
|
||||
while (true)
|
||||
{
|
||||
try
|
||||
{
|
||||
DeleteFileInternal(fileName);
|
||||
break;
|
||||
}
|
||||
catch (Exception)
|
||||
{
|
||||
if (attempts > 2)
|
||||
throw;
|
||||
|
||||
attempts++;
|
||||
System.Threading.Thread.Sleep(1000);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Deletes the specified file.
|
||||
/// </summary>
|
||||
/// <param name="fileName">The name of the file to be deleted.</param>
|
||||
private static void DeleteReadOnlyFile(string fileName)
|
||||
{
|
||||
FileInfo info = new FileInfo(fileName);
|
||||
info.Attributes = FileAttributes.Normal;
|
||||
info.Delete();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Deletes the specified file.
|
||||
/// </summary>
|
||||
/// <param name="fileName">The name of the file to be deleted.</param>
|
||||
private static void DeleteFileInternal(string fileName)
|
||||
{
|
||||
try
|
||||
{
|
||||
File.Delete(fileName);
|
||||
}
|
||||
catch (UnauthorizedAccessException)
|
||||
{
|
||||
DeleteReadOnlyFile(fileName);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Deletes the specified directory.
|
||||
/// </summary>
|
||||
/// <param name="directory">The name of the directory to be deleted.</param>
|
||||
public static void DeleteDirectoryAdvanced(string directory)
|
||||
{
|
||||
if (!Directory.Exists(directory))
|
||||
return;
|
||||
|
||||
// iterate through child folders
|
||||
string[] dirs = Directory.GetDirectories(directory);
|
||||
foreach (string dir in dirs)
|
||||
{
|
||||
DeleteDirectoryAdvanced(dir);
|
||||
}
|
||||
|
||||
// iterate through child files
|
||||
string[] files = Directory.GetFiles(directory);
|
||||
foreach (string file in files)
|
||||
{
|
||||
DeleteFileAdvanced(file);
|
||||
}
|
||||
|
||||
//try to delete dir for 3 times
|
||||
int attempts = 0;
|
||||
while (true)
|
||||
{
|
||||
try
|
||||
{
|
||||
DeleteDirectoryInternal(directory);
|
||||
break;
|
||||
}
|
||||
catch (Exception)
|
||||
{
|
||||
if (attempts > 2)
|
||||
throw;
|
||||
|
||||
attempts++;
|
||||
System.Threading.Thread.Sleep(1000);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Deletes the specified directory.
|
||||
/// </summary>
|
||||
/// <param name="directory">The name of the directory to be deleted.</param>
|
||||
public static void DeleteDirectoryInternal(string directory)
|
||||
{
|
||||
try
|
||||
{
|
||||
Directory.Delete(directory);
|
||||
}
|
||||
catch (IOException)
|
||||
{
|
||||
DeleteReadOnlyDirectory(directory);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Deletes the specified directory.
|
||||
/// </summary>
|
||||
/// <param name="directory">The name of the directory to be deleted.</param>
|
||||
private static void DeleteReadOnlyDirectory(string directory)
|
||||
{
|
||||
DirectoryInfo info = new DirectoryInfo(directory);
|
||||
info.Attributes = FileAttributes.Normal;
|
||||
info.Delete();
|
||||
}
|
||||
#endregion
|
||||
|
||||
}
|
||||
|
||||
#region File Size Calculation helper classes
|
||||
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)]
|
||||
class FindData
|
||||
{
|
||||
public int fileAttributes;
|
||||
public int creationTime_lowDateTime;
|
||||
public int creationTime_highDateTime;
|
||||
public int lastAccessTime_lowDateTime;
|
||||
public int lastAccessTime_highDateTime;
|
||||
public int lastWriteTime_lowDateTime;
|
||||
public int lastWriteTime_highDateTime;
|
||||
public uint nFileSizeHigh;
|
||||
public uint nFileSizeLow;
|
||||
public int dwReserved0;
|
||||
public int dwReserved1;
|
||||
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 260)]
|
||||
public String fileName;
|
||||
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 14)]
|
||||
public String alternateFileName;
|
||||
}
|
||||
|
||||
class Kernel32
|
||||
{
|
||||
[DllImport("Kernel32.dll", CharSet = CharSet.Auto)]
|
||||
public static extern IntPtr FindFirstFile(String fileName, [In, Out] FindData findFileData);
|
||||
|
||||
[DllImport("kernel32", CharSet = CharSet.Auto)]
|
||||
[return: MarshalAs(UnmanagedType.Bool)]
|
||||
public static extern bool FindNextFile(IntPtr hFindFile, [In, Out] FindData lpFindFileData);
|
||||
|
||||
[DllImport("kernel32", CharSet = CharSet.Auto)]
|
||||
[return: MarshalAs(UnmanagedType.Bool)]
|
||||
public static extern bool FindClose(IntPtr hFindFile);
|
||||
}
|
||||
#endregion
|
||||
}
|
155
WebsitePanel/Sources/WebsitePanel.Server.Utils/Log.cs
Normal file
155
WebsitePanel/Sources/WebsitePanel.Server.Utils/Log.cs
Normal file
|
@ -0,0 +1,155 @@
|
|||
// Copyright (c) 2011, Outercurve Foundation.
|
||||
// All rights reserved.
|
||||
//
|
||||
// Redistribution and use in source and binary forms, with or without modification,
|
||||
// are permitted provided that the following conditions are met:
|
||||
//
|
||||
// - Redistributions of source code must retain the above copyright notice, this
|
||||
// list of conditions and the following disclaimer.
|
||||
//
|
||||
// - 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.
|
||||
//
|
||||
// - Neither the name of the Outercurve Foundation nor the names of its
|
||||
// contributors may be used to endorse or promote products derived from this
|
||||
// software without specific prior written permission.
|
||||
//
|
||||
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
|
||||
// ANY EXPRESS 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 COPYRIGHT HOLDER OR CONTRIBUTORS 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.
|
||||
|
||||
using System;
|
||||
using System.Diagnostics;
|
||||
|
||||
namespace WebsitePanel.Server.Utils
|
||||
{
|
||||
/// <summary>
|
||||
/// Application log.
|
||||
/// </summary>
|
||||
public sealed class Log
|
||||
{
|
||||
private static TraceSwitch logSeverity = new TraceSwitch("Log", "General trace switch");
|
||||
|
||||
private Log()
|
||||
{
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Write error to the log.
|
||||
/// </summary>
|
||||
/// <param name="message">Error message.</param>
|
||||
/// <param name="ex">Exception.</param>
|
||||
public static void WriteError(string message, Exception ex)
|
||||
{
|
||||
try
|
||||
{
|
||||
if (logSeverity.TraceError)
|
||||
{
|
||||
string line = string.Format("[{0:G}] ERROR: {1}\n{2}\n", DateTime.Now, message, ex);
|
||||
Trace.TraceError(line);
|
||||
}
|
||||
}
|
||||
catch { }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Write error to the log.
|
||||
/// </summary>
|
||||
/// <param name="ex">Exception.</param>
|
||||
public static void WriteError(Exception ex)
|
||||
{
|
||||
|
||||
try
|
||||
{
|
||||
if (ex != null)
|
||||
{
|
||||
WriteError(ex.Message, ex);
|
||||
}
|
||||
}
|
||||
catch { }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Write info message to log
|
||||
/// </summary>
|
||||
/// <param name="message"></param>
|
||||
public static void WriteInfo(string message, params object[] args)
|
||||
{
|
||||
try
|
||||
{
|
||||
if (logSeverity.TraceInfo)
|
||||
{
|
||||
Trace.TraceInformation(FormatIncomingMessage(message, args));
|
||||
}
|
||||
}
|
||||
catch { }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Write info message to log
|
||||
/// </summary>
|
||||
/// <param name="message"></param>
|
||||
public static void WriteWarning(string message, params object[] args)
|
||||
{
|
||||
try
|
||||
{
|
||||
if (logSeverity.TraceWarning)
|
||||
{
|
||||
Trace.TraceWarning(FormatIncomingMessage(message, args));
|
||||
}
|
||||
}
|
||||
catch { }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Write start message to log
|
||||
/// </summary>
|
||||
/// <param name="message"></param>
|
||||
public static void WriteStart(string message, params object[] args)
|
||||
{
|
||||
try
|
||||
{
|
||||
if (logSeverity.TraceInfo)
|
||||
{
|
||||
Trace.TraceInformation(FormatIncomingMessage(message, args));
|
||||
}
|
||||
}
|
||||
catch { }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Write end message to log
|
||||
/// </summary>
|
||||
/// <param name="message"></param>
|
||||
public static void WriteEnd(string message, params object[] args)
|
||||
{
|
||||
try
|
||||
{
|
||||
if (logSeverity.TraceInfo)
|
||||
{
|
||||
Trace.TraceInformation(FormatIncomingMessage(message, args));
|
||||
}
|
||||
}
|
||||
catch { }
|
||||
}
|
||||
|
||||
private static string FormatIncomingMessage(string message, params object[] args)
|
||||
{
|
||||
//
|
||||
if (args.Length > 0)
|
||||
{
|
||||
message = String.Format(message, args);
|
||||
}
|
||||
//
|
||||
return String.Concat(String.Format("[{0:G}] END: ", DateTime.Now), message);
|
||||
}
|
||||
}
|
||||
}
|
|
@ -0,0 +1,283 @@
|
|||
// Copyright (c) 2011, Outercurve Foundation.
|
||||
// All rights reserved.
|
||||
//
|
||||
// Redistribution and use in source and binary forms, with or without modification,
|
||||
// are permitted provided that the following conditions are met:
|
||||
//
|
||||
// - Redistributions of source code must retain the above copyright notice, this
|
||||
// list of conditions and the following disclaimer.
|
||||
//
|
||||
// - 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.
|
||||
//
|
||||
// - Neither the name of the Outercurve Foundation nor the names of its
|
||||
// contributors may be used to endorse or promote products derived from this
|
||||
// software without specific prior written permission.
|
||||
//
|
||||
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
|
||||
// ANY EXPRESS 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 COPYRIGHT HOLDER OR CONTRIBUTORS 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.
|
||||
|
||||
using System;
|
||||
using System.Collections;
|
||||
using System.Collections.Generic;
|
||||
using System.Collections.Specialized;
|
||||
using System.Text;
|
||||
using System.Text.RegularExpressions;
|
||||
using System.IO;
|
||||
using System.Diagnostics;
|
||||
using System.Web;
|
||||
using WebsitePanel.Server.Utils;
|
||||
|
||||
namespace WebsitePanel.Providers.Utils.LogParser
|
||||
{
|
||||
public delegate void ProcessKeyFieldsEventHandler (string[] key_fields, string[] key_values, string[] log_fields, string[] log_values);
|
||||
public delegate void CalculateStatsLineEventHandler(StatsLine line, string[] fields, string[] values);
|
||||
/// <summary>
|
||||
/// Summary description for LogParser.
|
||||
/// </summary>
|
||||
public class LogParser
|
||||
{
|
||||
string serviceName;
|
||||
string logName;
|
||||
string logsPath;
|
||||
string[] keyFields;
|
||||
int keyFieldsLength;
|
||||
Regex re_clean = new Regex("\\W+", RegexOptions.Compiled);
|
||||
string[] _fields;
|
||||
|
||||
public event ProcessKeyFieldsEventHandler ProcessKeyFields;
|
||||
public event CalculateStatsLineEventHandler CalculateStatisticsLine;
|
||||
|
||||
public LogParser(string serviceName, string logName, string logsPath, params string[] keyFields)
|
||||
{
|
||||
this.serviceName = serviceName;
|
||||
this.logName = logName;
|
||||
this.logsPath = logsPath;
|
||||
this.keyFields = keyFields;
|
||||
this.keyFieldsLength = keyFields.Length;
|
||||
//
|
||||
List<string> fShadow = new List<string>(keyFields);
|
||||
fShadow.Add("sc-bytes");
|
||||
fShadow.Add("cs-bytes");
|
||||
fShadow.Add("date");
|
||||
//
|
||||
this._fields = fShadow.ToArray();
|
||||
}
|
||||
|
||||
public void ParseLogs()
|
||||
{
|
||||
ParseLogs<LogReader>();
|
||||
}
|
||||
|
||||
public void ParseLogs<T>() where T : LogReader
|
||||
{
|
||||
// ensure calculation logic has been initialized
|
||||
// with the default calculating routine
|
||||
if (CalculateStatisticsLine == null)
|
||||
CalculateStatisticsLine += new CalculateStatsLineEventHandler(Default_CalculateStatisticLine);
|
||||
//
|
||||
string statsDir = GetStatsFilePath();
|
||||
string statsName = null;
|
||||
// get site state
|
||||
LogState logState = new LogState(statsDir + logName + ".state");
|
||||
|
||||
LogReader reader = (LogReader)Activator.CreateInstance(typeof(T));
|
||||
reader.Open(logsPath, logState.LastAccessed, logState.Line);
|
||||
|
||||
Hashtable monthlyLogs = new Hashtable();
|
||||
|
||||
while (reader.Read())
|
||||
{
|
||||
try
|
||||
{
|
||||
// skip error and system lines
|
||||
if (reader.ErrorLine || reader.SystemLine)
|
||||
continue;
|
||||
// skip block with log data if fields aren't available
|
||||
if (!reader.CheckFieldsAvailable(_fields))
|
||||
continue;
|
||||
//
|
||||
string[] dateParts = reader["date"].Split('-'); // yyyy-mm-dd
|
||||
int day = Int32.Parse(dateParts[2]);
|
||||
|
||||
string[] keyValues = new string[keyFieldsLength];
|
||||
//
|
||||
for (int i = 0; i < keyFieldsLength; i++)
|
||||
keyValues[i] = reader[keyFields[i]];
|
||||
//
|
||||
if (ProcessKeyFields != null)
|
||||
ProcessKeyFields(keyFields, keyValues, reader.LineFields, reader.LineValues);
|
||||
// build stats file name
|
||||
statsName = GetMothlyStatsFileName(dateParts[0], dateParts[1], keyValues);
|
||||
//
|
||||
MonthlyStatistics monthlyStats = (MonthlyStatistics)monthlyLogs[statsName];
|
||||
if (monthlyStats == null)
|
||||
{
|
||||
// add new statistics
|
||||
try
|
||||
{
|
||||
monthlyStats = new MonthlyStatistics(Path.Combine(statsDir, statsName), true);
|
||||
monthlyLogs[statsName] = monthlyStats;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
// Handle an exception
|
||||
Log.WriteError(String.Format("LogParser: Failed to instantiate monthly stats file '{0}' at '{0}' path", statsName, statsDir), ex);
|
||||
// SKIP OVER THE NEXT ITERATION
|
||||
continue;
|
||||
}
|
||||
}
|
||||
|
||||
// get current day from statistic
|
||||
StatsLine dayStats = monthlyStats[day];
|
||||
if (dayStats == null)
|
||||
{
|
||||
dayStats = new StatsLine();
|
||||
monthlyStats[day] = dayStats;
|
||||
}
|
||||
// perform statistics line calculation
|
||||
// this workaround has been added due to avoid
|
||||
// IIS 6 vs. IIS 7 log files calculation logic discrepancies
|
||||
CalculateStatisticsLine(dayStats, reader.LineFields, reader.LineValues);
|
||||
}
|
||||
catch(Exception ex)
|
||||
{
|
||||
Log.WriteError(String.Format("Failed to process line {0}, statistics directory path {1}, statistics file name {2}", reader.LogLine, statsDir, reader.LogName), ex);
|
||||
}
|
||||
}
|
||||
|
||||
// save all accumulated statistics
|
||||
foreach (MonthlyStatistics monthlyStats in monthlyLogs.Values)
|
||||
monthlyStats.Save(statsDir);
|
||||
|
||||
// save site state
|
||||
logState.LastAccessed = reader.LogDate;
|
||||
logState.Line = reader.LogLine;
|
||||
logState.Save();
|
||||
}
|
||||
|
||||
public MonthlyStatistics GetMonthlyStatistics(int year, int month, params string[] keyValues)
|
||||
{
|
||||
string statsName = GetMothlyStatsFileName(year.ToString(), month.ToString(), keyValues);
|
||||
return new MonthlyStatistics(Path.Combine(this.GetStatsFilePath(), statsName), true);
|
||||
}
|
||||
|
||||
public DailyStatistics[] GetDailyStatistics(DateTime since, params string[] keyValues)
|
||||
{
|
||||
ArrayList days = new ArrayList();
|
||||
|
||||
// read statistics
|
||||
DateTime now = DateTime.Now;
|
||||
DateTime date = since;
|
||||
|
||||
if (date == DateTime.MinValue)
|
||||
date = GetLogsBeginDate();
|
||||
|
||||
// iterate from since to now
|
||||
while (date < now)
|
||||
{
|
||||
// get monthly statistics
|
||||
MonthlyStatistics stats = GetMonthlyStatistics(date.Year, date.Month, keyValues);
|
||||
foreach (int day in stats.Days.Keys)
|
||||
{
|
||||
StatsLine line = stats[day];
|
||||
DailyStatistics dailyStats = new DailyStatistics();
|
||||
dailyStats.Year = date.Year;
|
||||
dailyStats.Month = date.Month;
|
||||
dailyStats.Day = day;
|
||||
dailyStats.BytesSent = line.BytesSent;
|
||||
dailyStats.BytesReceived = line.BytesReceived;
|
||||
|
||||
days.Add(dailyStats);
|
||||
}
|
||||
|
||||
// advance month
|
||||
date = date.AddMonths(1);
|
||||
}
|
||||
|
||||
return (DailyStatistics[])days.ToArray(typeof(DailyStatistics));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Perform default statistics line calculation.
|
||||
/// Suits for the following providers: IIS 6.0;
|
||||
/// </summary>
|
||||
/// <param name="line">Statistic line is being calculated</param>
|
||||
/// <param name="fields">Log file available fields</param>
|
||||
/// <param name="values">Log file available values for the line is being read</param>
|
||||
private void Default_CalculateStatisticLine(StatsLine line, string[] fields, string[] values)
|
||||
{
|
||||
int cs_bytes = Array.IndexOf(fields, "cs-bytes");
|
||||
int sc_bytes = Array.IndexOf(fields, "sc-bytes");
|
||||
// run default calculation logic
|
||||
if (cs_bytes > -1)
|
||||
line.BytesReceived += Int64.Parse(values[cs_bytes]);
|
||||
//
|
||||
if (sc_bytes > -1)
|
||||
line.BytesSent += Int64.Parse(values[sc_bytes]);
|
||||
}
|
||||
|
||||
private DateTime GetLogsBeginDate()
|
||||
{
|
||||
DirectoryInfo dir = new DirectoryInfo(logsPath);
|
||||
FileInfo[] files = dir.GetFiles();
|
||||
DateTime minDate = DateTime.Now;
|
||||
foreach (FileInfo file in files)
|
||||
{
|
||||
if (file.CreationTime < minDate)
|
||||
minDate = file.CreationTime;
|
||||
}
|
||||
return minDate;
|
||||
}
|
||||
|
||||
private string GetMothlyStatsFileName(string year, string month, string[] keyValues)
|
||||
{
|
||||
// build statistics name
|
||||
StringBuilder sb = new StringBuilder();
|
||||
int i = 0;
|
||||
try
|
||||
{
|
||||
// loop for key values
|
||||
for (i = 0; i < keyFieldsLength; i++)
|
||||
{
|
||||
if (keyValues[i] != null && keyValues[i] != "")
|
||||
sb.Append(re_clean.Replace(keyValues[i], "_")).Append("_");
|
||||
}
|
||||
// normalize year
|
||||
if (year.Length == 2)
|
||||
sb.Append("20");
|
||||
sb.Append(year);
|
||||
// normalize month
|
||||
if (month.Length == 1)
|
||||
sb.Append("0");
|
||||
sb.Append(month);
|
||||
// append log file extension
|
||||
sb.Append(".log");
|
||||
//
|
||||
}
|
||||
catch(Exception ex)
|
||||
{
|
||||
Log.WriteError(String.Format("Monthly Statistics FileName: year - {0}, month - {1}, keyValue - {2}", year, month, keyValues[i]), ex);
|
||||
}
|
||||
return sb.ToString();
|
||||
}
|
||||
|
||||
private string GetStatsFilePath()
|
||||
{
|
||||
string homePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "LogParser");
|
||||
homePath = Path.Combine(homePath, serviceName);
|
||||
//
|
||||
return homePath.EndsWith(@"\") ? homePath : homePath + @"\";
|
||||
}
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,367 @@
|
|||
// Copyright (c) 2011, Outercurve Foundation.
|
||||
// All rights reserved.
|
||||
//
|
||||
// Redistribution and use in source and binary forms, with or without modification,
|
||||
// are permitted provided that the following conditions are met:
|
||||
//
|
||||
// - Redistributions of source code must retain the above copyright notice, this
|
||||
// list of conditions and the following disclaimer.
|
||||
//
|
||||
// - 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.
|
||||
//
|
||||
// - Neither the name of the Outercurve Foundation nor the names of its
|
||||
// contributors may be used to endorse or promote products derived from this
|
||||
// software without specific prior written permission.
|
||||
//
|
||||
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
|
||||
// ANY EXPRESS 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 COPYRIGHT HOLDER OR CONTRIBUTORS 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.
|
||||
|
||||
using System;
|
||||
using System.IO;
|
||||
using System.Collections;
|
||||
using System.Collections.Specialized;
|
||||
using System.Diagnostics;
|
||||
using WebsitePanel.Server.Utils;
|
||||
|
||||
namespace WebsitePanel.Providers.Utils.LogParser
|
||||
{
|
||||
|
||||
/// <summary>
|
||||
/// Summary description for LogReader.
|
||||
/// </summary>
|
||||
public class LogReader
|
||||
{
|
||||
public static long TotalBytesProcessed = 0;
|
||||
|
||||
public class FilesByCreationDateComparer : IComparer
|
||||
{
|
||||
public int Compare(object x, object y)
|
||||
{
|
||||
return DateTime.Compare(((FileInfo)x).CreationTime, ((FileInfo)y).CreationTime);
|
||||
}
|
||||
}
|
||||
|
||||
private const string FIELDS_LINE = "#Fields: ";
|
||||
private const int FIELDS_LINE_LENGTH = 9;
|
||||
protected const char FIELDS_SEPARATOR = ' ';
|
||||
protected static readonly char[] FIELDS_SPLITTER = new char[] { FIELDS_SEPARATOR };
|
||||
|
||||
protected int fieldsLength;
|
||||
|
||||
// initial log position
|
||||
private int fileIndex = -1;
|
||||
private long lineIndex = 0;
|
||||
private long lastLineIndex = 0;
|
||||
protected string line = null; // current log line
|
||||
protected bool errorLine = false;
|
||||
protected bool systemLine = false;
|
||||
private string logName = null;
|
||||
private long logDate = 0;
|
||||
private StreamReader reader;
|
||||
|
||||
// log files in the log directory
|
||||
protected ArrayList logFiles = new ArrayList();
|
||||
|
||||
// fields available in the current log file
|
||||
private string[] fields = new string[0];
|
||||
protected string[] fieldsValues = null;
|
||||
|
||||
// field values of the current log line
|
||||
protected Hashtable record = new Hashtable();
|
||||
|
||||
public LogReader()
|
||||
{
|
||||
// nothing to do
|
||||
}
|
||||
|
||||
public void Open(string logsPath)
|
||||
{
|
||||
// use this
|
||||
this.Open(logsPath, 0, 0);
|
||||
}
|
||||
|
||||
public void Open(string logsPath, long lastAccessed, long line)
|
||||
{
|
||||
// save specified line
|
||||
lineIndex = line;
|
||||
|
||||
// get logs directory
|
||||
DirectoryInfo logsDir = new DirectoryInfo(FileUtils.EvaluateSystemVariables(logsPath));
|
||||
|
||||
// get the list of files
|
||||
if (logsDir.Exists)
|
||||
GetDirectoryFiles(logsDir, logFiles);
|
||||
|
||||
// sort files by date
|
||||
logFiles.Sort(new FilesByCreationDateComparer());
|
||||
|
||||
// try to find specified file
|
||||
if (lastAccessed != 0)
|
||||
{
|
||||
for (int i = 0; i < logFiles.Count; i++)
|
||||
{
|
||||
if (((FileInfo)logFiles[i]).CreationTime.Ticks == lastAccessed)
|
||||
{
|
||||
fileIndex = i;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// check whether specified file was found
|
||||
if (fileIndex == -1)
|
||||
{
|
||||
// no
|
||||
fileIndex = 0;
|
||||
lineIndex = 0;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Checks whether requested fields are available against currently reading block with log data
|
||||
/// </summary>
|
||||
/// <param name="keyFields">Fields names to be accessed</param>
|
||||
/// <returns>Returns true if all of requested fields are available. Otherwise returns false.</returns>
|
||||
public bool CheckFieldsAvailable(string[] keyFields)
|
||||
{
|
||||
try
|
||||
{
|
||||
if (fields == null || fields.Length == 0)
|
||||
return false;
|
||||
//
|
||||
foreach (string keyField in keyFields)
|
||||
{
|
||||
//
|
||||
if (Array.IndexOf(fields, keyField) == -1)
|
||||
return false;
|
||||
}
|
||||
//
|
||||
}
|
||||
catch(Exception ex)
|
||||
{
|
||||
Log.WriteError(ex);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
public bool Read()
|
||||
{
|
||||
// first of all try to open the "next" log file
|
||||
while (reader == null && fileIndex < logFiles.Count)
|
||||
{
|
||||
// open reader
|
||||
FileInfo file = (FileInfo)logFiles[fileIndex];
|
||||
logName = file.FullName;
|
||||
logDate = file.CreationTime.Ticks;
|
||||
|
||||
try
|
||||
{
|
||||
Stream logStream = new FileStream(logName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
|
||||
reader = new StreamReader(logStream);
|
||||
|
||||
// update statistics counter
|
||||
TotalBytesProcessed += file.Length;
|
||||
|
||||
// position file to the specified line
|
||||
if (lineIndex > 0)
|
||||
{
|
||||
// skip lines up to required
|
||||
int seekLine = 0;
|
||||
while (((line = reader.ReadLine()) != null) && ++seekLine < lineIndex)
|
||||
{
|
||||
// try to get field names
|
||||
ParseFieldNames();
|
||||
}
|
||||
|
||||
lastLineIndex = lineIndex;
|
||||
}
|
||||
}
|
||||
catch(Exception ex)
|
||||
{
|
||||
// can't open log file
|
||||
// skip it
|
||||
Log.WriteError(String.Format("An error occured while reading log file: {0}", logName), ex);
|
||||
}
|
||||
|
||||
fileIndex++; // increment files pointer
|
||||
}
|
||||
|
||||
// return if it was the last log file in the list
|
||||
if (reader == null)
|
||||
return false;
|
||||
|
||||
// assumed that log file is already opened
|
||||
// read next line
|
||||
line = reader.ReadLine();
|
||||
if (line == null)
|
||||
{
|
||||
// the most propbably current log file is finished
|
||||
// reset current reader
|
||||
reader.Close();
|
||||
reader = null;
|
||||
lineIndex = 0;
|
||||
|
||||
// try to open next reader and read the first line
|
||||
return Read();
|
||||
}
|
||||
|
||||
// increment line index
|
||||
lineIndex++;
|
||||
lastLineIndex = lineIndex;
|
||||
|
||||
// parse line
|
||||
if (!String.IsNullOrEmpty(line))
|
||||
{
|
||||
if (line[0] == '#')
|
||||
{
|
||||
ParseFieldNames();
|
||||
}
|
||||
else
|
||||
{
|
||||
ParseFieldValues();
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
errorLine = true;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
|
||||
private void ParseFieldNames()
|
||||
{
|
||||
systemLine = true;
|
||||
|
||||
if (!line.StartsWith(FIELDS_LINE))
|
||||
return;
|
||||
|
||||
fields = line.Substring(FIELDS_LINE_LENGTH).Trim().Split(FIELDS_SPLITTER);
|
||||
fieldsLength = fields.Length;
|
||||
}
|
||||
|
||||
protected virtual void ParseFieldValues()
|
||||
{
|
||||
// clear state
|
||||
errorLine = systemLine = false;
|
||||
|
||||
// clear values hash
|
||||
// record.Clear();
|
||||
|
||||
/*if (line[0] == '#')
|
||||
{
|
||||
// it is a system line
|
||||
// skip it and go ahead
|
||||
systemLine = true;
|
||||
return;
|
||||
}*/
|
||||
//
|
||||
fieldsValues = line.Split(FIELDS_SPLITTER, StringSplitOptions.None);
|
||||
// error line
|
||||
if (fieldsValues.Length != fieldsLength)
|
||||
errorLine = true;
|
||||
}
|
||||
|
||||
private void GetDirectoryFiles(DirectoryInfo root, ArrayList files)
|
||||
{
|
||||
// get the files in the current directory
|
||||
files.AddRange(root.GetFiles());
|
||||
|
||||
// scan subdirectories
|
||||
DirectoryInfo[] dirs = root.GetDirectories();
|
||||
foreach (DirectoryInfo dir in dirs)
|
||||
GetDirectoryFiles(dir, files);
|
||||
}
|
||||
|
||||
// provide read-only access to the current log line fields
|
||||
public string this[string field]
|
||||
{
|
||||
get
|
||||
{
|
||||
if (!errorLine && !systemLine)
|
||||
{
|
||||
// get field index in fields array
|
||||
int indexOf = Array.IndexOf(fields, field);
|
||||
// ensure field exists
|
||||
if (indexOf > -1)
|
||||
return fieldsValues[indexOf]; ;
|
||||
}
|
||||
// field not found or line is either system or error
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
public bool ErrorLine
|
||||
{
|
||||
get
|
||||
{
|
||||
return errorLine;
|
||||
}
|
||||
set
|
||||
{
|
||||
errorLine = value;
|
||||
}
|
||||
}
|
||||
|
||||
public bool SystemLine
|
||||
{
|
||||
get
|
||||
{
|
||||
return systemLine;
|
||||
}
|
||||
set
|
||||
{
|
||||
systemLine = value;
|
||||
}
|
||||
}
|
||||
|
||||
public long LogDate
|
||||
{
|
||||
get
|
||||
{
|
||||
return logDate;
|
||||
}
|
||||
}
|
||||
|
||||
public string LogName
|
||||
{
|
||||
get
|
||||
{
|
||||
return logName;
|
||||
}
|
||||
}
|
||||
|
||||
public string[] LineFields
|
||||
{
|
||||
get { return fields; }
|
||||
}
|
||||
|
||||
public string[] LineValues
|
||||
{
|
||||
get { return fieldsValues; }
|
||||
}
|
||||
|
||||
public string CurrentLine
|
||||
{
|
||||
get { return line; }
|
||||
}
|
||||
|
||||
public long LogLine
|
||||
{
|
||||
get
|
||||
{
|
||||
return lastLineIndex;
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
}
|
|
@ -0,0 +1,114 @@
|
|||
// Copyright (c) 2011, Outercurve Foundation.
|
||||
// All rights reserved.
|
||||
//
|
||||
// Redistribution and use in source and binary forms, with or without modification,
|
||||
// are permitted provided that the following conditions are met:
|
||||
//
|
||||
// - Redistributions of source code must retain the above copyright notice, this
|
||||
// list of conditions and the following disclaimer.
|
||||
//
|
||||
// - 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.
|
||||
//
|
||||
// - Neither the name of the Outercurve Foundation nor the names of its
|
||||
// contributors may be used to endorse or promote products derived from this
|
||||
// software without specific prior written permission.
|
||||
//
|
||||
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
|
||||
// ANY EXPRESS 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 COPYRIGHT HOLDER OR CONTRIBUTORS 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.
|
||||
|
||||
using System;
|
||||
using System.IO;
|
||||
using WebsitePanel.Server.Utils;
|
||||
|
||||
namespace WebsitePanel.Providers.Utils.LogParser
|
||||
{
|
||||
/// <summary>
|
||||
/// Summary description for WebSiteState.
|
||||
/// </summary>
|
||||
public class LogState
|
||||
{
|
||||
private long lastAccessed = 0;
|
||||
private long line = 0;
|
||||
private string siteFileName = null;
|
||||
|
||||
public LogState(string logName)
|
||||
{
|
||||
// make file name
|
||||
siteFileName = logName;
|
||||
|
||||
// open and parse site state file
|
||||
if(!File.Exists(siteFileName))
|
||||
return;
|
||||
|
||||
StreamReader reader = null;
|
||||
try
|
||||
{
|
||||
reader = new StreamReader(siteFileName);
|
||||
string s = null;
|
||||
|
||||
// last accesses time
|
||||
if((s = reader.ReadLine()) != null)
|
||||
lastAccessed = Int64.Parse(s.Trim());
|
||||
|
||||
// line
|
||||
if((s = reader.ReadLine()) != null)
|
||||
line = Int64.Parse(s.Trim());
|
||||
|
||||
reader.Close();
|
||||
|
||||
}
|
||||
catch(Exception ex)
|
||||
{
|
||||
Log.WriteError(ex);
|
||||
|
||||
}
|
||||
finally
|
||||
{
|
||||
if (reader != null)
|
||||
{
|
||||
reader.Dispose();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public void Save()
|
||||
{
|
||||
// create directory if required
|
||||
string dir = Path.GetDirectoryName(siteFileName);
|
||||
if(!Directory.Exists(dir))
|
||||
Directory.CreateDirectory(dir);
|
||||
|
||||
StreamWriter writer = new StreamWriter(siteFileName);
|
||||
// last accesses time
|
||||
writer.WriteLine(lastAccessed.ToString());
|
||||
|
||||
// line
|
||||
writer.WriteLine(line);
|
||||
|
||||
// close writer
|
||||
writer.Close();
|
||||
}
|
||||
|
||||
public long LastAccessed
|
||||
{
|
||||
get { return lastAccessed; }
|
||||
set { lastAccessed = value; }
|
||||
}
|
||||
|
||||
public long Line
|
||||
{
|
||||
get { return line; }
|
||||
set { line = value; }
|
||||
}
|
||||
}
|
||||
}
|
|
@ -0,0 +1,137 @@
|
|||
// Copyright (c) 2011, Outercurve Foundation.
|
||||
// All rights reserved.
|
||||
//
|
||||
// Redistribution and use in source and binary forms, with or without modification,
|
||||
// are permitted provided that the following conditions are met:
|
||||
//
|
||||
// - Redistributions of source code must retain the above copyright notice, this
|
||||
// list of conditions and the following disclaimer.
|
||||
//
|
||||
// - 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.
|
||||
//
|
||||
// - Neither the name of the Outercurve Foundation nor the names of its
|
||||
// contributors may be used to endorse or promote products derived from this
|
||||
// software without specific prior written permission.
|
||||
//
|
||||
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
|
||||
// ANY EXPRESS 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 COPYRIGHT HOLDER OR CONTRIBUTORS 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.
|
||||
|
||||
using System;
|
||||
using System.IO;
|
||||
using System.Collections;
|
||||
|
||||
namespace WebsitePanel.Providers.Utils.LogParser
|
||||
{
|
||||
/// <summary>
|
||||
/// Summary description for WebSiteStatistics.
|
||||
/// </summary>
|
||||
public class MonthlyStatistics
|
||||
{
|
||||
private string statsFile = null;
|
||||
private Hashtable days = new Hashtable();
|
||||
|
||||
|
||||
public MonthlyStatistics(string statsFile)
|
||||
{
|
||||
// save file name
|
||||
this.statsFile = statsFile;
|
||||
}
|
||||
|
||||
public MonthlyStatistics(string statsFile, bool load)
|
||||
{
|
||||
// save file name
|
||||
this.statsFile = statsFile;
|
||||
//
|
||||
if (load)
|
||||
{
|
||||
if (File.Exists(statsFile))
|
||||
{
|
||||
Load();
|
||||
}
|
||||
//else
|
||||
//{
|
||||
// throw new ArgumentException(String.Format("File with specified name doesn't exist: {0}", statsFile), "statsFile");
|
||||
//}
|
||||
}
|
||||
}
|
||||
|
||||
public StatsLine this[int day]
|
||||
{
|
||||
get { return (StatsLine)days[day]; }
|
||||
set { days[day] = value; }
|
||||
}
|
||||
|
||||
public Hashtable Days
|
||||
{
|
||||
get { return days; }
|
||||
}
|
||||
|
||||
private void Load()
|
||||
{
|
||||
//
|
||||
StreamReader reader = new StreamReader(statsFile);
|
||||
string line = null;
|
||||
while ((line = reader.ReadLine()) != null)
|
||||
{
|
||||
// parse line
|
||||
string[] columns = line.Split(new char[] { ' ' });
|
||||
int day = Int32.Parse(columns[0]);
|
||||
|
||||
// add new stats line to the hash
|
||||
StatsLine statsLine = new StatsLine();
|
||||
statsLine.BytesSent = Int64.Parse(columns[1]);
|
||||
statsLine.BytesReceived = Int64.Parse(columns[2]);
|
||||
|
||||
days.Add(day, statsLine);
|
||||
}
|
||||
reader.Close();
|
||||
}
|
||||
|
||||
public void Save()
|
||||
{
|
||||
Save(Path.GetDirectoryName(statsFile));
|
||||
}
|
||||
|
||||
public void Save(string dir)
|
||||
{
|
||||
// create directory if required
|
||||
//string dir = Path.GetDirectoryName(statsFile);
|
||||
if (!Directory.Exists(dir))
|
||||
Directory.CreateDirectory(dir);
|
||||
|
||||
StreamWriter writer = null;
|
||||
|
||||
try
|
||||
{
|
||||
writer = new StreamWriter(Path.Combine(dir, statsFile));
|
||||
|
||||
foreach (int day in days.Keys)
|
||||
{
|
||||
StatsLine statsLine = (StatsLine)days[day];
|
||||
|
||||
// write line
|
||||
writer.WriteLine("{0} {1} {2}", day, statsLine.BytesSent, statsLine.BytesReceived);
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
throw new Exception(String.Format("Can't open '{0}' log file", statsFile), ex);
|
||||
}
|
||||
finally
|
||||
{
|
||||
if (writer != null)
|
||||
writer.Close();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
|
@ -0,0 +1,41 @@
|
|||
// Copyright (c) 2011, Outercurve Foundation.
|
||||
// All rights reserved.
|
||||
//
|
||||
// Redistribution and use in source and binary forms, with or without modification,
|
||||
// are permitted provided that the following conditions are met:
|
||||
//
|
||||
// - Redistributions of source code must retain the above copyright notice, this
|
||||
// list of conditions and the following disclaimer.
|
||||
//
|
||||
// - 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.
|
||||
//
|
||||
// - Neither the name of the Outercurve Foundation nor the names of its
|
||||
// contributors may be used to endorse or promote products derived from this
|
||||
// software without specific prior written permission.
|
||||
//
|
||||
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
|
||||
// ANY EXPRESS 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 COPYRIGHT HOLDER OR CONTRIBUTORS 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.
|
||||
|
||||
using System;
|
||||
|
||||
namespace WebsitePanel.Providers.Utils.LogParser
|
||||
{
|
||||
/// <summary>
|
||||
/// Summary description for StatsLine.
|
||||
/// </summary>
|
||||
public class StatsLine
|
||||
{
|
||||
public long BytesReceived = 0;
|
||||
public long BytesSent = 0;
|
||||
}
|
||||
}
|
386
WebsitePanel/Sources/WebsitePanel.Server.Utils/OS.cs
Normal file
386
WebsitePanel/Sources/WebsitePanel.Server.Utils/OS.cs
Normal file
|
@ -0,0 +1,386 @@
|
|||
// Copyright (c) 2011, Outercurve Foundation.
|
||||
// All rights reserved.
|
||||
//
|
||||
// Redistribution and use in source and binary forms, with or without modification,
|
||||
// are permitted provided that the following conditions are met:
|
||||
//
|
||||
// - Redistributions of source code must retain the above copyright notice, this
|
||||
// list of conditions and the following disclaimer.
|
||||
//
|
||||
// - 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.
|
||||
//
|
||||
// - Neither the name of the Outercurve Foundation nor the names of its
|
||||
// contributors may be used to endorse or promote products derived from this
|
||||
// software without specific prior written permission.
|
||||
//
|
||||
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
|
||||
// ANY EXPRESS 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 COPYRIGHT HOLDER OR CONTRIBUTORS 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.
|
||||
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Text;
|
||||
using System.Runtime.InteropServices;
|
||||
|
||||
namespace WebsitePanel.Server.Utils
|
||||
{
|
||||
public sealed class OS
|
||||
{
|
||||
[StructLayout(LayoutKind.Sequential)]
|
||||
public struct OSVERSIONINFO
|
||||
{
|
||||
public Int32 dwOSVersionInfoSize;
|
||||
public Int32 dwMajorVersion;
|
||||
public Int32 dwMinorVersion;
|
||||
public Int32 dwBuildNumber;
|
||||
public Int32 dwPlatformID;
|
||||
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 128)]
|
||||
public string szCSDVersion;
|
||||
}
|
||||
[StructLayout(LayoutKind.Sequential)]
|
||||
public struct OSVERSIONINFOEX
|
||||
{
|
||||
public Int32 dwOSVersionInfoSize;
|
||||
public Int32 dwMajorVersion;
|
||||
public Int32 dwMinorVersion;
|
||||
public Int32 dwBuildNumber;
|
||||
public Int32 dwPlatformID;
|
||||
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 128)]
|
||||
public string szCSDVersion;
|
||||
public short wServicePackMajor;
|
||||
public short wServicePackMinor;
|
||||
public short wSuiteMask;
|
||||
public byte wProductType;
|
||||
public byte wReserved;
|
||||
}
|
||||
[StructLayout(LayoutKind.Sequential)]
|
||||
public struct SYSTEM_INFO
|
||||
{
|
||||
public Int32 dwOemID;
|
||||
public Int32 dwPageSize;
|
||||
public Int32 wProcessorArchitecture;
|
||||
public Int32 lpMinimumApplicationAddress;
|
||||
public Int32 lpMaximumApplicationAddress;
|
||||
public Int32 dwActiveProcessorMask;
|
||||
public Int32 dwNumberOrfProcessors;
|
||||
public Int32 dwProcessorType;
|
||||
public Int32 dwAllocationGranularity;
|
||||
public Int32 dwReserved;
|
||||
}
|
||||
public enum WinSuiteMask : int
|
||||
{
|
||||
VER_SUITE_SMALLBUSINESS = 1,
|
||||
VER_SUITE_ENTERPRISE = 2,
|
||||
VER_SUITE_BACKOFFICE = 4,
|
||||
VER_SUITE_COMMUNICATIONS = 8,
|
||||
VER_SUITE_TERMINAL = 16,
|
||||
VER_SUITE_SMALLBUSINESS_RESTRICTED = 32,
|
||||
VER_SUITE_EMBEDDEDNT = 64,
|
||||
VER_SUITE_DATACENTER = 128,
|
||||
VER_SUITE_SINGLEUSERTS = 256,
|
||||
VER_SUITE_PERSONAL = 512,
|
||||
VER_SUITE_BLADE = 1024,
|
||||
VER_SUITE_STORAGE_SERVER = 8192,
|
||||
VER_SUITE_COMPUTE_SERVER = 16384
|
||||
}
|
||||
public enum WinPlatform : byte
|
||||
{
|
||||
VER_NT_WORKSTATION = 1,
|
||||
VER_NT_DOMAIN_CONTROLLER = 2,
|
||||
VER_NT_SERVER = 3
|
||||
}
|
||||
public enum OSMajorVersion : byte
|
||||
{
|
||||
VER_OS_NT4 = 4,
|
||||
VER_OS_2K_XP_2K3 = 5,
|
||||
VER_OS_VISTA_LONGHORN = 6
|
||||
}
|
||||
|
||||
private const Int32 SM_SERVERR2 = 89;
|
||||
private const Int32 SM_MEDIACENTER = 87;
|
||||
private const Int32 SM_TABLETPC = 86;
|
||||
|
||||
[DllImport("kernel32")]
|
||||
private static extern int GetSystemInfo(ref SYSTEM_INFO lpSystemInfo);
|
||||
[DllImport("user32")]
|
||||
private static extern int GetSystemMetrics(int nIndex);
|
||||
[DllImport("kernel32", EntryPoint = "GetVersion")]
|
||||
private static extern int GetVersionAdv(ref OSVERSIONINFO lpVersionInformation);
|
||||
[DllImport("kernel32")]
|
||||
private static extern int GetVersionEx(ref OSVERSIONINFOEX lpVersionInformation);
|
||||
|
||||
|
||||
/*public static string GetVersionEx()
|
||||
{
|
||||
OSVERSIONINFO osvi = new OSVERSIONINFO();
|
||||
OSVERSIONINFOEX xosvi = new OSVERSIONINFOEX();
|
||||
Int32 iRet = 0;
|
||||
string strDetails = string.Empty;
|
||||
osvi.dwOSVersionInfoSize = Marshal.SizeOf(typeof(OSVERSIONINFO));
|
||||
xosvi.dwOSVersionInfoSize = Marshal.SizeOf(typeof(OSVERSIONINFOEX));
|
||||
try
|
||||
{
|
||||
iRet = (int)System.Environment.OSVersion.Platform;
|
||||
if (iRet == 1)
|
||||
{
|
||||
iRet = GetVersionAdv(ref osvi);
|
||||
strDetails = Environment.NewLine + "Version: " + osvi.dwMajorVersion + "." + osvi.dwMinorVersion + "." + osvi.dwBuildNumber + Environment.NewLine + osvi.szCSDVersion;
|
||||
if (Len(osvi) == 0)
|
||||
{
|
||||
return "Windows 95" + strDetails;
|
||||
}
|
||||
else if (Len(osvi) == 10)
|
||||
{
|
||||
return "Windows 98" + strDetails;
|
||||
}
|
||||
else if (Len(osvi) == 9)
|
||||
{
|
||||
return "Windows ME" + strDetails;
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
iRet = GetVersionEx(xosvi);
|
||||
strDetails = Environment.NewLine + "Version: " + xosvi.dwMajorVersion + "." + xosvi.dwMinorVersion + "." + xosvi.dwBuildNumber + Environment.NewLine + xosvi.szCSDVersion + " (" + xosvi.wServicePackMajor + "." + xosvi.wServicePackMinor + ")";
|
||||
if (xosvi.dwMajorVersion == (byte)OSMajorVersion.VER_OS_NT4)
|
||||
{
|
||||
return "Windows NT 4" + strDetails;
|
||||
}
|
||||
else if (xosvi.dwMajorVersion == OSMajorVersion.VER_OS_2K_XP_2K3)
|
||||
{
|
||||
if (xosvi.dwMinorVersion == 0)
|
||||
{
|
||||
if (xosvi.wProductType == WinPlatform.VER_NT_WORKSTATION)
|
||||
{
|
||||
return "Windows 2000 Pro" + strDetails;
|
||||
}
|
||||
else if (xosvi.wProductType == WinPlatform.VER_NT_SERVER)
|
||||
{
|
||||
if ((xosvi.wSuiteMask & WinSuiteMask.VER_SUITE_DATACENTER) == WinSuiteMask.VER_SUITE_DATACENTER)
|
||||
{
|
||||
return "Windows 2000 Datacenter Server" + strDetails;
|
||||
}
|
||||
else if ((xosvi.wSuiteMask & WinSuiteMask.VER_SUITE_ENTERPRISE) == WinSuiteMask.VER_SUITE_ENTERPRISE)
|
||||
{
|
||||
return "Windows 2000 Advanced Server" + strDetails;
|
||||
}
|
||||
else if ((xosvi.wSuiteMask & WinSuiteMask.VER_SUITE_SMALLBUSINESS) == WinSuiteMask.VER_SUITE_SMALLBUSINESS)
|
||||
{
|
||||
return "Windows 2000 Small Business Server" + strDetails;
|
||||
}
|
||||
else
|
||||
{
|
||||
return "Windows 2000 Server" + strDetails;
|
||||
}
|
||||
}
|
||||
else if (xosvi.wProductType == WinPlatform.VER_NT_DOMAIN_CONTROLLER)
|
||||
{
|
||||
if ((xosvi.wSuiteMask & WinSuiteMask.VER_SUITE_DATACENTER) == WinSuiteMask.VER_SUITE_DATACENTER)
|
||||
{
|
||||
return "Windows 2000 Datacenter Server Domain Controller" + strDetails;
|
||||
}
|
||||
else if ((xosvi.wSuiteMask & WinSuiteMask.VER_SUITE_ENTERPRISE) == WinSuiteMask.VER_SUITE_ENTERPRISE)
|
||||
{
|
||||
return "Windows 2000 Advanced Server Domain Controller" + strDetails;
|
||||
}
|
||||
else if ((xosvi.wSuiteMask & WinSuiteMask.VER_SUITE_SMALLBUSINESS) == WinSuiteMask.VER_SUITE_SMALLBUSINESS)
|
||||
{
|
||||
return "Windows 2000 Small Business Server Domain Controller" + strDetails;
|
||||
}
|
||||
else
|
||||
{
|
||||
return "Windows 2000 Server Domain Controller" + strDetails;
|
||||
}
|
||||
}
|
||||
}
|
||||
else if (xosvi.dwMinorVersion == 1)
|
||||
{
|
||||
if ((xosvi.wSuiteMask & WinSuiteMask.VER_SUITE_PERSONAL) == WinSuiteMask.VER_SUITE_PERSONAL)
|
||||
{
|
||||
return "Windows XP Home Edition" + strDetails;
|
||||
}
|
||||
else
|
||||
{
|
||||
return "Windows XP Professional Edition" + strDetails;
|
||||
}
|
||||
}
|
||||
else if (xosvi.dwMinorVersion == 2)
|
||||
{
|
||||
if (xosvi.wProductType == WinPlatform.VER_NT_WORKSTATION)
|
||||
{
|
||||
return "Windows XP Professional x64 Edition" + strDetails;
|
||||
}
|
||||
else if (xosvi.wProductType == WinPlatform.VER_NT_SERVER)
|
||||
{
|
||||
if (GetSystemMetrics(SM_SERVERR2) == 1)
|
||||
{
|
||||
return "Windows Server 2003 R2" + strDetails;
|
||||
}
|
||||
else
|
||||
{
|
||||
return "Windows Server 2003" + strDetails;
|
||||
}
|
||||
}
|
||||
else if (xosvi.wProductType == WinPlatform.VER_NT_DOMAIN_CONTROLLER)
|
||||
{
|
||||
if (GetSystemMetrics(SM_SERVERR2) == 1)
|
||||
{
|
||||
return "Windows Server 2003 R2 Domain Controller" + strDetails;
|
||||
}
|
||||
else
|
||||
{
|
||||
return "Windows Server 2003 Domain Controller" + strDetails;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
else if (xosvi.dwMajorVersion == OSMajorVersion.VER_OS_VISTA_LONGHORN)
|
||||
{
|
||||
if (xosvi.wProductType == WinPlatform.VER_NT_WORKSTATION)
|
||||
{
|
||||
if ((xosvi.wSuiteMask & WinSuiteMask.VER_SUITE_PERSONAL) == WinSuiteMask.VER_SUITE_PERSONAL)
|
||||
{
|
||||
return "Windows Vista (Home Premium, Home Basic, or Home Ultimate) Edition";
|
||||
}
|
||||
else
|
||||
{
|
||||
return "Windows Vista (Enterprize or Business)" + strDetails;
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
return "Windows Server (Longhorn)" + strDetails;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
catch
|
||||
{
|
||||
MessageBox.Show(GetLastError.ToString);
|
||||
return string.Empty;
|
||||
}
|
||||
}*/
|
||||
|
||||
public enum WindowsVersion
|
||||
{
|
||||
Unknown = 0,
|
||||
Windows95,
|
||||
Windows98,
|
||||
WindowsMe,
|
||||
WindowsNT351,
|
||||
WindowsNT4,
|
||||
Windows2000,
|
||||
WindowsXP,
|
||||
WindowsServer2003,
|
||||
Vista,
|
||||
WindowsServer2008
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Determine OS version
|
||||
/// </summary>
|
||||
/// <returns></returns>
|
||||
public static WindowsVersion GetVersion()
|
||||
{
|
||||
WindowsVersion ret = WindowsVersion.Unknown;
|
||||
|
||||
OSVERSIONINFOEX info = new OSVERSIONINFOEX();
|
||||
info.dwOSVersionInfoSize = Marshal.SizeOf(typeof(OSVERSIONINFOEX));
|
||||
GetVersionEx(ref info);
|
||||
|
||||
// Get OperatingSystem information from the system namespace.
|
||||
System.OperatingSystem osInfo = System.Environment.OSVersion;
|
||||
|
||||
// Determine the platform.
|
||||
switch (osInfo.Platform)
|
||||
{
|
||||
// Platform is Windows 95, Windows 98, Windows 98 Second Edition, or Windows Me.
|
||||
case System.PlatformID.Win32Windows:
|
||||
switch (osInfo.Version.Minor)
|
||||
{
|
||||
case 0:
|
||||
ret = WindowsVersion.Windows95;
|
||||
break;
|
||||
case 10:
|
||||
ret = WindowsVersion.Windows98;
|
||||
break;
|
||||
case 90:
|
||||
ret = WindowsVersion.WindowsMe;
|
||||
break;
|
||||
}
|
||||
break;
|
||||
|
||||
// Platform is Windows NT 3.51, Windows NT 4.0, Windows 2000, or Windows XP.
|
||||
case System.PlatformID.Win32NT:
|
||||
switch (osInfo.Version.Major)
|
||||
{
|
||||
case 3:
|
||||
ret = WindowsVersion.WindowsNT351;
|
||||
break;
|
||||
case 4:
|
||||
ret = WindowsVersion.WindowsNT4;
|
||||
break;
|
||||
case 5:
|
||||
switch (osInfo.Version.Minor)
|
||||
{
|
||||
case 0:
|
||||
ret = WindowsVersion.Windows2000;
|
||||
break;
|
||||
case 1:
|
||||
ret = WindowsVersion.WindowsXP;
|
||||
break;
|
||||
case 2:
|
||||
int i = GetSystemMetrics(SM_SERVERR2);
|
||||
if (i != 0)
|
||||
{
|
||||
//Server 2003 R2
|
||||
ret = WindowsVersion.WindowsServer2003;
|
||||
}
|
||||
else
|
||||
{
|
||||
if (info.wProductType == (byte)WinPlatform.VER_NT_WORKSTATION)
|
||||
{
|
||||
//XP Pro x64
|
||||
ret = WindowsVersion.WindowsXP;
|
||||
}
|
||||
else
|
||||
{
|
||||
ret = WindowsVersion.WindowsServer2003;
|
||||
}
|
||||
break;
|
||||
}
|
||||
break;
|
||||
}
|
||||
break;
|
||||
case 6:
|
||||
if (info.wProductType == (byte)WinPlatform.VER_NT_WORKSTATION)
|
||||
ret = WindowsVersion.Vista;
|
||||
else
|
||||
ret = WindowsVersion.WindowsServer2008;
|
||||
break;
|
||||
}
|
||||
break;
|
||||
}
|
||||
return ret;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Returns Windows directory
|
||||
/// </summary>
|
||||
/// <returns></returns>
|
||||
public static string GetWindowsDirectory()
|
||||
{
|
||||
return Environment.GetEnvironmentVariable("windir");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
246
WebsitePanel/Sources/WebsitePanel.Server.Utils/PInvoke.cs
Normal file
246
WebsitePanel/Sources/WebsitePanel.Server.Utils/PInvoke.cs
Normal file
|
@ -0,0 +1,246 @@
|
|||
// Copyright (c) 2011, Outercurve Foundation.
|
||||
// All rights reserved.
|
||||
//
|
||||
// Redistribution and use in source and binary forms, with or without modification,
|
||||
// are permitted provided that the following conditions are met:
|
||||
//
|
||||
// - Redistributions of source code must retain the above copyright notice, this
|
||||
// list of conditions and the following disclaimer.
|
||||
//
|
||||
// - 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.
|
||||
//
|
||||
// - Neither the name of the Outercurve Foundation nor the names of its
|
||||
// contributors may be used to endorse or promote products derived from this
|
||||
// software without specific prior written permission.
|
||||
//
|
||||
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
|
||||
// ANY EXPRESS 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 COPYRIGHT HOLDER OR CONTRIBUTORS 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.
|
||||
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Text;
|
||||
using System.Runtime.InteropServices;
|
||||
using Microsoft.Win32;
|
||||
|
||||
namespace WebsitePanel.Server.Utils
|
||||
{
|
||||
public class PInvoke
|
||||
{
|
||||
public static class RegistryHive
|
||||
{
|
||||
/// <summary>
|
||||
/// Implements common methods to manipulate on a registry section's sub keys and their values
|
||||
/// </summary>
|
||||
public class RegistryHiveSection
|
||||
{
|
||||
private UIntPtr HiveSection;
|
||||
|
||||
public RegistryHiveSection(UIntPtr hiveSection)
|
||||
{
|
||||
this.HiveSection = hiveSection;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Provide seamless dev experience bypassing Registry Redirector feature
|
||||
/// to test the registry hive for a key existence on x86/x64 platforms.
|
||||
/// </summary>
|
||||
/// <param name="name">Registry key path being tested</param>
|
||||
/// <returns></returns>
|
||||
private bool SubKeyExists(string name, int samDesired)
|
||||
{
|
||||
UIntPtr hSubKey;
|
||||
// Open key
|
||||
int result = PInvoke.RegOpenKeyEx(HiveSection, name, 0, samDesired, out hSubKey);
|
||||
// Close key
|
||||
PInvoke.RegCloseKey(hSubKey);
|
||||
//
|
||||
return (result == 0);
|
||||
}
|
||||
|
||||
private string GetSubKeyValue(string keyPath, string keyValue, int samDesired)
|
||||
{
|
||||
if (SubKeyExists(keyPath, samDesired))
|
||||
{
|
||||
UIntPtr hSubKey;
|
||||
uint size = 1024;
|
||||
uint type;
|
||||
string valueStr = null;
|
||||
StringBuilder keyBuffer = new StringBuilder(unchecked((int)size));
|
||||
// Open key
|
||||
if (PInvoke.RegOpenKeyEx(HiveSection, keyPath, 0, samDesired, out hSubKey) == 0)
|
||||
{
|
||||
try
|
||||
{
|
||||
//
|
||||
if (PInvoke.RegQueryValueEx(hSubKey, keyValue, 0, out type, keyBuffer, ref size) == 0)
|
||||
valueStr = keyBuffer.ToString();
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Log.WriteError(ex);
|
||||
}
|
||||
finally
|
||||
{
|
||||
// Close key
|
||||
PInvoke.RegCloseKey(hSubKey);
|
||||
}
|
||||
}
|
||||
|
||||
return (valueStr);
|
||||
}
|
||||
//
|
||||
return null;
|
||||
}
|
||||
|
||||
private int GetDwordSubKeyValue(string keyPath, string keyValue, int samDesired)
|
||||
{
|
||||
if (SubKeyExists(keyPath, samDesired))
|
||||
{
|
||||
UIntPtr hSubKey;
|
||||
uint size = 1024;
|
||||
// REG_DWORD
|
||||
uint type = (uint)4;
|
||||
//
|
||||
int valueInt = 0;
|
||||
// Open key
|
||||
if (PInvoke.RegOpenKeyEx(HiveSection, keyPath, 0, samDesired, out hSubKey) == 0)
|
||||
{
|
||||
try
|
||||
{
|
||||
//
|
||||
if (PInvoke.RegQueryValueEx(hSubKey, keyValue, 0, ref type, ref valueInt, ref size) == 0)
|
||||
return valueInt;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Log.WriteError(ex);
|
||||
}
|
||||
finally
|
||||
{
|
||||
// Close key
|
||||
PInvoke.RegCloseKey(hSubKey);
|
||||
}
|
||||
}
|
||||
//
|
||||
return (valueInt);
|
||||
}
|
||||
//
|
||||
return 0;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Provide seamless dev experience bypassing Registry Redirector feature
|
||||
/// to test the registry for a key existence beneath WOW6432Node on x64 platform (even for 64-bit ASP.NET app pool).
|
||||
/// Works seamlessly on x64 platform.
|
||||
/// </summary>
|
||||
/// <param name="name">Registry key path being tested</param>
|
||||
/// <returns></returns>
|
||||
public bool SubKeyExists_x86(string name)
|
||||
{
|
||||
return SubKeyExists(name, KEY_READ | KEY_WOW64_32KEY);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Provide seamless dev experience bypassing Registry Redirector feature
|
||||
/// to test the registry for a key existence beneath WOW6464Node on x64 platform (even for 32-bit ASP.NET app pool).
|
||||
/// Works seamlessly on x86 platform.
|
||||
/// </summary>
|
||||
/// <param name="name">Registry key path being tested</param>
|
||||
/// <returns></returns>
|
||||
public bool SubKeyExists_x64(string name)
|
||||
{
|
||||
return SubKeyExists(name, KEY_READ | KEY_WOW64_64KEY);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Provide seamless dev experience bypassing Registry Redirector feature
|
||||
/// to get registry key value beneath WOW6464Node on x64 platform (even for 32-bit ASP.NET app pool).
|
||||
/// Works seamlessly on x86 platform.
|
||||
/// </summary>
|
||||
/// <param name="keyPath">Registry key path being queried</param>
|
||||
/// <param name="keyValue">Registry key value name</param>
|
||||
/// <returns></returns>
|
||||
public int GetDwordSubKeyValue_x64(string keyPath, string keyValue)
|
||||
{
|
||||
return GetDwordSubKeyValue(keyPath, keyValue, KEY_READ | KEY_WOW64_64KEY);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Provide seamless dev experience bypassing Registry Redirector feature
|
||||
/// to get registry key value beneath WOW6464Node on x64 platform (even for 32-bit ASP.NET app pool).
|
||||
/// Works seamlessly on x86 platform.
|
||||
/// </summary>
|
||||
/// <param name="keyPath">Registry key path being queried</param>
|
||||
/// <param name="keyValue">Registry key value name</param>
|
||||
/// <returns></returns>
|
||||
public string GetSubKeyValue_x64(string keyPath, string keyValue)
|
||||
{
|
||||
return GetSubKeyValue(keyPath, keyValue, KEY_READ | KEY_WOW64_64KEY);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Provide seamless dev experience bypassing Registry Redirector feature
|
||||
/// to get registry key value beneath WOW6432Node section on x64 platform (even for 64-bit ASP.NET app pool).
|
||||
/// Works seamlessly on x86 platform.
|
||||
/// </summary>
|
||||
/// <param name="keyPath">Registry key path being queried</param>
|
||||
/// <param name="keyValue">Registry key value name</param>
|
||||
/// <returns></returns>
|
||||
public string GetSubKeyValue_x86(string keyPath, string keyValue)
|
||||
{
|
||||
return GetSubKeyValue(keyPath, keyValue, KEY_READ | KEY_WOW64_32KEY);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Provide seamless dev experience bypassing Registry Redirector feature
|
||||
/// to get registry key value beneath WOW6432Node section on x64 platform (even for 64-bit ASP.NET app pool).
|
||||
/// Works seamlessly on x86 platform.
|
||||
/// </summary>
|
||||
/// <param name="keyPath">Registry key path being queried</param>
|
||||
/// <param name="keyValue">Registry key value name</param>
|
||||
/// <returns></returns>
|
||||
public int GetDwordSubKeyValue_x86(string keyPath, string keyValue)
|
||||
{
|
||||
return GetDwordSubKeyValue(keyPath, keyValue, KEY_READ | KEY_WOW64_32KEY);
|
||||
}
|
||||
};
|
||||
|
||||
/// <summary>
|
||||
/// Represents HKEY_LOCAL_MACHINE section
|
||||
/// </summary>
|
||||
public static RegistryHiveSection HKLM = new RegistryHiveSection(PInvoke.HKEY_LOCAL_MACHINE);
|
||||
};
|
||||
|
||||
#region Wrappers definitions for Windows Native API functions
|
||||
|
||||
public static UIntPtr HKEY_LOCAL_MACHINE = new UIntPtr(0x80000002u);
|
||||
|
||||
public const int KEY_READ = 0x20019;
|
||||
public const int KEY_WOW64_32KEY = 0x0200;
|
||||
public const int KEY_WOW64_64KEY = 0x0100;
|
||||
|
||||
[DllImport("advapi32.dll", CharSet = CharSet.Auto)]
|
||||
public static extern int RegOpenKeyEx(UIntPtr hKey, string subKey, int ulOptions, int samDesired, out UIntPtr hkResult);
|
||||
|
||||
[DllImport("advapi32.dll", SetLastError = true)]
|
||||
public static extern int RegCloseKey(UIntPtr hKey);
|
||||
|
||||
[DllImport("advapi32.dll", CharSet = CharSet.Unicode, EntryPoint = "RegQueryValueExW", SetLastError = true)]
|
||||
static extern int RegQueryValueEx(UIntPtr hKey, [MarshalAs(UnmanagedType.LPWStr)]string lpValueName, int lpReserved, out uint lpType, [Optional] System.Text.StringBuilder lpData, ref uint lpcbData);
|
||||
|
||||
[DllImport("advapi32.dll", CharSet = CharSet.Unicode, EntryPoint = "RegQueryValueExW", SetLastError = true)]
|
||||
static extern int RegQueryValueEx(UIntPtr hKey, [MarshalAs(UnmanagedType.LPWStr)]string lpValueName, int lpReserved, ref uint lpType, [Optional] ref int lpData, ref uint lpcbData);
|
||||
|
||||
#endregion
|
||||
}
|
||||
}
|
|
@ -0,0 +1,20 @@
|
|||
using System.Reflection;
|
||||
using System.Runtime.CompilerServices;
|
||||
using System.Runtime.InteropServices;
|
||||
|
||||
// General Information about an assembly is controlled through the following
|
||||
// set of attributes. Change these attribute values to modify the information
|
||||
// associated with an assembly.
|
||||
[assembly: AssemblyTitle("WebsitePanel.Server.Utils")]
|
||||
[assembly: AssemblyDescription("")]
|
||||
[assembly: AssemblyProduct("WebsitePanel.Server.Utils")]
|
||||
[assembly: AssemblyTrademark("")]
|
||||
[assembly: AssemblyCulture("")]
|
||||
|
||||
// Setting ComVisible to false makes the types in this assembly not visible
|
||||
// to COM components. If you need to access a type in this assembly from
|
||||
// COM, set the ComVisible attribute to true on that type.
|
||||
[assembly: ComVisible(false)]
|
||||
|
||||
// The following GUID is for the ID of the typelib if this project is exposed to COM
|
||||
[assembly: Guid("776389ab-bec1-481e-b01d-b6ba13b24139")]
|
1700
WebsitePanel/Sources/WebsitePanel.Server.Utils/SecurityUtils.cs
Normal file
1700
WebsitePanel/Sources/WebsitePanel.Server.Utils/SecurityUtils.cs
Normal file
File diff suppressed because it is too large
Load diff
|
@ -0,0 +1,55 @@
|
|||
// Copyright (c) 2011, Outercurve Foundation.
|
||||
// All rights reserved.
|
||||
//
|
||||
// Redistribution and use in source and binary forms, with or without modification,
|
||||
// are permitted provided that the following conditions are met:
|
||||
//
|
||||
// - Redistributions of source code must retain the above copyright notice, this
|
||||
// list of conditions and the following disclaimer.
|
||||
//
|
||||
// - 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.
|
||||
//
|
||||
// - Neither the name of the Outercurve Foundation nor the names of its
|
||||
// contributors may be used to endorse or promote products derived from this
|
||||
// software without specific prior written permission.
|
||||
//
|
||||
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
|
||||
// ANY EXPRESS 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 COPYRIGHT HOLDER OR CONTRIBUTORS 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.
|
||||
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Text;
|
||||
using System.Text.RegularExpressions;
|
||||
|
||||
namespace WebsitePanel.Providers.Utils
|
||||
{
|
||||
public class StringUtils
|
||||
{
|
||||
public static string ReplaceStringVariable(string str, string variable, string value)
|
||||
{
|
||||
if (String.IsNullOrEmpty(str) || String.IsNullOrEmpty(value))
|
||||
return str;
|
||||
|
||||
Regex re = new Regex("\\[" + variable + "\\]+", RegexOptions.IgnoreCase);
|
||||
return re.Replace(str, value);
|
||||
}
|
||||
|
||||
public static string CleanIdentifier(string str)
|
||||
{
|
||||
if (String.IsNullOrEmpty(str))
|
||||
return str;
|
||||
|
||||
return Regex.Replace(str, "\\W+", "_", RegexOptions.Compiled);
|
||||
}
|
||||
}
|
||||
}
|
50
WebsitePanel/Sources/WebsitePanel.Server.Utils/SystemSID.cs
Normal file
50
WebsitePanel/Sources/WebsitePanel.Server.Utils/SystemSID.cs
Normal file
|
@ -0,0 +1,50 @@
|
|||
// Copyright (c) 2011, Outercurve Foundation.
|
||||
// All rights reserved.
|
||||
//
|
||||
// Redistribution and use in source and binary forms, with or without modification,
|
||||
// are permitted provided that the following conditions are met:
|
||||
//
|
||||
// - Redistributions of source code must retain the above copyright notice, this
|
||||
// list of conditions and the following disclaimer.
|
||||
//
|
||||
// - 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.
|
||||
//
|
||||
// - Neither the name of the Outercurve Foundation nor the names of its
|
||||
// contributors may be used to endorse or promote products derived from this
|
||||
// software without specific prior written permission.
|
||||
//
|
||||
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
|
||||
// ANY EXPRESS 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 COPYRIGHT HOLDER OR CONTRIBUTORS 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.
|
||||
|
||||
using System;
|
||||
|
||||
namespace WebsitePanel.Providers.Utils
|
||||
{
|
||||
/// <summary>
|
||||
/// Summary description for SystemSID.
|
||||
/// </summary>
|
||||
public class SystemSID
|
||||
{
|
||||
/// <summary>"Administrators" SID</summary>
|
||||
public const string ADMINISTRATORS = "S-1-5-32-544";
|
||||
|
||||
/// <summary>"Local System (SYSTEM)" SID</summary>
|
||||
public const string SYSTEM = "S-1-5-18";
|
||||
|
||||
/// <summary>"NETWORK SERVICE" SID</summary>
|
||||
public const string NETWORK_SERVICE = "S-1-5-20";
|
||||
|
||||
/// <summary>"LOCAL SERVICE" SID</summary>
|
||||
public const string LOCAL_SERVICE = "S-1-5-19";
|
||||
}
|
||||
}
|
|
@ -0,0 +1,123 @@
|
|||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<Project DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003" ToolsVersion="4.0">
|
||||
<PropertyGroup>
|
||||
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
|
||||
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
|
||||
<ProductVersion>9.0.30729</ProductVersion>
|
||||
<SchemaVersion>2.0</SchemaVersion>
|
||||
<ProjectGuid>{E91E52F3-9555-4D00-B577-2B1DBDD87CA7}</ProjectGuid>
|
||||
<OutputType>Library</OutputType>
|
||||
<AppDesignerFolder>Properties</AppDesignerFolder>
|
||||
<RootNamespace>WebsitePanel.Server.Utils</RootNamespace>
|
||||
<AssemblyName>WebsitePanel.Server.Utils</AssemblyName>
|
||||
<FileUpgradeFlags>
|
||||
</FileUpgradeFlags>
|
||||
<OldToolsVersion>3.5</OldToolsVersion>
|
||||
<UpgradeBackupLocation>
|
||||
</UpgradeBackupLocation>
|
||||
<TargetFrameworkVersion>v4.0</TargetFrameworkVersion>
|
||||
<PublishUrl>publish\</PublishUrl>
|
||||
<Install>true</Install>
|
||||
<InstallFrom>Disk</InstallFrom>
|
||||
<UpdateEnabled>false</UpdateEnabled>
|
||||
<UpdateMode>Foreground</UpdateMode>
|
||||
<UpdateInterval>7</UpdateInterval>
|
||||
<UpdateIntervalUnits>Days</UpdateIntervalUnits>
|
||||
<UpdatePeriodically>false</UpdatePeriodically>
|
||||
<UpdateRequired>false</UpdateRequired>
|
||||
<MapFileExtensions>true</MapFileExtensions>
|
||||
<ApplicationRevision>0</ApplicationRevision>
|
||||
<ApplicationVersion>1.0.0.%2a</ApplicationVersion>
|
||||
<IsWebBootstrapper>false</IsWebBootstrapper>
|
||||
<UseApplicationTrust>false</UseApplicationTrust>
|
||||
<BootstrapperEnabled>true</BootstrapperEnabled>
|
||||
<TargetFrameworkProfile />
|
||||
</PropertyGroup>
|
||||
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
|
||||
<DebugSymbols>true</DebugSymbols>
|
||||
<DebugType>full</DebugType>
|
||||
<Optimize>false</Optimize>
|
||||
<OutputPath>bin\Debug\</OutputPath>
|
||||
<DefineConstants>DEBUG;TRACE</DefineConstants>
|
||||
<ErrorReport>prompt</ErrorReport>
|
||||
<WarningLevel>4</WarningLevel>
|
||||
<CodeAnalysisRuleSet>AllRules.ruleset</CodeAnalysisRuleSet>
|
||||
<WarningsAsErrors>618</WarningsAsErrors>
|
||||
</PropertyGroup>
|
||||
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
|
||||
<DebugType>none</DebugType>
|
||||
<Optimize>true</Optimize>
|
||||
<OutputPath>bin\Release\</OutputPath>
|
||||
<DefineConstants>TRACE</DefineConstants>
|
||||
<ErrorReport>prompt</ErrorReport>
|
||||
<WarningLevel>4</WarningLevel>
|
||||
<CodeAnalysisRuleSet>AllRules.ruleset</CodeAnalysisRuleSet>
|
||||
<WarningsAsErrors>618</WarningsAsErrors>
|
||||
</PropertyGroup>
|
||||
<ItemGroup>
|
||||
<Reference Include="Ionic.Zip.Reduced, Version=1.8.4.28, Culture=neutral, PublicKeyToken=edbe51ad942a3f5c, processorArchitecture=MSIL">
|
||||
<SpecificVersion>False</SpecificVersion>
|
||||
<HintPath>..\..\Lib\Ionic.Zip.Reduced.dll</HintPath>
|
||||
</Reference>
|
||||
<Reference Include="System" />
|
||||
<Reference Include="System.Data" />
|
||||
<Reference Include="System.DirectoryServices" />
|
||||
<Reference Include="System.Management" />
|
||||
<Reference Include="System.Xml" />
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
<Compile Include="..\VersionInfo.cs">
|
||||
<Link>VersionInfo.cs</Link>
|
||||
</Compile>
|
||||
<Compile Include="BsdDES.cs" />
|
||||
<Compile Include="CRC32.cs" />
|
||||
<Compile Include="EventLogTraceListener.cs" />
|
||||
<Compile Include="FileUtils.cs" />
|
||||
<Compile Include="Log.cs" />
|
||||
<Compile Include="LogParser\LogParser.cs" />
|
||||
<Compile Include="LogParser\LogReader.cs" />
|
||||
<Compile Include="LogParser\LogState.cs" />
|
||||
<Compile Include="LogParser\MonthlyStatistics.cs" />
|
||||
<Compile Include="LogParser\StatsLine.cs" />
|
||||
<Compile Include="OS.cs" />
|
||||
<Compile Include="PInvoke.cs" />
|
||||
<Compile Include="Properties\AssemblyInfo.cs" />
|
||||
<Compile Include="SecurityUtils.cs">
|
||||
<SubType>Code</SubType>
|
||||
</Compile>
|
||||
<Compile Include="StringUtils.cs" />
|
||||
<Compile Include="SystemSID.cs" />
|
||||
<Compile Include="WmiHelper.cs" />
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\WebsitePanel.Providers.Base\WebsitePanel.Providers.Base.csproj">
|
||||
<Project>{684C932A-6C75-46AC-A327-F3689D89EB42}</Project>
|
||||
<Name>WebsitePanel.Providers.Base</Name>
|
||||
</ProjectReference>
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
<BootstrapperPackage Include="Microsoft.Net.Client.3.5">
|
||||
<Visible>False</Visible>
|
||||
<ProductName>.NET Framework 3.5 SP1 Client Profile</ProductName>
|
||||
<Install>false</Install>
|
||||
</BootstrapperPackage>
|
||||
<BootstrapperPackage Include="Microsoft.Net.Framework.3.5.SP1">
|
||||
<Visible>False</Visible>
|
||||
<ProductName>.NET Framework 3.5 SP1</ProductName>
|
||||
<Install>true</Install>
|
||||
</BootstrapperPackage>
|
||||
<BootstrapperPackage Include="Microsoft.Windows.Installer.3.1">
|
||||
<Visible>False</Visible>
|
||||
<ProductName>Windows Installer 3.1</ProductName>
|
||||
<Install>true</Install>
|
||||
</BootstrapperPackage>
|
||||
</ItemGroup>
|
||||
<Import Project="$(MSBuildBinPath)\Microsoft.CSharp.targets" />
|
||||
<!-- To modify your build process, add your task inside one of the targets below and uncomment it.
|
||||
Other similar extension points exist, see Microsoft.Common.targets.
|
||||
<Target Name="BeforeBuild">
|
||||
</Target>
|
||||
<Target Name="AfterBuild">
|
||||
</Target>
|
||||
-->
|
||||
</Project>
|
120
WebsitePanel/Sources/WebsitePanel.Server.Utils/WmiHelper.cs
Normal file
120
WebsitePanel/Sources/WebsitePanel.Server.Utils/WmiHelper.cs
Normal file
|
@ -0,0 +1,120 @@
|
|||
// Copyright (c) 2011, Outercurve Foundation.
|
||||
// All rights reserved.
|
||||
//
|
||||
// Redistribution and use in source and binary forms, with or without modification,
|
||||
// are permitted provided that the following conditions are met:
|
||||
//
|
||||
// - Redistributions of source code must retain the above copyright notice, this
|
||||
// list of conditions and the following disclaimer.
|
||||
//
|
||||
// - 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.
|
||||
//
|
||||
// - Neither the name of the Outercurve Foundation nor the names of its
|
||||
// contributors may be used to endorse or promote products derived from this
|
||||
// software without specific prior written permission.
|
||||
//
|
||||
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
|
||||
// ANY EXPRESS 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 COPYRIGHT HOLDER OR CONTRIBUTORS 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.
|
||||
|
||||
using System;
|
||||
using System.Management;
|
||||
|
||||
namespace WebsitePanel.Providers.Utils
|
||||
{
|
||||
/// <summary>
|
||||
/// Summary description for WmiHelper.
|
||||
/// </summary>
|
||||
public class WmiHelper
|
||||
{
|
||||
// namespace
|
||||
string ns = null;
|
||||
ManagementScope scope = null;
|
||||
|
||||
public WmiHelper(string ns)
|
||||
{
|
||||
this.ns = ns;
|
||||
}
|
||||
|
||||
public ManagementObjectCollection ExecuteQuery(string query)
|
||||
{
|
||||
ObjectQuery objectQuery = new ObjectQuery(query);
|
||||
|
||||
ManagementObjectSearcher searcher =
|
||||
new ManagementObjectSearcher(WmiScope, objectQuery);
|
||||
return searcher.Get();
|
||||
}
|
||||
|
||||
// execute wmi query with parameters (taken from internal class Wmi used in Hyper-V provider)
|
||||
public ManagementObjectCollection ExecuteWmiQuery(string query, params object[] args)
|
||||
{
|
||||
if (args != null && args.Length > 0)
|
||||
query = String.Format(query, args);
|
||||
|
||||
ManagementObjectSearcher searcher = new ManagementObjectSearcher(WmiScope, new ObjectQuery(query));
|
||||
return searcher.Get();
|
||||
}
|
||||
|
||||
//(taken from internal class Wmi used in Hyper-V provider)
|
||||
public ManagementObject GetWmiObject(string className)
|
||||
{
|
||||
return GetWmiObject(className, null);
|
||||
}
|
||||
|
||||
//(taken from internal class Wmi used in Hyper-V provider)
|
||||
public ManagementObjectCollection GetWmiObjects(string className, string filter, params object[] args)
|
||||
{
|
||||
string query = "select * from " + className;
|
||||
if (!String.IsNullOrEmpty(filter))
|
||||
query += " where " + filter;
|
||||
return ExecuteWmiQuery(query, args);
|
||||
}
|
||||
|
||||
//(taken from internal class Wmi used in Hyper-V provider)
|
||||
public ManagementObject GetWmiObject(string className, string filter, params object[] args)
|
||||
{
|
||||
ManagementObjectCollection col = GetWmiObjects(className, filter, args);
|
||||
ManagementObjectCollection.ManagementObjectEnumerator enumerator = col.GetEnumerator();
|
||||
return enumerator.MoveNext() ? (ManagementObject)enumerator.Current : null;
|
||||
}
|
||||
|
||||
public ManagementClass GetClass(string path)
|
||||
{
|
||||
return new ManagementClass(WmiScope, new ManagementPath(path), null);
|
||||
}
|
||||
|
||||
public ManagementObject GetObject(string path)
|
||||
{
|
||||
return new ManagementObject(WmiScope, new ManagementPath(path), null);
|
||||
}
|
||||
|
||||
private ManagementScope WmiScope
|
||||
{
|
||||
get
|
||||
{
|
||||
if (scope == null)
|
||||
{
|
||||
ManagementPath path = new ManagementPath(ns);
|
||||
scope = new ManagementScope(path, new ConnectionOptions());
|
||||
scope.Connect();
|
||||
}
|
||||
return scope;
|
||||
}
|
||||
}
|
||||
|
||||
public ManagementObject CreateInstance(string path)
|
||||
{
|
||||
ManagementClass objClass = GetClass(path);
|
||||
return objClass.CreateInstance();
|
||||
}
|
||||
}
|
||||
}
|
Loading…
Add table
Add a link
Reference in a new issue