private void RunHeaderTest(string headerName, string expectedValue, bool expectNull, int port = -1)
        {
            HttpRequestInfo expectedRequest = new HttpRequestInfo("POST / HTTP/1.1\r\n\r\na=1\r\n");

            expectedRequest.Headers.Add(headerName, expectedValue);


            HttpRequestInfo  receivedReqInfo;
            HttpResponseInfo receivedRespInfo;

            if (port != -1)
            {
                SendTestRequestToMockProxy(expectedRequest, new HttpResponseInfo("HTTP/1.1 200 OK\r\n\r\n"),
                                           out receivedReqInfo,
                                           out receivedRespInfo,
                                           port);
            }
            else
            {
                SendTestRequestToMockProxy(expectedRequest, new HttpResponseInfo("HTTP/1.1 200 OK\r\n\r\n"),
                                           out receivedReqInfo,
                                           out receivedRespInfo);
            }



            if (expectNull)
            {
                Assert.IsNull(receivedReqInfo.Headers[headerName]);
            }
            else
            {
                Assert.AreEqual(expectedValue, receivedReqInfo.Headers[headerName]);
            }
        }
        public void InvalidIPAddressNoProtocol()
        {
            string          URL         = "127.0.0.1";
            HttpRequestInfo requestInfo = new HttpRequestInfo(URL, RequestType.Get, null);

            Assert.IsNull(requestInfo.GetURI());
        }
Example #3
0
 private void AreEqual(HttpRequestInfo exp, HttpRequestInfo act)
 {
     Assert.AreEqual(exp.ClientIpAddress, act.ClientIpAddress);
     Assert.AreEqual(exp.ClientRequestId, act.ClientRequestId);
     Assert.AreEqual(exp.Method, act.Method);
     Assert.AreEqual(exp.Uri, act.Uri);
 }
Example #4
0
        public string SendTest(string mutatedRequest, string host, int port, bool useSSL)
        {
            IHttpClient     client  = new WebRequestClient();
            HttpRequestInfo reqInfo = new HttpRequestInfo(mutatedRequest);

            reqInfo.IsSecure = useSSL;
            reqInfo.Host     = host;
            reqInfo.Port     = port;
            HttpResponseInfo resp = null;

            try
            {
                resp = client.SendRequest(reqInfo);
            }
            catch
            { }
            string response;

            if (resp != null)
            {
                PatternTracker.Instance.UpdatePatternValues(resp);
                response = resp.ToString();
            }
            else
            {
                response = String.Empty;
            }

            return(response);
        }
Example #5
0
        public Response Execute(Command commandToExecute)
        {
            if (commandToExecute == null)
            {
                throw new ArgumentNullException(nameof(commandToExecute), "commandToExecute cannot be null");
            }

            var info        = CommandInfoRepository.GetCommandInfo(commandToExecute.Name);
            var requestInfo = new HttpRequestInfo(RemoteServerUri, commandToExecute, info);

            HttpResponseInfo responseInfo = MakeHttpRequest(requestInfo);

            Response toReturn = CreateResponse(responseInfo);

            if (commandToExecute.Name == DriverCommand.NewSession && toReturn.IsSpecificationCompliant)
            {
                // If we are creating a new session, sniff the response to determine
                // what protocol level we are using. If the response contains a
                // field called "status", it's not a spec-compliant response.
                // Each response is polled for this, and sets a property describing
                // whether it's using the W3C protocol dialect.
                // TODO(jimevans): Reverse this test to make it the default path when
                // most remote ends speak W3C, then remove it entirely when legacy
                // protocol is phased out.
                CommandInfoRepository = new W3CWireProtocolCommandInfoRepository();
            }

            return(toReturn);
        }
