public StreamByteCounter(Stream src)
    {
        AsyncCallback onEndRead = null;
        onEndRead = delegate(IAsyncResult ar) {
            int c = src.EndRead(ar);
            if (c != 0) {
                lock(this) { pendingReads++; }

                //
                // For each read, we must allocate a new buffer.
                //

                byte[] nb = new byte[CHUNK_SIZE];
                src.BeginRead(nb, 0, nb.Length, onEndRead, nb);

                //
                // The buffer of the current read is passed through the
                // IAsyncResult.AsyncState property.
                //

                byte[] cb = (byte[])ar.AsyncState;

                //
                // Increment occurrence counters.
                //

                lock(this) {
                    for (int i = 0; i < c; i++) {
                        counters[cb[i]]++;
                    }
                }
            }

            //
            // The data of the current read processed; so, decrement
            // the pending counter, and if the counter reaches zero,
            // signal the "done" event.
            //

            lock(this) {
                if (--pendingReads == 0) {
                    done.Set();
                }
            }
        };

        //
        // Allocate the buffer for the first read, and issue it.
        //

        byte[] fb = new byte[CHUNK_SIZE];
        pendingReads = 1;
        src.BeginRead(fb, 0, fb.Length, onEndRead, fb);
    }
Beispiel #2
0
 private bool EndReading(IAsyncResult result)
 {
     try
     {
         int bytesRead = netStream?.EndRead(result) ?? 0;
         return(ProcessReadBytes(bytesRead));
     }
     catch (Exception ex)
     {
         RecordConnectionFailed(ConnectionFailureType.InternalFailure, ex);
         return(false);
     }
 }
 public static bool ReadBeyondEndTest(Stream s)
 {
     Console.WriteLine("Read Beyond End test on "+s.GetType().Name);
     byte[] bytes = new byte[10];
     for(int i=0; i<bytes.Length; i++)
         bytes[i] = (byte) i;
     s.Seek(5, SeekOrigin.End);
     if (s.Position != s.Length + 5)
     {
         iCountErrors++;
         throw new Exception("Position is incorrect!  Seek(5, SeekOrigin.End) should leave us at s.Length + 5, but got: "+s.Position);
     }
     int numRead = s.Read(bytes, 0, bytes.Length);
     if (numRead != 0)
     {
         iCountErrors++ ;
         throw new Exception("Reading from past end of stream is broken!  Expected 0, got: "+numRead);
     }
     for(int i=0; i<bytes.Length; i++)
     {
         if (bytes[i] != (byte) i)
         {
             iCountErrors++ ;
             throw new Exception("Error in byte[] - Read overwrote it!  pos: "+i+"  got: "+bytes[i]);
         }
     }
     numRead = s.ReadByte();
     if (numRead != -1)
     {
         iCountErrors++ ;
         throw new Exception("ReadByte didn't return -1!  got: "+numRead);
     }
     IAsyncResult ar = s.BeginRead(bytes, 0, bytes.Length, null, null);
     numRead = s.EndRead(ar);
     if (numRead != 0)
     {
         iCountErrors++ ;
         throw new Exception("Reading from past end of stream with BeginRead is broken!  Expected 0, got: "+numRead);
     }
     for(int i=0; i<bytes.Length; i++)
         if (bytes[i] != (byte) i)
         {
             iCountErrors++ ;
             throw new Exception("Error in byte[] - BeginRead overwrote it!  pos: "+i+"  got: "+bytes[i]);
         }
     return true;
 }
        private void OnReadInternal(IAsyncResult ares)
        {
            _timer.Change(Timeout.Infinite, Timeout.Infinite);
            int nread = -1;

            try
            {
                nread = _stream.EndRead(ares);
                _memoryStream !.Write(_buffer !, 0, nread);
                if (_memoryStream.Length > 32768)
                {
                    SendError(HttpStatusDescription.Get(400), 400);
                    Close(true);
                    return;
                }
            }
            catch
            {
                if (_memoryStream != null && _memoryStream.Length > 0)
                {
                    SendError();
                }
                if (_socket != null)
                {
                    CloseSocket();
                    Unbind();
                }
                return;
            }

            if (nread == 0)
            {
                CloseSocket();
                Unbind();
                return;
            }

            if (ProcessInput(_memoryStream))
            {
                if (!_context.HaveError)
                {
                    _context.Request.FinishInitialization();
                }

                if (_context.HaveError)
                {
                    SendError();
                    Close(true);
                    return;
                }

                if (!_epl.BindContext(_context))
                {
                    const int NotFoundErrorCode = 404;
                    SendError(HttpStatusDescription.Get(NotFoundErrorCode), NotFoundErrorCode);
                    Close(true);
                    return;
                }
                HttpListener listener = _context._listener !;
                if (_lastListener != listener)
                {
                    RemoveConnection();
                    listener.AddConnection(this);
                    _lastListener = listener;
                }

                _contextBound = true;
                listener.RegisterContext(_context);
                return;
            }
            _stream.BeginRead(_buffer !, 0, BufferSize, s_onreadCallback, this);
        }
 /// <summary>
 /// Waits for the pending asynchronous read to complete.
 /// </summary>
 /// <param name="asyncResult">
 /// The reference to the pending asynchronous request to finish.
 /// </param>
 /// <returns>
 /// The number of bytes read from the stream, between zero (0)
 /// and the number of bytes you requested. Streams only return
 /// zero (0) at the end of the stream, otherwise, they should
 /// block until at least one byte is available.
 /// </returns>
 public override int EndRead(IAsyncResult asyncResult)
 {
     CheckClosed();
     return(stream.EndRead(asyncResult));
 }
 public override int EndRead(IAsyncResult asyncResult)
 {
     return(_underlyingStream.EndRead(asyncResult));
 }
Beispiel #7
0
 public override int EndRead(IAsyncResult asyncResult)
 {
     return(_innerStream.EndRead(asyncResult));
 }
Beispiel #8
0
 public override int EndRead(IAsyncResult asyncResult)
 {
     return(mBaseStream.EndRead(asyncResult));
 }
        /// <exception cref="BadRequestException"><c>BadRequestException</c>.</exception>
        private void OnReceive(IAsyncResult ar)
        {
            try
            {
                int bytesRead = Stream.EndRead(ar);
                if (bytesRead == 0)
                {
                    Disconnect(SocketError.ConnectionReset);
                    return;
                }
                _bytesLeft += bytesRead;
                if (_bytesLeft > _buffer.Length)
                {
#if DEBUG
                    throw new BadRequestException("Too large HTTP header: " + Encoding.UTF8.GetString(_buffer, 0, bytesRead));
#else
                    throw new BadRequestException("Too large HTTP header: " + _bytesLeft);
#endif
                }

#if DEBUG
#pragma warning disable 219
                string temp = Encoding.ASCII.GetString(_buffer, 0, _bytesLeft);
                LogWriter.Write(this, LogPrio.Trace, "Received: " + temp);
#pragma warning restore 219
#endif
                int offset = _parser.Parse(_buffer, 0, _bytesLeft);
                if (Stream == null)
                {
                    return;                     // "Connection: Close" in effect.
                }
                // try again to see if we can parse another message (check parser to see if it is looking for a new message)
                int oldOffset = offset;
                while (_parser.CurrentState == RequestParserState.FirstLine && offset != 0 && _bytesLeft - offset > 0)
                {
#if DEBUG
                    temp = Encoding.ASCII.GetString(_buffer, offset, _bytesLeft - offset);
                    LogWriter.Write(this, LogPrio.Trace, "Processing: " + temp);
#endif
                    offset = _parser.Parse(_buffer, offset, _bytesLeft - offset);
                    if (Stream == null)
                    {
                        return;                         // "Connection: Close" in effect.
                    }
                }

                // need to be able to move prev bytes, so restore offset.
                if (offset == 0)
                {
                    offset = oldOffset;
                }

                // workaround until the source of the bug can be identified.
                if (_bytesLeft < offset)
                {
                    _log.Write(this, LogPrio.Error, "Have a bug where _bytesLeft is less then offset, trying to fix. BytsLeft: " + _bytesLeft + ", offset: " + offset);
                    _bytesLeft = offset;
                }

                // copy unused bytes to the beginning of the array
                if (offset > 0 && _bytesLeft != offset)
                {
                    Buffer.BlockCopy(_buffer, offset, _buffer, 0, _bytesLeft - offset);
                }

                _bytesLeft -= offset;
                if (Stream != null && Stream.CanRead)
                {
                    Stream.BeginRead(_buffer, _bytesLeft, _buffer.Length - _bytesLeft, OnReceive, null);
                }
                else
                {
                    _log.Write(this, LogPrio.Warning, "Could not read any more from the socket.");
                    Disconnect(SocketError.Success);
                }
            }
            catch (BadRequestException err)
            {
                LogWriter.Write(this, LogPrio.Warning, "Bad request, responding with it. Error: " + err);
                try
                {
                    Respond("HTTP/1.0", HttpStatusCode.BadRequest, err.Message);
                }
                catch (Exception err2)
                {
                    LogWriter.Write(this, LogPrio.Fatal, "Failed to reply to a bad request. " + err2);
                }
                Disconnect(SocketError.NoRecovery);
            }
            catch (IOException err)
            {
                LogWriter.Write(this, LogPrio.Debug, "Failed to end receive: " + err.Message);
                if (err.InnerException is SocketException)
                {
                    Disconnect((SocketError)((SocketException)err.InnerException).ErrorCode);
                }
                else
                {
                    Disconnect(SocketError.ConnectionReset);
                }
            }
            catch (ObjectDisposedException err)
            {
                LogWriter.Write(this, LogPrio.Debug, "Failed to end receive : " + err.Message);
                Disconnect(SocketError.NotSocket);
            }
            catch (NullReferenceException err)
            {
                LogWriter.Write(this, LogPrio.Debug, "Failed to end receive : NullRef: " + err.Message);
                Disconnect(SocketError.NoRecovery);
            }
        }
