ReadByte() public méthode

public ReadByte ( ) : int
Résultat int
Exemple #1
0
 private static void runServer()
 {
     //ctrl+pötty   auto using
     TcpListener listener = new TcpListener(IPAddress.Any,8888);
     new Thread(() =>
     {
     listener.Start();
     TcpClient client = listener.AcceptTcpClient();
     NetworkStream netStream = client.GetStream();
     using (CryptoStream cryptoStream = new CryptoStream(netStream, new SHA512Managed(), CryptoStreamMode.Read))
     {
         using (GZipStream zipStream = new GZipStream(cryptoStream, CompressionMode.Decompress))
         {
             using (BufferedStream buffStream = new BufferedStream(zipStream, 64))
             {
                 using (FileStream fileStream = new FileStream("message.txt", FileMode.Create))
                 {
                     int data = buffStream.ReadByte();
                     while (data != -1)
                     {
                         fileStream.WriteByte((byte)data);
                         data = buffStream.ReadByte();
                     }
                 }
             }
         }
     }
     }).Start();
     Thread.Sleep(1000);
 }
Exemple #2
0
 public static void Decompress(Stream instream, Stream outstream)
 {
     BufferedStream stream = new BufferedStream(outstream);
     BufferedStream zStream = new BufferedStream(instream);
     if ((zStream.ReadByte() == 0x42) && (zStream.ReadByte() == 90))
     {
         BZip2InputStream stream3 = new BZip2InputStream(zStream);
         for (int i = stream3.ReadByte(); i != -1; i = stream3.ReadByte())
         {
             stream.WriteByte((byte) i);
         }
         stream.Flush();
     }
 }
Exemple #3
0
 public static void Compress(Stream instream, Stream outstream, int blockSize)
 {
     BufferedStream inStream = new BufferedStream(outstream);
     inStream.WriteByte(0x42);
     inStream.WriteByte(90);
     BufferedStream stream2 = new BufferedStream(instream);
     int num = stream2.ReadByte();
     BZip2OutputStream stream3 = new BZip2OutputStream(inStream);
     while (num != -1)
     {
         stream3.WriteByte((byte) num);
         num = stream2.ReadByte();
     }
     stream2.Close();
     stream3.Close();
 }
Exemple #4
0
        public static bool AreIdentical(String imagePathA, String imagePathB)
        {
            if (imagePathA == null) return false;
            if (imagePathB == null) return false;
            if (File.Exists(imagePathA) == false) return false;
            if (File.Exists(imagePathB) == false) return false;

            FileInfo fileInfoA = new FileInfo(imagePathA);
            FileInfo fileInfoB = new FileInfo(imagePathB);

            if (fileInfoA.Length != fileInfoB.Length) return false;

            using (FileStream fileStreamA = new FileStream(imagePathA, FileMode.Open))
            using (FileStream fileStreamB = new FileStream(imagePathB, FileMode.Open))
            using (BufferedStream streamA = new BufferedStream(fileStreamA))
            using (BufferedStream streamB = new BufferedStream(fileStreamB))
            {
                while (true)
                {
                    int byteA = streamA.ReadByte();
                    int byteB = streamB.ReadByte();
                    if (byteA != byteB) return false;
                    if (byteA == -1) break;
                }
            }
            return true;
        }
Exemple #5
0
        public void Build(string filename) {
            positions = new List<long>();

            using (FileStream fs = new FileStream(filename, FileMode.Open, FileAccess.Read)) {
                using (BufferedStream bs = new BufferedStream(fs)) {
                    bool detectFirstLine = true;

                    int b = 0;
                    while ((b = bs.ReadByte()) != -1) {
                        if (b == '\n') {
                            positions.Add(bs.Position);
                            detectFirstLine = false;
                        }
                        if (detectFirstLine) {
                            if (bs.Position == 1 && b != 0xEF) {
                                positions.Add(0);
                                detectFirstLine = false;
                            }
                            if (bs.Position == 2 && b != 0xBB) {
                                positions.Add(0);
                                detectFirstLine = false;
                            }
                            if (bs.Position == 3 && b != 0xBF) {
                                positions.Add(0);
                                detectFirstLine = false;
                            }
                            if (bs.Position == 4 && detectFirstLine) {
                                positions.Add(3);
                                detectFirstLine = false;
                            }
                        }
                    }
                }
            }
        }
        public static bool Compare(Stream one, Stream other)
        {
            BufferedStream oneBuffered = new BufferedStream(one, BufferSize);
            BufferedStream otherBuffered = new BufferedStream(other, BufferSize);

            // Compare length first, if seekable
            if (oneBuffered.CanSeek && otherBuffered.CanSeek)
            {
                if (oneBuffered.Length != otherBuffered.Length)
                    return false;
            }

            while (true)
            {
                int oneByte = oneBuffered.ReadByte();
                int otherByte = otherBuffered.ReadByte();

                // Both streams ended at the same time
                if (oneByte == -1 && otherByte == -1)
                    return true;

                // Read bytes are not equal
                // ore one stream ended before the other
                if (oneByte != otherByte)
                    return false;
            }
        }
        static void Main()
        {
            var listener = new HttpListener
            {
                Prefixes = { "http://+:8080/" }
            };
            listener.Start();

            var buffer = new byte[512 * 1024];
            for (int i = 0; i < buffer.Length; i++)
            {
                buffer[i] = (byte)'a';
            }
            while (true)
            {
                try
                {
                    var ctx = listener.GetContext();
                    var sp = Stopwatch.StartNew();
                    switch (ctx.Request.HttpMethod)
                    {
                        case "GET":
                            break;
                        default: // PUT/ POST
                            // this just consume all sent data to memory
                            using (var buffered = new BufferedStream(ctx.Request.InputStream))
                            {
                                while (buffered.ReadByte() != -1)
                                {

                                }
                            }
                            break;
                    }

                    // one write call
                    //ctx.Response.OutputStream.Write(buffer, 0, buffer.Length);

                    // 16 write calls
                    int size = buffer.Length/16;
                    var wrote = 0;
                    for (int i = 0; i < 16; i++)
                    {
                        ctx.Response.OutputStream.Write(buffer, wrote, size);
                        wrote += size;
                    }

                    ctx.Response.Close();
                    Console.WriteLine(DateTime.Now + ": " + sp.ElapsedMilliseconds);
                }
                catch (Exception e)
                {
                    Console.WriteLine(e);
                }
            }
        }
Exemple #8
0
    static void FileStreamAndBufferedStream()
    {
        System.IO.Stream         fileStream     = System.IO.File.Open("./file.txt", System.IO.FileMode.Open);
        System.IO.BufferedStream bufferedStream = new System.IO.BufferedStream(fileStream);
        System.Console.WriteLine("CanRead: " + bufferedStream.CanRead);
        System.Console.WriteLine("CanWrite: " + bufferedStream.CanWrite);
        System.Console.WriteLine("CanSeek: " + bufferedStream.CanSeek);
        System.Console.WriteLine("Length: " + bufferedStream.Length);
        System.Console.WriteLine("Position: " + bufferedStream.Position);
        int firstByte = bufferedStream.ReadByte();

        System.Console.WriteLine("Byte:" + firstByte);
        bufferedStream.Position = 0;
        System.Console.WriteLine("Position: " + bufferedStream.Position);
        bufferedStream.WriteByte((byte)(firstByte + 1));
        bufferedStream.Flush();
        //bufferedStream.Position = 0;
        //firstByte = bufferedStream.ReadByte();
        //bufferedStream.Dispose();
        System.Console.WriteLine("Byte:" + firstByte);
    }