Example #6
0
        private void GenerateRequests(object sender, DoWorkEventArgs e)
        {
            _curDataAccessor.SetState(AccessorState.Loading);
            GetRecursiveListOfFiles(_rootDir);

            foreach (string fileName in _fileList)
            {
                try
                {
                    string requestPath = fileName.Replace(_rootDir, "");
                    requestPath = requestPath.Replace('\\', '/').TrimStart('/');
                    requestPath = Regex.Replace(requestPath, _replacementPattern, _replacementString);
                    var requestUri = new Uri(_rootUri, requestPath);
                    requestPath = requestUri.AbsolutePath;
                    string host = requestUri.Host;
                    int    port = requestUri.Port;

                    var getRequest  = new HttpRequestInfo(String.Format("GET {0} HTTP/1.1\r\n{1}\r\n\r\n", requestPath, _headers), true);
                    var postRequest = new HttpRequestInfo(String.Format("POST {0} HTTP/1.1\r\n{1}\r\n", requestPath, _headers), true);
                    postRequest.Headers["Content-Type"] = "application/x-www-form-urlencoded";

                    getRequest.Host = postRequest.Host = host;
                    getRequest.Port = postRequest.Port = port;

                    getRequest.IsSecure = postRequest.IsSecure = _rootUri.Scheme.Equals("https", StringComparison.OrdinalIgnoreCase);

                    string fileContents = GetFileContents(fileName, 0);

                    var parameters = GetParametersAndValues(_paramPattern, fileContents);

                    //add requests for all parameter values combinations
                    GenerateRequestsBasedOnParameters(getRequest, postRequest, parameters);


                    //parse all links and forms from the content
                    ExtractLinks(fileContents);

                    //parse forms
                    ExtractForms(fileContents);
                }
                catch (Exception ex)
                {
                    SdkSettings.Instance.Logger.Log(System.Diagnostics.TraceLevel.Error, ex.Message);
                }
            }

            foreach (var url in _foundUrls)
            {
                if (Uri.IsWellFormedUriString(url, UriKind.Absolute))
                {
                    Uri uri = new Uri(url);
                    //generate get requests
                    var getRequest = new HttpRequestInfo(String.Format("GET {0} HTTP/1.1\r\n{1}\r\n\r\n", uri.PathAndQuery, _headers), true);
                    getRequest.Host = uri.Host;
                    getRequest.Port = uri.Port;
                    AddHttpRequest(getRequest);
                }
            }
            _curDataAccessor.SetState(AccessorState.Idle);
        }
Example #7
0
        /// <summary>
        /// Navigates to a new page
        /// </summary>
        /// <param name="playbackBrowser"></param>
        /// <param name="reqInfo"></param>
        private static void Navigate(TrafficPlaybackBrowser playbackBrowser, HttpRequestInfo reqInfo)
        {
            WebBrowser browser = playbackBrowser.Browser;

            //try sending the next request
            try
            {
                string url = String.Format("http://{0}{1}", playbackBrowser.ProxyHost, reqInfo.PathAndQuery);
                playbackBrowser.AddressBox.Text = url;
                if (reqInfo.ContentLength > 0)
                {
                    browser.Navigate(url,
                                     String.Empty,
                                     reqInfo.ContentData,
                                     reqInfo.Headers.ToString());
                }
                else
                {
                    browser.Navigate(url,
                                     String.Empty,
                                     null,
                                     reqInfo.Headers.ToString());
                }
            }
            catch { }
        }
Example #8
0
        internal static QItemStream ReadRequest(HttpRequestInfo request)
        {
            var message = new QItemStream();

            message.EntityRead(request.Body, null);
            return(message);
        }
Example #9
0
        public void CustomTester_MatchHeaderValidation()
        {
            TrafficViewerFile  mockSite           = new TrafficViewerFile();
            MockTestController mockTestController = new MockTestController(mockSite);


            string testRequest = "GET /search.aspx?txtSearch=a&a1=a HTTP/1.1\r\nHost: 127.0.0.1\r\n\r\n";
            string paramName   = "txtSearch";

            CustomTestsFile file   = GetCustomTestFile();
            Tester          tester = new Tester(mockTestController, file);
            CustomTestDef   def    = file.GetCustomTests()["Path Traversal"];



            def.Validation = "$header=" + "root:\\s?:";

            HttpRequestInfo original = new HttpRequestInfo(testRequest, true);
            Uri             uri      = new Uri(original.FullUrl);

            string  entityId       = tester.GetEntityId(uri, paramName);
            string  entityString   = tester.GetEntityString(testRequest, uri, paramName, original.QueryVariables[paramName]);
            TestJob testJob        = new TestJob(paramName, original.QueryVariables[paramName], RequestLocation.Query, def);
            string  mutatedRequest = tester.GenerateMutatedRequestList(testRequest, testJob, entityString, entityId)[0];

            Assert.IsFalse(tester.ValidateSingleTest(testRequest, "HTTP/1.1 200 OK\r\nbla", new Uri("http://demo.testfire.net/search.aspx"),
                                                     paramName, entityId, def, mutatedRequest, "HTTP/1.1 200 OK\r\n\r\nroot::"));
            Assert.IsTrue(tester.ValidateSingleTest(testRequest, "HTTP/1.1 200 OK\r\nbla", new Uri("http://demo.testfire.net/search.aspx"),
                                                    paramName, entityId, def, mutatedRequest, "HTTP/1.1 200 OK\r\nroot::\r\n\r\nbody"));
        }
