Beispiel #1
0
        //Send chunked response
        private static void WriteResponseBodyChunked(CustomBinaryReader inStreamReader, Stream outStream)
        {
            while (true)
            {
                var chuchkHead = inStreamReader.ReadLine();
                var chunkSize  = int.Parse(chuchkHead, NumberStyles.HexNumber);

                if (chunkSize != 0)
                {
                    var buffer = inStreamReader.ReadBytes(chunkSize);

                    var chunkHead = Encoding.ASCII.GetBytes(chunkSize.ToString("x2"));

                    outStream.Write(chunkHead, 0, chunkHead.Length);
                    outStream.Write(NewLineBytes, 0, NewLineBytes.Length);

                    outStream.Write(buffer, 0, chunkSize);
                    outStream.Write(NewLineBytes, 0, NewLineBytes.Length);

                    inStreamReader.ReadLine();
                }
                else
                {
                    inStreamReader.ReadLine();
                    outStream.Write(ChunkEnd, 0, ChunkEnd.Length);
                    break;
                }
            }
        }
Beispiel #2
0
 public void Read(CustomBinaryReader reader)
 {
     Size           = reader.ReadUInt32();
     _startPosition = reader.Position;
     ID             = reader.ReadUInt32();
     ReadData(reader);
 }
 private void DoResponse(ushort code, byte[] postbytes, IProtocol data)
 {
     object[] args = new object[] { code, data.GetType().FullName };
     Debugger.Log(Utils.FormatString("静默处理 code:{0} class:{1}", args));
     switch (code)
     {
     case 7:
     {
         Debugger.Log("宝箱开启缓存请求 静默处理");
         CustomBinaryReader reader = new CustomBinaryReader(new MemoryStream(postbytes));
         byte   num  = reader.ReadByte();
         ushort num2 = reader.ReadUInt16();
         ushort num3 = reader.ReadUInt16();
         if (num2 == code)
         {
             IProtocol protocol = this.CreateProtocol(code, reader);
             if (protocol != null)
             {
                 protocol.ReadFromStream(reader);
                 CReqItemPacket packet    = protocol as CReqItemPacket;
                 object[]       objArray2 = new object[] { packet.m_nCoinAmount, packet.m_nExperince, packet.arrayEquipItems.Length };
                 Debugger.Log(Utils.FormatString("金币:{0} 经验:{1} 装备数量:{2}", objArray2));
                 for (int i = 0; i < packet.arrayEquipItems.Length; i++)
                 {
                     object[] objArray3 = new object[] { i, packet.arrayEquipItems[i].m_nEquipID, packet.arrayEquipItems[i].m_nFragment };
                     Debugger.Log(Utils.FormatString("装备[{0}] id:{1} count:{2}", objArray3));
                 }
             }
         }
         break;
     }
     }
 }
    private IProtocol CreateProtocol(ushort code, CustomBinaryReader reader)
    {
        switch (code)
        {
        case 4:
            return(new CRespMailList());

        case 7:
        case 11:
        case 0x12:
            return(new CRespItemPacket());

        case 8:
            return(new CRespUserLoginPacket());

        case 10:
            return(new CRespDimaonToCoin());

        case 15:
            return(new CRespInAppPurchase());

        case 0x11:
            return(new CRespFirstRewardInfo());
        }
        return(null);
    }
