/// <summary>Test AmIpFilter</summary> /// <exception cref="System.Exception"/> public virtual void TestFilter() { IDictionary <string, string> @params = new Dictionary <string, string>(); @params[AmIpFilter.ProxyHost] = proxyHost; @params[AmIpFilter.ProxyUriBase] = proxyUri; FilterConfig config = new TestAmFilter.DummyFilterConfig(@params); // dummy filter FilterChain chain = new _FilterChain_135(this); AmIpFilter testFilter = new AmIpFilter(); testFilter.Init(config); TestAmFilter.HttpServletResponseForTest response = new TestAmFilter.HttpServletResponseForTest (this); // Test request should implements HttpServletRequest ServletRequest failRequest = Org.Mockito.Mockito.Mock <ServletRequest>(); try { testFilter.DoFilter(failRequest, response, chain); NUnit.Framework.Assert.Fail(); } catch (ServletException e) { NUnit.Framework.Assert.AreEqual(ProxyUtils.EHttpHttpsOnly, e.Message); } // request with HttpServletRequest HttpServletRequest request = Org.Mockito.Mockito.Mock <HttpServletRequest>(); Org.Mockito.Mockito.When(request.GetRemoteAddr()).ThenReturn("redirect"); Org.Mockito.Mockito.When(request.GetRequestURI()).ThenReturn("/redirect"); testFilter.DoFilter(request, response, chain); // address "redirect" is not in host list NUnit.Framework.Assert.AreEqual(302, response.status); string redirect = response.GetHeader(ProxyUtils.Location); NUnit.Framework.Assert.AreEqual("http://bogus/redirect", redirect); // "127.0.0.1" contains in host list. Without cookie Org.Mockito.Mockito.When(request.GetRemoteAddr()).ThenReturn("127.0.0.1"); testFilter.DoFilter(request, response, chain); NUnit.Framework.Assert.IsTrue(doFilterRequest.Contains("javax.servlet.http.HttpServletRequest" )); // cookie added Cookie[] cookies = new Cookie[1]; cookies[0] = new Cookie(WebAppProxyServlet.ProxyUserCookieName, "user"); Org.Mockito.Mockito.When(request.GetCookies()).ThenReturn(cookies); testFilter.DoFilter(request, response, chain); NUnit.Framework.Assert.AreEqual("org.apache.hadoop.yarn.server.webproxy.amfilter.AmIpServletRequestWrapper" , doFilterRequest); // request contains principal from cookie NUnit.Framework.Assert.AreEqual("user", servletWrapper.GetUserPrincipal().GetName ()); NUnit.Framework.Assert.AreEqual("user", servletWrapper.GetRemoteUser()); NUnit.Framework.Assert.IsFalse(servletWrapper.IsUserInRole(string.Empty)); }
//Empty /// <exception cref="System.IO.IOException"/> /// <exception cref="Javax.Servlet.ServletException"/> public virtual void DoFilter(ServletRequest req, ServletResponse resp, FilterChain chain) { ProxyUtils.RejectNonHttpRequests(req); HttpServletRequest httpReq = (HttpServletRequest)req; HttpServletResponse httpResp = (HttpServletResponse)resp; if (Log.IsDebugEnabled()) { Log.Debug("Remote address for request is: {}", httpReq.GetRemoteAddr()); } if (!GetProxyAddresses().Contains(httpReq.GetRemoteAddr())) { string redirectUrl = FindRedirectUrl(); string target = redirectUrl + httpReq.GetRequestURI(); ProxyUtils.SendRedirect(httpReq, httpResp, target); return; } string user = null; if (httpReq.GetCookies() != null) { foreach (Cookie c in httpReq.GetCookies()) { if (WebAppProxyServlet.ProxyUserCookieName.Equals(c.GetName())) { user = c.GetValue(); break; } } } if (user == null) { if (Log.IsDebugEnabled()) { Log.Debug("Could not find " + WebAppProxyServlet.ProxyUserCookieName + " cookie, so user will not be set" ); } chain.DoFilter(req, resp); } else { AmIpPrincipal principal = new AmIpPrincipal(user); ServletRequest requestWrapper = new AmIpServletRequestWrapper(httpReq, principal); chain.DoFilter(requestWrapper, resp); } }
/// <exception cref="Javax.Servlet.ServletException"/> /// <exception cref="System.IO.IOException"/> protected override void DoGet(HttpServletRequest request, HttpServletResponse response ) { InputStreamReader @in = new InputStreamReader(request.GetInputStream()); TextWriter @out = new TextWriter(response.GetOutputStream()); calledTimes++; try { requestUri = new URI(null, null, request.GetRequestURI(), request.GetQueryString( ), null); } catch (URISyntaxException) { } @in.Close(); @out.Close(); }
/// <summary> /// Handle redirects with a status code that can in future support verbs other /// than GET, thus supporting full REST functionality. /// </summary> /// <remarks> /// Handle redirects with a status code that can in future support verbs other /// than GET, thus supporting full REST functionality. /// <p> /// The target URL is included in the redirect text returned /// <p> /// At the end of this method, the output stream is closed. /// </remarks> /// <param name="request"> /// request (hence: the verb and any other information /// relevant to a redirect) /// </param> /// <param name="response">the response</param> /// <param name="target">the target URL -unencoded</param> /// <exception cref="System.IO.IOException"/> public static void SendRedirect(HttpServletRequest request, HttpServletResponse response , string target) { if (Log.IsDebugEnabled()) { Log.Debug("Redirecting {} {} to {}", request.GetMethod(), request.GetRequestURI() , target); } string location = response.EncodeRedirectURL(target); response.SetStatus(HttpServletResponse.ScFound); response.SetHeader(Location, location); response.SetContentType(MimeType.Html); PrintWriter writer = response.GetWriter(); ProxyUtils.Page p = new ProxyUtils.Page(writer); p.Html().Head().Title("Moved").().Body().H1("Moved").Div().("Content has moved ") .A(location, "here").().().(); writer.Close(); }
/// <exception cref="Javax.Servlet.ServletException"/> /// <exception cref="System.IO.IOException"/> protected override void Service(HttpServletRequest req, HttpServletResponse res) { res.SetCharacterEncoding("UTF-8"); string uri = HtmlQuoting.QuoteHtmlChars(req.GetRequestURI()); if (uri == null) { uri = "/"; } if (devMode && uri.Equals("/__stop")) { // quick hack to restart servers in dev mode without OS commands res.SetStatus(res.ScNoContent); Log.Info("dev mode restart requested"); PrepareToExit(); return; } // if they provide a redirectPath go there instead of going to // "/" so that filters can differentiate the webapps. if (uri.Equals("/")) { string redirectPath = webApp.GetRedirectPath(); if (redirectPath != null && !redirectPath.IsEmpty()) { res.SendRedirect(redirectPath); return; } } string method = req.GetMethod(); if (method.Equals("OPTIONS")) { DoOptions(req, res); return; } if (method.Equals("TRACE")) { DoTrace(req, res); return; } if (method.Equals("HEAD")) { DoGet(req, res); // default to bad request return; } string pathInfo = req.GetPathInfo(); if (pathInfo == null) { pathInfo = "/"; } Controller.RequestContext rc = injector.GetInstance <Controller.RequestContext>(); if (SetCookieParams(rc, req) > 0) { Cookie ec = rc.Cookies()[ErrorCookie]; if (ec != null) { rc.SetStatus(System.Convert.ToInt32(rc.Cookies()[StatusCookie].GetValue())); RemoveErrorCookies(res, uri); rc.Set(Params.ErrorDetails, ec.GetValue()); Render(typeof(ErrorPage)); return; } } rc.prefix = webApp.Name(); Router.Dest dest = null; try { dest = router.Resolve(method, pathInfo); } catch (WebAppException e) { rc.error = e; if (!e.Message.Contains("not found")) { rc.SetStatus(res.ScInternalServerError); Render(typeof(ErrorPage)); return; } } if (dest == null) { rc.SetStatus(res.ScNotFound); Render(typeof(ErrorPage)); return; } rc.devMode = devMode; SetMoreParams(rc, pathInfo, dest); Controller controller = injector.GetInstance(dest.controllerClass); try { // TODO: support args converted from /path/:arg1/... dest.action.Invoke(controller, (object[])null); if (!rc.rendered) { if (dest.defaultViewClass != null) { Render(dest.defaultViewClass); } else { if (rc.status == 200) { throw new InvalidOperationException("No view rendered for 200"); } } } } catch (Exception e) { Log.Error("error handling URI: " + uri, e); // Page could be half rendered (but still not flushed). So redirect. RedirectToErrorPage(res, e, uri, devMode); } }
/// <summary>Shuffle specific utils - build string for encoding from URL</summary> /// <param name="request"/> /// <returns>string for encoding</returns> public static string BuildMsgFrom(HttpServletRequest request) { return(BuildMsgFrom(request.GetRequestURI(), request.GetQueryString(), request.GetLocalPort ())); }
/// <exception cref="System.IO.IOException"/> /// <exception cref="Javax.Servlet.ServletException"/> public override void DoFilter(HttpServletRequest request, HttpServletResponse response , FilterChain chain) { response.SetCharacterEncoding("UTF-8"); string uri = HtmlQuoting.QuoteHtmlChars(request.GetRequestURI()); if (uri == null) { uri = "/"; } RMWebApp rmWebApp = injector.GetInstance <RMWebApp>(); rmWebApp.CheckIfStandbyRM(); if (rmWebApp.IsStandby() && ShouldRedirect(rmWebApp, uri)) { string redirectPath = rmWebApp.GetRedirectPath(); if (redirectPath != null && !redirectPath.IsEmpty()) { redirectPath += uri; string redirectMsg = "This is standby RM. The redirect url is: " + redirectPath; PrintWriter @out = response.GetWriter(); @out.WriteLine(redirectMsg); response.SetHeader("Location", redirectPath); response.SetStatus(HttpServletResponse.ScTemporaryRedirect); return; } else { bool doRetry = true; string retryIntervalStr = request.GetParameter(YarnWebParams.NextRefreshInterval); int retryInterval = 0; if (retryIntervalStr != null) { try { retryInterval = System.Convert.ToInt32(retryIntervalStr.Trim()); } catch (FormatException) { doRetry = false; } } int next = CalculateExponentialTime(retryInterval); string redirectUrl = AppendOrReplaceParamter(path + uri, YarnWebParams.NextRefreshInterval + "=" + (retryInterval + 1)); if (redirectUrl == null || next > MaxSleepTime) { doRetry = false; } string redirectMsg = doRetry ? "Can not find any active RM. Will retry in next " + next + " seconds." : "There is no active RM right now."; redirectMsg += "\nHA Zookeeper Connection State: " + rmWebApp.GetHAZookeeperConnectionState (); PrintWriter @out = response.GetWriter(); @out.WriteLine(redirectMsg); if (doRetry) { response.SetHeader("Refresh", next + ";url=" + redirectUrl); response.SetStatus(HttpServletResponse.ScTemporaryRedirect); } } return; } base.DoFilter(request, response, chain); }
// should never happen! /// <summary>Parse the path component from the given request and return w/o decoding. /// </summary> /// <param name="request">Http request to parse</param> /// <param name="servletName">the name of servlet that precedes the path</param> /// <returns>path component, null if the default charset is not supported</returns> public static string GetRawPath(HttpServletRequest request, string servletName) { Preconditions.CheckArgument(request.GetRequestURI().StartsWith(servletName + "/") ); return(Runtime.Substring(request.GetRequestURI(), servletName.Length)); }