Beispiel #10
0
 /// <inheritdoc/>
 public override int EndRead(IAsyncResult asyncResult)
 {
     ThrowIfDisposed();
     return(_stream.EndRead(asyncResult));
 }
Beispiel #11
0
 public static bool CanPropertiesTest(Stream s) 
 {
     Console.WriteLine("  (06)  Can-Properties Test on "+s.GetType( ).Name);
     byte[]			bytes				= new byte[1];
     int				bytesTransferred;
     IAsyncResult	asyncResult;
     if(s.CanRead) 
     {			//	Ensure all Read methods work, if CanRead is true.
         int		n	= s.ReadByte( );
         if(n==-1)
             throw new Exception("On a readable stream, ReadByte returned -1...");
         bytesTransferred=s.Read(bytes,0,1);
         if(bytesTransferred!=1)
             throw new Exception("Read(byte[],0,1) should have returned 1!  got: "+bytesTransferred);
         asyncResult=s.BeginRead(bytes,0,1,null,null);									/*	BeginRead	*/ 
         bytesTransferred=s.EndRead(asyncResult);										/*	EndRead		*/ 
         if(bytesTransferred!=1)
             throw new Exception("BeginRead(byte[],0,1) should have returned 1!  got: "
                 +bytesTransferred);
     }						//	End of (s.CanRead) Block
     else 
     {					//	Begin of (!s.CanRead) Block
         try 
         {
             s.ReadByte( );
             throw new Exception("ReadByte on an unreadable stream should have thrown!");
         }
         catch(NotSupportedException)	{	}
         try 
         {
             s.Read(bytes,0,1);
             throw new Exception("Read(bytes,0,1) on an unreadable stream should have thrown!");
         }
         catch(NotSupportedException)	{	}
         try 
         {
             s.BeginRead(bytes,0,1,null,null);											/*	BeginRead	*/ 
             throw new Exception("BeginRead on an unreadable stream should have thrown!");
         }
         catch(NotSupportedException)	{	}
     }						//	End of (!s.CanRead) Block
     if(s.CanWrite) 
     {		//	Ensure write methods work if CanWrite returns true.
         s.WriteByte(0);
         s.Write(bytes,0,1);
         asyncResult = s.BeginWrite(bytes,0,1,null,null);								/*	BeginWrite	*/ 
         s.EndWrite(asyncResult);														/*	EndWrite	*/ 
     }						//	End of (s.CanWrite) Block
     else 
     {					//	Begin of (!s.CanWrite) Block
         try 
         {
             s.WriteByte(2);
             throw new Exception("WriteByte on an unreadable stream should have thrown!");
         }
         catch(NotSupportedException)	{	}
         try 
         {
             s.Write(bytes,0,1);
             throw new Exception("Write(bytes,0,1) on an unreadable stream should have thrown!");
         }
         catch(NotSupportedException)	{	}
         try 
         {
             s.BeginWrite(bytes,0,1,null,null);											/*	BeginWrite	*/ 
             throw new Exception("BeginWrite on an unreadable stream should have thrown!");
         }
         catch(NotSupportedException)	{	}
     }						//	End of (!s.CanWrite) Block
     if(s.CanSeek) 
     {			//	Ensure length-related methods work if CanSeek returns true
         long	n	= s.Length;
         n=s.Position;
         if(s.Position>s.Length)
             throw new Exception("Position is beyond the length of the stream!");
         s.Position=0;
         s.Position=s.Length;
         if(s.Position!=s.Seek(0,SeekOrigin.Current))
             throw new Exception("s.Position!=s.Seek(0,SeekOrigin.Current)");
         if(s.CanWrite)		//	Verify you can set the length, if it's writable.
             s.SetLength(s.Length);
     }						//	End of (s.CanSeek) Block
     else 
     {					//	Begin of (!s.CanSeek) Block
         try 
         {
             s.Position=5;
             throw new Exception("set_Position should throw on a non-seekable stream!");
         }
         catch(NotSupportedException)	{	}
         try 
         {
             long	n	= s.Position;
             throw new Exception("get_Position should throw on a non-seekable stream!");
         }
         catch(NotSupportedException)	{	}
         try 
         {
             long	n	= s.Length;
             throw new Exception("get_Length should throw on a non-seekable stream!");
         }
         catch(NotSupportedException)	{	}
         try 
         {
             s.SetLength(1);
             throw new Exception("SetLength should throw on a non-seekable stream!");
         }
         catch(NotSupportedException)	{	}
         try 
         {
             s.Seek(0,SeekOrigin.Current);
             throw new Exception("Seek should throw on a non-seekable stream!");
         }
         catch(NotSupportedException)	{	}
     }						//	End of (!s.CanSeek) Block
     return true;
 }
Beispiel #12
0
    //
    // File copy using APM performs asynchronous reads and asynchronous
    // write operations.
    //
    static long ApmFileCopy2(Stream src, Stream dst)
    {
        var done = new ManualResetEventSlim(false);
        long fileSize = 0;
        IOException ioex = null;
        int pendingWrites = 1;		// Account for the last read of 0 bytes.
        AsyncCallback onReadCompleted = null, onWriteCompleted = null;

        onReadCompleted = delegate (IAsyncResult ar) {
            int bytesRead = 0;
            byte[] _rbuffer = (byte[])ar.AsyncState;
            try {
                bytesRead = src.EndRead(ar);
            } catch (IOException _ioex) {
                src.Close();
                dst.Close();
                ioex = _ioex;
                done.Set();
                return;
            }
            if (bytesRead != 0) {

                //
                // Allocate a buffer for the next read, and start write the current
                // read buffer.
                //

                var writeFrom = (byte[])ar.AsyncState;

                //
                // Increment the pending writes counter and start writing
                // the current read block.
                //

                Interlocked.Increment(ref pendingWrites);
                dst.BeginWrite(writeFrom, 0, bytesRead, onWriteCompleted, bytesRead);

                //
                // After the write is taking place, start a new read.
                // We ensure that the read block are written with the proper order.
                //

                var readTo = new byte[BUFFER_SIZE];
                src.BeginRead(readTo, 0, readTo.Length, onReadCompleted, readTo);
            } else {

                // End of source file.

                src.Close();

                //
                // Decrement the pending writes count and terminate copy if
                // all writes are done.
                //

                if (Interlocked.Decrement(ref pendingWrites) == 0) {

                    //
                    // No writes are pending, close the destination file and
                    // set the *done* event.
                    //

                    dst.Close();
                    done.Set();
                }
            }
        };

        onWriteCompleted = delegate (IAsyncResult ar) {
            int bytesWritten = (int)ar.AsyncState;
            try {
                dst.EndWrite(ar);
                fileSize += bytesWritten;
            } catch (IOException _ioex) {
                dst.Close();
                src.Close();
                ioex = _ioex;
                done.Set();
                return;
            }

            //
            // Decrement the pending writes count and terminate copy if
            // all writes are done.
            //

            if (Interlocked.Decrement(ref pendingWrites) == 0) {

                //
                // No writes are pending, close the destination file and
                // set the *done* event.
                //

                dst.Close();
                done.Set();
            }
        };

        //
        // Start the copy process, issuing the first asynchronous read.
        //

        var firstBuf = new byte[BUFFER_SIZE];
        src.BeginRead(firstBuf, 0, firstBuf.Length, onReadCompleted, firstBuf);

        // Wait until completion.

        done.Wait();
        if (ioex != null) {
            throw ioex;
        }
        return fileSize;
    }