Exemple #9
0
        public static void Main(string[] args)
        {
            string filename =
                //"compl.bit";
                //"01-Lovecraft_s Death.mp3";
                //"01-enochian_crescent-tatan.mp3";
                //"bad-info-crc.mp3";
                //"test-id3v1.mp3";
                //"test-id3v2.mp3";
                "test-lame.mp3";

            Stream mp3Stream =
                new BufferedStream(
                    new FileStream(
                        filename,
                        FileMode.Open,
                        FileAccess.Read));

            Mp3Validator validator = new Mp3Validator();
            validator.OnValidationFailure += ValidationFailureEventHandler;
            validator.Validate(mp3Stream);
            Console.WriteLine("Done");
            mp3Stream.Seek(0, SeekOrigin.Begin);

            Mp3StreamReader reader = new Mp3StreamReader(mp3Stream);
            foreach (IMp3StreamRegion region in reader)
            {
            }
            Console.WriteLine("Done");
            mp3Stream.Seek(0, SeekOrigin.Begin);

            while (-1 != mp3Stream.ReadByte())
            {
            }
            Console.WriteLine("Done");

            Console.ReadKey();
        }
        protected virtual void ProcessBackendResponses_Ver_3( NpgsqlConnector context )
        {
            NpgsqlEventLog.LogMethodEnter(LogLevel.Debug, CLASSNAME, "ProcessBackendResponses");

            BufferedStream 	stream = new BufferedStream(context.Stream);
            NpgsqlMediator mediator = context.Mediator;

            // Often used buffers
            Byte[] inputBuffer = new Byte[ 4 ];
            String Str;

            Boolean readyForQuery = false;

            while (!readyForQuery)
            {
                // Check the first Byte of response.
                Int32 message = stream.ReadByte();
                switch ( message )
                {
                case NpgsqlMessageTypes_Ver_3.ErrorResponse :

                    {
                        NpgsqlError error = new NpgsqlError(context.BackendProtocolVersion);
                        error.ReadFromStream(stream, context.Encoding);

                        mediator.Errors.Add(error);

                        NpgsqlEventLog.LogMsg(resman, "Log_ErrorResponse", LogLevel.Debug, error.Message);
                    }

                    // Return imediately if it is in the startup state or connected state as
                    // there is no more messages to consume.
                    // Possible error in the NpgsqlStartupState:
                    //		Invalid password.
                    // Possible error in the NpgsqlConnectedState:
                    //		No pg_hba.conf configured.

                    if (! mediator.RequireReadyForQuery)
                    {
                        return;
                    }

                    break;


                case NpgsqlMessageTypes_Ver_3.AuthenticationRequest :

                    NpgsqlEventLog.LogMsg(resman, "Log_ProtocolMessage", LogLevel.Debug, "AuthenticationRequest");

                    // Eat length
                    PGUtil.ReadInt32(stream, inputBuffer);

                    {
                        Int32 authType = PGUtil.ReadInt32(stream, inputBuffer);

                        if ( authType == NpgsqlMessageTypes_Ver_3.AuthenticationOk )
                        {
                            NpgsqlEventLog.LogMsg(resman, "Log_AuthenticationOK", LogLevel.Debug);

                            break;
                        }

                        if ( authType == NpgsqlMessageTypes_Ver_3.AuthenticationClearTextPassword )
                        {
                            NpgsqlEventLog.LogMsg(resman, "Log_AuthenticationClearTextRequest", LogLevel.Debug);

                            // Send the PasswordPacket.

                            ChangeState( context, NpgsqlStartupState.Instance );
                            context.Authenticate(context.Password);

                            break;
                        }


                        if ( authType == NpgsqlMessageTypes_Ver_3.AuthenticationMD5Password )
                        {
                            NpgsqlEventLog.LogMsg(resman, "Log_AuthenticationMD5Request", LogLevel.Debug);
                            // Now do the "MD5-Thing"
                            // for this the Password has to be:
                            // 1. md5-hashed with the username as salt
                            // 2. md5-hashed again with the salt we get from the backend


                            MD5 md5 = MD5.Create();


                            // 1.
                            byte[] passwd = context.Encoding.GetBytes(context.Password);
                            byte[] saltUserName = context.Encoding.GetBytes(context.UserName);

                            byte[] crypt_buf = new byte[passwd.Length + saltUserName.Length];

                            passwd.CopyTo(crypt_buf, 0);
                            saltUserName.CopyTo(crypt_buf, passwd.Length);



                            StringBuilder sb = new StringBuilder ();
                            byte[] hashResult = md5.ComputeHash(crypt_buf);
                            foreach (byte b in hashResult)
                            sb.Append (b.ToString ("x2"));


                            String prehash = sb.ToString();

                            byte[] prehashbytes = context.Encoding.GetBytes(prehash);



                            stream.Read(inputBuffer, 0, 4);
                            // Send the PasswordPacket.
                            ChangeState( context, NpgsqlStartupState.Instance );


                            // 2.

                            crypt_buf = new byte[prehashbytes.Length + 4];
                            prehashbytes.CopyTo(crypt_buf, 0);
                            inputBuffer.CopyTo(crypt_buf, prehashbytes.Length);

                            sb = new StringBuilder ("md5"); // This is needed as the backend expects md5 result starts with "md5"
                            hashResult = md5.ComputeHash(crypt_buf);
                            foreach (byte b in hashResult)
                            sb.Append (b.ToString ("x2"));

                            context.Authenticate(sb.ToString ());

                            break;
                        }

                        // Only AuthenticationClearTextPassword and AuthenticationMD5Password supported for now.
                        mediator.Errors.Add(new NpgsqlError(context.BackendProtocolVersion, String.Format(resman.GetString("Exception_AuthenticationMethodNotSupported"), authType)));
                    }

                    return;

                case NpgsqlMessageTypes_Ver_3.RowDescription:
                    // This is the RowDescription message.
                    NpgsqlEventLog.LogMsg(resman, "Log_ProtocolMessage", LogLevel.Debug, "RowDescription");
                    {
                        NpgsqlRowDescription rd = new NpgsqlRowDescription(context.BackendProtocolVersion);
                        rd.ReadFromStream(stream, context.Encoding, context.OidToNameMapping);

                        mediator.AddRowDescription(rd);
                    }

                    // Now wait for the AsciiRow messages.
                    break;

                case NpgsqlMessageTypes_Ver_3.DataRow:
                    // This is the AsciiRow message.
                    NpgsqlEventLog.LogMsg(resman, "Log_ProtocolMessage", LogLevel.Debug, "DataRow");
                    {
                        NpgsqlAsciiRow asciiRow = new NpgsqlAsciiRow(context.Mediator.LastRowDescription, context.BackendProtocolVersion);
                        asciiRow.ReadFromStream(stream, context.Encoding);

                        // Add this row to the rows array.
                        mediator.AddAsciiRow(asciiRow);
                    }

                    // Now wait for CompletedResponse message.
                    break;

                case NpgsqlMessageTypes_Ver_3.ReadyForQuery :

                    NpgsqlEventLog.LogMsg(resman, "Log_ProtocolMessage", LogLevel.Debug, "ReadyForQuery");

                    // Possible status bytes returned:
                    //   I = Idle (no transaction active).
                    //   T = In transaction, ready for more.
                    //   E = Error in transaction, queries will fail until transaction aborted.
                    // Just eat the status byte, we have no use for it at this time.
                    PGUtil.ReadInt32(stream, inputBuffer);
                    PGUtil.ReadString(stream, context.Encoding, 1);

                    readyForQuery = true;
                    ChangeState( context, NpgsqlReadyState.Instance );

                    break;

                case NpgsqlMessageTypes_Ver_3.BackendKeyData :

                    NpgsqlEventLog.LogMsg(resman, "Log_ProtocolMessage", LogLevel.Debug, "BackendKeyData");
                    // BackendKeyData message.
                    NpgsqlBackEndKeyData backend_keydata = new NpgsqlBackEndKeyData(context.BackendProtocolVersion);
                    backend_keydata.ReadFromStream(stream);
                    mediator.SetBackendKeydata(backend_keydata);


                    // Wait for ReadForQuery message
                    break;

                case NpgsqlMessageTypes_Ver_3.NoticeResponse :

                    // Notices and errors are identical except that we
                    // just throw notices away completely ignored.
                    {
                        NpgsqlError notice = new NpgsqlError(context.BackendProtocolVersion);
                        notice.ReadFromStream(stream, context.Encoding);

                        mediator.Notices.Add(notice);

                        NpgsqlEventLog.LogMsg(resman, "Log_NoticeResponse", LogLevel.Debug, notice.Message);
                    }

                    // Wait for ReadForQuery message
                    break;

                case NpgsqlMessageTypes_Ver_3.CompletedResponse :
                    // This is the CompletedResponse message.
                    // Get the string returned.

                    PGUtil.ReadInt32(stream, inputBuffer);
                    Str = PGUtil.ReadString(stream, context.Encoding);

                    NpgsqlEventLog.LogMsg(resman, "Log_CompletedResponse", LogLevel.Debug, Str);

                    // Add result from the processing.
                    mediator.AddCompletedResponse(Str);

                    break;

                case NpgsqlMessageTypes_Ver_3.ParseComplete :
                    NpgsqlEventLog.LogMsg(resman, "Log_ProtocolMessage", LogLevel.Debug, "ParseComplete");
                    // Just read up the message length.
                    PGUtil.ReadInt32(stream, inputBuffer);
                    readyForQuery = true;
                    break;

                case NpgsqlMessageTypes_Ver_3.BindComplete :
                    NpgsqlEventLog.LogMsg(resman, "Log_ProtocolMessage", LogLevel.Debug, "BindComplete");
                    // Just read up the message length.
                    PGUtil.ReadInt32(stream, inputBuffer);
                    readyForQuery = true;
                    break;

                case NpgsqlMessageTypes_Ver_3.EmptyQueryResponse :
                    NpgsqlEventLog.LogMsg(resman, "Log_ProtocolMessage", LogLevel.Debug, "EmptyQueryResponse");
                    PGUtil.ReadInt32(stream, inputBuffer);
                    break;

                case NpgsqlMessageTypes_Ver_3.NotificationResponse  :
                    NpgsqlEventLog.LogMsg(resman, "Log_ProtocolMessage", LogLevel.Debug, "NotificationResponse");

                    // Eat the length
                    PGUtil.ReadInt32(stream, inputBuffer);
                    {
                        // Process ID sending notification
                        Int32 PID = PGUtil.ReadInt32(stream, inputBuffer);
                        // Notification string
                        String notificationResponse = PGUtil.ReadString( stream, context.Encoding );
                        // Additional info, currently not implemented by PG (empty string always), eat it
                        PGUtil.ReadString( stream, context.Encoding );
                        mediator.AddNotification(new NpgsqlNotificationEventArgs(PID, notificationResponse));
                    }

                    // Wait for ReadForQuery message
                    break;

                case NpgsqlMessageTypes_Ver_3.ParameterStatus :
                    NpgsqlEventLog.LogMsg(resman, "Log_ProtocolMessage", LogLevel.Debug, "ParameterStatus");
                    NpgsqlParameterStatus parameterStatus = new NpgsqlParameterStatus();
                    parameterStatus.ReadFromStream(stream, context.Encoding);

                    NpgsqlEventLog.LogMsg(resman, "Log_ParameterStatus", LogLevel.Debug, parameterStatus.Parameter, parameterStatus.ParameterValue);

                    mediator.AddParameterStatus(parameterStatus.Parameter, parameterStatus);

                    if (parameterStatus.Parameter == "server_version")
                    {
                        // Add this one under our own name so that if the parameter name
                        // changes in a future backend version, we can handle it here in the
                        // protocol handler and leave everybody else put of it.
                        mediator.AddParameterStatus("__npgsql_server_version", parameterStatus);
                        //                        context.ServerVersionString = parameterStatus.ParameterValue;
                    }

                    break;
                case NpgsqlMessageTypes_Ver_3.NoData :
                    // This nodata message may be generated by prepare commands issued with queries which doesn't return rows
                    // for example insert, update or delete.
                    // Just eat the message.
                    NpgsqlEventLog.LogMsg(resman, "Log_ProtocolMessage", LogLevel.Debug, "ParameterStatus");
                    PGUtil.ReadInt32(stream, inputBuffer);
                    break;


                default :
                    // This could mean a number of things
                    //   We've gotten out of sync with the backend?
                    //   We need to implement this type?
                    //   Backend has gone insane?
                    // FIXME
                    // what exception should we really throw here?
                    throw new NotSupportedException(String.Format("Backend sent unrecognized response type: {0}", (Char)message));

                }
            }
        }