Example #10
0
 private void AddSpecialHeader(HttpRequestInfo requestInfo)
 {
     if (requestInfo.Headers[TRAFFIC_VIEWER_HEADER] == null)
     {
         requestInfo.Headers.Add(TRAFFIC_VIEWER_HEADER, _trackingReqInfo.Id.ToString());
     }
 }
Example #11
0
        public HttpResponseInfo SendRequest(string method, string path,
                                            Dictionary <string, string> queryParams = null, string postData = null, string range = null)
        {
            HttpRequestInfo request;



            request = new HttpRequestInfo(Encoding.UTF8.GetBytes(String.Format("{0} {1} HTTP/1.1\r\n\r\n", method, path)));

            if (!String.IsNullOrWhiteSpace(range))
            {
                request.Headers["Range"] = range;
            }

            if (!String.IsNullOrWhiteSpace(postData))
            {
                request.ContentData             = Encoding.UTF8.GetBytes(postData);
                request.Headers["Content-Type"] = "application/json";
            }

            if (queryParams != null)
            {
                foreach (string paramName in queryParams.Keys)
                {
                    request.QueryVariables.Add(paramName, queryParams[paramName]);
                }
            }



            return(SendRequest(request));
        }
Example #12
0
        /// <summary>
        /// Gets a search criteria for the request info
        /// </summary>
        /// <param name="requestInfo"></param>
        /// <param name="currentMatchMode"></param>
        /// <returns></returns>
        private SearchCriteriaSet GetCriteriaSet(HttpRequestInfo requestInfo, TrafficServerMode currentMatchMode)
        {
            SearchCriteriaSet criteriaSet;

            criteriaSet = new SearchCriteriaSet();
            criteriaSet.Add(new SearchCriteria(SearchContext.RequestLine, true, requestInfo.SearchRegex));

            //reduce the search area by adding the variable names and values as seach matches

            bool incVal = currentMatchMode != TrafficServerMode.BrowserFriendly;

            if (requestInfo.QueryVariables.Count > 0)
            {
                criteriaSet.Add(
                    requestInfo.QueryVariables.GetSearchCriteria(incVal));
            }

            //for POST requests add the body variables as criteria
            if (requestInfo.ContentLength > 0)
            {
                if (requestInfo.BodyVariables.Count > 0)
                {
                    criteriaSet.Add(
                        requestInfo.BodyVariables.GetSearchCriteria(incVal));
                }
                else
                {
                    //we are dealing with custom parameters so just add the full post data as
                    //a criteria
                    criteriaSet.Add(new SearchCriteria(SearchContext.RequestBody, false, requestInfo.ContentDataString));
                }
            }
            return(criteriaSet);
        }
        private void RunRequestLineTest(string expectedValue)
        {
            WebRequestClient  wrClient  = new WebRequestClient();
            TrafficViewerFile dataStore = new TrafficViewerFile();
            TrafficViewerFile mockSite  = new TrafficViewerFile();
            MockProxy         mockProxy = new MockProxy(dataStore, mockSite);

            mockProxy.Start();

            HttpRequestInfo expectedRequest = new HttpRequestInfo(expectedValue);

            expectedRequest.Host = mockProxy.Host;
            expectedRequest.Port = mockProxy.Port;

            //set the webrequest to use a proxy

            HttpResponseInfo respInfo = wrClient.SendRequest(expectedRequest);

            mockProxy.Stop();
            if (!expectedRequest.IsConnect)
            {
                Assert.AreEqual(1, dataStore.RequestCount);

                byte[] receivedReqBytes = dataStore.LoadRequestData(0);

                HttpRequestInfo receivedRequest = new HttpRequestInfo(receivedReqBytes);

                Assert.AreEqual(expectedValue, receivedRequest.RequestLine);
            }
            else
            {
                Assert.AreEqual("HTTP/1.1 200 Connection established", respInfo.StatusLine);
            }
        }