Beispiel #13
0
        /// <exception cref="BadRequestException"><c>BadRequestException</c>.</exception>
        private void OnReceive(IAsyncResult ar)
        {
            try
            {
                lock (_syncRoot)
                {
                    int bytesRead = 0;

                    if (Stream != null)
                    {
                        bytesRead = Stream.EndRead(ar);
                    }

                    if (bytesRead == 0)
                    {
                        Disconnect(SocketError.ConnectionReset);
                        return;
                    }
                    _bytesLeft += bytesRead;
                    if (_bytesLeft > _buffer.Length)
                    {
#if DEBUG
                        throw new BadRequestException("Too large HTTP header: " + Encoding.UTF8.GetString(_buffer, 0, bytesRead));
#else
                        throw new BadRequestException("Too large HTTP header: " + _bytesLeft);
#endif
                    }

                    LogWriter.Write(this, LogPrio.Trace, "Received " + _bytesLeft + " bytes");

                    int offset = _parser.Parse(_buffer, 0, _bytesLeft);
                    if (Stream == null)
                    {
                        return; // "Connection: Close" in effect.
                    }
                    // try again to see if we can parse another message (check parser to see if it is looking for a new message)
                    int oldOffset = offset;
                    while (_parser.CurrentState == RequestParserState.FirstLine && offset != 0 && _bytesLeft - offset > 0)
                    {
                        offset = _parser.Parse(_buffer, offset, _bytesLeft - offset);
                        if (Stream == null)
                        {
                            return; // "Connection: Close" in effect.
                        }
                    }

                    // need to be able to move prev bytes, so restore offset.
                    if (offset == 0)
                    {
                        offset = oldOffset;
                    }

                    if (_bytesLeft - offset >= 0)
                    {
                        // copy unused bytes to the beginning of the array
                        if (offset > 0 && _bytesLeft != offset)
                        {
                            Buffer.BlockCopy(_buffer, offset, _buffer, 0, _bytesLeft - offset);
                        }

                        _bytesLeft -= offset;
                    }
                    else
                    {
                        _log.Write(this, LogPrio.Warning, "Cannot copy bytes, _bytesLeft=" + _bytesLeft + ", offset=" + offset);
                    }

                    if (Stream != null && Stream.CanRead)
                    {
                        Stream.BeginRead(_buffer, _bytesLeft, _buffer.Length - _bytesLeft, OnReceive, null);
                    }
                    else
                    {
                        _log.Write(this, LogPrio.Warning, "Could not read any more from the socket.");
                        Disconnect(SocketError.Success);
                    }
                }
            }
            catch (BadRequestException err)
            {
                LogWriter.Write(this, LogPrio.Warning, "Bad request, responding with it. Error: " + err);
                try
                {
                    Respond(HttpHelper.HTTP10, HttpStatusCode.BadRequest, err.Message);
                }
                catch (Exception err2)
                {
                    LogWriter.Write(this, LogPrio.Fatal, "Failed to reply to a bad request. " + err2);
                }
                Disconnect(SocketError.NoRecovery);
            }
            catch (IOException err)
            {
                LogWriter.Write(this, LogPrio.Debug, "Failed to end receive: " + err.Message);
                if (err.InnerException is SocketException)
                {
                    Disconnect((SocketError)((SocketException)err.InnerException).ErrorCode);
                }
                else
                {
                    Disconnect(SocketError.ConnectionReset);
                }
            }
            catch (ObjectDisposedException err)
            {
                LogWriter.Write(this, LogPrio.Debug, "Failed to end receive : " + err.Message);
                Disconnect(SocketError.NotSocket);
            }
        }
Beispiel #14
0
        private void readPacket(Stream st, CancellationToken token)
        {
            byte[] buf = new byte[0x40];
            int    offset = 0, buf_length = 0;

            MemoryStream st_page = new MemoryStream(buf, 4, 32, false);
            BinaryReader reader  = new BinaryReader(st_page);

            const int packet_length = 38;

            bool read_next = true;

            while (read_next)
            {
                bool reading = true;

                if (offset > 0)
                {
                    Array.Copy(buf, offset, buf, 0, buf_length -= offset);
                }

                st.BeginRead(buf, buf_length, packet_length - buf_length, result =>
                {
                    try
                    {
                        int additional = st.EndRead(result);
                        if (additional == 0)
                        {
                            read_next = false;
                        }
                        buf_length += additional;
                    }
                    catch (Exception ex)
                    {
                        if (ex is IOException || ex is ObjectDisposedException)
                        {
                            read_next = false;
                        }
                        else
                        {
                            throw;
                        }
                    }
                    reading = false;
                }, null);

                while (reading)
                {
                    token.ThrowIfCancellationRequested();
                }

                if (buf_length < packet_length)
                {
                    continue;
                }

                offset = 0;
                if (buf[0] != Sylphide_Protocol.header0)
                {
                    offset = 1;
                    continue;
                }
                if (buf[1] != Sylphide_Protocol.header1)
                {
                    offset = 2;
                    continue;
                }

                // buf[2..3] sequence number, not necessary
                // buf[36..37] cheksum, not necessary

                st_page.Position = 0;
                readOnePage(reader); // update by using page information

                buf_length = 0;
            }
        }
Beispiel #15
0
        private void ReceivedData(IAsyncResult ar)
        {
            RequestState   rs        = (RequestState)ar.AsyncState;
            HttpWebRequest req       = rs.Req;
            Stream         resStream = rs.ResStream;
            string         url       = rs.Url;
            UrlType        urltype   = rs.WebUrlType;
            string         html      = null;
            int            index     = rs.Index;
            int            read      = 0;
            string         HttpStatus;

            try
            {
                read = resStream.EndRead(ar);
                if (_stop)
                {
                    rs.ResStream.Close();
                    req.Abort();
                    return;
                }
                if (read > 0)
                {
                    MemoryStream ms     = new MemoryStream(rs.Data, 0, read);
                    StreamReader reader = new StreamReader(ms, _encoding);
                    string       str    = reader.ReadToEnd();
                    rs.Html.Append(str);
                    var result = resStream.BeginRead(rs.Data, 0, rs.BufferSize,
                                                     new AsyncCallback(ReceivedData), rs);
                    return;
                }
                html = rs.Html.ToString();
                SgmlReader sgmlRreader = new SgmlReader();
                sgmlRreader.DocType     = "HTML";
                sgmlRreader.InputStream = new StringReader(html);
                StringWriter  sw     = new StringWriter();
                XmlTextWriter writer = new XmlTextWriter(sw);
                writer.Formatting = Formatting.Indented;
                while (sgmlRreader.Read())
                {
                    if (sgmlRreader.NodeType != XmlNodeType.Whitespace)
                    {
                        writer.WriteNode(sgmlRreader, true);
                    }
                }

                SaveContents(sw.ToString(), url, urltype);
                HttpStatus = WebExceptionStatus.Success.ToString();
            }
            catch (WebException we)
            {
                _log.Error("ReceivedData: url = {0}, HttpStatus = {1}, Exception:{2}.", url, we.Status, we.Message);
                _log.Error(we.StackTrace);

                HttpStatus = we.Status.ToString();
            }
            catch (Exception e)
            {
                _log.Error("ReceivedData: url = {0}, Exception:{1}.", url, e.Message);
                _log.Error(e.StackTrace);

                HttpStatus = e.Message;
            }

            UrlInfo urlInfo = new UrlInfo(url, HttpStatus);

            _dbm.write_to_db(urlInfo);

            if (ContentsSaved != null)
            {
                ContentsSaved(HttpStatus, url);
            }

            _reqsBusy[index] = false;
            RequestResource(index);
        }
Beispiel #16
0
        private void ReadCallback(IAsyncResult iar)
        {
            byte[] input = null;
            try {
                input = (byte[])iar.AsyncState;
                usb_fs.EndRead(iar);
            } catch (Exception ex) {
                System.Console.WriteLine("EndRead exception:");
                System.Console.WriteLine(ex);
            }

            try {
                /* Data received, as bytes
                 */
                if (this.verbose_mode > 0)
                {
                    System.Console.WriteLine("");
                    System.Console.WriteLine("IN BYTES:");
                    for (int i = 0; i < input.Length; i++)
                    {
                        if (i > 0 && i % 16 == 0)
                        {
                            System.Console.WriteLine("");
                        }
                        System.Console.Write("{0:x} ", input[i]);
                    }
                    System.Console.WriteLine("");
                    System.Console.WriteLine("");
                }
                if (input.Length > 3 && input[2] == 0x6) // ACK 0x1 0x1 0x6
                {
                    last_message = null;
                    System.Console.WriteLine("ACK : DEVICE");
                }
                else if (input.Length > 3 && input[2] == 0x15) // NACK 0x1 0x1 0x15
                {
                    System.Console.WriteLine("NACK : DEVICE");
                    // resend message?
                }
                else if (read_continues && input.Length > 0)
                {
                    for (int i = 2; i < input[1] + 2; i++)
                    {
                        long_buffer.Add(input[i]);
                    }
                    if (long_buffer[long_buffer.Count - 2] == 0x3)
                    {
                        read_continues = false;
                        SendAck();
                        byte[] sliced = new byte[long_buffer.Count];
                        long_buffer.CopyTo(sliced);
                        long_buffer.Clear();
                        HandleMessageFromDevice(sliced);
                    }
                }
                else if (input.Length > 3 && input[1] + 2 <= usb_report_size && input[input[1]] == 0x3 && input[2] == 0x2)
                {
                    // single report message
                    // 0x1 {message_length_byte} {message_data_bytes}
                    System.Console.WriteLine("ACK : POS");
                    SendAck();
                    byte[] sliced = new byte[input.Length - 2];
                    Array.Copy(input, 2, sliced, 0, sliced.Length);
                    HandleMessageFromDevice(sliced);
                }
                else if (input.Length > 3 && input[1] == 30)
                {
                    // long message begins
                    read_continues = true;
                    long_buffer.Clear();
                    for (int i = 2; i < input[1] + 2; i++)
                    {
                        long_buffer.Add(input[i]);
                    }
                }
                else
                {
                    SendNack();
                    System.Console.WriteLine("unknown message");
                }
            } catch (Exception ex) {
                System.Console.WriteLine("Message data exception:");
                System.Console.WriteLine(ex);
            }

            AsyncRead();
        }
 public override int EndRead(IAsyncResult asyncResult)
 {
     resetFileStream();
     return(_fileStream.EndRead(asyncResult));
 }
