Пример #1
0
        public override int EndRead(IAsyncResult asyncResult)
        {
            if (_disposed)
            {
                throw new ObjectDisposedException(GetType().ToString());
            }

            if (asyncResult == null)
            {
                throw new ArgumentNullException("asyncResult");
            }

            var ares = asyncResult as HttpStreamAsyncResult;

            if (ares == null)
            {
                throw new ArgumentException("A wrong IAsyncResult.", "asyncResult");
            }

            if (!ares.IsCompleted)
            {
                ares.AsyncWaitHandle.WaitOne();
            }

            if (ares.HasException)
            {
                throw new HttpListenerException(400, "I/O operation aborted.");
            }

            return(ares.Count);
        }
Пример #2
0
        private void onRead(IAsyncResult asyncResult)
        {
            var rState = (ReadBufferState)asyncResult.AsyncState;
            var ares   = rState.AsyncResult;

            try
            {
                var nread = base.EndRead(asyncResult);
                _decoder.Write(ares.Buffer, ares.Offset, nread);
                nread          = _decoder.Read(rState.Buffer, rState.Offset, rState.Count);
                rState.Offset += nread;
                rState.Count  -= nread;
                if (rState.Count == 0 || !_decoder.WantMore || nread == 0)
                {
                    _noMoreData = !_decoder.WantMore && nread == 0;
                    ares.Count  = rState.InitialCount - rState.Count;
                    ares.Complete();

                    return;
                }

                ares.Offset = 0;
                ares.Count  = Math.Min(_bufferLength, _decoder.ChunkLeft + 6);
                base.BeginRead(ares.Buffer, ares.Offset, ares.Count, onRead, rState);
            }
            catch (Exception ex)
            {
                _context.Connection.SendError(ex.Message, 400);
                ares.Complete(ex);
            }
        }
Пример #3
0
        public override WebResponse EndGetResponse(IAsyncResult asyncResult)
        {
            if (asyncResult == null)
            {
                throw new ArgumentNullException("AsyncResult cannot be null!");
            }

            if (!(asyncResult is FtpAsyncResult) || asyncResult != this.asyncResult)
            {
                throw new ArgumentException("AsyncResult is from another request!");
            }

            FtpAsyncResult asyncFtpResult = (FtpAsyncResult)asyncResult;

            if (!asyncFtpResult.WaitUntilComplete(timeout, false))
            {
                Abort();
                throw new WebException("Transfer timed out.", WebExceptionStatus.Timeout);
            }

            CheckIfAborted();

            asyncResult = null;

            if (asyncFtpResult.GotException)
            {
                throw asyncFtpResult.Exception;
            }

            return(asyncFtpResult.Response);
        }
Пример #4
0
        /// <summary>
        /// Ends an async request to get the external ip address of the router
        /// </summary>
        public override IPAddress EndGetExternalIP(IAsyncResult result)
        {
            if (result == null)
            {
                throw new ArgumentNullException("result");
            }

            PortMapAsyncResult mappingResult = result as PortMapAsyncResult;

            if (mappingResult == null)
            {
                throw new ArgumentException("Invalid AsyncResult", "result");
            }

            if (!result.IsCompleted)
            {
                result.AsyncWaitHandle.WaitOne();
            }

            if (mappingResult.SavedMessage is ErrorMessage)
            {
                ErrorMessage msg = mappingResult.SavedMessage as ErrorMessage;
                throw new MappingException(msg.ErrorCode, msg.Description);
            }

            return(((GetExternalIPAddressResponseMessage)mappingResult.SavedMessage).ExternalIPAddress);
        }