Beispiel #5
0
        /// <summary>
        /// copies the specified bytes to the stream from the input stream
        /// </summary>
        /// <param name="streamReader"></param>
        /// <param name="stream"></param>
        /// <param name="totalBytesToRead"></param>
        /// <returns></returns>
        internal static async Task CopyBytesToStream(this CustomBinaryReader streamReader, Stream stream, long totalBytesToRead)
        {
            var  buffer         = streamReader.Buffer;
            long remainingBytes = totalBytesToRead;

            while (remainingBytes > 0)
            {
                int bytesToRead = buffer.Length;
                if (remainingBytes < bytesToRead)
                {
                    bytesToRead = (int)remainingBytes;
                }

                int bytesRead = await streamReader.ReadBytesAsync(buffer, bytesToRead);

                if (bytesRead == 0)
                {
                    break;
                }

                remainingBytes -= bytesRead;

                await stream.WriteAsync(buffer, 0, bytesRead);
            }
        }
        internal static async Task CopyBytesToStream(this CustomBinaryReader streamReader, Stream stream, long totalBytesToRead)
        {
            var totalbytesRead = 0;

            long bytesToRead;

            if (totalBytesToRead < Constants.BUFFER_SIZE)
            {
                bytesToRead = totalBytesToRead;
            }
            else
            {
                bytesToRead = Constants.BUFFER_SIZE;
            }


            while (totalbytesRead < totalBytesToRead)
            {
                var buffer = await streamReader.ReadBytesAsync(bytesToRead);

                if (buffer.Length == 0)
                {
                    break;
                }

                totalbytesRead += buffer.Length;

                var remainingBytes = totalBytesToRead - totalbytesRead;
                if (remainingBytes < bytesToRead)
                {
                    bytesToRead = remainingBytes;
                }
                await stream.WriteAsync(buffer, 0, buffer.Length);
            }
        }
        /// <summary>
        /// copies the specified bytes to the stream from the input stream
        /// </summary>
        /// <param name="streamReader"></param>
        /// <param name="bufferSize"></param>
        /// <param name="stream"></param>
        /// <param name="totalBytesToRead"></param>
        /// <returns></returns>
        internal static async Task CopyBytesToStream(this CustomBinaryReader streamReader, int bufferSize, Stream stream, long totalBytesToRead)
        {
            var totalbytesRead = 0;

            long bytesToRead = totalBytesToRead < bufferSize ? totalBytesToRead : bufferSize;

            while (totalbytesRead < totalBytesToRead)
            {
                var buffer = await streamReader.ReadBytesAsync(bufferSize, bytesToRead);

                if (buffer.Length == 0)
                {
                    break;
                }

                totalbytesRead += buffer.Length;

                var remainingBytes = totalBytesToRead - totalbytesRead;
                if (remainingBytes < bytesToRead)
                {
                    bytesToRead = remainingBytes;
                }

                await stream.WriteAsync(buffer, 0, buffer.Length);
            }
        }
        //Send chunked response
        private static async Task WriteResponseBodyChunked(CustomBinaryReader inStreamReader, Stream outStream)
        {
            while (true)
            {
                var chunkHead = await inStreamReader.ReadLineAsync().ConfigureAwait(false);

                var chunkSize = int.Parse(chunkHead, NumberStyles.HexNumber);

                if (chunkSize != 0)
                {
                    var buffer = await inStreamReader.ReadBytesAsync(chunkSize).ConfigureAwait(false);

                    var chunkHeadBytes = Encoding.ASCII.GetBytes(chunkSize.ToString("x2"));

                    await outStream.WriteAsync(chunkHeadBytes, 0, chunkHeadBytes.Length).ConfigureAwait(false);

                    await outStream.WriteAsync(Constants.NewLineBytes, 0, Constants.NewLineBytes.Length).ConfigureAwait(false);

                    await outStream.WriteAsync(buffer, 0, chunkSize).ConfigureAwait(false);

                    await outStream.WriteAsync(Constants.NewLineBytes, 0, Constants.NewLineBytes.Length).ConfigureAwait(false);

                    await inStreamReader.ReadLineAsync().ConfigureAwait(false);
                }
                else
                {
                    await inStreamReader.ReadLineAsync().ConfigureAwait(false);

                    await outStream.WriteAsync(Constants.ChunkEnd, 0, Constants.ChunkEnd.Length).ConfigureAwait(false);

                    break;
                }
            }
        }
        internal static async Task CopyBytesToStreamChunked(this CustomBinaryReader clientStreamReader, Stream stream)
        {
            while (true)
            {
                var chuchkHead = await clientStreamReader.ReadLineAsync().ConfigureAwait(false);

                var chunkSize = int.Parse(chuchkHead, NumberStyles.HexNumber);

                if (chunkSize != 0)
                {
                    var buffer = await clientStreamReader.ReadBytesAsync(chunkSize);

                    await stream.WriteAsync(buffer, 0, buffer.Length);

                    //chunk trail
                    await clientStreamReader.ReadLineAsync().ConfigureAwait(false);
                }
                else
                {
                    await clientStreamReader.ReadLineAsync().ConfigureAwait(false);

                    break;
                }
            }
        }