Beispiel #18
0
 public static bool ErrorTest(Stream s) 
 {
     Console.WriteLine("  (09)  Error test on stream: "+s.GetType( ).Name);
     //	Test EndRead & EndWrite's Type safety
     byte[]				bytes		= new byte[0];
     IAsyncResult		asyncResult;
     BogusIAsyncResult	bogus		= new BogusIAsyncResult( );
     if(s.CanRead) 
     {
         asyncResult = s.BeginRead(bytes,0,0,null,null);									/*	BeginRead	*/ 
         try 
         {
             s.EndWrite(asyncResult);													/*	EndWrite	*/ 
             throw new Exception("EndWrite with an asyncResult from BeginRead should have thrown!");
         }
         catch(ArgumentException)	{	}
     }
     if(s.CanWrite) 
     {
         asyncResult=s.BeginWrite(bytes,0,0,null,null);									/*	BeginWrite	*/ 
         try 
         {
             s.EndRead(asyncResult);														/*	EndRead		*/ 
             throw new Exception("EndRead with an asyncResult from BeginWrite should have thrown!");
         }
         catch(ArgumentException)	{	}
         //	Verify EndWrite doesn't allow using the same asyncResult twice.
         s.EndWrite(asyncResult);														/*	EndWrite	*/ 
         try 
         {
             s.EndWrite(asyncResult);													/*	EndWrite	*/ 
             throw new Exception("Exception EndWrite was called twice w/ same IAsyncResult from "
                 +s.GetType( ).Name+", but didn't throw!");
         }
         catch(InvalidOperationException)	{	}
     }
     try 
     {
         s.EndRead(bogus);																/*	EndRead		*/ 
         throw new Exception("EndRead with a bogus IAsyncResult object should have thrown!");
     }
     catch(ArgumentException)	{	}
     try 
     {
         s.EndWrite(bogus);																/*	EndWrite	*/ 
         throw new Exception("EndWrite with a bogus IAsyncResult object should have thrown!");
     }
     catch(ArgumentException)	{	}
     return true;
 }
 public override int EndRead(IAsyncResult asyncResult) => _stream.EndRead(asyncResult);
 public override int EndRead(IAsyncResult asyncResult)
 {
     return(_requestStream.EndRead(asyncResult));
 }
        private void receiveData(IAsyncResult ar)
        {
            withExceptionHandling(() =>
            {
                var bytesRead = _socketStream.EndRead(ar);
                if (bytesRead == 0)
                {
                    _client.OnEndConnection();
                    return;
                }

                _currentFrameBufferCount += bytesRead;
                if (_currentFrameBufferCount < 6)
                {
                    goto readMore;
                }

                // Frames coming from a client must be masked.
                if ((_currentFrameBuffer[1] & 0x80) == 0)
                {
                    end();
                    return;
                }

                var payloadLenRaw = _currentFrameBuffer[1] & 0x7f;
                if (payloadLenRaw == 126 && _currentFrameBufferCount < 8)
                {
                    goto readMore;
                }
                if (payloadLenRaw == 127 && _currentFrameBufferCount < 14)
                {
                    goto readMore;
                }

                var payloadLen =
                    payloadLenRaw == 126 ? (int)Ut.BytesToUShort(_currentFrameBuffer, 2, true) :
                    payloadLenRaw == 127 ? (int)Ut.BytesToULong(_currentFrameBuffer, 2, true) :
                    payloadLenRaw;
                var i =
                    payloadLenRaw == 126 ? 4 :
                    payloadLenRaw == 127 ? 10 : 2;
                var maskingKeyIndex = i;
                i += 4;
                if (_currentFrameBufferCount < i + payloadLen)
                {
                    goto readMore;
                }
                var payloadIndex = i;

                // The frame is complete. Unmask the payload data...
                for (var j = 0; i < _currentFrameBufferCount; i++, j++)
                {
                    _currentFrameBuffer[i] ^= _currentFrameBuffer[maskingKeyIndex + (j % 4)];
                }

                // ... and then append the payload data to the current message.
                int dest;
                if (_currentMessage == null)
                {
                    _currentMessage       = new byte[payloadLen];
                    _currentMessageOpcode = (byte)(_currentFrameBuffer[0] & 0xf);
                    dest = 0;
                }
                else
                {
                    dest = _currentMessage.Length;
                    Array.Resize(ref _currentMessage, _currentMessage.Length + payloadLen);
                }
                Buffer.BlockCopy(_currentFrameBuffer, payloadIndex, _currentMessage, dest, payloadLen);

                // Check if the message is complete
                if ((_currentFrameBuffer[0] & 0x80) == 0x80)
                {
                    if (processMessage())
                    {
                        return;
                    }
                    _currentMessage = null;
                }

                // We’ve used the frame buffer, reinitialize it
                _currentFrameBufferCount = 0;
                if (_currentFrameBuffer.Length > 256)
                {
                    _currentFrameBuffer = new byte[256];
                }

                readMore:
                beginRead();
            });
        }
Beispiel #22
0
        private void EndReadHeader(IAsyncResult r)
        {
            var bytesRead = m_stream.EndRead(r);

            if (bytesRead <= 0)
            {
                return;
            }

            m_streamBytesRead += bytesRead;

            if (OnReadHeader != null)
            {
                OnReadHeader(m_streamBytesRead, m_streamReadBuffer);
            }

            if (m_streamBytesRead < m_streamBytesNeeded)
            {
                BeginReadHeader();
                return;
            }

            switch (m_streamReadState)
            {
            case StreamReadState.Response:
                if (Convert.ToChar(m_streamReadBuffer[0]) == '+')
                {
                    m_streamReadState   = StreamReadState.Size;
                    m_streamBytesNeeded = SizeLen;
                }
                else
                {
                    m_nextFileCompleteEventArgs.Result = DownloadResult.FileNotFound;
                    m_streamReadState   = StreamReadState.Id;
                    m_streamBytesNeeded = IdLen;
                }

                break;

            case StreamReadState.Size:
                m_nextFileCompleteEventArgs.Size = Util.ReadUInt64(m_streamReadBuffer, 0);
                m_streamReadState   = StreamReadState.Id;
                m_streamBytesNeeded = IdLen;
                break;

            case StreamReadState.Id:
                m_mutex.WaitOne();
                var next = m_downloadQueue.Peek();
                m_mutex.ReleaseMutex();
                m_nextFileCompleteEventArgs.DownloadItem = next;

                var match =
                    Util.ByteArraysAreEqual(next.Id.guid, 0, m_streamReadBuffer, 0, GuidLen) &&
                    Util.ByteArraysAreEqual(next.Id.hash, 0, m_streamReadBuffer, GuidLen, HashLen);

                if (!match)
                {
                    Close();
                    throw new InvalidDataException();
                }

                if (m_nextFileCompleteEventArgs.Result == DownloadResult.FileNotFound)
                {
                    OnDownloadFinished(m_nextFileCompleteEventArgs);
                }
                else
                {
                    var size = m_nextFileCompleteEventArgs.Size;
                    m_nextWriteStream   = next.GetWriteStream(size);
                    m_streamBytesNeeded = (int)size;
                    m_streamBytesRead   = 0;
                    BeginReadData();
                }

                return;

            default:
                throw new ArgumentOutOfRangeException();
            }

            m_streamBytesRead = 0;
            BeginReadHeader();
        }
