Exemplo n.º 1
0
        public override IAsyncResult BeginGetRequestStream(AsyncCallback callback, object state)
        {
            if (method != WebRequestMethods.Ftp.UploadFile && method != WebRequestMethods.Ftp.UploadFileWithUniqueName && method != WebRequestMethods.Ftp.AppendFile)
            {
                throw new ProtocolViolationException();
            }

            lock (locker)
            {
                CheckIfAborted();

                if (State != RequestState.Before)
                {
                    throw new InvalidOperationException("Cannot re-call BeginGetRequestStream/BeginGetResponse while a previous call is still in progress");
                }

                State = RequestState.Scheduled;
            }

            asyncResult = new FtpAsyncResult(callback, state);
#if SSHARP
            ThreadPool.QueueUserWorkItem(ProcessRequest);
#else
            Thread thread = new Thread(ProcessRequest);
            thread.Start();
#endif

            return(asyncResult);
        }
 public ReceiveRecordAsyncResult(AsyncCallback userCallback, object userState, byte[] initialBuffer, Stream record)
 {
     _userCallback  = userCallback;
     _userState     = userState;
     _initialBuffer = initialBuffer;
     _record        = record;
 }
Exemplo n.º 3
0
        public override IAsyncResult BeginWrite(byte[] buffer, int offset, int size, AsyncCallback cb, object state)
        {
            CheckDisposed();
            if (isRead)
            {
                throw new NotSupportedException();
            }
            if (buffer == null)
            {
                throw new ArgumentNullException("buffer");
            }
            if (offset < 0 || offset > buffer.Length)
            {
                throw new ArgumentOutOfRangeException("offset");
            }
            if (size < 0 || size > buffer.Length - offset)
            {
                throw new ArgumentOutOfRangeException("offset+size");
            }

            WriteDelegate del = WriteInternal;

#if SSHARP
            return(del.BeginInvokeEx(cb, state, buffer, offset, size));
#else
            return(del.BeginInvoke(buffer, offset, size, cb, state));
#endif
        }
Exemplo n.º 4
0
        /// <summary>
        /// Begins an async call to get the external ip address of the router
        /// </summary>
        public override IAsyncResult BeginGetExternalIP(AsyncCallback callback, object asyncState)
        {
            // Create the port map message
            GetExternalIPAddressMessage message = new GetExternalIPAddressMessage(this);

            return(BeginMessageInternal(message, callback, asyncState, EndGetExternalIPInternal));
        }
 public WebAsyncResult(AsyncCallback cb, object state, byte[] buffer, int offset, int size)
     : base(cb, state)
 {
     this.buffer = buffer;
     this.offset = offset;
     this.size   = size;
 }
        public override IAsyncResult BeginGetRequestStream(AsyncCallback callback, object state)
        {
            if (string.Compare("GET", method, true) == 0 || string.Compare("HEAD", method, true) == 0 || string.Compare("CONNECT", method, true) == 0)
            {
                throw new ProtocolViolationException("Cannot send a content-body with this verb-type.");
            }
            lock (this)
            {
                if (asyncResponding || webResponse != null)
                {
                    throw new InvalidOperationException("This operation cannot be performed after the request has been submitted.");
                }
                if (requesting)
                {
                    throw new InvalidOperationException("Cannot re-call start of asynchronous method while a previous call is still in progress.");
                }
                requesting = true;
            }
            GetRequestStreamCallback c = new GetRequestStreamCallback(this.GetRequestStreamInternal);

#if SSHARP
            return(c.BeginInvokeEx(callback, state));
#else
            return(c.BeginInvoke(callback, state));
#endif
        }