Example #14
0
        /// <summary>
        /// Records statistics collected from incoming requests.
        /// </summary>
        /// <param name="request">The request.</param>
        internal static void RecordRequestStatistics(HttpRequestInfo request)
        {
            Contract.Requires(request != null);

            // In release builds, just quietly return.
            if (request == null)
            {
                return;
            }

            if (Enabled)
            {
                if (Configuration.IncludeCultures)
                {
                    observedCultures.Add(Thread.CurrentThread.CurrentCulture.Name);
                }

                if (Configuration.IncludeLocalRequestUris && !observedRequests.IsFull)
                {
                    var requestBuilder = new UriBuilder(request.UrlBeforeRewriting);
                    requestBuilder.Query    = null;
                    requestBuilder.Fragment = null;
                    observedRequests.Add(requestBuilder.Uri.AbsoluteUri);
                }

                Touch();
            }
        }
		public virtual OutgoingWebResponse VerifyAccess(HttpRequestInfo httpRequestInfo, out string userName, out HashSet<string> scope) {
			Requires.NotNull(httpRequestInfo, "httpRequestInfo");

			AccessProtectedResourceRequest request = null;
			try {
				if (this.Channel.TryReadFromRequest<AccessProtectedResourceRequest>(httpRequestInfo, out request)) {
					if (this.AccessTokenAnalyzer.TryValidateAccessToken(request, request.AccessToken, out userName, out scope)) {
						// No errors to return.
						return null;
					}

					throw ErrorUtilities.ThrowProtocol(OAuth2Strings.InvalidAccessToken);
				} else {
					var response = new UnauthorizedResponse(new ProtocolException(OAuth2Strings.MissingAccessToken));

					userName = null;
					scope = null;
					return this.Channel.PrepareResponse(response);
				}
			} catch (ProtocolException ex) {
				var response = request != null ? new UnauthorizedResponse(request, ex) : new UnauthorizedResponse(ex);

				userName = null;
				scope = null;
				return this.Channel.PrepareResponse(response);
			}
		}
Example #16
0
        public void CustomTester_SingleCharacterValue()
        {
            TrafficViewerFile  mockSite           = new TrafficViewerFile();
            MockTestController mockTestController = new MockTestController(mockSite);


            string          testRequest = "GET /search.aspx?txtSearch=a&a1=a HTTP/1.1\r\nHost: 127.0.0.1\r\n\r\n";
            string          paramName   = "txtSearch";
            string          paramName2  = "a1";
            CustomTestsFile file        = GetCustomTestFile();
            Tester          tester      = new Tester(mockTestController, file);
            CustomTestDef   def         = file.GetCustomTests()["Path Traversal"];
            HttpRequestInfo original    = new HttpRequestInfo(testRequest, true);
            Uri             uri         = new Uri(original.FullUrl);

            string          entityId       = tester.GetEntityId(uri, paramName);
            string          entityString   = tester.GetEntityString(testRequest, uri, paramName, original.QueryVariables[paramName]);
            TestJob         testJob        = new TestJob(paramName, original.QueryVariables[paramName], RequestLocation.Query, def);
            string          mutatedRequest = tester.GenerateMutatedRequestList(testRequest, testJob, entityString, entityId)[0];
            HttpRequestInfo mutatedReqInfo = new HttpRequestInfo(mutatedRequest, true);

            Assert.IsTrue(mutatedReqInfo.QueryVariables.ContainsKey(paramName), "Could no longer find parameter");
            Assert.AreEqual(original.QueryVariables[paramName] + MockTestController.PATH_TRAVERSAL, mutatedReqInfo.QueryVariables[paramName], "Incorrect test value");
            Assert.AreEqual(original.QueryVariables[paramName2], mutatedReqInfo.QueryVariables[paramName2], "Incorrect non-test value");
        }