Exemple #11
0
 private static void MyBufferStream()
 {
     MemoryStream ms = new MemoryStream();
     BufferedStream bs = new BufferedStream(ms, 4096);
     byte [] b=new  byte[10];
     for (int i = 0; i < 10; i++)
     {
         bs.WriteByte((byte)i);
     }
     bs.Position = 0;
     bs.Read(b, 0, 9);
     for (int i = 0; i < 10; i++)
     {
         Console.WriteLine("读的值是:{0}", b[i]);
     }
     Console.WriteLine("值是:{0}", bs.ReadByte());
 }
Exemple #12
0
		public byte[] SendAndReceiveAttempt(byte[] data)
		{
			TcpClient tcpClient = null;

			try
			{
				if (LocalEndPoint != null)
					tcpClient = new TcpClient(LocalEndPoint);
				else
					tcpClient = new TcpClient();



				IAsyncResult result = tcpClient.BeginConnect(RemoteEndPoint.Address, RemoteEndPoint.Port, null, null);
				bool success = result.AsyncWaitHandle.WaitOne(Timeout, true);

				if (!success || !tcpClient.Connected)
				{
					tcpClient.Close();
					throw new Exception("Could not connect with server." + (RemoteEndPoint == null ? "" : " Server=" + RemoteEndPoint.Address + ":" + RemoteEndPoint.Port));
				}

				var bs = new BufferedStream(tcpClient.GetStream());
				bs.WriteByte((byte) ((data.Length >> 8) & 0xff));
				bs.WriteByte((byte) (data.Length & 0xff));
				bs.Write(data, 0, data.Length);
				bs.Flush();


				while (true)
				{
					int intLength = bs.ReadByte() << 8 | bs.ReadByte();
					if (intLength <= 0)
					{
						tcpClient.Close();
						throw new Exception("Connection to nameserver failed." + (RemoteEndPoint == null ? "" : " Server=" + RemoteEndPoint.Address + ":" + RemoteEndPoint.Port));
					}
					data = new byte[intLength];
					bs.Read(data, 0, intLength);
					return data;
				}
			}
			finally
			{
				if (tcpClient != null)
				{
					tcpClient.Close();
				}
			}
		}
Exemple #13
0
 private ArrayList ReadASCIIListingData(string dirname)
 {
     this.log.Debug("Reading ASCII listing data");
     BufferedStream stream = new BufferedStream(this.GetInputStream());
     MemoryStream stream2 = new MemoryStream(this.TransferBufferSize * 2);
     long byteCount = 0L;
     long num2 = 0L;
     try
     {
         int num3;
         while (((num3 = stream.ReadByte()) != -1) && !this.cancelTransfer)
         {
             if ((((num3 >= 0x20) || (num3 == 10)) || (num3 == 13)) && (num3 <= 0x7f))
             {
                 byteCount += 1L;
                 num2 += 1L;
                 stream2.WriteByte((byte) num3);
                 if ((this.transferNotifyListings && (this.BytesTransferred != null)) && (!this.cancelTransfer && (num2 >= this.monitorInterval)))
                 {
                     this.BytesTransferred(this, new BytesTransferredEventArgs(dirname, byteCount, 0L));
                     num2 = 0L;
                 }
             }
         }
         if (this.transferNotifyListings && (this.BytesTransferred != null))
         {
             this.BytesTransferred(this, new BytesTransferredEventArgs(dirname, byteCount, 0L));
         }
     }
     finally
     {
         this.CloseDataSocket(stream);
     }
     stream2.Seek(0L, SeekOrigin.Begin);
     StreamReader input = new StreamReader(stream2, Encoding.ASCII);
     ArrayList list = new ArrayList(10);
     string str = null;
     while ((str = this.ReadLine(input)) != null)
     {
         list.Add(str);
         this.log.Debug("-->" + str);
     }
     input.Close();
     stream2.Close();
     return list;
 }