Beispiel #10
0
        /// <summary>
        /// Handle dispose of a client/server session
        /// </summary>
        /// <param name="tcpClient"></param>
        /// <param name="clientStream"></param>
        /// <param name="clientStreamReader"></param>
        /// <param name="clientStreamWriter"></param>
        /// <param name="args"></param>
        private void Dispose(Stream clientStream, CustomBinaryReader clientStreamReader,
                             StreamWriter clientStreamWriter, IDisposable args)
        {
            if (clientStream != null)
            {
                clientStream.Close();
                clientStream.Dispose();
            }

            if (args != null)
            {
                args.Dispose();
            }

            if (clientStreamReader != null)
            {
                clientStreamReader.Dispose();
            }

            if (clientStreamWriter != null)
            {
                clientStreamWriter.Close();
                clientStreamWriter.Dispose();
            }
        }
Beispiel #11
0
 public void Read(CustomBinaryReader reader)
 {
     id = reader.ReadUInt32();
     changeOccursWhen = reader.ReadByte();
     numberOfStates   = reader.ReadUInt16();
     states           = reader.ReadMany((r) => new CustomSettingsState(r), numberOfStates);
 }
        /// <summary>
        /// Copies the streams chunked
        /// </summary>
        /// <param name="inStreamReader"></param>
        /// <param name="outStream"></param>
        /// <returns></returns>
        internal static async Task WriteResponseBodyChunked(this CustomBinaryReader inStreamReader, Stream outStream)
        {
            while (true)
            {
                var chunkHead = await inStreamReader.ReadLineAsync();

                var chunkSize = int.Parse(chunkHead, NumberStyles.HexNumber);

                if (chunkSize != 0)
                {
                    var chunkHeadBytes = Encoding.ASCII.GetBytes(chunkSize.ToString("x2"));
                    await outStream.WriteAsync(chunkHeadBytes, 0, chunkHeadBytes.Length);

                    await outStream.WriteAsync(ProxyConstants.NewLineBytes, 0, ProxyConstants.NewLineBytes.Length);

                    await CopyBytesToStream(inStreamReader, outStream, chunkSize);

                    await outStream.WriteAsync(ProxyConstants.NewLineBytes, 0, ProxyConstants.NewLineBytes.Length);

                    await inStreamReader.ReadLineAsync();
                }
                else
                {
                    await inStreamReader.ReadLineAsync();

                    await outStream.WriteAsync(ProxyConstants.ChunkEnd, 0, ProxyConstants.ChunkEnd.Length);

                    break;
                }
            }
        }
        protected override void DoOpen()
        {
            using (CustomBinaryReader reader = new CustomBinaryReader(new FileStream(ArchivePath, FileMode.Open, FileAccess.Read)))
            {
                uint signature = reader.ReadUInt32();
                if (signature != 0x58445442)
                {
                    throw new InvalidDataException("File is not BA2");
                }

                version = reader.ReadUInt32();
                if (version > 1)
                {
                    throw new InvalidDataException("Unsupported archive file version: " + version);
                }

                type = (ArchiveType)reader.ReadUInt32();
                if (type != ArchiveType.General)
                {
                    Log.Fine("Skipping archive file which is not the general purpose type.");
                    return;
                }

                long baseOffset          = reader.BaseStream.Position;
                uint fileCount           = reader.ReadUInt32();
                long fileNameTableOffset = reader.ReadInt64();

                FileInfo[] files = new FileInfo[fileCount];
                for (int i = 0; i < fileCount; i++)
                {
                    files[i] = new FileInfo()
                    {
                        NameHash             = reader.ReadUInt32(),
                        Type                 = reader.ReadUInt32(),
                        DirectoryNameHash    = reader.ReadUInt32(),
                        Unknown1             = reader.ReadUInt32(),
                        DataOffset           = reader.ReadInt64(),
                        DataCompressedSize   = reader.ReadUInt32(),
                        DataUncompressedSize = reader.ReadUInt32(),
                        Unknown2             = reader.ReadUInt32()
                    };
                }

                reader.BaseStream.Position = fileNameTableOffset;
                for (int i = 0; i < fileCount; i++)
                {
                    ushort length = reader.ReadUInt16();
                    string path   = reader.ReadStringFixedLength(length).ToLower();

                    string dir      = Path.GetDirectoryName(path).ToLower();
                    string filename = Path.GetFileName(path).ToLower();
                    if (!sorted.ContainsKey(dir))
                    {
                        sorted.Add(dir, new SortedDictionary <string, FileInfo>());
                    }
                    sorted[dir].Add(filename, files[i]);
                }
            }
        }