Beispiel #23
0
        internal static void WriteToSync <T>(this Stream stream, Stream toStream, long?copyLength, long?maxLength, ChecksumRequested calculateChecksum, bool syncRead, ExecutionState <T> executionState, StreamDescriptor streamCopyState)
        {
            if (copyLength.HasValue && maxLength.HasValue)
            {
                throw new ArgumentException(SR.StreamLengthMismatch);
            }

            if (stream.CanSeek && maxLength.HasValue && stream.Length - stream.Position > maxLength)
            {
                throw new InvalidOperationException(SR.StreamLengthError);
            }

            if (stream.CanSeek && copyLength.HasValue && stream.Length - stream.Position < copyLength)
            {
                throw new ArgumentOutOfRangeException("copyLength", SR.StreamLengthShortError);
            }

            byte[] buffer = new byte[GetBufferSize(stream)];

            if (streamCopyState != null && calculateChecksum.HasAny && streamCopyState.ChecksumWrapper == null)
            {
                streamCopyState.ChecksumWrapper = new ChecksumWrapper(calculateChecksum.MD5, calculateChecksum.CRC64);
            }

            RegisteredWaitHandle waitHandle     = null;
            ManualResetEvent     completedEvent = null;

            if (!syncRead && executionState.OperationExpiryTime.HasValue)
            {
                completedEvent = new ManualResetEvent(false);
                waitHandle     = ThreadPool.RegisterWaitForSingleObject(
                    completedEvent,
                    StreamExtensions.MaximumCopyTimeCallback <T>,
                    executionState,
                    executionState.RemainingTimeout,
                    true);
            }

            try
            {
                long?bytesRemaining = copyLength;
                int  readCount;
                do
                {
                    if (executionState.OperationExpiryTime.HasValue && DateTime.Now.CompareTo(executionState.OperationExpiryTime.Value) > 0)
                    {
                        throw Exceptions.GenerateTimeoutException(executionState.Cmd != null ? executionState.Cmd.CurrentResult : null, null);
                    }

                    // Determine how many bytes to read this time so that no more than copyLength bytes are read
                    int bytesToRead = MinBytesToRead(bytesRemaining, buffer.Length);

                    if (bytesToRead == 0)
                    {
                        break;
                    }

                    // Read synchronously or asynchronously
                    readCount = syncRead
                                    ? stream.Read(buffer, 0, bytesToRead)
                                    : stream.EndRead(stream.BeginRead(buffer, 0, bytesToRead, null /* Callback */, null /* State */));

                    // Decrement bytes to write from bytes read
                    if (bytesRemaining.HasValue)
                    {
                        bytesRemaining -= readCount;
                    }

                    // Write
                    if (readCount > 0)
                    {
                        toStream.Write(buffer, 0, readCount);

                        // Update the StreamDescriptor after the bytes are successfully committed to the output stream
                        if (streamCopyState != null)
                        {
                            streamCopyState.Length += readCount;

                            if (maxLength.HasValue && streamCopyState.Length > maxLength.Value)
                            {
                                throw new InvalidOperationException(SR.StreamLengthError);
                            }

                            if (streamCopyState.ChecksumWrapper != null)
                            {
                                streamCopyState.ChecksumWrapper.UpdateHash(buffer, 0, readCount);
                            }
                        }
                    }
                }while (readCount != 0);

                if (bytesRemaining.HasValue && bytesRemaining != 0)
                {
                    throw new ArgumentOutOfRangeException("copyLength", SR.StreamLengthShortError);
                }
            }
            catch (Exception)
            {
                if (executionState.OperationExpiryTime.HasValue && DateTime.Now.CompareTo(executionState.OperationExpiryTime.Value) > 0)
                {
                    throw Exceptions.GenerateTimeoutException(executionState.Cmd != null ? executionState.Cmd.CurrentResult : null, null);
                }
                else
                {
                    throw;
                }
            }
            finally
            {
                if (waitHandle != null)
                {
                    waitHandle.Unregister(null);
                }

                if (completedEvent != null)
                {
                    completedEvent.Close();
                }
            }

            if (streamCopyState != null && streamCopyState.ChecksumWrapper != null)
            {
                if (streamCopyState.ChecksumWrapper.CRC64 != null)
                {
                    streamCopyState.Crc64 = streamCopyState.ChecksumWrapper.CRC64.ComputeHash();
                }
                if (streamCopyState.ChecksumWrapper.MD5 != null)
                {
                    streamCopyState.Md5 = streamCopyState.ChecksumWrapper.MD5.ComputeHash();
                }
                streamCopyState.ChecksumWrapper = null;
            }
        }
    private Boolean StreamTest(Stream stream, Boolean fSuppress)
    {
        if (!fSuppress)
        {
            Console.WriteLine("Testing " + stream.GetType() + " for read/write tests");
        }
        String strValue;
        Int32  iValue;
        Int32  iLength = 1 << 10;

        stream.Seek(0, SeekOrigin.Begin);
        for (int i = 0; i < iLength; i++)
        {
            stream.WriteByte((Byte)i);
        }
        Byte[] btArr = new Byte[iLength];
        for (int i = 0; i < iLength; i++)
        {
            btArr[i] = (Byte)i;
        }
        stream.Write(btArr, 0, iLength);
        BinaryWriter bw1 = new BinaryWriter(stream);

        bw1.Write(false);
        bw1.Write(true);
        for (int i = 0; i < 10; i++)
        {
            bw1.Write((Byte)i);
            bw1.Write((SByte)i);
            bw1.Write((Int16)i);
            bw1.Write((Char)i);
            bw1.Write((UInt16)i);
            bw1.Write(i);
            bw1.Write((UInt32)i);
            bw1.Write((Int64)i);
            bw1.Write((UInt64)i);
            bw1.Write((Single)i);
            bw1.Write((Double)i);
        }
        Char[] chArr = new Char[iLength];
        for (int i = 0; i < iLength; i++)
        {
            chArr[i] = (Char)i;
        }
        bw1.Write(chArr);
        bw1.Write(chArr, 512, 512);
        bw1.Write(new String(chArr));
        bw1.Write(new String(chArr));
        stream.Seek(0, SeekOrigin.Begin);
        for (int i = 0; i < iLength; i++)
        {
            if (stream.ReadByte() != i % 256)
            {
                return(false);
            }
        }
        btArr = new Byte[iLength];
        stream.Read(btArr, 0, iLength);
        for (int i = 0; i < iLength; i++)
        {
            if (btArr[i] != (Byte)i)
            {
                Console.WriteLine(i + " " + btArr[i] + " " + (Byte)i);
                return(false);
            }
        }
        BinaryReader br1 = new BinaryReader(stream);

        if (br1.ReadBoolean())
        {
            return(false);
        }
        if (!br1.ReadBoolean())
        {
            return(false);
        }
        for (int i = 0; i < 10; i++)
        {
            if (br1.ReadByte() != (Byte)i)
            {
                return(false);
            }
            if (br1.ReadSByte() != (SByte)i)
            {
                return(false);
            }
            if (br1.ReadInt16() != (Int16)i)
            {
                return(false);
            }
            if (br1.ReadChar() != (Char)i)
            {
                return(false);
            }
            if (br1.ReadUInt16() != (UInt16)i)
            {
                return(false);
            }
            if (br1.ReadInt32() != i)
            {
                return(false);
            }
            if (br1.ReadUInt32() != (UInt32)i)
            {
                return(false);
            }
            if (br1.ReadInt64() != (Int64)i)
            {
                return(false);
            }
            if (br1.ReadUInt64() != (UInt64)i)
            {
                return(false);
            }
            if (br1.ReadSingle() != (Single)i)
            {
                return(false);
            }
            if (br1.ReadDouble() != (Double)i)
            {
                return(false);
            }
        }
        chArr = br1.ReadChars(iLength);
        for (int i = 0; i < iLength; i++)
        {
            if (chArr[i] != (Char)i)
            {
                return(false);
            }
        }
        chArr = new Char[512];
        chArr = br1.ReadChars(iLength / 2);
        for (int i = 0; i < iLength / 2; i++)
        {
            if (chArr[i] != (Char)(iLength / 2 + i))
            {
                return(false);
            }
        }
        chArr = new Char[iLength];
        for (int i = 0; i < iLength; i++)
        {
            chArr[i] = (Char)i;
        }
        strValue = br1.ReadString();
        if (!strValue.Equals(new String(chArr)))
        {
            return(false);
        }
        strValue = br1.ReadString();
        if (!strValue.Equals(new String(chArr)))
        {
            return(false);
        }
        try{
            stream.Seek(1, SeekOrigin.Current);
            return(true);
        }catch (Exception) {
        }
        stream.Position = 0;
        btArr           = new Byte[iLength];
        for (int i = 0; i < iLength; i++)
        {
            btArr[i] = (Byte)(i + 5);
        }
        AsyncCallback acb1   = new AsyncCallback(new Co3965StreamMethods().AsyncTestCB);
        IAsyncResult  isync1 = stream.BeginWrite(btArr, 0, btArr.Length, acb1, stream.GetType().ToString());

        stream.EndWrite(isync1);
        stream.Position = 0;
        for (int i = 0; i < iLength; i++)
        {
            if (stream.ReadByte() != (Byte)(i + 5))
            {
                return(false);
            }
        }
        stream.Position = 0;
        AsyncCallback acb2 = new AsyncCallback(new Co3965StreamMethods().AsyncTestCB);

        Byte[]       btArr1 = new Byte[iLength];
        IAsyncResult isync2 = stream.BeginRead(btArr1, 0, btArr1.Length, acb2, stream.GetType().ToString());

        iValue = stream.EndRead(isync2);
        if (iValue != btArr.Length)
        {
            return(false);
        }
        for (int i = 0; i < iLength; i++)
        {
            if (btArr[i] != btArr1[i])
            {
                return(false);
            }
        }
        return(true);
    }
        public static int ReadEx(this Stream stream, byte[] buffer, int offset, int count, CancellationToken cancellation = default(CancellationToken))
        {
            if (stream == null)
            {
                throw new ArgumentNullException("stream");
            }
            if (buffer == null)
            {
                throw new ArgumentNullException("buffer");
            }
            if (offset < 0 || offset > buffer.Length)
            {
                throw new ArgumentOutOfRangeException("offset");
            }
            if (count <= 0 || count > buffer.Length)
            {
                throw new ArgumentOutOfRangeException("count"); //Disallow 0 as a debugging aid.
            }
            if (offset > buffer.Length - count)
            {
                throw new ArgumentOutOfRangeException("count");
            }

            int totalReadCount = 0;

            while (totalReadCount < count)
            {
                cancellation.ThrowIfCancellationRequested();

                int currentReadCount;

                //Big performance problem with BeginRead for other stream types than NetworkStream.
                //Only take the slow path if cancellation is possible.
                if (stream is NetworkStream && cancellation.CanBeCanceled)
                {
                    var ar = stream.BeginRead(buffer, offset + totalReadCount, count - totalReadCount, null, null);
                    if (!ar.CompletedSynchronously)
                    {
                        WaitHandle.WaitAny(new WaitHandle[] { ar.AsyncWaitHandle, cancellation.WaitHandle }, -1);
                    }

                    //EndRead might block, so we need to test cancellation before calling it.
                    //This also is a bug because calling EndRead after BeginRead is contractually required.
                    //A potential fix is to use the ReadAsync API. Another fix is to register a callback with BeginRead that calls EndRead in all cases.
                    cancellation.ThrowIfCancellationRequested();

                    currentReadCount = stream.EndRead(ar);
                }
                else
                {
                    //IO interruption not supported in this path.
                    currentReadCount = stream.Read(buffer, offset + totalReadCount, count - totalReadCount);
                }

                if (currentReadCount == 0)
                {
                    return(0);
                }

                totalReadCount += currentReadCount;
            }

            return(totalReadCount);
        }
        void OnReadInternal(IAsyncResult ares)
        {
            int nread = -1;

            try
            {
                nread = stream.EndRead(ares);
                ms.Write(buffer, 0, nread);

                if (ms.Length > 32768)
                {
                    SendError("Bad request", 400);
                    Close(true);
                    return;
                }
            }
            catch
            {
                if (ms != null && ms.Length > 0)
                {
                    SendError();
                }
                if (sock != null)
                {
                    CloseSocket();
                    Unbind();
                }
                return;
            }


            if (nread == 0)
            {
                //if (ms.Length > 0)
                //	SendError (); // Why bother?
                CloseSocket();
                Unbind();
                return;
            }

            if (ProcessInput(ms))
            {
                if (!context.HaveError)
                {
                    context.Request.FinishInitialization();
                }

                if (context.HaveError)
                {
                    SendError();
                    Close(true);
                    return;
                }

                if (!epl.BindContext(context))
                {
                    SendError("Invalid host", 400);
                    Close(true);
                    return;
                }
                HttpListener listener = context.Listener;
                if (last_listener != listener)
                {
                    RemoveConnection();
                    listener.AddConnection(this);
                    last_listener = listener;
                }

                context_bound = true;
                listener.RegisterContext(context);
                return;
            }
#if !ASYNCREAD
            stream.BeginRead(buffer, 0, BufferSize, onread_cb, this);
#else
            ReadLibuv();
            //BeginReadRequest();
#endif
        }