Пример #5
0
        private void EndOp(IAsyncResult supplied, ref AsyncResult actual)
        {
            if (supplied == null)
            {
                throw new ArgumentNullException("result");
            }

            if (supplied != actual)
            {
                throw new ArgumentException("Supplied IAsyncResult does not match the stored result");
            }

            if (!supplied.IsCompleted)
            {
                supplied.AsyncWaitHandle.WaitOne();
            }

            if (actual.StoredException != null)
            {
                throw actual.StoredException;
            }

            pendingOp = false;
            actual    = null;
        }
        public override int EndRead(IAsyncResult asyncResult)
        {
            this.checkDisposed();

            InternalAsyncResult internalResult = asyncResult as InternalAsyncResult;

            if (internalResult == null)
            {
                throw new ArgumentNullException("asyncResult is null or was not obtained by calling BeginRead.");
            }

            // Always wait until the read is complete
            if (!asyncResult.IsCompleted)
            {
                if (!asyncResult.AsyncWaitHandle.WaitOne())
                {
                    throw new TlsException(AlertDescription.InternalError, "Couldn't complete EndRead");
                }
            }

            if (internalResult.CompletedWithError)
            {
                throw internalResult.AsyncException;
            }

            return(internalResult.BytesRead);
        }
        public override void EndWrite(IAsyncResult ares)
        {
            if (disposed)
            {
                throw new ObjectDisposedException(GetType().ToString());
            }

            if (ignore_errors)
            {
                try
                {
                    stream.EndWrite(ares);
                    if (response.SendChunked)
                    {
                        stream.Write(crlf, 0, 2);
                    }
                }
                catch
                {
                }
            }
            else
            {
                stream.EndWrite(ares);
                if (response.SendChunked)
                {
                    stream.Write(crlf, 0, 2);
                }
            }
        }
        public override WebResponse EndGetResponse(IAsyncResult asyncResult)
        {
            if (asyncResult == null)
            {
                throw new ArgumentNullException("asyncResult");
            }
            if (!asyncResult.IsCompleted)
            {
                asyncResult.AsyncWaitHandle.WaitOne();
            }
            AsyncResult         async = (AsyncResult)asyncResult;
            GetResponseCallback cb    = (GetResponseCallback)async.AsyncDelegate;

#if SSHARP
            FileWebResponse webResponse = (FileWebResponse)cb.EndInvokeEx(asyncResult);
#else
            FileWebResponse webResponse = (FileWebResponse)cb.EndInvoke(asyncResult);
#endif
            asyncResponding = false;
            if (webResponse.HasError)
            {
                throw webResponse.Error;
            }
            return(webResponse);
        }
Пример #9
0
        private void WriteAsyncCB(IAsyncResult r)
        {
            WebAsyncResult result = (WebAsyncResult)r.AsyncState;

            result.InnerAsyncResult = null;

            try
            {
                cnc.EndWrite(request, true, r);
                result.SetCompleted(false, 0);
                if (!initRead)
                {
                    initRead = true;
                    WebConnection.InitRead(cnc);
                }
            }
            catch (Exception e)
            {
                KillBuffer();
                nextReadCalled = true;
                cnc.Close(true);
                if (e is System.Net.Sockets.SocketException)
                {
                    e = new IOException("Error writing request", e);
                }
                result.SetCompleted(false, e);
            }

            if (allowBuffering && !sendChunked && request.ContentLength > 0 && totalWritten == request.ContentLength)
            {
                complete_request_written = true;
            }

            result.DoCallback();
        }
        public override void EndWrite(IAsyncResult asyncResult)
        {
            this.checkDisposed();

            InternalAsyncResult internalResult = asyncResult as InternalAsyncResult;

            if (internalResult == null)
            {
                throw new ArgumentNullException("asyncResult is null or was not obtained by calling BeginWrite.");
            }


            if (!asyncResult.IsCompleted)
            {
                if (!internalResult.AsyncWaitHandle.WaitOne())
                {
                    throw new TlsException(AlertDescription.InternalError, "Couldn't complete EndWrite");
                }
            }

            if (internalResult.CompletedWithError)
            {
                throw internalResult.AsyncException;
            }
        }
Пример #11
0
        private void CompleteMessage(IAsyncResult result)
        {
            PortMapAsyncResult mappingResult = result.AsyncState as PortMapAsyncResult;

            mappingResult.CompletedSynchronously = result.CompletedSynchronously;
            mappingResult.Complete();
        }