Beispiel #14
0
        /// <summary>
        /// Десериализует процесс
        /// </summary>
        /// <param name="br">Читатель из потока</param>
        protected virtual void DeserializeInternal(CustomBinaryReader br)
        {
            this.CompleteExecution = br.ReadBoolean();
            this.Id = br.ReadGuid();
            this.PopulateExceptions = br.ReadBoolean();
            this.Stage           = (BpStage)br.ReadByte();
            this.StartedOnServer = br.ReadNullableBoolean();
            this._status         = (BpStatus)br.ReadByte();
            this.TrackMode       = (BpTrackMode)br.ReadByte();
            this.StartTime       = br.ReadDateTime();
            this.FinishTime      = br.ReadDateTime();

            if (br.ReadBoolean())
            {
                this._contextData = new ContextData();
                this._contextData.DeserializeInternal(br);
            }

            int           count      = br.Read7BitEncodedInt();
            List <string> paramNames = new List <string>(count);

            this.Parameters = new Dictionary <string, object>(count);
            for (int i = 0; i < count; i++)
            {
                paramNames.Add(br.ReadString());
            }
            for (int i = 0; i < count; i++)
            {
                this.Parameters.Add(paramNames[i], br.ReadObject());
            }

            //this.Progress = (BpProgressData)br.ReadObject();
            //this.Result = (BpResultData)br.ReadObject();

            if (br.ReadBoolean())
            {
                this.Progress = this.GetProgressInstance();
                ((ICustomSerializable)this.Progress).DeserializeInternal(br);
            }

            if (br.ReadBoolean())
            {
                this.Result = this.GetResultInstance();
                ((ICustomSerializable)this.Result).DeserializeInternal(br);
            }

            count = br.Read7BitEncodedInt();
            this.ChildProcesses = new List <BizProcess>(count);
            for (int i = 0; i < count; i++)
            {
                BizProcess process = this.ReadChildProcess(br);
                this.AddChild(process);
            }

            BpRunningNode.Type brnType = (BpRunningNode.Type)br.ReadByte();
            string             brnName = br.ReadString();

            this.Node = new BpRunningNode(brnType, brnName);
        }
Beispiel #15
0
 public override void Read(CustomBinaryReader reader, bool readData = true)
 {
     base.Read(reader, false);
     if (readData)
     {
         ReadData(reader);
     }
 }