Beispiel #27
0
        private void InternalReadCallback(IAsyncResult asyncResult)
        {
            if (disposed)
            {
                return;
            }

            InternalAsyncResult internalAsyncResult = (InternalAsyncResult)asyncResult.AsyncState;
            bool haveDataToReturn = false;

            try
            {
                int bytesRead = 0;
                try
                {
                    bytesRead = innerStream.EndRead(asyncResult);
                }
                catch (Exception ex)
                {
                    // Set the exception into the internal async result
                    internalAsyncResult.SetComplete(ex);
                }
                if (bytesRead <= 0)
                {
                    // Zero byte read most likely indicates connection closed (if it's a network stream)
                    internalAsyncResult.SetComplete(0);
                    throw new IOException("Connection was closed by the remote endpoint");
                }
                else
                {
                    // Copy encrypted data into the SSL read_bio
                    read_bio.Write(read_buffer, bytesRead);
                    if (handShakeState == HandshakeState.InProcess ||
                        handShakeState == HandshakeState.RenegotiateInProcess)
                    {
                        // We are in the handshake, complete the async operation to fire the async
                        // handshake callback for processing
                        internalAsyncResult.SetComplete(bytesRead);
                        return;
                    }
                    uint   nBytesPending = read_bio.BytesPending;
                    byte[] decrypted_buf = new byte[SSL3_RT_MAX_PACKET_SIZE];
                    while (nBytesPending > 0)
                    {
                        int decryptedBytesRead = ssl.Read(decrypted_buf, decrypted_buf.Length);
                        if (decryptedBytesRead <= 0)
                        {
                            SslError lastError = ssl.GetError(decryptedBytesRead);
                            if (lastError == SslError.SSL_ERROR_WANT_READ)
                            {
                                // if we have bytes pending in the write bio.
                                // the client has requested a renegotiation
                                if (write_bio.BytesPending > 0)
                                {
                                    // Start the renegotiation by writing the write_bio data, and use the RenegotiationWriteCallback
                                    // to handle the rest of the renegotiation
                                    ArraySegment <byte> buf = write_bio.ReadBytes((int)write_bio.BytesPending);
                                    innerStream.BeginWrite(buf.Array, 0, buf.Count,
                                                           new AsyncCallback(RenegotiationWriteCallback),
                                                           internalAsyncResult);
                                    return;
                                }
                                // no data in the out bio, we just need more data to complete the record
                                //break;
                            }
                            else if (lastError == SslError.SSL_ERROR_WANT_WRITE)
                            {
                                // unexpected error!
                                //!!TODO debug log
                            }
                            else if (lastError == SslError.SSL_ERROR_ZERO_RETURN)
                            {
                                // Shutdown alert
                                SendShutdownAlert();
                                break;
                            }
                            else
                            {
                                //throw new OpenSslException();
                            }
                        }
                        if (decryptedBytesRead > 0)
                        {
                            // Write decrypted data to memory stream
                            long pos = decrypted_data_stream.Position;
                            decrypted_data_stream.Seek(0, SeekOrigin.End);
                            decrypted_data_stream.Write(decrypted_buf, 0, decryptedBytesRead);
                            decrypted_data_stream.Seek(pos, SeekOrigin.Begin);
                            haveDataToReturn = true;
                        }

                        // See if we have more data to process
                        nBytesPending = read_bio.BytesPending;
                    }
                    // Check to see if we have data to return, if not, fire the async read again
                    if (!haveDataToReturn)
                    {
                        innerStream.BeginRead(read_buffer, 0, read_buffer.Length, new AsyncCallback(InternalReadCallback),
                                              internalAsyncResult);
                    }
                    else
                    {
                        int bytesReadIntoUserBuffer = 0;

                        // Read the data into the buffer provided by the user (now hosted in the InternalAsyncResult)
                        bytesReadIntoUserBuffer = decrypted_data_stream.Read(internalAsyncResult.Buffer,
                                                                             internalAsyncResult.Offset,
                                                                             internalAsyncResult.Count);

                        internalAsyncResult.SetComplete(bytesReadIntoUserBuffer);
                    }
                }
            }
            //catch (IOException)
            //{
            //Connection lost
            // Close();
            //}
            catch (Exception ex)
            {
                internalAsyncResult.SetComplete(ex);
            }
        }
        public static Task <int> ReadAsync(this Stream stream, byte[] buffer)
        {
#if NET_4_6 || UNITY_WSA
            return(stream.ReadAsync(buffer, 0, buffer.Length));
#else
            return(FromAsync(cb => stream.BeginRead(buffer, 0, buffer.Length, cb, null), ar => stream.EndRead(ar)));
#endif
        }
Beispiel #29
0
        // 读取http返回数据流(回调)
        private void OnReadCallback(IAsyncResult asyncResult)
        {
            Stream responseStream = (Stream)asyncResult.AsyncState;

            try
            {
                int readCount = responseStream.EndRead(asyncResult);
                if (readCount > 0)
                {
                    mCurrentDownloadByte += readCount;

                    // write to file
                    if (mFileStream == null)
                    {
                        mFileStream = new FileStream(mTmpFile, FileMode.Create);
                    }
                    mFileStream.Write(m_Buffer, 0, readCount);

                    UpdateTimeOut();

                    // 进度回调
                    lock (mEvent)
                    {
                        for (int i = mEvent.Count - 1; i >= 0; i--)
                        {
                            if (mEvent[i] == DownloadEvent.Progress)
                            {
                                mEvent.RemoveAt(i);
                            }
                        }

                        mEvent.Add(DownloadEvent.Progress);
                    }

                    // 继续读取
                    responseStream.BeginRead(m_Buffer, 0, BUFFER_SIZE, new AsyncCallback(OnReadCallback), responseStream);
                }
                else // 已经读完
                {
                    responseStream.Close();
                    mFileStream.Close();

                    if (File.Exists(m_SaveFile))
                    {
                        File.Delete(m_SaveFile);
                    }
                    File.Move(mTmpFile, m_SaveFile);
                    Log.I("Finished!! fileLength:" + mFileLength + ",Download byte:" + mCurrentDownloadByte);

                    // 进度回调
                    lock (mEvent)
                    {
                        mEvent.Clear();
                        mEvent.Add(DownloadEvent.Finish);
                    }
                }
            }
            catch (Exception exception)
            {
                HandleError(exception.Message);
            }
        }
Beispiel #30
0
        void Read(IAsyncResult ar)
        {
            Stream stm = (Stream)ar.AsyncState;

            bytesRead = stm.EndRead(ar);
        }
Beispiel #31
0
 public override int EndRead(IAsyncResult async_result)
 {
     return(base_stream.EndRead(async_result));
 }