Exemplo n.º 7
0
        public override IAsyncResult BeginGetResponse(AsyncCallback callback, object state)
        {
            if (asyncResult != null && !asyncResult.IsCompleted)
            {
                throw new InvalidOperationException("Cannot re-call BeginGetRequestStream/BeginGetResponse while a previous call is still in progress");
            }

            CheckIfAborted();

            asyncResult = new FtpAsyncResult(callback, state);

            lock (locker)
            {
                if (InFinalState())
                {
                    asyncResult.SetCompleted(true, ftpResponse);
                }
                else
                {
                    if (State == RequestState.Before)
                    {
                        State = RequestState.Scheduled;
                    }

#if SSHARP
                    ThreadPool.QueueUserWorkItem(ProcessRequest);
#else
                    Thread thread = new Thread(ProcessRequest);
                    thread.Start();
#endif
                }
            }

            return(asyncResult);
        }
        public override IAsyncResult BeginRead(
            byte[] buffer, int offset, int count, AsyncCallback callback, object state)
        {
            if (_disposed)
            {
                throw new ObjectDisposedException(GetType().ToString());
            }

            var nread = fillFromBuffer(buffer, offset, count);

            if (nread > 0 || nread == -1)
            {
                var ares = new HttpStreamAsyncResult(callback, state);
                ares.Buffer   = buffer;
                ares.Offset   = offset;
                ares.Count    = count;
                ares.SyncRead = nread > 0 ? nread : 0;
                ares.Complete();

                return(ares);
            }

            // Avoid reading past the end of the request to allow for HTTP pipelining.
            if (_bodyLeft >= 0 && count > _bodyLeft)
            {
                count = (int)_bodyLeft;
            }

            return(_stream.BeginRead(buffer, offset, count, callback, state));
        }
        public override IAsyncResult BeginRead(byte[] buffer, int offset, int count, AsyncCallback cback, object state)
        {
            if (disposed)
            {
                throw new ObjectDisposedException(typeof(RequestStream).ToString());
            }

            int nread = FillFromBuffer(buffer, offset, count);

            if (nread > 0 || nread == -1)
            {
                HttpStreamAsyncResult ares = new HttpStreamAsyncResult();
                ares.Buffer    = buffer;
                ares.Offset    = offset;
                ares.Count     = count;
                ares.Callback  = cback;
                ares.State     = state;
                ares.SynchRead = Math.Max(0, nread);
                ares.Complete();
                return(ares);
            }

            // Avoid reading past the end of the request to allow
            // for HTTP pipelining
            if (remaining_body >= 0 && count > remaining_body)
            {
                count = (int)Math.Min(Int32.MaxValue, remaining_body);
            }
            return(stream.BeginRead(buffer, offset, count, cback, state));
        }
Exemplo n.º 10
0
        /*
         *      Client											Server
         *
         *      ClientHello                 -------->
         *                                                                                                      ServerHello
         *                                                                                                      Certificate*
         *                                                                                                      ServerKeyExchange*
         *                                                                                                      CertificateRequest*
         *                                                              <--------			ServerHelloDone
         *      Certificate*
         *      ClientKeyExchange
         *      CertificateVerify*
         *      [ChangeCipherSpec]
         *      Finished                    -------->
         *                                                                                                      [ChangeCipherSpec]
         *                                                              <--------           Finished
         *      Application Data            <------->			Application Data
         *
         *                      Fig. 1 - Message flow for a full handshake
         */

        internal override IAsyncResult BeginNegotiateHandshake(AsyncCallback callback, object state)
        {
            try
            {
                if (this.context.HandshakeState != HandshakeState.None)
                {
                    this.context.Clear();
                }

                // Obtain supported cipher suites
                this.context.SupportedCiphers = CipherSuiteFactory.GetSupportedCiphers(false, this.context.SecurityProtocol);

                // Set handshake state
                this.context.HandshakeState = HandshakeState.Started;

                // Send client hello
                return(this.protocol.BeginSendRecord(HandshakeType.ClientHello, callback, state));
            }
            catch (TlsException ex)
            {
                this.protocol.SendAlert(ex.Alert);

                throw new IOException("The authentication or decryption has failed.", ex);
            }
            catch (Exception ex)
            {
                this.protocol.SendAlert(AlertDescription.InternalError);

                throw new IOException("The authentication or decryption has failed.", ex);
            }
        }
        public override IAsyncResult BeginRead(byte[] buffer, int offset, int count, AsyncCallback cback, object state)
        {
            if (disposed)
            {
                throw new ObjectDisposedException(GetType().ToString());
            }

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

            int len = buffer.Length;

            if (offset < 0 || offset > len)
            {
                throw new ArgumentOutOfRangeException("offset exceeds the size of buffer");
            }

            if (count < 0 || offset > len - count)
            {
                throw new ArgumentOutOfRangeException("offset+size exceeds the size of buffer");
            }

            HttpStreamAsyncResult ares = new HttpStreamAsyncResult();

            ares.Callback = cback;
            ares.State    = state;
            if (no_more_data)
            {
                ares.Complete();
                return(ares);
            }
            int nread = decoder.Read(buffer, offset, count);

            offset += nread;
            count  -= nread;
            if (count == 0)
            {
                // got all we wanted, no need to bother the decoder yet
                ares.Count = nread;
                ares.Complete();
                return(ares);
            }
            if (!decoder.WantMore)
            {
                no_more_data = nread == 0;
                ares.Count   = nread;
                ares.Complete();
                return(ares);
            }
            ares.Buffer = new byte[8192];
            ares.Offset = 0;
            ares.Count  = 8192;
            ReadBufferState rb = new ReadBufferState(buffer, offset, count, ares);

            rb.InitialCount += nread;
            base.BeginRead(ares.Buffer, ares.Offset, ares.Count, OnRead, rb);
            return(ares);
        }