Beispiel #16
0
        //This is called when this proxy acts as a reverse proxy (like a real http server)
        //So for HTTPS requests we would start SSL negotiation right away without expecting a CONNECT request from client
        private async Task HandleClient(TransparentProxyEndPoint endPoint, TcpClient tcpClient)
        {
            Stream clientStream = tcpClient.GetStream();

            clientStream.ReadTimeout  = ConnectionTimeOutSeconds * 1000;
            clientStream.WriteTimeout = ConnectionTimeOutSeconds * 1000;

            CustomBinaryReader clientStreamReader = null;
            StreamWriter       clientStreamWriter = null;
            X509Certificate2   certificate        = null;

            if (endPoint.EnableSsl)
            {
                var sslStream = new SslStream(clientStream, true);

                //implement in future once SNI supported by SSL stream, for now use the same certificate
                certificate = certificateCacheManager.CreateCertificate(endPoint.GenericCertificateName, false);

                try
                {
                    //Successfully managed to authenticate the client using the fake certificate
                    await sslStream.AuthenticateAsServerAsync(certificate, false,
                                                              SslProtocols.Tls, false);

                    clientStreamReader = new CustomBinaryReader(sslStream);
                    clientStreamWriter = new StreamWriter(sslStream)
                    {
                        NewLine = ProxyConstants.NewLine
                    };
                    //HTTPS server created - we can now decrypt the client's traffic
                }
                catch (Exception)
                {
                    sslStream.Dispose();

                    Dispose(sslStream, clientStreamReader, clientStreamWriter, null);
                    return;
                }
                clientStream = sslStream;
            }
            else
            {
                clientStreamReader = new CustomBinaryReader(clientStream);
                clientStreamWriter = new StreamWriter(clientStream)
                {
                    NewLine = ProxyConstants.NewLine
                };
            }

            //now read the request line
            var httpCmd = await clientStreamReader.ReadLineAsync();

            //Now create the request
            await HandleHttpSessionRequest(tcpClient, httpCmd, clientStream, clientStreamReader, clientStreamWriter,
                                           endPoint.EnableSsl?endPoint.GenericCertificateName : null, endPoint, null);
        }
Beispiel #17
0
 public void Read(CustomBinaryReader reader)
 {
     gameParameterID = reader.ReadUInt32();
     yType           = reader.ReadUInt32();
     unknownID       = reader.ReadUInt32();
     //_unknown = reader.ReadByte();
     numPoints = reader.ReadByte();
     _unknown2 = reader.ReadByte();
     points    = reader.ReadMany((r) => new Point(r), (ulong)numPoints);
 }
Beispiel #18
0
        internal static async Task ReadHeaders(CustomBinaryReader reader, HeaderCollection headerCollection)
        {
            string tmpLine;

            while (!string.IsNullOrEmpty(tmpLine = await reader.ReadLineAsync()))
            {
                var header = tmpLine.Split(ProxyConstants.ColonSplit, 2);
                headerCollection.AddHeader(header[0], header[1]);
            }
        }
Beispiel #19
0
 /// <summary>
 /// Десериализует процесс
 /// </summary>
 protected BizProcess(SerializationInfo info, StreamingContext context)
 {
     using (MemoryStream ms = new MemoryStream((byte[])info.GetValue("_", typeof(byte[]))))
     {
         using (CustomBinaryReader br = new CustomBinaryReader(ms))
         {
             this.DeserializeInternal(br);
         }
     }
 }
Beispiel #20
0
 // TODO: Populate Offset
 public virtual void Read(CustomBinaryReader reader, bool readData = true)
 {
     Size           = reader.ReadUInt32();
     _startPosition = reader.Position;
     ID             = reader.ReadUInt32();
     if (readData)
     {
         ReadData(reader);
     }
 }