Пример #12
0
        public override int EndRead(IAsyncResult asyncResult)
        {
            if (asyncResult == null)
            {
                throw new ArgumentNullException("asyncResult");
            }

            AsyncResult ar = asyncResult as AsyncResult;

            if (ar == null)
            {
                throw new ArgumentException("Invalid asyncResult", "asyncResult");
            }

            ReadDelegate del = ar.AsyncDelegate as ReadDelegate;

            if (del == null)
            {
                throw new ArgumentException("Invalid asyncResult", "asyncResult");
            }

#if SSHARP
            return(del.EndInvokeEx <int> (asyncResult));
#else
            return(del.EndInvoke(asyncResult));
#endif
        }
        public override int EndRead(IAsyncResult ares)
        {
            if (disposed)
            {
                throw new ObjectDisposedException(GetType().ToString());
            }

            HttpStreamAsyncResult my_ares = ares as HttpStreamAsyncResult;

            if (ares == null)
            {
                throw new ArgumentException("Invalid IAsyncResult", "ares");
            }

            if (!ares.IsCompleted)
            {
                ares.AsyncWaitHandle.WaitOne();
            }

            if (my_ares.Error != null)
            {
                throw new HttpListenerException(400, "I/O operation aborted: " + my_ares.Error.Message);
            }

            return(my_ares.Count);
        }
Пример #14
0
        public override void EndWrite(IAsyncResult ar)
        {
            var s = socket;

            Debug.WriteLine("NS ({0}): EndWrite ({1}) ", s == null ? "<unknown>" : s.InternalRemoteEndPoint.ToString(), ar == null ? "<unknown>" : ar.GetType().Name);

            CheckDisposed();
            if (ar == null)
            {
                throw new ArgumentNullException("async result is null");
            }

            if (s == null)
            {
                throw new IOException("Connection closed");
            }

            try
            {
                s.EndSend(ar);
            }
            catch (Exception e)
            {
                throw new IOException("EndWrite failure", e);
            }
        }
        private void OnRead(IAsyncResult base_ares)
        {
            ReadBufferState       rb   = (ReadBufferState)base_ares.AsyncState;
            HttpStreamAsyncResult ares = rb.Ares;

            try
            {
                int nread = base.EndRead(base_ares);
                decoder.Write(ares.Buffer, ares.Offset, nread);
                nread      = decoder.Read(rb.Buffer, rb.Offset, rb.Count);
                rb.Offset += nread;
                rb.Count  -= nread;
                if (rb.Count == 0 || !decoder.WantMore || nread == 0)
                {
                    no_more_data = !decoder.WantMore && nread == 0;
                    ares.Count   = rb.InitialCount - rb.Count;
                    ares.Complete();
                    return;
                }
                ares.Offset = 0;
                ares.Count  = Math.Min(8192, decoder.ChunkLeft + 6);
                base.BeginRead(ares.Buffer, ares.Offset, ares.Count, OnRead, rb);
            }
            catch (Exception e)
            {
                context.Connection.SendError(e.Message, 400);
                ares.Complete(e);
            }
        }
Пример #16
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="result"></param>
        public override void EndDeletePortMap(IAsyncResult result)
        {
            if (result == null)
            {
                throw new ArgumentNullException("result");
            }

            PortMapAsyncResult mappingResult = result as PortMapAsyncResult;

            if (mappingResult == null)
            {
                throw new ArgumentException("Invalid AsyncResult", "result");
            }

            // Check if we need to wait for the operation to finish
            if (!mappingResult.IsCompleted)
            {
                mappingResult.AsyncWaitHandle.WaitOne();
            }

            // If we have a saved exception, it means something went wrong during the mapping
            // so we just rethrow the exception and let the user figure out what they should do.
            if (mappingResult.SavedMessage is ErrorMessage)
            {
                ErrorMessage msg = mappingResult.SavedMessage as ErrorMessage;
                throw new MappingException(msg.ErrorCode, msg.Description);
            }

            // If all goes well, we just return
            //return true;
        }
Пример #17
0
        public override int EndRead(IAsyncResult ar)
        {
            var s = socket;

            Debug.WriteLine(String.Format("NS ({0}): EndRead ({1})", s == null ? "<unknown>" : s.InternalRemoteEndPoint.ToString(),
                                          ar == null ? "<unknown>" : ar.GetType().Name));

            int res = 0;

            CheckDisposed();

            if (ar == null)
            {
                throw new ArgumentNullException("async result is null");
            }

            if (s == null)
            {
                throw new IOException("Connection closed");
            }

            try
            {
                res = s.EndReceive(ar);
            }
            catch (Exception e)
            {
                throw new IOException("EndRead failure", e);
            }

            return(res);
        }