Exemple #14
0
        private Response TcpRequest(Request request)
        {
            //System.Diagnostics.Stopwatch sw = new System.Diagnostics.Stopwatch();
            //sw.Start();

            for (var intAttempts = 0; intAttempts < _mRetries; intAttempts++)
            {
                for (var intDnsServer = 0; intDnsServer < _mDnsServers.Count; intDnsServer++)
                {
                    //var tcpClient = new TcpClient(AddressFamily.InterNetworkV6) {ReceiveTimeout = _mTimeout*1000};
                    var tcpClient = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                    //tcpClient.SetSocketOption(SocketOptionLevel.IPv6, SocketOptionName.IPv6Only, false);

                    try
                    {
                        Verbose(";; Connecting to nameserver {0}", _mDnsServers[intDnsServer].Address);
                        var result = tcpClient.BeginConnect(_mDnsServers[intDnsServer].Address, _mDnsServers[intDnsServer].Port,
                                                                     null, null);

                        var success = result.AsyncWaitHandle.WaitOne(_mTimeout*1000, true);

                        if (!success || !tcpClient.Connected)
                        {
                            tcpClient.Close();
                            Verbose(string.Format(";; Connection to nameserver {0} failed", _mDnsServers[intDnsServer].Address));
                            continue;
                        }

                        var bs = new BufferedStream(new NetworkStream(tcpClient));

                        var data = request.Data;
                        bs.WriteByte((byte) ((data.Length >> 8) & 0xff));
                        bs.WriteByte((byte) (data.Length & 0xff));
                        bs.Write(data, 0, data.Length);
                        bs.Flush();

                        var transferResponse = new Response();
                        var intSoa = 0;
                        var intMessageSize = 0;

                        //Debug.WriteLine("Sending "+ (request.Length+2) + " bytes in "+ sw.ElapsedMilliseconds+" mS");

                        while (true)
                        {
                            var intLength = bs.ReadByte() << 8 | bs.ReadByte();
                            if (intLength <= 0)
                            {
                                tcpClient.Close();
                                Verbose(string.Format(";; Connection to nameserver {0} failed", (intDnsServer + 1)));
                                throw new SocketException(); // next try
                            }

                            intMessageSize += intLength;

                            data = new byte[intLength];
                            bs.Read(data, 0, intLength);
                            var response = new Response(_mDnsServers[intDnsServer], data);

                            //Debug.WriteLine("Received "+ (intLength+2)+" bytes in "+sw.ElapsedMilliseconds +" mS");

                            if (response.Header.RCODE != RCode.NoError)
                                return response;

                            if (response.Questions[0].QType != QType.AXFR)
                            {
                                AddToCache(response);
                                return response;
                            }

                            // Zone transfer!!

                            if (transferResponse.Questions.Count == 0)
                                transferResponse.Questions.AddRange(response.Questions);
                            transferResponse.Answers.AddRange(response.Answers);
                            transferResponse.Authorities.AddRange(response.Authorities);
                            transferResponse.Additionals.AddRange(response.Additionals);

                            if (response.Answers[0].Type == Type.SOA)
                                intSoa++;

                            if (intSoa != 2) continue;
                            transferResponse.Header.QDCOUNT = (ushort) transferResponse.Questions.Count;
                            transferResponse.Header.ANCOUNT = (ushort) transferResponse.Answers.Count;
                            transferResponse.Header.NSCOUNT = (ushort) transferResponse.Authorities.Count;
                            transferResponse.Header.ARCOUNT = (ushort) transferResponse.Additionals.Count;
                            transferResponse.MessageSize = intMessageSize;
                            return transferResponse;
                        }
                    } // try
                    catch (SocketException)
                    {
                        continue; // next try
                    }
                    finally
                    {
                        _mUnique++;

                        // close the socket
                        tcpClient.Close();
                    }
                }
            }
            var responseTimeout = new Response {Error = "Timeout Error"};
            return responseTimeout;
        }
        protected virtual void ProcessBackendResponses_Ver_2( NpgsqlConnector context )
        {
            NpgsqlEventLog.LogMethodEnter(LogLevel.Debug, CLASSNAME, "ProcessBackendResponses");

            BufferedStream 	stream = new BufferedStream(context.Stream);
            NpgsqlMediator mediator = context.Mediator;

            // Often used buffer
            Byte[] inputBuffer = new Byte[ 4 ];

            Boolean readyForQuery = false;

            while (!readyForQuery)
            {
                // Check the first Byte of response.
                switch ( stream.ReadByte() )
                {
                case NpgsqlMessageTypes_Ver_2.ErrorResponse :

                    {
                        NpgsqlError error = new NpgsqlError(context.BackendProtocolVersion);
                        error.ReadFromStream(stream, context.Encoding);

                        mediator.Errors.Add(error);

                        NpgsqlEventLog.LogMsg(resman, "Log_ErrorResponse", LogLevel.Debug, error.Message);
                    }

                    // Return imediately if it is in the startup state or connected state as
                    // there is no more messages to consume.
                    // Possible error in the NpgsqlStartupState:
                    //		Invalid password.
                    // Possible error in the NpgsqlConnectedState:
                    //		No pg_hba.conf configured.

                    if (! mediator.RequireReadyForQuery)
                    {
                        return;
                    }

                    break;


                case NpgsqlMessageTypes_Ver_2.AuthenticationRequest :

                    NpgsqlEventLog.LogMsg(resman, "Log_ProtocolMessage", LogLevel.Debug, "AuthenticationRequest");

                    {
                        Int32 authType = PGUtil.ReadInt32(stream, inputBuffer);

                        if ( authType == NpgsqlMessageTypes_Ver_2.AuthenticationOk )
                        {
                            NpgsqlEventLog.LogMsg(resman, "Log_AuthenticationOK", LogLevel.Debug);

                            break;
                        }

                        if ( authType == NpgsqlMessageTypes_Ver_2.AuthenticationClearTextPassword )
                        {
                            NpgsqlEventLog.LogMsg(resman, "Log_AuthenticationClearTextRequest", LogLevel.Debug);

                            // Send the PasswordPacket.

                            ChangeState( context, NpgsqlStartupState.Instance );
                            context.Authenticate(context.Password);

                            break;
                        }


                        if ( authType == NpgsqlMessageTypes_Ver_2.AuthenticationMD5Password )
                        {
                            NpgsqlEventLog.LogMsg(resman, "Log_AuthenticationMD5Request", LogLevel.Debug);
                            // Now do the "MD5-Thing"
                            // for this the Password has to be:
                            // 1. md5-hashed with the username as salt
                            // 2. md5-hashed again with the salt we get from the backend


                            MD5 md5 = MD5.Create();


                            // 1.
                            byte[] passwd = context.Encoding.GetBytes(context.Password);
                            byte[] saltUserName = context.Encoding.GetBytes(context.UserName);

                            byte[] crypt_buf = new byte[passwd.Length + saltUserName.Length];

                            passwd.CopyTo(crypt_buf, 0);
                            saltUserName.CopyTo(crypt_buf, passwd.Length);



                            StringBuilder sb = new StringBuilder ();
                            byte[] hashResult = md5.ComputeHash(crypt_buf);
                            foreach (byte b in hashResult)
                            sb.Append (b.ToString ("x2"));


                            String prehash = sb.ToString();

                            byte[] prehashbytes = context.Encoding.GetBytes(prehash);



                            byte[] saltServer = new byte[4];
                            stream.Read(saltServer, 0, 4);
                            // Send the PasswordPacket.
                            ChangeState( context, NpgsqlStartupState.Instance );


                            // 2.

                            crypt_buf = new byte[prehashbytes.Length + saltServer.Length];
                            prehashbytes.CopyTo(crypt_buf, 0);
                            saltServer.CopyTo(crypt_buf, prehashbytes.Length);

                            sb = new StringBuilder ("md5"); // This is needed as the backend expects md5 result starts with "md5"
                            hashResult = md5.ComputeHash(crypt_buf);
                            foreach (byte b in hashResult)
                            sb.Append (b.ToString ("x2"));

                            context.Authenticate(sb.ToString ());

                            break;
                        }

                        // Only AuthenticationClearTextPassword and AuthenticationMD5Password supported for now.

                        mediator.Errors.Add(new NpgsqlError(context.BackendProtocolVersion, String.Format(resman.GetString("Exception_AuthenticationMethodNotSupported"), authType)));
                    }

                    return;

                case NpgsqlMessageTypes_Ver_2.RowDescription:
                    // This is the RowDescription message.
                    NpgsqlEventLog.LogMsg(resman, "Log_ProtocolMessage", LogLevel.Debug, "RowDescription");

                    {
                        NpgsqlRowDescription rd = new NpgsqlRowDescription(context.BackendProtocolVersion);
                        rd.ReadFromStream(stream, context.Encoding, context.OidToNameMapping);

                        // Initialize the array list which will contain the data from this rowdescription.
                        mediator.AddRowDescription(rd);
                    }

                    // Now wait for the AsciiRow messages.
                    break;

                case NpgsqlMessageTypes_Ver_2.AsciiRow:
                    // This is the AsciiRow message.
                    NpgsqlEventLog.LogMsg(resman, "Log_ProtocolMessage", LogLevel.Debug, "AsciiRow");

                    {
                        NpgsqlAsciiRow asciiRow = new NpgsqlAsciiRow(context.Mediator.LastRowDescription, context.BackendProtocolVersion);
                        asciiRow.ReadFromStream(stream, context.Encoding);

                        // Add this row to the rows array.
                        mediator.AddAsciiRow(asciiRow);
                    }

                    // Now wait for CompletedResponse message.
                    break;

                case NpgsqlMessageTypes_Ver_2.BinaryRow:
                    NpgsqlEventLog.LogMsg(resman, "Log_ProtocolMessage", LogLevel.Debug, "BinaryRow");

                    {
                        NpgsqlBinaryRow binaryRow = new NpgsqlBinaryRow(context.Mediator.LastRowDescription);
                        binaryRow.ReadFromStream(stream, context.Encoding);

                        mediator.AddBinaryRow(binaryRow);
                    }

                    break;

                case NpgsqlMessageTypes_Ver_2.ReadyForQuery :

                    NpgsqlEventLog.LogMsg(resman, "Log_ProtocolMessage", LogLevel.Debug, "ReadyForQuery");
                    readyForQuery = true;
                    ChangeState( context, NpgsqlReadyState.Instance );
                    break;

                case NpgsqlMessageTypes_Ver_2.BackendKeyData :

                    NpgsqlEventLog.LogMsg(resman, "Log_ProtocolMessage", LogLevel.Debug, "BackendKeyData");
                    // BackendKeyData message.
                    NpgsqlBackEndKeyData backend_keydata = new NpgsqlBackEndKeyData(context.BackendProtocolVersion);
                    backend_keydata.ReadFromStream(stream);
                    mediator.SetBackendKeydata(backend_keydata);


                    // Wait for ReadForQuery message
                    break;
                    ;

                case NpgsqlMessageTypes_Ver_2.NoticeResponse :

                    {
                        NpgsqlError notice = new NpgsqlError(context.BackendProtocolVersion);
                        notice.ReadFromStream(stream, context.Encoding);

                        mediator.Notices.Add(notice);

                        NpgsqlEventLog.LogMsg(resman, "Log_NoticeResponse", LogLevel.Debug, notice.Message);
                    }

                    // Wait for ReadForQuery message
                    break;

                case NpgsqlMessageTypes_Ver_2.CompletedResponse :
                    // This is the CompletedResponse message.
                    // Get the string returned.


                    String result = PGUtil.ReadString(stream, context.Encoding);

                    NpgsqlEventLog.LogMsg(resman, "Log_CompletedResponse", LogLevel.Debug, result);
                    // Add result from the processing.

                    mediator.AddCompletedResponse(result);

                    // Now wait for ReadyForQuery message.
                    break;

                case NpgsqlMessageTypes_Ver_2.CursorResponse :
                    // This is the cursor response message.
                    // It is followed by a C NULL terminated string with the name of
                    // the cursor in a FETCH case or 'blank' otherwise.
                    // In this case it should be always 'blank'.
                    // [FIXME] Get another name for this function.
                    NpgsqlEventLog.LogMsg(resman, "Log_ProtocolMessage", LogLevel.Debug, "CursorResponse");

                    String cursorName = PGUtil.ReadString(stream, context.Encoding);
                    // Continue waiting for ReadyForQuery message.
                    break;

                case NpgsqlMessageTypes_Ver_2.EmptyQueryResponse :
                    NpgsqlEventLog.LogMsg(resman, "Log_ProtocolMessage", LogLevel.Debug, "EmptyQueryResponse");
                    PGUtil.ReadString(stream, context.Encoding);
                    break;

                case NpgsqlMessageTypes_Ver_2.NotificationResponse  :

                    NpgsqlEventLog.LogMsg(resman, "Log_ProtocolMessage", LogLevel.Debug, "NotificationResponse");

                    Int32 PID = PGUtil.ReadInt32(stream, inputBuffer);
                    String notificationResponse = PGUtil.ReadString( stream, context.Encoding );
                    mediator.AddNotification(new NpgsqlNotificationEventArgs(PID, notificationResponse));

                    // Wait for ReadForQuery message
                    break;

                default :
                    // This could mean a number of things
                    //   We've gotten out of sync with the backend?
                    //   We need to implement this type?
                    //   Backend has gone insane?
                    // FIXME
                    // what exception should we really throw here?
                    throw new NotSupportedException("Backend sent unrecognized response type");

                }
            }
        }