Beispiel #21
0
        public void Read(CustomBinaryReader reader)
        {
            header     = reader.ReadBytes(4);
            headerName = Encoding.UTF8.GetString(header);
            size       = reader.ReadUInt32();
            long _startPosition = reader.Position;

            count   = reader.ReadInt32();
            objects = new List <HIRCObject>();
            long offset = reader.Position;

            for (int i = 0; i < count; i++)
            {
                byte       objType = reader.ReadByte();
                HIRCObject tmp;
                switch (objType)
                {
                case HIRCObject.TYPE_SOUNDSFXVOICE:
                    tmp = new SFXHIRCObject(reader, objType);
                    break;

                case HIRCObject.TYPE_EVENT:
                    tmp = new EventHIRCObject(reader, objType);
                    break;

                case HIRCObject.TYPE_MUSICSEGMENT:
                    tmp = new MusicSegmentHIRCObject(reader, objType);
                    break;

                case HIRCObject.TYPE_MUSICTRACK:
                    tmp = new MusicTrackHIRCObject(reader, objType);
                    break;

                case HIRCObject.TYPE_MUSICSWITCHCONTAINER:
                    tmp = new MusicSwitchContainerHIRCObject(reader, objType);
                    //tmp = new HIRCObject(reader, objType);
                    //File.WriteAllBytes("tempSwitchContainer.dat", tmp.Data);
                    break;

                default:
                    tmp = new HIRCObject(reader, objType);
                    break;
                }
                tmp.Offset = offset.ToString("X");
                offset     = reader.Position;
                objects.Add(tmp);
            }
            // Double check!
            if (size - (reader.Position - _startPosition) != 0)
            {
                Console.WriteLine("Incorrect IO!");
            }
        }
        /// <summary>
        ///  Handle dispose of a client/server session
        /// </summary>
        /// <param name="clientStream"></param>
        /// <param name="clientStreamReader"></param>
        /// <param name="clientStreamWriter"></param>
        /// <param name="serverConnection"></param>
        private void Dispose(CustomBufferedStream clientStream, CustomBinaryReader clientStreamReader, HttpResponseWriter clientStreamWriter, TcpConnection serverConnection)
        {
            clientStream?.Dispose();

            clientStreamReader?.Dispose();
            clientStreamWriter?.Dispose();

            if (serverConnection != null)
            {
                serverConnection.Dispose();
                UpdateServerConnectionCount(false);
            }
        }
Beispiel #23
0
 public override void Read(CustomBinaryReader reader, bool readData = true)
 {
     base.Read(reader, false);
     _unknown  = reader.ReadUInt32();
     State     = reader.ReadUInt32();
     IDAudio   = reader.ReadUInt32();
     IDSource  = reader.ReadUInt32();
     SoundType = reader.ReadByte();
     if (readData)
     {
         ReadData(reader);
     }
 }
Beispiel #24
0
        //This is called when requests are routed through router to this endpoint
        //For ssl requests
        private static void HandleClient(TransparentProxyEndPoint endPoint, TcpClient tcpClient)
        {
            Stream             clientStream       = tcpClient.GetStream();
            CustomBinaryReader clientStreamReader = null;
            StreamWriter       clientStreamWriter = null;
            X509Certificate2   certificate        = null;

            if (endPoint.EnableSsl)
            {
                var sslStream = new SslStream(clientStream, true);
                //if(endPoint.UseServerNameIndication)
                //{
                //   //implement in future once SNI supported by SSL stream
                //    certificate = CertManager.CreateCertificate(endPoint.GenericCertificateName);
                //}
                //else
                certificate = CertManager.CreateCertificate(endPoint.GenericCertificateName);

                try
                {
                    //Successfully managed to authenticate the client using the fake certificate
                    sslStream.AuthenticateAsServer(certificate, false,
                                                   SslProtocols.Tls, false);

                    clientStreamReader = new CustomBinaryReader(sslStream, Encoding.ASCII);
                    clientStreamWriter = new StreamWriter(sslStream);
                    //HTTPS server created - we can now decrypt the client's traffic
                }
                catch (Exception)
                {
                    if (sslStream != null)
                    {
                        sslStream.Dispose();
                    }

                    Dispose(tcpClient, sslStream, clientStreamReader, clientStreamWriter, null);
                    return;
                }
                clientStream = sslStream;
            }
            else
            {
                clientStreamReader = new CustomBinaryReader(clientStream, Encoding.ASCII);
            }

            var httpCmd = clientStreamReader.ReadLine();

            //Now create the request
            HandleHttpSessionRequest(tcpClient, httpCmd, clientStream, clientStreamReader, clientStreamWriter,
                                     true);
        }