Example #17
0
        /// <summary>
        /// Generates all possible parameter combinations
        /// </summary>
        /// <param name="getRequest"></param>
        /// <param name="postRequest"></param>
        /// <param name="parameters"></param>
        private void GenerateRequestsBasedOnParameters(HttpRequestInfo getRequest, HttpRequestInfo postRequest, List <string> parameters)
        {
            if (parameters.Count == 0)
            {
                AddHttpRequest(getRequest);
                AddHttpRequest(postRequest);
            }
            else
            {
                foreach (string parameterString in parameters)
                {
                    string[] nameValuePairs = parameterString.Split('&');

                    getRequest.QueryVariables.Clear();
                    postRequest.BodyVariables.Clear();

                    foreach (string nameValuePair in nameValuePairs)
                    {
                        string[] nameValueArray = nameValuePair.Split('=');

                        if (nameValueArray.Length == 2)
                        {
                            var paramName = nameValueArray[0];
                            var paramVal  = nameValueArray[1];
                            getRequest.QueryVariables.Add(paramName, paramVal);
                            postRequest.BodyVariables.Add(paramName, paramVal);
                        }
                    }
                    AddHttpRequest(getRequest);
                    AddHttpRequest(postRequest);
                }
            }
        }
Example #18
0
        public void CustomTester_ParametersWithSameValue()
        {
            MockTestController mockTestController = new MockTestController();


            string          testRequest = "GET /search.jsp?a=1&b=1 HTTP/1.1\r\nHost: 127.0.0.1\r\n\r\n";
            string          paramName1  = "a";
            string          paramName2  = "b";
            CustomTestsFile file        = GetCustomTestFile();
            Tester          tester      = new Tester(mockTestController, file);
            CustomTestDef   def         = file.GetCustomTests()["Path Traversal"];
            HttpRequestInfo original    = new HttpRequestInfo(testRequest, true);
            Uri             uri         = new Uri(original.FullUrl);

            tester.ExecuteTests(testRequest, "", uri, paramName1, null, RequestLocation.Query, def);
            Assert.IsTrue(mockTestController.IssuesFound.ContainsKey(paramName1));
            string          mutReq     = mockTestController.MutatedRequests[0];
            HttpRequestInfo mutReqInfo = new HttpRequestInfo(mutReq);

            Assert.AreEqual(MockTestController.PATH_TRAVERSAL, mutReqInfo.QueryVariables[paramName1], "Invalid mutation for " + paramName1);
            Assert.AreEqual("1", mutReqInfo.QueryVariables[paramName2], "Invalid value for " + paramName2);
            tester.ExecuteTests(testRequest, "", uri, paramName2, null, RequestLocation.Query, def);
            Assert.IsTrue(mockTestController.IssuesFound.ContainsKey(paramName2));
            mutReq     = mockTestController.MutatedRequests[1];
            mutReqInfo = new HttpRequestInfo(mutReq);
            Assert.AreEqual("1", mutReqInfo.QueryVariables[paramName1], "Invalid value for " + paramName1);
            Assert.AreEqual(MockTestController.PATH_TRAVERSAL, mutReqInfo.QueryVariables[paramName2], "Invalid mutation for " + paramName2);
        }
Example #19
0
        public IEnumerable <RoleVM> Update(List <RoleVM> roles, HttpRequestInfo info)
        {
            var addedRoles = new List <Role>();

            roles.ForEach(role =>
            {
                if (role.IdRole == 0)
                {
                    throw new System.Exception("IdRole alanı her zaman dolu olmalıdır.");
                }

                var entity = modelToEntity.Compile()(role);

                entity.OperationIsDeleted = (short)Active;
                entity.OperationIP        = info.IpAddress;
                entity.OperationIdUserRef = info.UserID;
                entity.OperationDate      = DateTime.Now;

                CRUD.Update(entity, info);
                addedRoles.Add(entity);
            });

            Save();

            return(addedRoles.Select(entityToModel.Compile()));
        }