Exemple #16
0
 /// <summary>
 /// Reads the listing data for ASCII encoding.
 /// </summary>
 /// <remarks>Skips non-ASCII chars found in the stream</remarks>
 /// <returns>array of listing lines</returns>
 private ArrayList ReadASCIIListingData(string dirname, LineCallback lineCallback, object state) 
 {
     log.Debug("Reading ASCII listing data");
     BufferedStream bstr = new BufferedStream(GetInputStream());
     MemoryStream mstr = new MemoryStream();
     int b;
     long size = 0;
     long monitorCount = 0;
     ArrayList lines = new ArrayList(10);
     try
     {
         while ((b = bstr.ReadByte()) != -1 && !cancelTransfer) 
         {
             // end of line?
             if (b == '\r' || b == '\n')
             {
                 if (mstr.Length > 0)
                 {
                     byte[] mstrbytes = mstr.ToArray();
                     string line = Encoding.ASCII.GetString(mstrbytes, 0, mstrbytes.Length);
                     lines.Add(line);
                     if (lineCallback != null)
                         lineCallback(line, state);
                     log.Debug("-->" + line);
                     mstr = new MemoryStream();
                 }
             }
             else if (b < 0x20 || b > 0x7f)  // strip out non-printable chars
                 continue;
             else
                 mstr.WriteByte((byte)b);
             size++;
             monitorCount++;
             if (transferNotifyListings && BytesTransferred != null && 
                 !cancelTransfer && monitorCount >= monitorInterval)
             {
                 BytesTransferred(this, new BytesTransferredEventArgs(dirname, size, 0));
                 monitorCount = 0;
             }       
         }
         if (lineCallback != null)
             lineCallback(null, state);
         if (transferNotifyListings && BytesTransferred != null)
             BytesTransferred(this, new BytesTransferredEventArgs(dirname, size, 0));
     }
     finally
     {
         CloseDataSocket(bstr); // need to close here
     }
     return lines;   
 }
	public void Close6 ()
	{
		BufferedStream stream = new BufferedStream (mem);
		stream.Close ();
		stream.ReadByte ();
	}
	 public void Position ()
	 {
		mem = new MemoryStream ();
		BufferedStream stream = new BufferedStream (mem,5);
		stream.Write (new byte [] {0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15}, 0, 16);
	 	
		stream.Position = 0;
		Assert.AreEqual (0, stream.Position, "test#01");		
		Assert.AreEqual (0, stream.ReadByte (), "test#02");		
		
		stream.Position = 5;
		Assert.AreEqual (5, stream.Position, "test#01");		
		Assert.AreEqual (5, stream.ReadByte (), "test#02");		
		
		// Should not need to read from the underlying stream:
		stream.Position = 7;
		Assert.AreEqual (7, stream.Position, "test#01");		
		Assert.AreEqual (7, stream.ReadByte (), "test#02");		
		
		// Should not need to read from the underlying stream:
		stream.Position = 5;
		Assert.AreEqual (5, stream.Position, "test#01");		
		Assert.AreEqual (5, stream.ReadByte (), "test#02");		
				
		// Should not need to read from the underlying stream:
		stream.Position = 9;
		Assert.AreEqual (9, stream.Position, "test#01");
		Assert.AreEqual (9, stream.ReadByte (), "test#02");
		
		stream.Position = 10;
		Assert.AreEqual (10, stream.Position, "test#01");		
		Assert.AreEqual (10, stream.ReadByte (), "test#02");		
		
		stream.Position = 9;
		Assert.AreEqual (9, stream.Position, "test#01");		
		Assert.AreEqual (9, stream.ReadByte (), "test#02");		
	 }
        /// <summary>
        /// Reads the specified number of bytes from the buffered input stream,
        /// starting at offset.
        /// </summary>
        /// <param name="bis">
        /// A <see cref="BufferedStream"/>
        /// </param>
        /// <param name="length">
        /// A <see cref="System.Int32"/>
        /// </param>
        /// <returns>
        /// A <see cref="System.Byte"/>
        /// </returns>
        private byte[] ReadBytes(BufferedStream bis, int length)
        {
            byte[] binaryTag = new byte[length];

            for (int i = 0; i < length; i++)
            {
                binaryTag[i] = (byte)bis.ReadByte();
            }

            return binaryTag;
        }
        /// <summary>  
        /// Test to see if two files are identical, byte for byte
        /// </summary>
        /// <param name="file1"> first file object
        /// </param>
        /// <param name="file2"> second file object
        /// </param>
        internal virtual void AssertIdentical(FileInfo file1, FileInfo file2)
        {
            log.Debug("Comparing [" + file1.Name + "," + file2.Name + "]");
            BufferedStream is1 = null;
            BufferedStream is2 = null;
            try
            {
                // check lengths first
                Assert.AreEqual(file1.Length, file2.Length);
                log.Debug("Identical size [" + file1.Name + "," + file2.Name + "]");

                // now check each byte
                is1 = new BufferedStream(new FileStream(file1.FullName, FileMode.Open, FileAccess.Read));
                is2 = new BufferedStream(new FileStream(file2.FullName, FileMode.Open, FileAccess.Read));
                int ch1 = 0;
                int ch2 = 0;
                while ((ch1 = is1.ReadByte()) != - 1 && (ch2 = is2.ReadByte()) != - 1)
                {
                    Assert.AreEqual(ch1, ch2);
                }
                log.Debug("Contents equal");
            }
            catch (SystemException ex)
            {
                Assert.Fail("Caught exception: " + ex.Message);
            }
            finally
            {
                if (is1 != null)
                    is1.Close();
                if (is2 != null)
                    is2.Close();
            }
        }
