Beispiel #1
0
        public Message Request(Message message, TimeSpan timeout)
        {
            Message message3 = null;

            // check input parameters
            if (message == null)
            {
                throw new ArgumentNullException("message");
            }
            if (timeout < TimeSpan.Zero)
            {
                throw new ArgumentOutOfRangeException("timeout");
            }

            // check if underlying stream has not been closed by the server
            if (_endpointController != null)
            {
                _to = _endpointController.Address;

                if (_endpointController.WsaEnabled)
                {
                    message.Headers.To = _endpointController.Address.Uri;
                }
                else
                {
                    // clear headers since not all cameras understand them.
                    message.Headers.Action    = null;
                    message.Headers.ReplyTo   = null;
                    message.Headers.MessageId = null;
                }
            }
            else
            {
                // clear headers since not all cameras understand them.
                message.Headers.Action    = null;
                message.Headers.ReplyTo   = null;
                message.Headers.MessageId = null;
            }

            _networkStream.EnsureOpen(_to);

            base.ThrowIfDisposedOrNotOpen();


            // send message
            WriteMessageToStream(message);

            // Start reading
            // Wait first byte for timeout.TotalMilliseconds
            int readTimeout = (int)timeout.TotalMilliseconds;

            // initialize variables
            MemoryStream responseStream;
            HttpPacket   header = null;

            do
            {
                responseStream = new MemoryStream();
                GetResponse(responseStream, out header, readTimeout);

                if (header.StatusCode == 100)
                {
                    System.Diagnostics.Debug.WriteLine("100-Continue received");
                }
            } while (header.StatusCode == 100);

            System.Diagnostics.Debug.WriteLine("Real answer received");

            _networkStream.Close();

            int count = (int)responseStream.Length - header.BodyOffset;

            // parse response and notify listeners
            string response = HttpHelper.GetFormattedMessage(responseStream.GetBuffer(), header.BodyOffset);

            foreach (ITrafficListener listener in _listeners)
            {
                listener.LogResponse(response);
            }

            if (header.ContentLength < count)
            {
                if (header.Headers.ContainsKey(HttpHelper.CONTENTLENGTH))
                {
                    throw new HttpProtocolException(
                              string.Format("An error occurred while receiving packet. Expected length: {0}, received: {1}",
                                            header.ContentLength, count));
                }
                else
                {
                    if (!header.NoBodySupposed)
                    {
                        if (header.StatusCode != 200)
                        {
                            throw new HttpProtocolException(
                                      string.Format("An error returned. Error code: {0}, error description: {1}",
                                                    header.StatusCode, header.StatusDescription));
                        }
                        else
                        {
                            throw new HttpProtocolException("Content-Length header is missing");
                        }
                    }
                }
            }

            // validate headers
            HttpHelper.ValidateHttpHeaders(header);

            int start = header.BodyOffset;

            if (start >= 0)
            {
                byte[] buffer = _bufferManager.TakeBuffer(count);
                Array.Copy(responseStream.GetBuffer(), start, buffer, 0, count);

                responseStream.Close();

                if (_validatingControllers.Count > 0)
                {
                    int offset = 0;
                    while (buffer[offset] != (byte)'<')
                    {
                        offset++;
                    }

                    MemoryStream stream = new MemoryStream(buffer, offset, count - offset, false);
                    foreach (IValidatingController controller in _validatingControllers)
                    {
                        controller.Validate(stream);
                    }
                    stream.Close();
                }

                message3 = _encoder.ReadMessage(new ArraySegment <byte>(buffer, 0, count), _bufferManager);

                _bufferManager.ReturnBuffer(buffer);
            }
            else
            {
                responseStream.Close();
                throw new ProtocolException(string.Format("The server returned unexpected reply: {0} {1}", header.StatusCode, header.StatusDescription));
            }
            return(message3);
        }
