Exemple #1
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");
            }

            _currentMessage = message;

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

            if (_wsaController != null)
            {
                _wsaController.ProcessRequest(message);
                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;
            }

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

            base.ThrowIfDisposedOrNotOpen();

            _currentMessageBytes = null;

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

            // initialize variables
            MemoryStream responseStream = null;
            HttpPacket   header         = null;
            var          messageCopy    = message.CreateBufferedCopy(int.MaxValue);

            try
            {
                WriteMessageToStream(messageCopy.CreateMessage());

                do
                {
                    responseStream = new MemoryStream();
                    GetResponse(responseStream, out header, readTimeout);
                } while (header.StatusCode == (int)System.Net.HttpStatusCode.Continue);
            }
            catch (ApplicationException)
            {
                throw;
            }
            catch (Exception e)
            {
                if (InternalLog)
                {
                    InternalLogger.GetInstance().SwitchOnForCurrentThread();
                }
                else
                {
                    InternalLogger.GetInstance().SwitchOffForCurrentThread();
                }
                InternalLogger.GetInstance().LogMessage("During sending request to the DUT exception has been thrown!");
                InternalLogger.GetInstance().LogException(e);
                InternalLogger.GetInstance().LogMessage("EnsureOpen was called. Trying to forcibly reopen the network stream and send the request again.");
                NetworkStream.Close();
                NetworkStream.Connect();
                WriteMessageToStream(messageCopy.CreateMessage());

                do
                {
                    responseStream = new MemoryStream();
                    GetResponse(responseStream, out header, readTimeout);
                } while (header.StatusCode == (int)System.Net.HttpStatusCode.Continue);
            }

            // check status 401
            bool digestEnabled = false;

            if (CredentialsProvider != null)
            {
                digestEnabled = CredentialsProvider.Security == Security.Digest ||
                                CredentialsProvider.Security == Security.DigestTesting;
            }

            if (header.StatusCode == (int)System.Net.HttpStatusCode.Unauthorized)
            {
                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 == (int)System.Net.HttpStatusCode.Continue);

                    if (header.StatusCode == (int)System.Net.HttpStatusCode.Unauthorized)
                    {
                        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)");
                }
            }

            // 2011/12/06: optimization postponed to the next project.
            // 2012/04/13: restore
            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 != (int)System.Net.HttpStatusCode.OK)
                        {
                            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));
        }