Exemplo n.º 12
0
        private IAsyncResult BeginMessageInternal(MessageBase message, AsyncCallback storedCallback, object asyncState, AsyncCallback callback)
        {
            byte[]             body;
            WebRequest         request       = message.Encode(out body);
            PortMapAsyncResult mappingResult = PortMapAsyncResult.Create(message, request, storedCallback, asyncState);

            if (body.Length > 0)
            {
                request.ContentLength = body.Length;
                request.BeginGetRequestStream(delegate(IAsyncResult result)
                {
                    try
                    {
                        Stream s = request.EndGetRequestStream(result);
                        s.Write(body, 0, body.Length);
                        request.BeginGetResponse(callback, mappingResult);
                    }
                    catch (Exception ex)
                    {
                        mappingResult.Complete(ex);
                    }
                }, null);
            }
            else
            {
                request.BeginGetResponse(callback, mappingResult);
            }
            return(mappingResult);
        }
Exemplo n.º 13
0
 public SendFileInfo(string fileName, CrestronSocket socket, TransmitFileOptions flags, SendFileAsyncResult iar, AsyncCallback callback)
 {
     FileName = fileName;
     Socket   = socket;
     Flags    = flags;
     Iar      = iar;
     Callback = callback;
 }
        public IAsyncResult BeginSendChangeCipherSpec(AsyncCallback callback, object state)
        {
            DebugHelper.WriteLine(">>>> Write Change Cipher Spec");

            // Send Change Cipher Spec message with the current cipher
            // or as plain text if this is the initial negotiation
            return(this.BeginSendRecord(ContentType.ChangeCipherSpec, new byte[] { 1 }, callback, state));
        }
Exemplo n.º 15
0
        public override IAsyncResult BeginGetExternalIP(AsyncCallback callback, object asyncState)
        {
            StartOp(ref externalIpResult, callback, asyncState);
            AsyncResult result = externalIpResult;

            result.Complete();
            return(result);
        }
 public InternalAsyncResult(AsyncCallback userCallback, object userState, byte[] buffer, int offset, int count, bool fromWrite, bool proceedAfterHandshake)
 {
     _userCallback          = userCallback;
     _userState             = userState;
     _buffer                = buffer;
     _offset                = offset;
     _count                 = count;
     _fromWrite             = fromWrite;
     _proceedAfterHandshake = proceedAfterHandshake;
 }
Exemplo n.º 17
0
        private void StartOp(ref AsyncResult result, AsyncCallback callback, object asyncState)
        {
            if (pendingOp == true)
            {
                throw new InvalidOperationException("Can only have one simultaenous async operation");
            }

            pendingOp = true;
            result    = new AsyncResult(callback, asyncState);
        }
Exemplo n.º 18
0
        public override IAsyncResult BeginWrite(
            byte[] buffer, int offset, int count, AsyncCallback callback, object state)
        {
            if (_disposed)
            {
                throw new ObjectDisposedException(GetType().ToString());
            }

            return(_body.BeginWrite(buffer, offset, count, callback, state));
        }
Exemplo n.º 19
0
 protected static void DoAsyncCallback(AsyncCallback callback, IAsyncResult result)
 {
     try
     {
         callback(result);
     }
     catch (Exception)
     {
     }
 }
Exemplo n.º 20
0
 protected SimpleAsyncResult(AsyncCallback cb, object state)
 {
     this.state = state;
     this.cb    = result =>
     {
         if (cb != null)
         {
             cb(this);
         }
     };
 }