Exemple #21
0
		private void readMap(Stream s, List<ITile> tiles)
		{
			BufferedStream input = new BufferedStream(s);
			int rows = input.ReadByte();
			int cols = input.ReadByte();
			int height = input.ReadByte();

			mapSize = new MapSize(rows, cols, height);

			//map = new MapTile[rows,cols,height];
			mapData = new XCMapTile[rows * cols * height];

			for (int h = 0; h < height; h++)
				for (int r = 0; r < rows; r++)
					for (int c = 0; c < cols; c++)
					{
						int q1 = input.ReadByte();
						int q2 = input.ReadByte();
						int q3 = input.ReadByte();
						int q4 = input.ReadByte();

						this[r, c, h] = createTile(tiles, q1, q2, q3, q4);
					}
			input.Close();
		}
		string ReadLine(BufferedStream stream)
		{
			List<byte> line = new List<byte>(4096);

			do
			{
				int i = stream.ReadByte();

				if (i == -1)
					break; 

				byte b = (byte)i;

				if (b == (byte)'\r')
					continue;
				else if (b == (byte)'\n')
					break;

				line.Add(b);
			} while (true);

			return Encoding.UTF8.GetString(line.ToArray());
		}
 private string streamReadLine(BufferedStream _in)
 {
     int next_char;
     string data = "";
     while (true)
     {
         next_char = _in.ReadByte();
         if (next_char == '\n') { break; }
         if (next_char == '\r') { continue; }
         if (next_char == -1) { Thread.Sleep(1); continue; };
         data += Convert.ToChar(next_char);
     }
     return data;
 }
		public UnityWebResponse(UnityWebRequest request)
		{
			ThreadPool.QueueUserWorkItem((arg) =>
			{
				try
				{
					int redirection = 0;

					TcpClient client = new TcpClient();
					Uri uri = request.uri;
					client.Connect(uri.Host, uri.Port);
					bool newConnection = true;
					Stream stream = null;

					do
					{
						#region Get stream
						if (newConnection)
						{
							client.SendTimeout = TIMEOUT;
							client.ReceiveTimeout = TIMEOUT;

							stream = client.GetStream();

							if (uri.Scheme == "https")
							{
								stream = new SslStream(stream, false,
									new RemoteCertificateValidationCallback((sender, cert, chain, error) => true));
								(stream as SslStream).AuthenticateAsClient(uri.Host);
							}
						}
						#endregion

						#region Request
						{
							BinaryWriter writer = new BinaryWriter(stream);
							writer.Write(Encoding.UTF8.GetBytes(request.method + " " +
								uri.PathAndQuery + " " + request.protocol + "\r\n"));

							request.headers["Host"] = uri.Host;
							
							foreach (DictionaryEntry kv in request.headers)
							{
								if (kv.Key is string && kv.Value is string)
								{
									writer.Write(Encoding.UTF8.GetBytes(kv.Key + ": " +
											kv.Value + "\r\n"));
								}
								else if (kv.Key is string && kv.Value is string[])
								{
									for (int i = 0; i < (kv.Value as string[]).Length; i++)
									{
										writer.Write(Encoding.UTF8.GetBytes(kv.Key + ": " +
												(kv.Value as string[])[i] + "\r\n"));
									}
								}
							}

							if (request.body != null)
							{
								writer.Write(Encoding.UTF8.GetBytes("Content-Length:" +
									request.body.Length + "\r\n\r\n"));
								writer.Write(request.body);
							}
							else
							{
								writer.Write(Encoding.UTF8.GetBytes("\r\n"));
							}
						}
						#endregion

						#region Response
						{
							BufferedStream bufferedStream = new BufferedStream(stream);

							#region Read headers
							{
								List<string> lines = new List<string>();

								do
								{
									string line = ReadLine(bufferedStream);

									if (line.Length == 0)
										break;

									lines.Add(line);
								} while (true);

								string[] statusLine = lines[0].Split(' ');
								this.httpVersion = statusLine[0];
								this.statusCode = int.Parse(statusLine[1]);
								this.reasonPhrase = string.Join(" ", statusLine, 2, statusLine.Length - 2);

								this.headers = new Hashtable();

								for (int i = 1; i < lines.Count; i++)
								{
									string k = lines[i].Substring(0, lines[i].IndexOf(':')).Trim();
									string v = lines[i].Substring(lines[i].IndexOf(':') + 1).Trim();

									if (!this.headers.ContainsKey(k))
									{
										this.headers.Add(k, v);
									}
									else
									{
										if (this.headers[k] is string)
										{
											string a = this.headers[k] as string;
											string[] b = { a, v };

											this.headers[k] = b;
										}
										else if (this.headers[k] is string[])
										{
											string[] a = this.headers[k] as string[];
											string[] b = new string[a.Length + 1];
											
											a.CopyTo(b, 0);
											b[a.Length - 1] = v;

											this.headers[k] = b;
										}
									}
								}
							}
							#endregion

							//UnityEngine.Debug.Log(DumpHeaders() +
							//    "\r\n" +
							//    "----");

							#region Read body
							{
								int contentLength = -1;
								if (this.headers.ContainsKey("Content-Length"))
									contentLength = int.Parse(this.headers["Content-Length"] as string);

								string transferEncoding = null;
								if (this.headers.ContainsKey("Transfer-Encoding"))
									transferEncoding = (this.headers["Transfer-Encoding"] as string).ToLower();

								if (contentLength >= 0)
								{
									this.bytes = new byte[contentLength];
									int bytesReceived = 0;

									while (bytesReceived < contentLength)
									{
										bytesReceived += bufferedStream.Read(this.bytes,
											bytesReceived, this.bytes.Length - bytesReceived);
									}
								}
								else if (transferEncoding == "chunked")
								{
									MemoryStream ms = new MemoryStream(4096);
									byte[] buffer = new byte[4096];
									
									do
									{
										string chunkSizeString = ReadLine(bufferedStream);
										
										if (chunkSizeString.Length == 0)
											break;

										int chunkSize = Convert.ToInt32(chunkSizeString, 16);

										if (chunkSize == 0)
											break;

										int bytesReceived = 0;

										while (bytesReceived < chunkSize)
										{
											int read = bufferedStream.Read(buffer, 0, 
												chunkSize - bytesReceived < buffer.Length ? 
												chunkSize - bytesReceived : buffer.Length);

											ms.Write(buffer, 0, read);
											bytesReceived += read;
										}

										bufferedStream.ReadByte(); // \r
										bufferedStream.ReadByte(); // \n
									} while (true);

									this.bytes = ms.ToArray();
									ms.Dispose();
								}
								else
								{
									MemoryStream ms = new MemoryStream(4096);
									byte[] buffer = new byte[4096];
									int read = 0;

									do
									{
										read = bufferedStream.Read(buffer, 0, buffer.Length);
										ms.Write(buffer, 0, read);
									} while (read > 0);

									this.bytes = ms.ToArray();
									ms.Dispose();
								}

								cachedText = null;
							}
							#endregion

							#region Redirection
							if ((this.statusCode == 301 ||
								this.statusCode == 302 ||
								this.statusCode == 303 ||
								this.statusCode == 307) &&
								this.headers.ContainsKey("Location") &&
								redirection < MAX_REDIRECTION)
							{
								string oldHost = uri.Host;

								string location = this.headers["Location"] as string;
								uri = new Uri(uri, location);

								if (oldHost != uri.Host)
								{
									stream.Close();
									client.Close();

									client = new TcpClient();
									client.Connect(uri.Host, uri.Port);

									newConnection = true;
								}
								else
									newConnection = false;

								redirection++;
								continue;
							}
							#endregion

							#region Decoding
							if (this.headers.ContainsKey("Content-Encoding"))
							{
								bytes = Decompress((this.headers["Content-Encoding"] as string).ToLower(), bytes);
							}
							#endregion

#if UNITY_EDITOR
							// test---
							UnityEngine.Debug.LogWarning(request.DumpHeaders() +
								(request.body == null ? "" : "Content-Length: " + request.body.Length + "\r\n") +
								"\r\n" +
								(request.body == null ? "" : Encoding.UTF8.GetString(request.body)));
							UnityEngine.Debug.LogWarning(DumpHeaders() +
								"\r\n" +
								this.text);
#endif
						}
						#endregion

						stream.Close();
						client.Close();
						break;
					} while (redirection < MAX_REDIRECTION);
				}
				catch (Exception e)
				{
					error = e;
				}
				finally
				{
					isDone = true;
				}
			});
		}