Example #20
0
        public void ReadFromRequestAuthorizationScattered()
        {
            // Start by creating a standard POST HTTP request.
            var fields = new Dictionary <string, string> {
                { "age", "15" },
            };
            HttpRequestInfo requestInfo = CreateHttpRequestInfo(HttpDeliveryMethods.PostRequest, fields);

            // Now add another field to the request URL
            UriBuilder builder = new UriBuilder(requestInfo.UrlBeforeRewriting);

            builder.Query = "Name=Andrew";
            requestInfo.UrlBeforeRewriting = builder.Uri;
            requestInfo.RawUrl             = builder.Path + builder.Query + builder.Fragment;

            // Finally, add an Authorization header
            fields = new Dictionary <string, string> {
                { "Location", "http://hostb/pathB" },
                { "Timestamp", XmlConvert.ToString(DateTime.UtcNow, XmlDateTimeSerializationMode.Utc) },
            };
            requestInfo.Headers.Add(HttpRequestHeader.Authorization, CreateAuthorizationHeader(fields));

            IDirectedProtocolMessage requestMessage = this.channel.ReadFromRequest(requestInfo);

            Assert.IsNotNull(requestMessage);
            Assert.IsInstanceOf <TestMessage>(requestMessage);
            TestMessage testMessage = (TestMessage)requestMessage;

            Assert.AreEqual(15, testMessage.Age);
            Assert.AreEqual("Andrew", testMessage.Name);
            Assert.AreEqual("http://hostb/pathB", testMessage.Location.AbsoluteUri);
        }
Example #21
0
        internal static HttpRequestInfo CreateHttpRequestInfo(string method, IDictionary <string, string> fields)
        {
            string              query      = MessagingUtilities.CreateQueryString(fields);
            UriBuilder          requestUri = new UriBuilder("http://localhost/path");
            WebHeaderCollection headers    = new WebHeaderCollection();
            MemoryStream        ms         = new MemoryStream();

            if (method == "POST")
            {
                headers.Add(HttpRequestHeader.ContentType, "application/x-www-form-urlencoded");
                StreamWriter sw = new StreamWriter(ms);
                sw.Write(query);
                sw.Flush();
                ms.Position = 0;
            }
            else if (method == "GET")
            {
                requestUri.Query = query;
            }
            else
            {
                throw new ArgumentOutOfRangeException("method", method, "Expected POST or GET");
            }
            HttpRequestInfo request = new HttpRequestInfo {
                HttpMethod         = method,
                UrlBeforeRewriting = requestUri.Uri,
                Headers            = headers,
                InputStream        = ms,
            };

            return(request);
        }
Example #22
0
        /// <summary>
        /// Read Request
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        protected override IQueueMessage ReadRequest(HttpRequestInfo request)
        {
            //throw new Exception("Not implemented.");

            MessageStream stream = null;

            if (request.BodyStream != null)
            {
                stream = MessageStream.ParseStream(request.BodyStream, NetProtocol.Http);
            }
            else
            {
                var message = new HttpMessage();

                if (request.QueryString != null)//request.BodyType == HttpBodyType.QueryString)
                {
                    message.EntityRead(request.QueryString, null);
                }
                else if (request.Body != null)
                {
                    message.EntityRead(request.Body, null);
                }
                //else if (request.Url.LocalPath != null && request.Url.LocalPath.Length > 1)
                //    message.EntityRead(request.Url.LocalPath.TrimStart('/').TrimEnd('/'), null);

                stream = message;
            }

            return(new QueueRequest(stream.GetStream()));
        }
Example #23
0
        protected virtual HttpWebRequest CreateHttpWebRequest(HttpRequestInfo requestInfo)
        {
            HttpWebRequest request = WebRequest.Create(requestInfo.FullUri) as HttpWebRequest;

            request.Method    = requestInfo.HttpMethod;
            request.Timeout   = (int)ServerResponseTimeout.TotalMilliseconds;
            request.Accept    = RequestAcceptHeader;
            request.KeepAlive = EnableKeepAlive;
            request.ServicePoint.ConnectionLimit = 2000;

            if (request.Method == CommandInfo.PostCommand)
            {
                string payload = requestInfo.RequestBody;
                byte[] data    = Encoding.UTF8.GetBytes(payload);
                request.ContentType = ContentTypeHeader;
                Stream requestStream = request.GetRequestStream();
                requestStream.Write(data, 0, data.Length);
                requestStream.Close();
            }

            if (!string.IsNullOrEmpty(requestInfo.FullUri.UserInfo) && UseBasicAuth)
            {
                string basicAuth = Convert.ToBase64String(Encoding.UTF8.GetBytes(requestInfo.FullUri.UserInfo));
                request.Headers.Add(HttpRequestHeader.Authorization, $"Basic {basicAuth}");
            }

            return(request);
        }
        private void HandleSendingRequestLine(string line)
        {
            byte[] bytes;

            bytes = ReadNextBytes(line, _sendingRequestRegex);
            if (bytes != null)
            {
                if (_currentRequestData == null || _currentRequestData.RawResponse != null)
                {
                    _currentRequestData = new RequestResponseBytes();
                    _currentHeader      = null;
                }

                _currentRequestData.AddToRequest(bytes);
                //check if this the start of a new request
                if (_currentHeader == null || String.IsNullOrEmpty(_currentHeader.RequestLine))
                {
                    string reqLine = HttpRequestInfo.GetRequestLine(_currentRequestData.RawRequest);
                    //check if it's recognized as a valid request line
                    if (_lineTypeSelector.GetLineType(reqLine) == LineType.FirstRequestLine)
                    {
                        HandleFirstRequestLine(reqLine, null);
                    }
                }
            }
        }
        public void InvalidURLWithTopLevelDomain()
        {
            string          URL         = "ADomainHere.com";
            HttpRequestInfo requestInfo = new HttpRequestInfo(URL, RequestType.Get, null);

            Assert.IsNull(requestInfo.GetURI());
        }
        public void NoUrlSupplied()
        {
            HttpContentToSend content     = new HttpContentToSend();
            HttpRequestInfo   requestInfo = new HttpRequestInfo(string.Empty, RequestType.Get, content);

            HttpRunner.SendHttpRequest(requestInfo);
        }