Exemplo n.º 21
0
        public WebConnectionStream(WebConnection cnc, WebConnectionData data)
        {
            if (data == null)
            {
                throw new InvalidOperationException("data was not initialized");
            }
            if (data.Headers == null)
            {
                throw new InvalidOperationException("data.Headers was not initialized");
            }
            if (data.request == null)
            {
                throw new InvalidOperationException("data.request was not initialized");
            }
            isRead        = true;
            cb_wrapper    = new AsyncCallback(ReadCallbackWrapper);
            pending       = new ManualResetEvent(true);
            this.request  = data.request;
            read_timeout  = request.ReadWriteTimeout;
            write_timeout = read_timeout;
            this.cnc      = cnc;
            string contentType = data.Headers["Transfer-Encoding"];
            bool   chunkedRead = (contentType != null && contentType.IndexOf("chunked", StringComparison.OrdinalIgnoreCase) != -1);
            string clength     = data.Headers["Content-Length"];

            if (!chunkedRead && clength != null && clength != "")
            {
                try
                {
                    contentLength = Int32.Parse(clength);
                    if (contentLength == 0 && !IsNtlmAuth())
                    {
                        ReadAll();
                    }
                }
                catch
                {
                    contentLength = Int32.MaxValue;
                }
            }
            else
            {
                contentLength = Int32.MaxValue;
            }

            // Negative numbers?
#if SSHARP
            if (!TryParsers.Int32TryParse(clength, out stream_length))
#else
            if (!Int32.TryParse(clength, out stream_length))
#endif
            { stream_length = -1; }
        }
        public IAsyncResult BeginGetClientCertificate(AsyncCallback requestCallback, object state)
        {
            if (gcc_delegate == null)
            {
                gcc_delegate = new GCCDelegate(GetClientCertificate);
            }
#if SSHARP
            return(gcc_delegate.BeginInvokeEx(requestCallback, state));
#else
            return(gcc_delegate.BeginInvoke(requestCallback, state));
#endif
        }
        public override IAsyncResult BeginWrite(
            byte[] buffer,
            int offset,
            int count,
            AsyncCallback callback,
            object state)
        {
            this.checkDisposed();

            if (buffer == null)
            {
                throw new ArgumentNullException("buffer is a null reference.");
            }
            if (offset < 0)
            {
                throw new ArgumentOutOfRangeException("offset is less than 0.");
            }
            if (offset > buffer.Length)
            {
                throw new ArgumentOutOfRangeException("offset is greater than the length of buffer.");
            }
            if (count < 0)
            {
                throw new ArgumentOutOfRangeException("count is less than 0.");
            }
            if (count > (buffer.Length - offset))
            {
                throw new ArgumentOutOfRangeException("count is less than the length of buffer minus the value of the offset parameter.");
            }


            InternalAsyncResult asyncResult = new InternalAsyncResult(callback, state, buffer, offset, count, true, true);

            if (this.MightNeedHandshake)
            {
                if (!BeginNegotiateHandshake(asyncResult))
                {
                    //we made it down here so the handshake was not started.
                    //another thread must have started it in the mean time.
                    //wait for it to complete and then perform our original operation
                    this.negotiationComplete.WaitOne();

                    InternalBeginWrite(asyncResult);
                }
            }
            else
            {
                InternalBeginWrite(asyncResult);
            }

            return(asyncResult);
        }
        public IAsyncResult BeginSendRecord(HandshakeType handshakeType, AsyncCallback callback, object state)
        {
            HandshakeMessage msg = this.GetMessage(handshakeType);

            msg.Process();

            DebugHelper.WriteLine(">>>> Write handshake record ({0}|{1})", context.Protocol, msg.ContentType);

            SendRecordAsyncResult internalResult = new SendRecordAsyncResult(callback, state, msg);

            this.BeginSendRecord(msg.ContentType, msg.EncodeMessage(), new AsyncCallback(InternalSendRecordCallback), internalResult);

            return(internalResult);
        }