Beispiel #32
0
	private Boolean StreamTest(Stream stream, Boolean fSuppress){
		if(!fSuppress)
			Console.WriteLine("Testing " + stream.GetType() + " for read/write tests");
		String strValue;
		Int32 iValue;
		Int32 iLength = 1 << 10;
		stream.Seek(0, SeekOrigin.Begin);
		for(int i=0; i<iLength; i++)
			stream.WriteByte((Byte)i);
		Byte[] btArr = new Byte[iLength];
		for(int i=0; i<iLength; i++)
			btArr[i] = (Byte)i;
		stream.Write(btArr, 0, iLength);
		BinaryWriter bw1 = new BinaryWriter(stream);
		bw1.Write(false);
		bw1.Write(true);
		for(int i=0; i<10; i++){
			bw1.Write((Byte)i);
			bw1.Write((SByte)i);
			bw1.Write((Int16)i);
			bw1.Write((Char)i);
			bw1.Write((UInt16)i);
			bw1.Write(i);
			bw1.Write((UInt32)i);
			bw1.Write((Int64)i);
			bw1.Write((UInt64)i);
			bw1.Write((Single)i);
			bw1.Write((Double)i);
		}
		Char[] chArr = new Char[iLength];
		for(int i=0; i<iLength;i++)
			chArr[i] = (Char)i;
		bw1.Write(chArr);
		bw1.Write(chArr, 512, 512);
		bw1.Write(new String(chArr));
		bw1.Write(new String(chArr));
		stream.Seek(0, SeekOrigin.Begin);
		for(int i=0; i<iLength; i++){
			if(stream.ReadByte() != i%256){
                return false;
            }
		}
		btArr = new Byte[iLength];
		stream.Read(btArr, 0, iLength);
		for(int i=0; i<iLength; i++){
			if(btArr[i] != (Byte)i){
				Console.WriteLine(i + " "  + btArr[i] + " " + (Byte)i);
				return false;
			}
		}
		BinaryReader br1 = new BinaryReader(stream);
		if(br1.ReadBoolean())
			return false;
		if(!br1.ReadBoolean())
			return false;
		for(int i=0; i<10; i++){
			if(br1.ReadByte() != (Byte)i)
			return false;
			if(br1.ReadSByte() != (SByte)i)
			return false;
			if(br1.ReadInt16() != (Int16)i)
			return false;
			if(br1.ReadChar() != (Char)i)
			return false;
			if(br1.ReadUInt16() != (UInt16)i)
			return false;
			if(br1.ReadInt32() != i)
			return false;
			if(br1.ReadUInt32() != (UInt32)i)
			return false;
			if(br1.ReadInt64() != (Int64)i)
			return false;
			if(br1.ReadUInt64() != (UInt64)i)
			return false;
			if(br1.ReadSingle() != (Single)i)
			return false;
			if(br1.ReadDouble() != (Double)i)
			return false;
		}
		chArr = br1.ReadChars(iLength);
		for(int i=0; i<iLength;i++){
			if(chArr[i] != (Char)i)
			return false;
		}
		chArr = new Char[512];
		chArr = br1.ReadChars(iLength/2);
		for(int i=0; i<iLength/2;i++){
			if(chArr[i] != (Char)(iLength/2+i))
			return false;
		}
		chArr = new Char[iLength];
		for(int i=0; i<iLength;i++)
			chArr[i] = (Char)i;
		strValue = br1.ReadString();
		if(!strValue.Equals(new String(chArr)))
			return false;
		strValue = br1.ReadString();
		if(!strValue.Equals(new String(chArr))){
            return false;
        }
		try{
			stream.Seek(1, SeekOrigin.Current);
			return true;
			}catch(Exception){
		}
		stream.Position =  0;
		btArr = new Byte[iLength];
		for(int i=0; i<iLength; i++)
			btArr[i] = (Byte)(i + 5);
		AsyncCallback acb1 = new AsyncCallback(new Co3965StreamMethods().AsyncTestCB);
		IAsyncResult isync1 = stream.BeginWrite(btArr, 0, btArr.Length, acb1, stream.GetType().ToString());
		stream.EndWrite(isync1);
		stream.Position = 0;
		for(int i=0; i<iLength; i++){
			if(stream.ReadByte() != (Byte)(i+5))
			return false;
		}
		stream.Position = 0;
		AsyncCallback acb2 = new AsyncCallback(new Co3965StreamMethods().AsyncTestCB);
		Byte[] btArr1 = new Byte[iLength];
		IAsyncResult isync2 = stream.BeginRead(btArr1, 0, btArr1.Length, acb2, stream.GetType().ToString());
		iValue = stream.EndRead(isync2);
		if(iValue!=btArr.Length)
			return false;
		for(int i=0; i<iLength; i++){
			if(btArr[i] != btArr1[i])
				return false;
		}
		return true;
	}
Beispiel #33
0
 public int EndReceive(IAsyncResult asyncResult)
 {
     return(stream.EndRead(asyncResult, Error.Raise));
 }
Beispiel #34
0
 public override int EndRead(IAsyncResult result)
 {
     return(m_stream.EndRead(result));
 }
Beispiel #35
0
        internal int EndRead(HttpWebRequest request, IAsyncResult result)
        {
            Stream s = null;

            lock (this) {
                if (Data.request != request)
                {
                    throw new ObjectDisposedException(typeof(NetworkStream).FullName);
                }
                if (nstream == null)
                {
                    throw new ObjectDisposedException(typeof(NetworkStream).FullName);
                }
                s = nstream;
            }

            int            nbytes  = 0;
            bool           done    = false;
            WebAsyncResult wr      = null;
            IAsyncResult   nsAsync = ((WebAsyncResult)result).InnerAsyncResult;

            if (chunkedRead && (nsAsync is WebAsyncResult))
            {
                wr = (WebAsyncResult)nsAsync;
                IAsyncResult inner = wr.InnerAsyncResult;
                if (inner != null && !(inner is WebAsyncResult))
                {
                    nbytes = s.EndRead(inner);
                    done   = nbytes == 0;
                }
            }
            else if (!(nsAsync is WebAsyncResult))
            {
                nbytes = s.EndRead(nsAsync);
                wr     = (WebAsyncResult)result;
                done   = nbytes == 0;
            }

            if (chunkedRead)
            {
                try {
                    chunkStream.WriteAndReadBack(wr.Buffer, wr.Offset, wr.Size, ref nbytes);
                    if (!done && nbytes == 0 && chunkStream.WantMore)
                    {
                        nbytes = EnsureRead(wr.Buffer, wr.Offset, wr.Size);
                    }
                } catch (Exception e) {
                    if (e is WebException)
                    {
                        throw e;
                    }

                    throw new WebException("Invalid chunked data.", e,
                                           WebExceptionStatus.ServerProtocolViolation, null);
                }

                if ((done || nbytes == 0) && chunkStream.ChunkLeft != 0)
                {
                    HandleError(WebExceptionStatus.ReceiveFailure, null, "chunked EndRead");
                    throw new WebException("Read error", null, WebExceptionStatus.ReceiveFailure, null);
                }
            }

            return((nbytes != 0) ? nbytes : -1);
        }
Beispiel #36
0
 public static bool AsyncTest(Stream s) 
 {
     byte[]				bigArr		= new byte[80000];
     byte[]				smArr		= new byte[128];
     int					numBytes;
     AsyncCallback		cb;
     IAsyncResult		asyncResult;
     DateTime			startWait;
     TimeSpan			thirtySecs	= new TimeSpan(0,0,30);
     bool				firstTime;
     TimeSpan			diff;
     if(s.GetType( )==typeof(IsolatedStorageFileStream)) 
     {
         Console.WriteLine("AsyncTest won't run on an IsolatedStorageFileStream "
             +"since it doesn't support async operations.");
         return true;
     }
     Console.WriteLine("  (08)  Async test on "+s.GetType( ).Name);
     if(s.Position!=0)
         throw new Exception("AsyncTest assumes stream's position will be 0 when starting.");
     for(int i=0;i<smArr.Length;i++)		smArr[i] = (byte)i;
     //	Try writing something more than 64KB so we have a chance of doing an async write.
     for(int i=0;i<bigArr.Length;i++)	bigArr[i] = (byte)((i%26)+(byte)'A');
     //	Ensure that we do run our async callback at some point.
     didAsyncCallbackRun=false;
     cb = new AsyncCallback(AsyncTestCallback);
     asyncResult=s.BeginWrite(smArr,0,smArr.Length,cb,String.Empty);						/*	BeginWrite	*/ 
     s.EndWrite(asyncResult);															/*	EndWrite	*/ 
     if(s.Position!=smArr.Length)
         throw new Exception("After first BeginWrite call, (s.Position!=smArr.Length)  got: "
             +s.Position);
     asyncResult=s.BeginWrite(bigArr,0,bigArr.Length,null,String.Empty);
     s.EndWrite(asyncResult);
     if(s.Position!=bigArr.Length+smArr.Length)
         throw new Exception("After second BeginWrite call, s.Position wasn't right!  expected: "
             +(bigArr.Length+smArr.Length)+"  got: "+s.Position);
     //	And to be sure things work, test write with an offset.
     asyncResult=s.BeginWrite(smArr,smArr.Length/2,smArr.Length/2,null,null);			/*	BeginWrite	*/ 
     s.EndWrite(asyncResult);															/*	EndWrite	*/ 
     if(s.Position!=(smArr.Length/2+bigArr.Length+smArr.Length))
         throw new Exception("After third BeginWrite call, s.Position wasn't correct! expected: "
             +(smArr.Length/2+bigArr.Length+smArr.Length)
             +"  got: "+s.Position);
     startWait=DateTime.Now;
     firstTime=true;
     while(!didAsyncCallbackRun) 
     {
         if(firstTime) 
         {
             Console.WriteLine("Waiting for async callback to be run from first BeginWrite call.");
             firstTime=false;
         }
         else
             Console.Write(".");
         Thread.Sleep(20);
         diff=DateTime.Now-startWait;
         if(diff>thirtySecs)
             throw new Exception("Async callback didn't run yet after 2 BeginWRITE calls and "
                 +"30 seconds of blocking!  "
                 +"This could be a bug in a particular stream class, "
                 +"or an extremely pathetic race condition in this test.");
     }
     didAsyncCallbackRun=false;
     s.Position=0;
     byte[]		input	= new byte[(int)s.Length];
     //	Retest running the async callback here.
     asyncResult=s.BeginRead(input,0,smArr.Length,cb,String.Empty);						/*	BeginRead	*/ 
     numBytes=s.EndRead(asyncResult);													/*	BeginRead	*/ 
     if(numBytes!=smArr.Length)
         throw new Exception("After first BeginRead call, (numBytes!=smArr.Length)  got: "
             +numBytes);
     if(s.Position!=smArr.Length)
         throw new Exception("After first BeginRead call, (s.Position!=smArr.Length)  got: "
             +s.Position);
     asyncResult=s.BeginRead(input,smArr.Length,bigArr.Length,null,String.Empty);		/*	BeginRead	*/ 
     numBytes=s.EndRead(asyncResult);													/*	EndRead		*/ 
     if(numBytes!=bigArr.Length)
         throw new Exception("After second BeginRead call, (numBytes!=bigArr.Length)  got: "
             +numBytes);
     if(s.Position!=bigArr.Length+smArr.Length)
         throw new Exception("After second BeginRead call, s.Position wasn't right!  expected: "
             +(bigArr.Length+smArr.Length)+"  got: "+s.Position);
     asyncResult=s.BeginRead(input,smArr.Length+bigArr.Length,smArr.Length/2,null,null);	/*	BeginRead	*/ 
     numBytes=s.EndRead(asyncResult);													/*	EndRead		*/ 
     if(numBytes!=smArr.Length/2)
         throw new Exception("After third BeginRead call, (numBytes!=smArr.Length/2)  got: "
             +numBytes);
     if(s.Position!=(smArr.Length/2+bigArr.Length+smArr.Length))
         throw new Exception("After third BeginRead call, s.Position wasn't correct! expected: "
             +(smArr.Length/2+bigArr.Length+smArr.Length)
             +"  got: "+s.Position);
     for(int i=0;i<smArr.Length;i++)
         if (smArr[i]!=input[i])
             throw new Exception("When reading first smArr copy, position "
                 +i+" was wrong!  got: "
                 +input[i]+"  expected: "+smArr[i]);
     int		offset	= smArr.Length;
     for(int i=0;i<bigArr.Length;i++)
         if (bigArr[i]!=input[i+offset])
             throw new Exception("When reading bigArr copy, position "
                 +(i+offset)+" was wrong! i: "+i+"  got: "
                 +input[i+offset]+"  expected: "+bigArr[i]);
     offset=smArr.Length+bigArr.Length;
     for(int i=0;i<smArr.Length/2;i++)
         if (smArr[i+smArr.Length/2]!=input[i+offset])
             throw new Exception("When reading second smArr copy, position "
                 +(i+offset)+" was wrong! i: "+i+"  got: "
                 +input[i+offset]+"  expected: "
                 +smArr[i+smArr.Length/2]);
     startWait=DateTime.Now;
     firstTime=true;
     while(!didAsyncCallbackRun) 
     {
         if (firstTime) 
         {
             Console.WriteLine("Waiting for async callback to be run from "
                 +"first BeginRead call.");
             firstTime=false;
         }
         else
             Console.Write(".");
         Thread.Sleep(20);
         diff=DateTime.Now-startWait;
         if(diff>thirtySecs)
             throw new Exception("Async callback didn't run yet after 2 BeginREAD "
                 +"calls and 30 seconds of blocking!  "
                 +"This could be a bug in a particular stream "
                 +"class, or an extremely pathetic race "
                 +"condition in this test.");
     }
     didAsyncCallbackRun=false;
     return true;
 }