Beispiel #25
0
 public override void Read(CustomBinaryReader reader, bool readData = true)
 {
     base.Read(reader, false);
     //EventCount = reader.ReadInt32();
     //EventIDs = new List<int>();
     //for (int i = 0; i < EventCount; i++)
     //{
     //    EventIDs.Add(reader.ReadInt32());
     //}
     if (readData)
     {
         ReadData(reader);
     }
 }
Beispiel #26
0
        /// <summary>
        /// This is called when this proxy acts as a reverse proxy (like a real http server)
        /// So for HTTPS requests we would start SSL negotiation right away without expecting a CONNECT request from client
        /// </summary>
        /// <param name="endPoint"></param>
        /// <param name="tcpClient"></param>
        /// <returns></returns>
        private async Task HandleClient(TransparentProxyEndPoint endPoint, TcpClient tcpClient)
        {
            bool disposed     = false;
            var  clientStream = new CustomBufferedStream(tcpClient.GetStream(), BufferSize);

            CustomBinaryReader clientStreamReader = null;
            HttpResponseWriter clientStreamWriter = null;

            try
            {
                if (endPoint.EnableSsl)
                {
                    var clientHelloInfo = await SslTools.PeekClientHello(clientStream);

                    if (clientHelloInfo != null)
                    {
                        var sslStream = new SslStream(clientStream);
                        clientStream = new CustomBufferedStream(sslStream, BufferSize);

                        string sniHostName = clientHelloInfo.GetServerName();

                        string certName    = HttpHelper.GetWildCardDomainName(sniHostName ?? endPoint.GenericCertificateName);
                        var    certificate = CertificateManager.CreateCertificate(certName, false);

                        //Successfully managed to authenticate the client using the fake certificate
                        await sslStream.AuthenticateAsServerAsync(certificate, false, SslProtocols.Tls, false);
                    }

                    //HTTPS server created - we can now decrypt the client's traffic
                }

                clientStreamReader = new CustomBinaryReader(clientStream, BufferSize);
                clientStreamWriter = new HttpResponseWriter(clientStream, BufferSize);

                //now read the request line
                string httpCmd = await clientStreamReader.ReadLineAsync();

                //Now create the request
                disposed = await HandleHttpSessionRequest(tcpClient, httpCmd, clientStream, clientStreamReader, clientStreamWriter,
                                                          endPoint.EnableSsl?endPoint.GenericCertificateName : null, endPoint, null, true);
            }
            finally
            {
                if (!disposed)
                {
                    Dispose(clientStream, clientStreamReader, clientStreamWriter, null);
                }
            }
        }
        /// <summary>
        /// This is called when this proxy acts as a reverse proxy (like a real http server)
        /// So for HTTPS requests we would start SSL negotiation right away without expecting a CONNECT request from client
        /// </summary>
        /// <param name="endPoint"></param>
        /// <param name="tcpClient"></param>
        /// <returns></returns>
        private async Task HandleClient(TransparentProxyEndPoint endPoint, TcpClient tcpClient)
        {
            var clientStream = new CustomBufferedStream(tcpClient.GetStream(), BufferSize);

            var clientStreamReader = new CustomBinaryReader(clientStream, BufferSize);
            var clientStreamWriter = new HttpResponseWriter(clientStream, BufferSize);

            try
            {
                if (endPoint.EnableSsl)
                {
                    var clientHelloInfo = await SslTools.PeekClientHello(clientStream);

                    if (clientHelloInfo != null)
                    {
                        var sslStream = new SslStream(clientStream);
                        clientStream = new CustomBufferedStream(sslStream, BufferSize);

                        string sniHostName = clientHelloInfo.GetServerName() ?? endPoint.GenericCertificateName;

                        string certName    = HttpHelper.GetWildCardDomainName(sniHostName);
                        var    certificate = await CertificateManager.CreateCertificateAsync(certName);

                        try
                        {
                            //Successfully managed to authenticate the client using the fake certificate
                            await sslStream.AuthenticateAsServerAsync(certificate, false, SslProtocols.Tls, false);
                        }
                        catch (Exception e)
                        {
                            ExceptionFunc(new Exception($"Could'nt authenticate client '{sniHostName}' with fake certificate.", e));
                            return;
                        }
                    }

                    //HTTPS server created - we can now decrypt the client's traffic
                }

                //Now create the request
                await HandleHttpSessionRequest(tcpClient, clientStream, clientStreamReader, clientStreamWriter,
                                               endPoint.EnableSsl?endPoint.GenericCertificateName : null, endPoint, null, true);
            }
            finally
            {
                clientStreamReader.Dispose();
                clientStream.Dispose();
            }
        }