Beispiel #2
0
        public string SendSoapMessage(string request)
        {
            byte[] bytes = CreateMessageBytes(request);

            _networkStream = new RequestNetworkStream(new EndpointAddress(_address.OriginalString));
            _networkStream.Connect();

            _networkStream.Write(bytes, 0, bytes.Length);

            MemoryStream responseStream = new MemoryStream();
            int          readTimeout    = _timeout;
            HttpPacket   header         = null;

            do
            {
                responseStream = new MemoryStream();
                GetResponse(responseStream, out header, readTimeout);

                if (header.StatusCode == 100)
                {
                    //System.Diagnostics.Debug.WriteLine("100-Continue received");
                }
            } while (header.StatusCode == 100);

            _networkStream.Close();

            bool digestEnabled = false;

            if (_credentialsProvider != null)
            {
                digestEnabled = _credentialsProvider.Security == Security.Digest;
            }
            if (header.StatusCode == 401)
            {
                if (digestEnabled)
                {
                    System.Diagnostics.Debug.WriteLine("HTTP 401 received");
                    _networkStream.Close();

                    _networkStream.EnsureOpen(new EndpointAddress(_address.OriginalString));

                    // Send request once more.
                    _digestAuthChallenge = header;

                    // uses _digestAuthChallenge (and _currentMessageBytes), so behaviour will be different
                    // (_digestAuthChallenge might be not null by the first attempt, but if we get status 401,
                    // it will be updated)
                    byte[] messageBytes = CreateMessageBytes(request);
                    _networkStream.Write(messageBytes, 0, messageBytes.Length);

                    //System.Diagnostics.Debug.WriteLine(string.Format("After ResendMessage: socket: {0}", _networkStream.Connected));

                    do
                    {
                        responseStream = new MemoryStream();
                        GetResponse(responseStream, out header, readTimeout);
                    } while (header.StatusCode == 100);

                    if (header.StatusCode == 401)
                    {
                        _networkStream.Close();
                        throw new AccessDeniedException("Digest authentication FAILED (HTTP status 401 received)");
                    }
                }
                else
                {
                    _networkStream.Close();
                    throw new AccessDeniedException("Access denied (HTTP status 401 received)");
                }
            }

            _networkStream.Close();

            int count = (int)responseStream.Length - header.BodyOffset;

            if (header.ContentLength < count)
            {
                throw new HttpProtocolException(
                          string.Format("An error occurred while receiving packet. Expected length: {0}, received: {1}",
                                        header.ContentLength, count));
            }

            // parse response and notify listeners
            string response = HttpHelper.GetFormattedMessage(responseStream.GetBuffer(), header.BodyOffset);

            responseStream.Close();
            return(response);
        }
Beispiel #3
0
        void GetResponse(MemoryStream responseStream, out HttpPacket header, int readTimeout)
        {
            int bytes = 0;

            byte[] responseBuffer = new byte[2048];
            bool   bContinue      = false;

            int readTimeoutLocal = readTimeout;

            DateTime startTime = DateTime.Now;

            // read response
            do
            {
                IAsyncResult result = _networkStream.BeginRead(responseBuffer, 0, responseBuffer.Length);

                // wait for bytes received, stop event or timeout
                WaitHandle[] handles;
                if (_executionController != null && _executionController.StopEvent != null)
                {
                    handles = new WaitHandle[] { result.AsyncWaitHandle, _executionController.StopEvent };
                }
                else
                {
                    handles = new WaitHandle[] { result.AsyncWaitHandle };
                }
                int handle = System.Threading.WaitHandle.WaitAny(handles, readTimeoutLocal);

                if (handle == WaitHandle.WaitTimeout)
                {
                    _networkStream.Close();
                    throw new Interfaces.Exceptions.TimeoutException("The HTTP request has exceeded the allotted timeout");
                }

                if (handle == 1)
                {
                    //Stop event
                    _networkStream.Close();
                    _executionController.ReportStop();
                }

                bytes = _networkStream.EndRead(result);

                DateTime endTime = DateTime.Now;

                //System.Diagnostics.Debug.WriteLine(string.Format("--- Bytes received: {0}", bytes));

                responseStream.Write(responseBuffer, 0, bytes);

                // timeout for next part of answer
                int ms = (int)((endTime - startTime).TotalMilliseconds);

                // parse response received by this moment.
                try
                {
                    bContinue = HttpHelper.ContinueReading(responseStream, out header);
                }
                catch (Exception exc)
                {
                    _networkStream.Close();
                    // clean resources somehow ?
                    throw new Exception("An error occurred while parsing HTTP packet", exc);
                }

                readTimeoutLocal = readTimeout - ms;
                //System.Diagnostics.Debug.WriteLine("Timeout: " + readTimeoutLocal);
                if (readTimeoutLocal < 0)
                {
                    _networkStream.Close();
                    throw new IOException("The HTTP request has exceeded the allotted timeout");
                }

                //System.Diagnostics.Debug.WriteLine(string.Format("DataAvailable: {0}, continue: {1} ", _networkStream.DataAvailable, bContinue));
            }while (_networkStream.DataAvailable || bContinue);
        }