Exemplo n.º 25
0
        public override int Read(byte[] buffer, int offset, int size)
        {
            AsyncCallback  cb  = cb_wrapper;
            WebAsyncResult res = (WebAsyncResult)BeginRead(buffer, offset, size, cb, null);

            if (!res.IsCompleted && !res.WaitUntilComplete(ReadTimeout, false))
            {
                nextReadCalled = true;
                cnc.Close(true);
                throw new WebException("The operation has timed out.", WebExceptionStatus.Timeout);
            }

            return(EndRead(res));
        }
Exemplo n.º 26
0
        public override void Write(byte[] buffer, int offset, int size)
        {
            AsyncCallback  cb  = cb_wrapper;
            WebAsyncResult res = (WebAsyncResult)BeginWrite(buffer, offset, size, cb, null);

            if (!res.IsCompleted && !res.WaitUntilComplete(WriteTimeout, false))
            {
                KillBuffer();
                nextReadCalled = true;
                cnc.Close(true);
                throw new IOException("Write timed out.");
            }

            EndWrite(res);
        }
Exemplo n.º 27
0
        public static IAsyncResult BeginInvokeEx(this Delegate dlg, AsyncCallback callback, object obj, params object[] args)
        {
            var iar        = new AsyncResult(dlg, obj);
            var invokeInfo = new InvokeInfo {
                result = iar, callback = callback, state = obj, args = args
            };

            if (_delQueueUserWorkItem != null)
            {
                _delQueueUserWorkItem(DoDelegate, invokeInfo);
            }
            else
            {
                CrestronInvoke.BeginInvoke(DoDelegate, invokeInfo);
            }
            return(iar);
        }
Exemplo n.º 28
0
        /*
         *      Client											Server
         *
         *      ClientHello                 -------->
         *                                                                                                      ServerHello
         *                                                                                                      Certificate*
         *                                                                                                      ServerKeyExchange*
         *                                                                                                      CertificateRequest*
         *                                                              <--------			ServerHelloDone
         *      Certificate*
         *      ClientKeyExchange
         *      CertificateVerify*
         *      [ChangeCipherSpec]
         *      Finished                    -------->
         *                                                                                                      [ChangeCipherSpec]
         *                                                              <--------           Finished
         *      Application Data            <------->			Application Data
         *
         *                      Fig. 1 - Message flow for a full handshake
         */

        internal override IAsyncResult BeginNegotiateHandshake(AsyncCallback callback, object state)
        {
            // Reset the context if needed
            if (this.context.HandshakeState != HandshakeState.None)
            {
                this.context.Clear();
            }

            // Obtain supported cipher suites
            this.context.SupportedCiphers = CipherSuiteFactory.GetSupportedCiphers(true, context.SecurityProtocol);

            // Set handshake state
            this.context.HandshakeState = HandshakeState.Started;

            // Receive Client Hello message
            return(this.protocol.BeginReceiveRecord(this.innerStream, callback, state));
        }
Exemplo n.º 29
0
        public override IAsyncResult BeginWrite(byte[] buffer, int offset, int size,
                                                AsyncCallback callback, object state)
        {
            var s = socket;

            Debug.WriteLine("NS ({0}): BeginWrite (buffer, {1}, {2})", s == null ? "<unknown>" : s.InternalRemoteEndPoint.ToString(), offset, size);

            CheckDisposed();
            IAsyncResult retval;

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

            int len = buffer.Length;

            if (offset < 0 || offset > len)
            {
                throw new ArgumentOutOfRangeException("offset exceeds the size of buffer");
            }
            if (size < 0 || offset + size > len)
            {
                throw new ArgumentOutOfRangeException("offset+size exceeds the size of buffer");
            }

            if (s == null
#if SSHARP
                || !s.Connected
#endif
                )
            {
                throw new IOException("Connection closed");
            }

            try
            {
                retval = s.BeginSend(buffer, offset, size, 0, callback, state);
            }
            catch (Exception e)
            {
                throw new IOException("BeginWrite failure", e);
            }

            return(retval);
        }
Exemplo n.º 30
0
        public override IAsyncResult BeginDeletePortMap(Mapping mapping, AsyncCallback callback, object asyncState)
        {
            PortMapAsyncResult pmar = new PortMapAsyncResult(mapping, callback, asyncState);

            ThreadPool.QueueUserWorkItem(delegate
            {
                try
                {
                    CreatePortMap(pmar.Mapping, false);
                    pmar.Complete();
                }
                catch (Exception e)
                {
                    pmar.Complete(e);
                }
            });
            return(pmar);
        }