Exemple #25
0
        /// <summary>
        /// Get the crc32 value for a Stream, setting the position to to the beginPosition and calculation to the length.
        /// The position is set back to the original position when complete.
        /// </summary>
        /// <param name="st">The stream to perform the crc32 calculation on.</param>
        /// <param name="beginPosition">The begin position of the stream to start the calculation.</param>
        /// <param name="length">The length you wish to run the calculation on.</param>
        /// <returns>The crc32 value.</returns>
        public long CRC(Stream st, long beginPosition, long length)
        {
            ulong ulCRC = poly;
            long originalPos = st.Position;
            long endPos = beginPosition + length;
            byte by;

            if (endPos > st.Length)
            {
                throw new Exception("Out of bounds. beginposition + length is greater than the length of the Stream");
            }

            try
            {
                st.Position = beginPosition;
                BufferedStream bs = new BufferedStream(st);

                for(long i = beginPosition; i < endPos; i++)
                {
                    by =  Convert.ToByte(bs.ReadByte());
                    ulCRC = (ulCRC >> 8) ^ crcLookup[(ulCRC & 0xFF) ^ by];
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e.ToString());
            }
            finally
            {
            //For now do nothing
            }
            st.Position = originalPos;
            return Convert.ToInt64( ulCRC ^ poly);
        }
        //throws ServletException, IOException
        private int HandleRequest(HttpRequest request,
            HttpResponse response,
            HmuxChannel hmuxChannel,
            BufferedStream rs,
            BufferedStream ws,
            byte[] buf, int length, bool isComplete,
            bool allowBusy)
        {
            String traceId = hmuxChannel.GetTraceId();

              StringBuilder cb = new StringBuilder();

              bool isDebugFiner = true;

              String uri = Uri.EscapeUriString(request.RawUrl);
              Trace.TraceInformation("Hmux[{0}] >>U:uri {1}->{2}", traceId, request.RawUrl, uri);
              WriteRequestString(ws, HmuxChannel.HMUX_URI, uri, traceId);

              Trace.TraceInformation("Hmux[{0}] >>m:method {1}", traceId, request.HttpMethod);
              WriteRequestString(ws, HmuxChannel.HMUX_METHOD, request.HttpMethod, traceId);

              Trace.TraceInformation("Hmux[{0}] >>u:server type {1}", traceId, "IIS");
              WriteRequestString(ws, HmuxChannel.CSE_SERVER_TYPE, "IIS", traceId);

              NameValueCollection serverVariables = request.ServerVariables;

              String serverPort = serverVariables.Get("SERVER_PORT");
              String serverName = serverVariables.Get("SERVER_NAME") + ':' + serverPort;
              Trace.TraceInformation("Hmux[{0}] >>v:server name {1}", traceId, serverName);
              WriteRequestString(ws, HmuxChannel.HMUX_SERVER_NAME, serverName, traceId);

              Trace.TraceInformation("Hmux[{0}] >>g:server port {1}", traceId, serverPort);
              WriteRequestString(ws, HmuxChannel.CSE_SERVER_PORT, serverPort, traceId);

              String remoteAddr = serverVariables.Get("REMOTE_ADDR");
              Trace.TraceInformation("Hmux[{0}] >>i:remote address {1}", traceId, remoteAddr);
              WriteRequestString(ws, HmuxChannel.CSE_REMOTE_ADDR, remoteAddr, traceId);

              String remoteHost = serverVariables.Get("REMOTE_HOST");
              if (remoteHost == null)
            remoteHost = remoteAddr;

              Trace.TraceInformation("Hmux[{0}] >>h:remote host {1}", traceId, remoteHost);
              WriteRequestString(ws, HmuxChannel.CSE_REMOTE_HOST, remoteHost, traceId);

              String protocol = serverVariables.Get("HTTP_VERSION");
              Trace.TraceInformation("Hmux[{0}] >>c:protocol {1}", traceId, protocol);
              WriteRequestString(ws, HmuxChannel.CSE_PROTOCOL, protocol, traceId);

              HttpClientCertificate clientCertificate = request.ClientCertificate;
              if (request.IsSecureConnection) {
            Trace.TraceInformation("Hmux[{0}] >>r:secure", traceId);
            WriteRequestString(ws, HmuxChannel.CSE_IS_SECURE, "", traceId);

            WriteRequestHeader(ws, "HTTPS", "on", traceId);
            WriteRequestHeader(ws, "SSL_SECRETKEYSIZE", clientCertificate.KeySize.ToString(), traceId);
              }

              if (clientCertificate.IsPresent) {
            Trace.TraceInformation("Hmux[{0}] >>r:certificate ({1})", traceId, clientCertificate.Certificate.Length);
            ws.WriteByte(HmuxChannel.CSE_CLIENT_CERT);
            WriteHmuxLength(ws, clientCertificate.Certificate.Length);
            ws.Write(clientCertificate.Certificate, 0, clientCertificate.Certificate.Length);
              }

              NameValueCollection headers = request.Headers;
              foreach (String key in headers.AllKeys) {
            if ("Connection".Equals(key, StringComparison.OrdinalIgnoreCase))
              continue;

            String[] values = headers.GetValues(key);
            foreach (String value in values) {
              WriteRequestHeader(ws, key, value, traceId);
            }
              }

              Stream requestStream = request.InputStream;
              Stream responseStream = null;

              bool hasHeader = true;
              bool hasStatus = false;

              if (length > 0) {
            Trace.TraceInformation("Hmux[{0}] >>D: data ({1})", traceId, length);
            WriteRequestData(ws, HmuxChannel.HMUX_DATA, buf, length, traceId);
              }

              int len;

              int code;

              while (!isComplete && (len = requestStream.Read(buf, 0, buf.Length)) > 0) {
            Trace.TraceInformation("Hmux[{0}] >>D: data ({1})", traceId, length);
            WriteRequestData(ws, HmuxChannel.HMUX_DATA, buf, len, traceId);

            Trace.TraceInformation("Hmux[{0}] >>Y: (yield)", traceId);
            ws.WriteByte(HmuxChannel.HMUX_YIELD);
            ws.Flush();

            while (true) {
              code = rs.ReadByte();

              if (code < 0) {
            Trace.TraceInformation("Hmux[{0}] <<w: end of file", traceId);

            if (hasStatus)
              return OK | EXIT;
            else {
              Trace.TraceInformation("Hmux[{0}] <<w: unexpected end of file", traceId);

              return FAIL | EXIT;
            }
              } else if (code == HmuxChannel.HMUX_QUIT) {
            Trace.TraceInformation("Hmux[{0}] <<Q: (keepalive)", traceId);

            if (hasStatus)
              return OK | QUIT;
            else {
              Trace.TraceInformation("Hmux[{0}] <<Q: unexpected quit file", traceId);

              return FAIL | QUIT;
            }
              } else if (code == HmuxChannel.HMUX_EXIT) {
            Trace.TraceInformation("Hmux[{0}] <<X: (exit)", traceId);

            if (hasStatus) {
              return OK | EXIT;
            } else {
              Trace.TraceInformation("Hmux[{0}] <<X: unexpected exit", traceId);

              return FAIL | EXIT;
            }
              } else if (code == HmuxChannel.HMUX_YIELD) {
            Trace.TraceInformation("Hmux[{0}] <<Y: (yield)", traceId);

            continue;
              }

              int sublen = ReadHmuxLength(rs);

              if (code == HmuxChannel.HMUX_ACK) {
            if (isDebugFiner)
              Trace.TraceInformation("Hmux[{0}] <<A: (ack) ({1})", traceId, sublen);

            break;
              } else if (code == HmuxChannel.HMUX_CHANNEL) {
            int channel = sublen;
            Trace.TraceInformation("Hmux[{0}] <<C: (channel) ({1})", traceId, channel);
              } else if (code == HmuxChannel.HMUX_STATUS && hasHeader) {
            String status = ReadHmuxString(rs, sublen);
            Trace.TraceInformation("Hmux[{0}] <<s: (status) ({1})", traceId, status);
            int statusCode = 0;
            for (int i = 0; i < 3; i++)
              statusCode = 10 * statusCode + status[i] - '0';

            if (statusCode != 200)
              response.StatusCode = statusCode;

            hasStatus = true;
              } else if (code == HmuxChannel.HMUX_HEADER && hasHeader) {
            String name = ReadHmuxString(rs, sublen);
            rs.ReadByte();
            sublen = ReadHmuxLength(rs);
            String value = ReadHmuxString(rs, sublen);

            Trace.TraceInformation("Hmux[{0}] <<H,S: (header) ({1}={2})", traceId, name, value);

            RelayResponseHeader(response, name, value);
              } else if (code == HmuxChannel.HMUX_DATA) {
            Trace.TraceInformation("Hmux[{0}] <<D: (data)({1})", traceId, sublen);

            if (responseStream == null)
              responseStream = response.OutputStream;

            RelayResponseData(rs, responseStream, sublen);
              } else if (code == HmuxChannel.HMUX_META_HEADER) {
            String name = ReadHmuxString(rs, sublen);
            rs.ReadByte();
            sublen = ReadHmuxLength(rs);
            String value = ReadHmuxString(rs, sublen);

            Trace.TraceInformation("Hmux[{0}] <<M,S: header ({1}={2})", traceId, name, value);

            if ("cpu-load".Equals(name)) {
              double loadAvg = 0.001 * long.Parse(value);

              hmuxChannel.GetPool().SetCpuLoadAvg(loadAvg);
            }
              } else {
            Skip(rs, sublen);
              }
            }
              }

              ws.WriteByte(HmuxChannel.HMUX_QUIT);
              ws.Flush();

              code = rs.ReadByte();

              // #2369 - A slow modem can cause the app-tier and web-tier times
              // to get out of sync, with the app-tier thinking it's completed
              // (and starts the keepalive timeout) 30s before the web-tier reads
              // its data.
              // As a temporary measure, we start the idle time at the first data
              // read (later we might mark the time it takes to read an app-tier
              // packet.  If it's short, e.g. 250ms, don't update the time.)
              hmuxChannel.SetIdleStartTime(DateTime.Now.Ticks);

              bool isBusy = false;
              for (; code >= 0; code = rs.ReadByte()) {
            if (code == HmuxChannel.HMUX_QUIT) {
              if (isDebugFiner)
            Trace.TraceInformation("Hmux[{0}] <<Q: (keepalive)", traceId);

              return isBusy ? BUSY | QUIT : OK | QUIT;
            } else if (code == HmuxChannel.HMUX_EXIT) {

              Trace.TraceInformation("Hmux[{0}] <<X: (exit)", traceId);

              return (isBusy || !hasStatus) ? BUSY | EXIT : OK | EXIT;
            } else if (code == HmuxChannel.HMUX_YIELD) {
              Trace.TraceInformation("Hmux[{0}] <<Y: (yield)", traceId);

              continue;
            }

            int sublen = (rs.ReadByte() << 8) + rs.ReadByte();

            if (code == HmuxChannel.HMUX_DATA) {
              if (responseStream == null)
            responseStream = response.OutputStream;

              Trace.TraceInformation("Hmux[{0}] <<D: (data)({1})", traceId, sublen);

              if (!isBusy)
            RelayResponseData(rs, responseStream, sublen);
              else
            Skip(rs, sublen);
            } else if (code == HmuxChannel.HMUX_STATUS && hasHeader) {
              hasStatus = true;
              String status = ReadHmuxString(rs, sublen);
              Trace.TraceInformation("Hmux[{0}] <<s: (status) ({1})", traceId, status);

              int statusCode = 0;
              for (int i = 0; i < 3; i++)
            statusCode = 10 * statusCode + status[i] - '0';

              if (statusCode == 503 && allowBusy)
            isBusy = true;
              else if (statusCode != 200)
            response.StatusCode = statusCode;
            } else if (code == HmuxChannel.HMUX_HEADER && hasHeader) {
              String name = ReadHmuxString(rs, sublen);
              rs.ReadByte();
              sublen = ReadHmuxLength(rs);
              String value = ReadHmuxString(rs, sublen);

              Trace.TraceInformation("Hmux[{0}] <<H,S: (header) ({1}={2})", traceId, name, value);

              if (!isBusy)
            RelayResponseHeader(response, name, value);
            } else if (code == HmuxChannel.HMUX_META_HEADER) {
              String name = ReadHmuxString(rs, sublen);
              rs.ReadByte();
              sublen = ReadHmuxLength(rs);
              String value = ReadHmuxString(rs, sublen);

              Trace.TraceInformation("Hmux[{0}] <<M,S: header ({1}={2})", traceId, name, value);

              if ("cpu-load".Equals(name)) {
            double loadAvg = 0.001 * long.Parse(value);

            hmuxChannel.GetPool().SetCpuLoadAvg(loadAvg);
              }
            } else if (code == HmuxChannel.HMUX_CHANNEL) {
              int channel = sublen;
              Trace.TraceInformation("Hmux[{0}] <<C: (channel) ({1})", traceId, channel);
            } else if (code == 0) {
              Trace.TraceInformation("Hmux[{0}] <<0: unknown code (0)", traceId);

              return FAIL | EXIT;
            } else {
              Trace.TraceInformation("Hmux[{0}] <<?: unknown code ({1})", traceId, code);
              Skip(rs, sublen);
            }
              }
              Trace.TraceInformation("Hmux[{0}] end of file", traceId);

              // server/269q
              if (hasStatus)
            return isBusy ? BUSY | EXIT : OK | EXIT;
              else {
            Trace.TraceInformation("Hmux[{0}] unexpected end of file", traceId, code);
            return FAIL | EXIT;
              }
        }