Пример #18
0
        private void EndGetAllMappingsInternal(IAsyncResult result)
        {
            EndMessageInternal(result);

            GetAllMappingsAsyncResult mappingResult           = result.AsyncState as GetAllMappingsAsyncResult;
            GetGenericPortMappingEntryResponseMessage message = mappingResult.SavedMessage as GetGenericPortMappingEntryResponseMessage;

            if (message != null)
            {
                Mapping mapping = new Mapping(message.Protocol, message.InternalPort, message.ExternalPort, message.LeaseDuration);
                mapping.Description = message.PortMappingDescription;
                mappingResult.Mappings.Add(mapping);
                GetGenericPortMappingEntry next = new GetGenericPortMappingEntry(mappingResult.Mappings.Count, this);

                // It's ok to do this synchronously because we should already be on anther thread
                // and this won't block the user.
                byte[]     body;
                WebRequest request = next.Encode(out body);
                if (body.Length > 0)
                {
                    request.ContentLength = body.Length;
                    request.GetRequestStream().Write(body, 0, body.Length);
                }
                mappingResult.Request = request;
                request.BeginGetResponse(EndGetAllMappingsInternal, mappingResult);
                return;
            }

            CompleteMessage(result);
        }
        public override int EndRead(IAsyncResult asyncResult)
        {
            if (_disposed)
            {
                throw new ObjectDisposedException(GetType().ToString());
            }

            if (asyncResult == null)
            {
                throw new ArgumentNullException("asyncResult");
            }

            if (asyncResult is HttpStreamAsyncResult)
            {
                var ares = (HttpStreamAsyncResult)asyncResult;
                if (!ares.IsCompleted)
                {
                    ares.AsyncWaitHandle.WaitOne();
                }

                return(ares.SyncRead);
            }

            // Close on exception?
            var nread = _stream.EndRead(asyncResult);

            if (nread > 0 && _bodyLeft > 0)
            {
                _bodyLeft -= nread;
            }

            return(nread);
        }
Пример #20
0
        private void WriteCallbackWrapper(IAsyncResult r)
        {
            WebAsyncResult result = r as WebAsyncResult;

            if (result != null && result.AsyncWriteAll)
            {
                return;
            }

            if (r.AsyncState != null)
            {
                result = (WebAsyncResult)r.AsyncState;
                result.InnerAsyncResult = r;
                result.DoCallback();
            }
            else
            {
                try
                {
                    EndWrite(r);
                }
                catch
                {
                }
            }
        }
Пример #21
0
        private void EndMessageInternal(IAsyncResult result)
        {
            HttpWebResponse    response      = null;
            PortMapAsyncResult mappingResult = result.AsyncState as PortMapAsyncResult;

            try
            {
                try
                {
                    response = (HttpWebResponse)mappingResult.Request.EndGetResponse(result);
                }
                catch (WebException ex)
                {
                    // Even if the request "failed" i want to continue on to read out the response from the router
                    response = ex.Response as HttpWebResponse;
                    if (response == null)
                    {
                        mappingResult.SavedMessage = new ErrorMessage((int)ex.Status, ex.Message);
                    }
                }
                if (response != null)
                {
                    mappingResult.SavedMessage = DecodeMessageFromResponse(response.GetResponseStream(), response.ContentLength);
                }
            }

            finally
            {
                if (response != null)
                {
                    response.Close();
                }
            }
        }
Пример #22
0
        public override Mapping EndGetSpecificMapping(IAsyncResult result)
        {
            if (result == null)
            {
                throw new ArgumentNullException("result");
            }

            GetAllMappingsAsyncResult mappingResult = result as GetAllMappingsAsyncResult;

            if (mappingResult == null)
            {
                throw new ArgumentException("Invalid AsyncResult", "result");
            }

            if (!mappingResult.IsCompleted)
            {
                mappingResult.AsyncWaitHandle.WaitOne();
            }

            if (mappingResult.SavedMessage is ErrorMessage)
            {
                ErrorMessage message = mappingResult.SavedMessage as ErrorMessage;
                if (message.ErrorCode != 0x2ca)
                {
                    throw new MappingException(message.ErrorCode, message.Description);
                }
            }
            if (mappingResult.Mappings.Count == 0)
            {
                return(new Mapping(Protocol.Tcp, -1, -1));
            }

            return(mappingResult.Mappings[0]);
        }