Beispiel #4
0
        public Message Request(Message message, TimeSpan timeout)
        {
            // check input parameters
            if (message == null)
            {
                throw new ArgumentNullException("message");
            }
            if (timeout < TimeSpan.Zero)
            {
                throw new ArgumentOutOfRangeException("timeout");
            }

            if (_endpointController != null)
            {
                _to = _endpointController.Address;

                if (_endpointController.WsaEnabled)
                {
                    message.Headers.To = _endpointController.Address.Uri;
                }
                else
                {
                    // clear headers since not all cameras understand them.
                    message.Headers.Action    = null;
                    message.Headers.ReplyTo   = null;
                    message.Headers.MessageId = null;
                }
            }
            else
            {
                // clear headers since not all cameras understand them.
                message.Headers.Action    = null;
                message.Headers.ReplyTo   = null;
                message.Headers.MessageId = null;
            }

            // check if underlying stream has not been closed by the server
            _networkStream.EnsureOpen(_to);

            base.ThrowIfDisposedOrNotOpen();

            _currentMessageBytes = null;

            // send message
            WriteMessageToStream(message);

            // Start reading
            // Wait first byte for timeout.TotalMilliseconds
            int readTimeout = (int)timeout.TotalMilliseconds;

            // initialize variables
            MemoryStream responseStream;
            HttpPacket   header = null;

            do
            {
                responseStream = new MemoryStream();
                GetResponse(responseStream, out header, readTimeout);
            } while (header.StatusCode == 100);

            // check status 401
            bool digestEnabled = false;

            if (_credentialsProvider != null)
            {
                digestEnabled = _credentialsProvider.Security == Security.Digest;
            }

            if (header.StatusCode == 401)
            {
                if (digestEnabled)
                {
                    System.Diagnostics.Debug.WriteLine("HTTP 401 received");

                    foreach (string connectionHeader in header.Connection)
                    {
                        if (StringComparer.InvariantCultureIgnoreCase.Compare(connectionHeader, "close") == 0)
                        {
                            _networkStream.Close();
                            _networkStream.EnsureOpen(_to);
                            break;
                        }
                    }

                    // Send request once more.
                    _digestAuthChallenge = header;

                    // uses _digestAuthChallenge (and _currentMessageBytes), so behaviour will be different
                    // (_digestAuthChallenge might be not null by the first attempt, but if we get status 401,
                    // it will be updated)
                    WriteMessageToStream(message);

                    do
                    {
                        responseStream = new MemoryStream();
                        GetResponse(responseStream, out header, readTimeout);
                    } while (header.StatusCode == 100);

                    if (header.StatusCode == 401)
                    {
                        LogResponse(responseStream, header);
                        _networkStream.Close();
                        throw new AccessDeniedException("Digest authentication FAILED (HTTP status 401 received)");
                    }
                }
                else
                {
                    _networkStream.Close();
                    LogResponse(responseStream, header);
                    throw new AccessDeniedException("Access denied (HTTP status 401 received)");
                }
            }

            foreach (string connectionHeader in header.Connection)
            {
                if (StringComparer.InvariantCultureIgnoreCase.Compare(connectionHeader, "close") == 0)
                {
                    _networkStream.Close();
                    break;
                }
            }

            int count = (int)responseStream.Length - header.BodyOffset;

            // parse response and notify listeners
            LogResponse(responseStream, header);

            if (header.ContentLength < count)
            {
                if (header.Headers.ContainsKey(HttpHelper.CONTENTLENGTH))
                {
                    throw new HttpProtocolException(
                              string.Format("An error occurred while receiving packet. Expected length: {0}, received: {1}",
                                            header.ContentLength, count));
                }
                else
                {
                    if (!header.NoBodySupposed)
                    {
                        if (header.StatusCode != 200)
                        {
                            throw new HttpProtocolException(
                                      string.Format("An error returned. Error code: {0}, error description: {1}",
                                                    header.StatusCode, header.StatusDescription));
                        }
                        else
                        {
                            throw new HttpProtocolException("Content-Length header is missing");
                        }
                    }
                }
            }

            // validate headers
            HttpHelper.ValidateHttpHeaders(header);

            return(ReadMessage(responseStream, header));
        }
        public Message Request(Message message, TimeSpan timeout)
        {
            Message message3 = null;

            // check input parameters
            if (message == null)
            {
                throw new ArgumentNullException("message");
            }
            if (timeout < TimeSpan.Zero)
            {
                throw new ArgumentOutOfRangeException("timeout");
            }

            // check if underlying stream has not been closed by the server
            if (_endpointController != null)
            {
                _to = _endpointController.Address;

                if (_endpointController.WsaEnabled)
                {
                    message.Headers.To = _endpointController.Address.Uri;
                }
                else
                {
                    // clear headers since not all cameras understand them.
                    message.Headers.Action    = null;
                    message.Headers.ReplyTo   = null;
                    message.Headers.MessageId = null;
                }
            }
            else
            {
                // clear headers since not all cameras understand them.
                message.Headers.Action    = null;
                message.Headers.ReplyTo   = null;
                message.Headers.MessageId = null;
            }

            _networkStream.EnsureOpen(_to);

            base.ThrowIfDisposedOrNotOpen();


            // send message
            WriteMessageToStream(message);

            // Start reading
            // Wait first byte for timeout.TotalMilliseconds
            int readTimeout = (int)timeout.TotalMilliseconds;

            // initialize variables
            MemoryStream responseStream;
            HttpPacket   header = null;

            do
            {
                responseStream = new MemoryStream();
                GetResponse(responseStream, out header, readTimeout);

                if (header.StatusCode == 100)
                {
                    System.Diagnostics.Debug.WriteLine("100-Continue received");
                }
            } while (header.StatusCode == 100);

            System.Diagnostics.Debug.WriteLine("Real answer received");

            // check status 401

            /*
             * if (header.StatusCode == 401)
             * {
             *  System.Diagnostics.Debug.WriteLine("HTTP 401 received");
             *  _networkStream.Close();
             *
             *  _networkStream.EnsureOpen(_to);
             *
             *  System.Diagnostics.Debug.WriteLine(string.Format("After EnsureOpen: socket: {0}", _networkStream.Connected));
             *
             *  // Send request once more.
             *
             *  // something else should be used instead of "WriteMessageToStream(message);"
             *  ResendMessage(message, header);
             *
             *  System.Diagnostics.Debug.WriteLine(string.Format("After ResendMessage: socket: {0}", _networkStream.Connected));
             *
             *  do
             *  {
             *      responseStream = new MemoryStream();
             *      GetResponse(responseStream, out header, readTimeout);
             *
             *      System.Diagnostics.Debug.WriteLine(string.Format("After GetResponse: socket: {0}", _networkStream.Connected));
             *
             *      if (header.StatusCode == 100)
             *      {
             *          System.Diagnostics.Debug.WriteLine("100-Continue received");
             *      }
             *
             *  } while (header.StatusCode == 100);
             *
             *  if (header.StatusCode == 401)
             *  {
             *      _networkStream.Close();
             *      throw new ApplicationException("Digest authentication FAILED (HTTP status 401 received)");
             *  }
             * }
             */

            _networkStream.Close();

            int count = (int)responseStream.Length - header.BodyOffset;

            // parse response and notify listeners
            string response = HttpHelper.GetFormattedMessage(responseStream.GetBuffer(), header.BodyOffset);

            foreach (ITrafficListener listener in _listeners)
            {
                listener.LogResponse(response);
            }

            if (header.ContentLength < count)
            {
                if (header.Headers.ContainsKey(HttpHelper.CONTENTLENGTH))
                {
                    throw new HttpProtocolException(
                              string.Format("An error occurred while receiving packet. Expected length: {0}, received: {1}",
                                            header.ContentLength, count));
                }
                else
                {
                    if (!header.NoBodySupposed)
                    {
                        if (header.StatusCode != 200)
                        {
                            throw new HttpProtocolException(
                                      string.Format("An error returned. Error code: {0}, error description: {1}",
                                                    header.StatusCode, header.StatusDescription));
                        }
                        else
                        {
                            throw new HttpProtocolException("Content-Length header is missing");
                        }
                    }
                }
            }

            // validate headers
            HttpHelper.ValidateHttpHeaders(header);

            return(ReadMessage(responseStream, header));
        }