Exemple #27
0
	public void ReadByte_CantRead () 
	{
		WriteOnlyStream wo = new WriteOnlyStream ();
		BufferedStream stream = new BufferedStream (wo);
		stream.ReadByte ();
	}
	public void ReadByte ()
	{
		mem.Write (new byte [] {0, 1, 2, 3, 4, 5, 6, 7}, 0, 8);
		BufferedStream stream = new BufferedStream (mem);

		Assert.AreEqual (-1, stream.ReadByte (), "test#01");
		Assert.AreEqual (-1, stream.ReadByte (), "test#02");
		Assert.AreEqual (-1, stream.ReadByte (), "test#03");

		stream.Seek (0, SeekOrigin.Begin);
		Assert.AreEqual (0, stream.ReadByte (), "test#04");
		Assert.AreEqual (1, stream.ReadByte (), "test#05");
		Assert.AreEqual (2, stream.ReadByte (), "test#06");
		Assert.AreEqual (3, stream.ReadByte (), "test#07");		
	}
 private int ReadHmuxLength(BufferedStream stream)
 {
     int length = (stream.ReadByte() << 8) + stream.ReadByte();
       return length;
 }
Exemple #30
0
        private Response TcpRequest(Request request)
        {
            //System.Diagnostics.Stopwatch sw = new System.Diagnostics.Stopwatch();
            //sw.Start();

            byte[] responseMessage = new byte[512];

            for (int intAttempts = 0; intAttempts < m_Retries; intAttempts++)
            {
                for (int intDnsServer = 0; intDnsServer < m_DnsServers.Count; intDnsServer++)
                {
                    using( TcpClient tcpClient = new TcpClient() )
                    {
                        tcpClient.ReceiveTimeout = m_Timeout * 1000;

                        try
                        {
                            IAsyncResult result = tcpClient.BeginConnect(m_DnsServers[intDnsServer].Address, m_DnsServers[intDnsServer].Port, null, null);

                            bool success = result.AsyncWaitHandle.WaitOne(m_Timeout*1000, true);

                            if (!success || !tcpClient.Connected)
                            {
                                Verbose(string.Format(";; Connection to nameserver {0} failed", (intDnsServer + 1)));
                                continue;
                            }

                            BufferedStream bs = new BufferedStream(tcpClient.GetStream());

                            byte[] data = request.Data;
                            bs.WriteByte((byte)((data.Length >> 8) & 0xff));
                            bs.WriteByte((byte)(data.Length & 0xff));
                            bs.Write(data, 0, data.Length);
                            bs.Flush();

                            Response TransferResponse = new Response();
                            int intSoa = 0;
                            int intMessageSize = 0;

                            //Debug.WriteLine("Sending "+ (request.Length+2) + " bytes in "+ sw.ElapsedMilliseconds+" mS");

                            while (true)
                            {
                                int intLength = bs.ReadByte() << 8 | bs.ReadByte();
                                if (intLength <= 0)
                                {
                                    Verbose(string.Format(";; Connection to nameserver {0} failed", (intDnsServer + 1)));
                                    throw new SocketException(); // next try
                                }

                                intMessageSize += intLength;

                                data = new byte[intLength];
                                bs.Read(data, 0, intLength);
                                Response response = new Response(m_DnsServers[intDnsServer], data);

                                //Debug.WriteLine("Received "+ (intLength+2)+" bytes in "+sw.ElapsedMilliseconds +" mS");

                                if (response.header.RCODE != RCode.NoError)
                                    return response;

                                if (response.Questions[0].QType != QType.AXFR)
                                {
                                    AddToCache(response);
                                    return response;
                                }

                                // Zone transfer!!

                                if(TransferResponse.Questions.Count==0)
                                    TransferResponse.Questions.AddRange(response.Questions);
                                TransferResponse.Answers.AddRange(response.Answers);
                                TransferResponse.Authorities.AddRange(response.Authorities);
                                TransferResponse.Additionals.AddRange(response.Additionals);

                                if (response.Answers[0].Type == Type.SOA)
                                        intSoa++;

                                if (intSoa == 2)
                                {
                                    TransferResponse.header.QDCOUNT = (ushort)TransferResponse.Questions.Count;
                                    TransferResponse.header.ANCOUNT = (ushort)TransferResponse.Answers.Count;
                                    TransferResponse.header.NSCOUNT = (ushort)TransferResponse.Authorities.Count;
                                    TransferResponse.header.ARCOUNT = (ushort)TransferResponse.Additionals.Count;
                                    TransferResponse.MessageSize = intMessageSize;
                                    return TransferResponse;
                                }
                            }
                        } // try
                        catch (SocketException)
                        {
                            continue; // next try
                        }
                        finally
                        {
                            m_Unique++;
                        }
                    }
                }
            }
            Response responseTimeout = new Response();
            responseTimeout.Error = "Timeout Error";
            return responseTimeout;
        }
 private string ReadMessage(BufferedStream _in)
 {
     string ret = "";
     string line;
     while ((line = streamReadLine(_in)) != null)
     {
         ret += line + "\n";
         if (ret.ToString().EndsWith("\n\n"))
             break;
     }
     if (ret.Contains("Content-Length:"))
     {
         int conLen = int.Parse(ASocketMessage.ParseProperties(ret)["Content-Length"]);
         for (int x = 0; x < conLen; x++)
         {
             ret += Convert.ToChar(_in.ReadByte());
         }
     }
     return ret.Trim();
 }