Пример #23
0
        public override void EndWrite(IAsyncResult asyncResult)
        {
            if (asyncResult == null)
            {
                throw new ArgumentNullException("asyncResult");
            }

            AsyncResult ar = asyncResult as AsyncResult;

            if (ar == null)
            {
                throw new ArgumentException("Invalid asyncResult.", "asyncResult");
            }

            WriteDelegate del = ar.AsyncDelegate as WriteDelegate;

            if (del == null)
            {
                throw new ArgumentException("Invalid asyncResult.", "asyncResult");
            }

#if SSHARP
            del.EndInvokeEx(asyncResult);
#else
            del.EndInvoke(asyncResult);
#endif
        }
Пример #24
0
        public override Mapping[] EndGetAllMappings(IAsyncResult result)
        {
            if (result == null)
            {
                throw new ArgumentNullException("result");
            }

            GetAllMappingsAsyncResult mappingResult = result as GetAllMappingsAsyncResult;

            if (mappingResult == null)
            {
                throw new ArgumentException("Invalid AsyncResult", "result");
            }

            if (!mappingResult.IsCompleted)
            {
                mappingResult.AsyncWaitHandle.WaitOne();
            }

            if (mappingResult.SavedMessage is ErrorMessage)
            {
                ErrorMessage msg = mappingResult.SavedMessage as ErrorMessage;
                if (msg.ErrorCode != 713)
                {
                    throw new MappingException(msg.ErrorCode, msg.Description);
                }
            }

            return(mappingResult.Mappings.ToArray());
        }
        public override int EndRead(IAsyncResult ares)
        {
            if (disposed)
            {
                throw new ObjectDisposedException(typeof(RequestStream).ToString());
            }

            if (ares == null)
            {
                throw new ArgumentNullException("async_result");
            }

            if (ares is HttpStreamAsyncResult)
            {
                HttpStreamAsyncResult r = (HttpStreamAsyncResult)ares;
                if (!ares.IsCompleted)
                {
                    ares.AsyncWaitHandle.WaitOne();
                }
                return(r.SynchRead);
            }

            // Close on exception?
            int nread = stream.EndRead(ares);

            if (remaining_body > 0 && nread > 0)
            {
                remaining_body -= nread;
            }
            return(nread);
        }
Пример #26
0
        public static object EndInvokeEx(this Delegate dlg, IAsyncResult result)
        {
            var asyncResult = result as AsyncResult;

            if (asyncResult == null)
            {
                throw new ArgumentException("invalid IAsyncResult", "result");
            }

            if (asyncResult.EndInvokeCalled)
            {
                throw new InvalidOperationException("EndInvoke can only be called once");
            }
            asyncResult.EndInvokeCalled = true;

            if (!asyncResult.CompletedSynchronously)
            {
                asyncResult.AsyncWaitHandle.Wait();
            }

            if (asyncResult.Exception != null)
            {
                throw asyncResult.Exception;
            }

            return(asyncResult.Result);
        }
        private static void acceptCallback(IAsyncResult iar)
        {
            var tuple = (Tuple <Socket, SocketAsyncEventArgs>)iar.AsyncState;

            tuple.Item2.curSocket    = tuple.Item1;
            tuple.Item2.AcceptSocket = tuple.Item1.EndAccept(iar);

            OnAccept(tuple.Item1, tuple.Item2);
        }
        //===================// Event Handlers //===================//

        //-------------------------------------//
        //      Method | BeginWriteCallback
        // Description | ...
        //-------------------------------------//
        private static void BeginWriteCallback(Crestron.SimplSharp.CrestronIO.IAsyncResult _res)
        {
            if (_res.IsCompleted)
            {
                fStream.EndWrite(_res);
                fStream.Close();
                Scheduler.DebugMessage(String.Format("[DEBUG] Completed File Write Operation!"));
            }
        }
Пример #29
0
        public override void EndWrite(IAsyncResult asyncResult)
        {
            if (_disposed)
            {
                throw new ObjectDisposedException(GetType().ToString());
            }

            _body.EndWrite(asyncResult);
        }
        public override int Read(
#if !NETCF
            [In, Out]
#endif
            byte[] buffer, int offset, int count)
        {
            IAsyncResult ares = BeginRead(buffer, offset, count, null, null);

            return(EndRead(ares));
        }