Example #27
0
        /// <summary>
        /// Executes a command
        /// </summary>
        /// <param name="commandToExecute">The command you wish to execute</param>
        /// <returns>A response from the browser</returns>
        public virtual Response Execute(Command commandToExecute)
        {
            if (commandToExecute == null)
            {
                throw new ArgumentNullException("commandToExecute", "commandToExecute cannot be null");
            }

            CommandInfo info = this.commandInfoRepository.GetCommandInfo(commandToExecute.Name);

            if (info == null)
            {
                throw new NotImplementedException(string.Format("The command you are attempting to execute, {0}, does not exist in the protocol dialect used by the remote end.", commandToExecute.Name));
            }

            HttpRequestInfo  requestInfo  = new HttpRequestInfo(this.remoteServerUri, commandToExecute, info);
            HttpResponseInfo responseInfo = this.MakeHttpRequest(requestInfo);

            Response toReturn = this.CreateResponse(responseInfo);

            if (commandToExecute.Name == DriverCommand.NewSession && toReturn.IsSpecificationCompliant)
            {
                // If we are creating a new session, sniff the response to determine
                // what protocol level we are using. If the response contains a
                // field called "status", it's not a spec-compliant response.
                // Each response is polled for this, and sets a property describing
                // whether it's using the W3C protocol dialect.
                // TODO(jimevans): Reverse this test to make it the default path when
                // most remote ends speak W3C, then remove it entirely when legacy
                // protocol is phased out.
                this.commandInfoRepository = new W3CWireProtocolCommandInfoRepository();
            }

            return(toReturn);
        }