Beispiel #28
0
        public StringTableReader(Stream stream)
        {
            reader = new CustomBinaryReader(stream);

            uint count    = reader.ReadUInt32();
            uint dataSize = reader.ReadUInt32();

            long dataPosition = 8 + count * 8;

            for (int i = 0; i < count; i++)
            {
                uint index  = reader.ReadUInt32();
                uint offset = reader.ReadUInt32();
                table.Add(index, dataPosition + offset);
            }
        }
        /// <summary>
        /// This is called when this proxy acts as a reverse proxy (like a real http server)
        /// So for HTTPS requests we would start SSL negotiation right away without expecting a CONNECT request from client
        /// </summary>
        /// <param name="endPoint"></param>
        /// <param name="tcpClient"></param>
        /// <returns></returns>
        private async Task HandleClient(TransparentProxyEndPoint endPoint, TcpClient tcpClient)
        {
            bool disposed     = false;
            var  clientStream = new CustomBufferedStream(tcpClient.GetStream(), BufferSize);

            CustomBinaryReader clientStreamReader = null;
            StreamWriter       clientStreamWriter = null;

            try
            {
                if (endPoint.EnableSsl)
                {
                    var sslStream = new SslStream(clientStream);
                    clientStream = new CustomBufferedStream(sslStream, BufferSize);

                    //implement in future once SNI supported by SSL stream, for now use the same certificate
                    var certificate = CertificateManager.CreateCertificate(endPoint.GenericCertificateName, false);

                    //Successfully managed to authenticate the client using the fake certificate
                    await sslStream.AuthenticateAsServerAsync(certificate, false,
                                                              SslProtocols.Tls, false);

                    //HTTPS server created - we can now decrypt the client's traffic
                }

                clientStreamReader = new CustomBinaryReader(clientStream, BufferSize);
                clientStreamWriter = new StreamWriter(clientStream)
                {
                    NewLine = ProxyConstants.NewLine
                };

                //now read the request line
                var httpCmd = await clientStreamReader.ReadLineAsync();

                //Now create the request
                disposed = await HandleHttpSessionRequest(tcpClient, httpCmd, clientStream, clientStreamReader, clientStreamWriter,
                                                          endPoint.EnableSsl?endPoint.GenericCertificateName : null, endPoint, null);
            }
            finally
            {
                if (!disposed)
                {
                    Dispose(clientStream, clientStreamReader, clientStreamWriter, null);
                }
            }
        }
Beispiel #30
0
        /// <summary/>
        protected BizProcess ReadChildProcess(CustomBinaryReader br)
        {
            bool optimized = br.ReadBoolean();

            if (optimized)
            {
                string     typeId       = br.ReadString();
                Type       type         = BizProcessHolder.Instance.GetType(typeId);
                BizProcess childProcess = (BizProcess)Activator.CreateInstance(type, true);
                childProcess.DeserializeInternal(br);
                return(childProcess);
            }
            else
            {
                return(br.ReadObject <BizProcess>());
            }
        }