Beispiel #6
0
        public string SendSoapMessage(string request)
        {
            // create request bytes
            byte[] soapBytes = Encoding.UTF8.GetBytes(request);

            // create headers
            byte[] httpHeaders = HttpHelper.CreateHttpHeaders(soapBytes.Length,
                                                              _address.AbsolutePath,
                                                              _address.Host);

            //whole message with headers
            byte[] bytes = new byte[httpHeaders.Length + soapBytes.Length];

            Array.Copy(httpHeaders, bytes, httpHeaders.Length);

            Array.Copy(soapBytes, 0, bytes, httpHeaders.Length, soapBytes.Length);

#if DEBUG
            //string str = Encoding.UTF8.GetString(bytes);
            //System.Diagnostics.Debug.WriteLine(string.Format("SEND: {0}", str));
#endif

            RequestNetworkStream _networkStream = new RequestNetworkStream(new EndpointAddress(_address.OriginalString));
            _networkStream.Connect();

            _networkStream.Write(bytes, 0, bytes.Length);

            MemoryStream responseStream = new MemoryStream();
            byte[]       responseBuffer = new byte[2048];
            int          readTimeout    = _timeout;
            int          bytesCount     = 0;
            bool         bContinue      = false;
            HttpPacket   header         = null;

            do
            {
                DateTime startTime = DateTime.Now;

                IAsyncResult result = _networkStream.BeginRead(responseBuffer, 0, responseBuffer.Length);

                // wait for bytes receied, stop event or timeout
                WaitHandle[] handles;
                if (_executionController != null && _executionController.StopEvent != null)
                {
                    handles = new WaitHandle[] { result.AsyncWaitHandle, _executionController.StopEvent };
                }
                else
                {
                    handles = new WaitHandle[] { result.AsyncWaitHandle };
                }
                int handle = System.Threading.WaitHandle.WaitAny(handles, readTimeout);

                if (handle == WaitHandle.WaitTimeout)
                {
                    _networkStream.Close();
                    throw new IOException("The HTTP request has exceeded the allotted timeout");
                }

                if (handle == 1)
                {
                    System.Diagnostics.Debug.WriteLine("Stop event");
                    _networkStream.Close();
                    _executionController.ReportStop();
                }

                bytesCount = _networkStream.EndRead(result);

                DateTime endTime = DateTime.Now;

                System.Diagnostics.Debug.WriteLine(string.Format("--- Bytes received: {0}", bytesCount));

                responseStream.Write(responseBuffer, 0, bytesCount);

                // timeout for next part of answer
                readTimeout -= (int)((endTime - startTime).TotalMilliseconds);

                // parse response received by this moment.
                try
                {
                    bContinue = HttpHelper.ContinueReading(responseStream, out header);
                }
                catch (Exception exc)
                {
                    _networkStream.Close();
                    // clean resources somehow ?
                    throw new Exception("An error occurred while parsing HTTP packet", exc);
                }

                if (readTimeout < 0)
                {
                    _networkStream.Close();
                    throw new IOException("The HTTP request has exceeded the allotted timeout");
                }
            }while (_networkStream.DataAvailable || bContinue);

            _networkStream.Close();

            int count = (int)responseStream.Length - header.BodyOffset;

            if (header.ContentLength < count)
            {
                throw new HttpProtocolException(
                          string.Format("An error occurred while receiving packet. Expected length: {0}, received: {1}",
                                        header.ContentLength, count));
            }

            // parse response and notify listeners
            string response = HttpHelper.GetFormattedMessage(responseStream.GetBuffer(), header.BodyOffset);

            responseStream.Close();
            return(response);
        }