Beispiel #37
0
        static void ReadDone(IAsyncResult result)
        {
            WebConnection     cnc  = (WebConnection)result.AsyncState;
            WebConnectionData data = cnc.Data;
            Stream            ns   = cnc.nstream;

            if (ns == null)
            {
                cnc.Close(true);
                return;
            }

            int nread = -1;

            try {
                nread = ns.EndRead(result);
            } catch (ObjectDisposedException) {
                return;
            } catch (Exception e) {
                if (e.InnerException is ObjectDisposedException)
                {
                    return;
                }

                cnc.HandleError(WebExceptionStatus.ReceiveFailure, e, "ReadDone1");
                return;
            }

            if (nread == 0)
            {
                cnc.HandleError(WebExceptionStatus.ReceiveFailure, null, "ReadDone2");
                return;
            }

            if (nread < 0)
            {
                cnc.HandleError(WebExceptionStatus.ServerProtocolViolation, null, "ReadDone3");
                return;
            }

            int pos = -1;

            nread += cnc.position;
            if (data.ReadState == ReadState.None)
            {
                Exception exc = null;
                try {
                    pos = GetResponse(data, cnc.sPoint, cnc.buffer, nread);
                } catch (Exception e) {
                    exc = e;
                }

                if (exc != null || pos == -1)
                {
                    cnc.HandleError(WebExceptionStatus.ServerProtocolViolation, exc, "ReadDone4");
                    return;
                }
            }

            if (data.ReadState == ReadState.Aborted)
            {
                cnc.HandleError(WebExceptionStatus.RequestCanceled, null, "ReadDone");
                return;
            }

            if (data.ReadState != ReadState.Content)
            {
                int     est       = nread * 2;
                int     max       = (est < cnc.buffer.Length) ? cnc.buffer.Length : est;
                byte [] newBuffer = new byte [max];
                Buffer.BlockCopy(cnc.buffer, 0, newBuffer, 0, nread);
                cnc.buffer     = newBuffer;
                cnc.position   = nread;
                data.ReadState = ReadState.None;
                InitRead(cnc);
                return;
            }

            cnc.position = 0;

            WebConnectionStream stream = new WebConnectionStream(cnc, data);
            bool   expect_content      = ExpectContent(data.StatusCode, data.request.Method);
            string tencoding           = null;

            if (expect_content)
            {
                tencoding = data.Headers ["Transfer-Encoding"];
            }

            cnc.chunkedRead = (tencoding != null && tencoding.IndexOf("chunked", StringComparison.OrdinalIgnoreCase) != -1);
            if (!cnc.chunkedRead)
            {
                stream.ReadBuffer       = cnc.buffer;
                stream.ReadBufferOffset = pos;
                stream.ReadBufferSize   = nread;
                try {
                    stream.CheckResponseInBuffer();
                } catch (Exception e) {
                    cnc.HandleError(WebExceptionStatus.ReceiveFailure, e, "ReadDone7");
                }
            }
            else if (cnc.chunkStream == null)
            {
                try {
                    cnc.chunkStream = new ChunkStream(cnc.buffer, pos, nread, data.Headers);
                } catch (Exception e) {
                    cnc.HandleError(WebExceptionStatus.ServerProtocolViolation, e, "ReadDone5");
                    return;
                }
            }
            else
            {
                cnc.chunkStream.ResetBuffer();
                try {
                    cnc.chunkStream.Write(cnc.buffer, pos, nread);
                } catch (Exception e) {
                    cnc.HandleError(WebExceptionStatus.ServerProtocolViolation, e, "ReadDone6");
                    return;
                }
            }

            data.stream = stream;

            if (!expect_content)
            {
                stream.ForceCompletion();
            }

            data.request.SetResponseData(data);
        }
Beispiel #38
0
 public static bool SetLengthTest(Stream s) 
 {
     Console.WriteLine("  (10)  SetLengthTest on "+s.GetType( ).Name);
     if(!s.CanSeek) 
     {
         Console.WriteLine("SetLengthTest shouldn't run on non-seekable stream "+s.GetType( ).Name);
         try 
         {
             s.SetLength(0);
             throw new Exception("SetLength to 0 on a non-seekable stream should have failed!");
         }
         catch(NotSupportedException)	{	}
         return true;
     }
     if(!s.CanWrite) 
     {
         Console.WriteLine("SetLengthTest shouldn't run on non-writable stream "+s.GetType( ).Name);
         try 
         {
             s.SetLength(0);
             throw new Exception("SetLength to 0 on a non-writable stream should have failed!  "
                 +"s.Length: "+s.Length);
         }
         catch(NotSupportedException)	{	}
         return true;
     }
     s.SetLength(0);
     if(s.Length!=0)
         throw new Exception("SetLength to 0, but Length is: "+s.Length);
     if(s.Position!=0)
         throw new Exception("Set length to 0.  Position should be zero too: "+s.Position);
     s.SetLength(10);
     if(s.Length!=10)
         throw new Exception("SetLength to 10, but Length is: "+s.Length);
     if(s.Position!=0)
         throw new Exception("Set length to 10, yet Position should be zero still: "+s.Position);
     if(s.CanRead) 
     {
         byte[]			bytes			= new byte[500];
         IAsyncResult	asyncResult		= s.BeginRead(bytes,0,500,null,null);
         int				numBytes		= s.EndRead(asyncResult);
         if(numBytes!=10)
             throw new Exception("Number of bytes got back from EndRead was wrong!  "
                 +"should have been 10, but got: "+numBytes);
         if(s.Position!=10)
             throw new Exception("After async read, position should be 10, but was: "+s.Position);
     }
     return true;
 }
Beispiel #39
0
    //
    // File copy using APM asynchronous read and synchronous write operations.
    //
    static long ApmFileCopy(Stream src, Stream dst)
    {
        var done = new ManualResetEventSlim(false);
        long fileSize = 0;
        IOException ioex = null;
        AsyncCallback onReadCompleted = null;
        onReadCompleted = delegate(IAsyncResult iar) {
            int bytesRead = 0;
            try {
                bytesRead = src.EndRead(iar);
            } catch (IOException _ioex) {
                src.Close();
                dst.Close();
                ioex = _ioex;
                done.Set();
                return;
            }
            if (bytesRead != 0) {

                //
                // The read buffer is passed through IasyncResult.AsyncState.
                // Allocate a new buffer for the next read and issue an synchronous write.
                //
                // The lock ensures that we can't process the completion of the new read
                // completion before terminate the current write.
                //

                var writeFrom = (byte[])iar.AsyncState;
                var readTo = new byte[BUFFER_SIZE];
                lock(dst) {
                    src.BeginRead(readTo, 0, readTo.Length, onReadCompleted, readTo);
                    dst.Write(writeFrom, 0, bytesRead);
                    fileSize += bytesRead;
                }
            } else {

                //
                // We reach the EOF on the source stream.
                // We must ensure that the write of the last block is done,
                // before close the destination stream and set the event.
                //

                src.Close();
                lock(dst) {}
                dst.Close();
                done.Set();
                return;
            }
        };

        //
        // Start the copy process, issuingthe first asynchronous read.
        //

        var firstBuf = new byte[BUFFER_SIZE];
        src.BeginRead(firstBuf, 0, firstBuf.Length, onReadCompleted, firstBuf);

        // Wait until completion.

        done.Wait();
        if (ioex != null) {
            throw ioex;
        }
        return fileSize;
    }