Example #28
0
        internal static UriBuilder GetResolvedRealm(Page page, string realm, HttpRequestInfo requestContext)
        {
            Contract.Requires <ArgumentNullException>(page != null);
            Contract.Requires <ArgumentNullException>(requestContext != null);

            // Allow for *. realm notation, as well as ASP.NET ~/ shortcuts.

            // We have to temporarily remove the *. notation if it's there so that
            // the rest of our URL manipulation will succeed.
            bool foundWildcard = false;

            // Note: we don't just use string.Replace because poorly written URLs
            // could potentially have multiple :// sequences in them.
            MatchEvaluator matchDelegate = delegate(Match m) {
                foundWildcard = true;
                return(m.Groups[1].Value);
            };
            string realmNoWildcard = Regex.Replace(realm, @"^(\w+://)\*\.", matchDelegate);

            UriBuilder fullyQualifiedRealm = new UriBuilder(
                new Uri(requestContext.UrlBeforeRewriting, page.ResolveUrl(realmNoWildcard)));

            if (foundWildcard)
            {
                fullyQualifiedRealm.Host = "*." + fullyQualifiedRealm.Host;
            }

            // Is it valid?
            new Realm(fullyQualifiedRealm);             // throws if not valid

            return(fullyQualifiedRealm);
        }
        public void Test_HttpClient_RequestBody_POST_Binary()
        {
            ByteArrayBuilder builder = new ByteArrayBuilder();

            byte [] requestHead = Encoding.UTF8.GetBytes("POST / HTTP/1.1\r\nContent-Type: application/octet-stream\r\nContent-Length:4\r\n\r\n");
            builder.AddChunkReference(requestHead, requestHead.Length);
            builder.AddChunkReference(new byte[4] {
                0, 1, 0, 1
            }, 4);
            HttpRequestInfo reqInfo = new HttpRequestInfo(builder.ToArray());

            HttpRequestInfo  receivedRequestInfo;
            HttpResponseInfo receivedResponseInfo;

            SendTestRequestToMockProxy(reqInfo, new HttpResponseInfo("HTTP/1.1 200 OK\r\n\r\n"), out receivedRequestInfo, out receivedResponseInfo);


            byte [] respBody = receivedRequestInfo.ContentData.ToArray();

            Assert.AreEqual(4, respBody.Length);
            Assert.AreEqual(0, respBody[0]);
            Assert.AreEqual(1, respBody[1]);
            Assert.AreEqual(0, respBody[2]);
            Assert.AreEqual(1, respBody[3]);
        }
        private void TrafficViewSaveRequested(RequestTrafficViewSaveArgs e)
        {
            if (_currentId > -1)
            {
                //update the request info
                //parse the data
                HttpRequestInfo reqInfo = new HttpRequestInfo(e.Request);
                _responseBytes = Constants.DefaultEncoding.GetBytes(e.Response);
                HttpResponseInfo respInfo = new HttpResponseInfo();
                respInfo.ProcessResponse(_responseBytes);

                TVRequestInfo currentTVInfo = _dataSource.GetRequestInfo(_currentId);

                //do not set the dom uniqueness id, needs to be explicitly calculated
                currentTVInfo.DomUniquenessId = String.Empty;
                currentTVInfo.RequestLine     = reqInfo.RequestLine;
                currentTVInfo.RequestTime     = DateTime.Now;
                currentTVInfo.ResponseStatus  = respInfo.Status.ToString();
                currentTVInfo.ResponseTime    = DateTime.Now;
                currentTVInfo.Description     = "Traffic Viewer Request";
                currentTVInfo.ThreadId        = "[0000]";

                //convert the strings to bytes
                RequestResponseBytes reqData = new RequestResponseBytes();
                reqData.AddToRequest(Constants.DefaultEncoding.GetBytes(e.Request));
                reqData.AddToResponse(_responseBytes);

                //save the requests to the current data source
                _dataSource.SaveRequest(_currentId, reqData);
                _dataSource.SaveResponse(_currentId, reqData);

                _requestText  = e.Request;
                _responseText = e.Response;
            }
        }
Example #31
0
        private HttpRequestInfo CreateCheckIdRequest(bool sharedAssociation)
        {
            var            rp             = CreateRelyingParty(true);
            CheckIdRequest checkidMessage = new CheckIdRequest(
                Protocol.Default.Version,
                OPUri,
                DotNetOpenAuth.OpenId.RelyingParty.AuthenticationRequestMode.Setup);

            if (sharedAssociation)
            {
                checkidMessage.AssociationHandle = SharedAssociationHandle;
            }
            checkidMessage.ClaimedIdentifier = OPLocalIdentifiers[0];
            checkidMessage.LocalIdentifier   = OPLocalIdentifiers[0];
            checkidMessage.Realm             = RPRealmUri;
            checkidMessage.ReturnTo          = RPUri;
            Channel    rpChannel = rp.Channel;
            UriBuilder receiver  = new UriBuilder(OPUri);

            receiver.Query = MessagingUtilities.CreateQueryString(rpChannel.MessageDescriptions.GetAccessor(checkidMessage));
            var headers     = new WebHeaderCollection();
            var httpRequest = new HttpRequestInfo("GET", receiver.Uri, receiver.Uri.PathAndQuery, headers, null);

            return(httpRequest);
        }
		public virtual OutgoingWebResponse VerifyAccess(HttpRequestInfo httpRequestInfo, out IPrincipal principal) {
			string username;
			HashSet<string> scope;
			var result = this.VerifyAccess(httpRequestInfo, out username, out scope);
			principal = result == null ? new OAuthPrincipal(username, scope != null ? scope.ToArray() : new string[0]) : null;
			return result;
		}