use of jakarta.servlet.http.Cookie in project tomcat by apache.
the class Request method doGetSession.
// ------------------------------------------------------ Protected Methods
protected Session doGetSession(boolean create) {
// There cannot be a session if no context has been assigned yet
Context context = getContext();
if (context == null) {
return null;
}
// Return the current session if it exists and is valid
if ((session != null) && !session.isValid()) {
session = null;
}
if (session != null) {
return session;
}
// Return the requested session if it exists and is valid
Manager manager = context.getManager();
if (manager == null) {
// Sessions are not supported
return null;
}
if (requestedSessionId != null) {
try {
session = manager.findSession(requestedSessionId);
} catch (IOException e) {
if (log.isDebugEnabled()) {
log.debug(sm.getString("request.session.failed", requestedSessionId, e.getMessage()), e);
} else {
log.info(sm.getString("request.session.failed", requestedSessionId, e.getMessage()));
}
session = null;
}
if ((session != null) && !session.isValid()) {
session = null;
}
if (session != null) {
session.access();
return session;
}
}
// Create a new session if requested and the response is not committed
if (!create) {
return null;
}
boolean trackModesIncludesCookie = context.getServletContext().getEffectiveSessionTrackingModes().contains(SessionTrackingMode.COOKIE);
if (trackModesIncludesCookie && response.getResponse().isCommitted()) {
throw new IllegalStateException(sm.getString("coyoteRequest.sessionCreateCommitted"));
}
// Re-use session IDs provided by the client in very limited
// circumstances.
String sessionId = getRequestedSessionId();
if (requestedSessionSSL) {
// If the session ID has been obtained from the SSL handshake then
// use it.
} else if (("/".equals(context.getSessionCookiePath()) && isRequestedSessionIdFromCookie())) {
/* This is the common(ish) use case: using the same session ID with
* multiple web applications on the same host. Typically this is
* used by Portlet implementations. It only works if sessions are
* tracked via cookies. The cookie must have a path of "/" else it
* won't be provided for requests to all web applications.
*
* Any session ID provided by the client should be for a session
* that already exists somewhere on the host. Check if the context
* is configured for this to be confirmed.
*/
if (context.getValidateClientProvidedNewSessionId()) {
boolean found = false;
for (Container container : getHost().findChildren()) {
Manager m = ((Context) container).getManager();
if (m != null) {
try {
if (m.findSession(sessionId) != null) {
found = true;
break;
}
} catch (IOException e) {
// Ignore. Problems with this manager will be
// handled elsewhere.
}
}
}
if (!found) {
sessionId = null;
}
}
} else {
sessionId = null;
}
session = manager.createSession(sessionId);
// Creating a new session cookie based on that session
if (session != null && trackModesIncludesCookie) {
Cookie cookie = ApplicationSessionCookieConfig.createSessionCookie(context, session.getIdInternal(), isSecure());
response.addSessionCookieInternal(cookie);
}
if (session == null) {
return null;
}
session.access();
return session;
}
use of jakarta.servlet.http.Cookie in project tomcat by apache.
the class RequestDumperFilter method doFilter.
/**
* Log the interesting request parameters, invoke the next Filter in the
* sequence, and log the interesting response parameters.
*
* @param request The servlet request to be processed
* @param response The servlet response to be created
* @param chain The filter chain being processed
*
* @exception IOException if an input/output error occurs
* @exception ServletException if a servlet error occurs
*/
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
HttpServletRequest hRequest = null;
HttpServletResponse hResponse = null;
if (request instanceof HttpServletRequest) {
hRequest = (HttpServletRequest) request;
}
if (response instanceof HttpServletResponse) {
hResponse = (HttpServletResponse) response;
}
// Log pre-service information
doLog("START TIME ", getTimestamp());
if (hRequest == null) {
doLog(" requestURI", NON_HTTP_REQ_MSG);
doLog(" authType", NON_HTTP_REQ_MSG);
} else {
doLog(" requestURI", hRequest.getRequestURI());
doLog(" authType", hRequest.getAuthType());
}
doLog(" characterEncoding", request.getCharacterEncoding());
doLog(" contentLength", Long.toString(request.getContentLengthLong()));
doLog(" contentType", request.getContentType());
if (hRequest == null) {
doLog(" contextPath", NON_HTTP_REQ_MSG);
doLog(" cookie", NON_HTTP_REQ_MSG);
doLog(" header", NON_HTTP_REQ_MSG);
} else {
doLog(" contextPath", hRequest.getContextPath());
Cookie[] cookies = hRequest.getCookies();
if (cookies != null) {
for (Cookie cookie : cookies) {
doLog(" cookie", cookie.getName() + "=" + cookie.getValue());
}
}
Enumeration<String> hnames = hRequest.getHeaderNames();
while (hnames.hasMoreElements()) {
String hname = hnames.nextElement();
Enumeration<String> hvalues = hRequest.getHeaders(hname);
while (hvalues.hasMoreElements()) {
String hvalue = hvalues.nextElement();
doLog(" header", hname + "=" + hvalue);
}
}
}
doLog(" locale", request.getLocale().toString());
if (hRequest == null) {
doLog(" method", NON_HTTP_REQ_MSG);
} else {
doLog(" method", hRequest.getMethod());
}
Enumeration<String> pnames = request.getParameterNames();
while (pnames.hasMoreElements()) {
String pname = pnames.nextElement();
String[] pvalues = request.getParameterValues(pname);
StringBuilder result = new StringBuilder(pname);
result.append('=');
for (int i = 0; i < pvalues.length; i++) {
if (i > 0) {
result.append(", ");
}
result.append(pvalues[i]);
}
doLog(" parameter", result.toString());
}
if (hRequest == null) {
doLog(" pathInfo", NON_HTTP_REQ_MSG);
} else {
doLog(" pathInfo", hRequest.getPathInfo());
}
doLog(" protocol", request.getProtocol());
if (hRequest == null) {
doLog(" queryString", NON_HTTP_REQ_MSG);
} else {
doLog(" queryString", hRequest.getQueryString());
}
doLog(" remoteAddr", request.getRemoteAddr());
doLog(" remoteHost", request.getRemoteHost());
if (hRequest == null) {
doLog(" remoteUser", NON_HTTP_REQ_MSG);
doLog("requestedSessionId", NON_HTTP_REQ_MSG);
} else {
doLog(" remoteUser", hRequest.getRemoteUser());
doLog("requestedSessionId", hRequest.getRequestedSessionId());
}
doLog(" scheme", request.getScheme());
doLog(" serverName", request.getServerName());
doLog(" serverPort", Integer.toString(request.getServerPort()));
if (hRequest == null) {
doLog(" servletPath", NON_HTTP_REQ_MSG);
} else {
doLog(" servletPath", hRequest.getServletPath());
}
doLog(" isSecure", Boolean.valueOf(request.isSecure()).toString());
doLog("------------------", "--------------------------------------------");
// Perform the request
chain.doFilter(request, response);
// Log post-service information
doLog("------------------", "--------------------------------------------");
if (hRequest == null) {
doLog(" authType", NON_HTTP_REQ_MSG);
} else {
doLog(" authType", hRequest.getAuthType());
}
doLog(" contentType", response.getContentType());
if (hResponse == null) {
doLog(" header", NON_HTTP_RES_MSG);
} else {
Iterable<String> rhnames = hResponse.getHeaderNames();
for (String rhname : rhnames) {
Iterable<String> rhvalues = hResponse.getHeaders(rhname);
for (String rhvalue : rhvalues) {
doLog(" header", rhname + "=" + rhvalue);
}
}
}
if (hRequest == null) {
doLog(" remoteUser", NON_HTTP_REQ_MSG);
} else {
doLog(" remoteUser", hRequest.getRemoteUser());
}
if (hResponse == null) {
doLog(" status", NON_HTTP_RES_MSG);
} else {
doLog(" status", Integer.toString(hResponse.getStatus()));
}
doLog("END TIME ", getTimestamp());
doLog("==================", "============================================");
}
use of jakarta.servlet.http.Cookie in project tomcat by apache.
the class RewriteValve method invoke.
@Override
public void invoke(Request request, Response response) throws IOException, ServletException {
if (!getEnabled() || rules == null || rules.length == 0) {
getNext().invoke(request, response);
return;
}
if (Boolean.TRUE.equals(invoked.get())) {
try {
getNext().invoke(request, response);
} finally {
invoked.set(null);
}
return;
}
try {
Resolver resolver = new ResolverImpl(request);
invoked.set(Boolean.TRUE);
// As long as MB isn't a char sequence or affiliated, this has to be
// converted to a string
Charset uriCharset = request.getConnector().getURICharset();
String originalQueryStringEncoded = request.getQueryString();
MessageBytes urlMB = context ? request.getRequestPathMB() : request.getDecodedRequestURIMB();
urlMB.toChars();
CharSequence urlDecoded = urlMB.getCharChunk();
CharSequence host = request.getServerName();
boolean rewritten = false;
boolean done = false;
boolean qsa = false;
boolean qsd = false;
for (int i = 0; i < rules.length; i++) {
RewriteRule rule = rules[i];
CharSequence test = (rule.isHost()) ? host : urlDecoded;
CharSequence newtest = rule.evaluate(test, resolver);
if (newtest != null && !test.equals(newtest.toString())) {
if (containerLog.isDebugEnabled()) {
containerLog.debug("Rewrote " + test + " as " + newtest + " with rule pattern " + rule.getPatternString());
}
if (rule.isHost()) {
host = newtest;
} else {
urlDecoded = newtest;
}
rewritten = true;
}
// Check QSA before the final reply
if (!qsa && newtest != null && rule.isQsappend()) {
qsa = true;
}
if (!qsa && newtest != null && rule.isQsdiscard()) {
qsd = true;
}
// - forbidden
if (rule.isForbidden() && newtest != null) {
response.sendError(HttpServletResponse.SC_FORBIDDEN);
done = true;
break;
}
// - gone
if (rule.isGone() && newtest != null) {
response.sendError(HttpServletResponse.SC_GONE);
done = true;
break;
}
// - redirect (code)
if (rule.isRedirect() && newtest != null) {
// Append the query string to the url if there is one and it
// hasn't been rewritten
String urlStringDecoded = urlDecoded.toString();
int index = urlStringDecoded.indexOf('?');
String rewrittenQueryStringDecoded;
if (index == -1) {
rewrittenQueryStringDecoded = null;
} else {
rewrittenQueryStringDecoded = urlStringDecoded.substring(index + 1);
urlStringDecoded = urlStringDecoded.substring(0, index);
}
StringBuilder urlStringEncoded = new StringBuilder(URLEncoder.DEFAULT.encode(urlStringDecoded, uriCharset));
if (!qsd && originalQueryStringEncoded != null && originalQueryStringEncoded.length() > 0) {
if (rewrittenQueryStringDecoded == null) {
urlStringEncoded.append('?');
urlStringEncoded.append(originalQueryStringEncoded);
} else {
if (qsa) {
// if qsa is specified append the query
urlStringEncoded.append('?');
urlStringEncoded.append(URLEncoder.QUERY.encode(rewrittenQueryStringDecoded, uriCharset));
urlStringEncoded.append('&');
urlStringEncoded.append(originalQueryStringEncoded);
} else if (index == urlStringEncoded.length() - 1) {
// if the ? is the last character delete it, its only purpose was to
// prevent the rewrite module from appending the query string
urlStringEncoded.deleteCharAt(index);
} else {
urlStringEncoded.append('?');
urlStringEncoded.append(URLEncoder.QUERY.encode(rewrittenQueryStringDecoded, uriCharset));
}
}
} else if (rewrittenQueryStringDecoded != null) {
urlStringEncoded.append('?');
urlStringEncoded.append(URLEncoder.QUERY.encode(rewrittenQueryStringDecoded, uriCharset));
}
// 3. the url isn't absolute
if (context && urlStringEncoded.charAt(0) == '/' && !UriUtil.hasScheme(urlStringEncoded)) {
urlStringEncoded.insert(0, request.getContext().getEncodedPath());
}
if (rule.isNoescape()) {
response.sendRedirect(UDecoder.URLDecode(urlStringEncoded.toString(), uriCharset));
} else {
response.sendRedirect(urlStringEncoded.toString());
}
response.setStatus(rule.getRedirectCode());
done = true;
break;
}
// - cookie
if (rule.isCookie() && newtest != null) {
Cookie cookie = new Cookie(rule.getCookieName(), rule.getCookieResult());
cookie.setDomain(rule.getCookieDomain());
cookie.setMaxAge(rule.getCookieLifetime());
cookie.setPath(rule.getCookiePath());
cookie.setSecure(rule.isCookieSecure());
cookie.setHttpOnly(rule.isCookieHttpOnly());
response.addCookie(cookie);
}
// - env (note: this sets a request attribute)
if (rule.isEnv() && newtest != null) {
for (int j = 0; j < rule.getEnvSize(); j++) {
request.setAttribute(rule.getEnvName(j), rule.getEnvResult(j));
}
}
// to do that)
if (rule.isType() && newtest != null) {
request.setContentType(rule.getTypeValue());
}
// - chain (skip remaining chained rules if this one does not match)
if (rule.isChain() && newtest == null) {
for (int j = i; j < rules.length; j++) {
if (!rules[j].isChain()) {
i = j;
break;
}
}
continue;
}
// - last (stop rewriting here)
if (rule.isLast() && newtest != null) {
break;
}
// - next (redo again)
if (rule.isNext() && newtest != null) {
i = 0;
continue;
}
// - skip (n rules)
if (newtest != null) {
i += rule.getSkip();
}
}
if (rewritten) {
if (!done) {
// See if we need to replace the query string
String urlStringDecoded = urlDecoded.toString();
String queryStringDecoded = null;
int queryIndex = urlStringDecoded.indexOf('?');
if (queryIndex != -1) {
queryStringDecoded = urlStringDecoded.substring(queryIndex + 1);
urlStringDecoded = urlStringDecoded.substring(0, queryIndex);
}
// Save the current context path before re-writing starts
String contextPath = null;
if (context) {
contextPath = request.getContextPath();
}
// Populated the encoded (i.e. undecoded) requestURI
request.getCoyoteRequest().requestURI().setString(null);
CharChunk chunk = request.getCoyoteRequest().requestURI().getCharChunk();
chunk.recycle();
if (context) {
// This is neither decoded nor normalized
chunk.append(contextPath);
}
chunk.append(URLEncoder.DEFAULT.encode(urlStringDecoded, uriCharset));
request.getCoyoteRequest().requestURI().toChars();
// Decoded and normalized URI
// Rewriting may have denormalized the URL
urlStringDecoded = RequestUtil.normalize(urlStringDecoded);
request.getCoyoteRequest().decodedURI().setString(null);
chunk = request.getCoyoteRequest().decodedURI().getCharChunk();
chunk.recycle();
if (context) {
// This is decoded and normalized
chunk.append(request.getServletContext().getContextPath());
}
chunk.append(urlStringDecoded);
request.getCoyoteRequest().decodedURI().toChars();
// Set the new Query if there is one
if (queryStringDecoded != null) {
request.getCoyoteRequest().queryString().setString(null);
chunk = request.getCoyoteRequest().queryString().getCharChunk();
chunk.recycle();
chunk.append(URLEncoder.QUERY.encode(queryStringDecoded, uriCharset));
if (qsa && originalQueryStringEncoded != null && originalQueryStringEncoded.length() > 0) {
chunk.append('&');
chunk.append(originalQueryStringEncoded);
}
if (!chunk.isNull()) {
request.getCoyoteRequest().queryString().toChars();
}
}
// Set the new host if it changed
if (!host.equals(request.getServerName())) {
request.getCoyoteRequest().serverName().setString(null);
chunk = request.getCoyoteRequest().serverName().getCharChunk();
chunk.recycle();
chunk.append(host.toString());
request.getCoyoteRequest().serverName().toChars();
}
request.getMappingData().recycle();
// Reinvoke the whole request recursively
Connector connector = request.getConnector();
try {
if (!connector.getProtocolHandler().getAdapter().prepare(request.getCoyoteRequest(), response.getCoyoteResponse())) {
return;
}
} catch (Exception e) {
// This doesn't actually happen in the Catalina adapter implementation
}
Pipeline pipeline = connector.getService().getContainer().getPipeline();
request.setAsyncSupported(pipeline.isAsyncSupported());
pipeline.getFirst().invoke(request, response);
}
} else {
getNext().invoke(request, response);
}
} finally {
invoked.set(null);
}
}
use of jakarta.servlet.http.Cookie in project tomcat by apache.
the class TestLoadBalancerDrainingValve method runValve.
@Test
public void runValve() throws Exception {
IMocksControl control = EasyMock.createControl();
ServletContext servletContext = control.createMock(ServletContext.class);
Context ctx = control.createMock(Context.class);
Request request = control.createMock(Request.class);
Response response = control.createMock(Response.class);
String sessionCookieName = "JSESSIONID";
String sessionId = "cafebabe";
String requestURI = "/test/path";
SessionCookieConfig cookieConfig = new CookieConfig();
cookieConfig.setDomain("example.com");
cookieConfig.setName(sessionCookieName);
cookieConfig.setPath("/");
cookieConfig.setSecure(secureSessionConfig);
// Valve.init requires all of this stuff
EasyMock.expect(ctx.getMBeanKeyProperties()).andStubReturn("");
EasyMock.expect(ctx.getName()).andStubReturn("");
EasyMock.expect(ctx.getPipeline()).andStubReturn(new StandardPipeline());
EasyMock.expect(ctx.getDomain()).andStubReturn("foo");
EasyMock.expect(ctx.getLogger()).andStubReturn(org.apache.juli.logging.LogFactory.getLog(LoadBalancerDrainingValve.class));
EasyMock.expect(ctx.getServletContext()).andStubReturn(servletContext);
// Set up the actual test
EasyMock.expect(request.getAttribute(LoadBalancerDrainingValve.ATTRIBUTE_KEY_JK_LB_ACTIVATION)).andStubReturn(jkActivation);
EasyMock.expect(Boolean.valueOf(request.isRequestedSessionIdValid())).andStubReturn(Boolean.valueOf(validSessionId));
ArrayList<Cookie> cookies = new ArrayList<>();
if (enableIgnore) {
cookies.add(new Cookie("ignore", "true"));
}
if (!validSessionId && jkActivation.equals("DIS")) {
MyCookie cookie = new MyCookie(cookieConfig.getName(), sessionId);
cookie.setPath(cookieConfig.getPath());
cookie.setValue(sessionId);
cookies.add(cookie);
EasyMock.expect(request.getRequestedSessionId()).andStubReturn(sessionId);
EasyMock.expect(request.getRequestURI()).andStubReturn(requestURI);
EasyMock.expect(request.getCookies()).andStubReturn(cookies.toArray(new Cookie[0]));
EasyMock.expect(request.getContext()).andStubReturn(ctx);
EasyMock.expect(ctx.getSessionCookieName()).andStubReturn(sessionCookieName);
EasyMock.expect(servletContext.getSessionCookieConfig()).andStubReturn(cookieConfig);
EasyMock.expect(request.getQueryString()).andStubReturn(queryString);
EasyMock.expect(ctx.getSessionCookiePath()).andStubReturn("/");
if (!enableIgnore) {
EasyMock.expect(Boolean.valueOf(ctx.getSessionCookiePathUsesTrailingSlash())).andStubReturn(Boolean.TRUE);
EasyMock.expect(request.getQueryString()).andStubReturn(queryString);
// Response will have cookie deleted
MyCookie expectedCookie = new MyCookie(cookieConfig.getName(), "");
expectedCookie.setPath(cookieConfig.getPath());
expectedCookie.setMaxAge(0);
EasyMock.expect(Boolean.valueOf(request.isSecure())).andReturn(secureRequest);
// These two lines just mean EasyMock.expect(response.addCookie) but for a void method
response.addCookie(expectedCookie);
// Indirect call
EasyMock.expect(ctx.getSessionCookieName()).andReturn(sessionCookieName);
String expectedRequestURI = requestURI;
if (null != queryString) {
expectedRequestURI = expectedRequestURI + '?' + queryString;
}
response.setHeader("Location", expectedRequestURI);
response.setStatus(307);
}
}
Valve next = control.createMock(Valve.class);
if (expectInvokeNext) {
// Expect the "next" Valve to fire
// Next 2 lines are basically EasyMock.expect(next.invoke(req,res)) but for a void method
next.invoke(request, response);
EasyMock.expectLastCall();
}
// Get set to actually test
control.replay();
LoadBalancerDrainingValve valve = new LoadBalancerDrainingValve();
valve.setContainer(ctx);
valve.init();
valve.setNext(next);
valve.setIgnoreCookieName("ignore");
valve.setIgnoreCookieValue("true");
valve.invoke(request, response);
control.verify();
}
use of jakarta.servlet.http.Cookie in project tomcat by apache.
the class TestCookieProcessorGeneration method doTestDomain.
private void doTestDomain(String domain, String expectedRfc6265) {
Cookie cookie = new Cookie("foo", "bar");
cookie.setDomain(domain);
doTest(cookie, new Rfc6265CookieProcessor(), expectedRfc6265);
}
Aggregations