001: /*
002: * Copyright 1999-2004 The Apache Software Foundation
003: *
004: * Licensed under the Apache License, Version 2.0 (the "License");
005: * you may not use this file except in compliance with the License.
006: * You may obtain a copy of the License at
007: *
008: * http://www.apache.org/licenses/LICENSE-2.0
009: *
010: * Unless required by applicable law or agreed to in writing, software
011: * distributed under the License is distributed on an "AS IS" BASIS,
012: * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013: * See the License for the specific language governing permissions and
014: * limitations under the License.
015: */
016:
017: package org.apache.coyote.tomcat4;
018:
019: import java.io.IOException;
020: import javax.servlet.http.Cookie;
021: import javax.servlet.http.HttpServletRequest;
022:
023: import org.apache.tomcat.util.buf.B2CConverter;
024: import org.apache.tomcat.util.buf.ByteChunk;
025: import org.apache.tomcat.util.buf.CharChunk;
026: import org.apache.tomcat.util.buf.MessageBytes;
027: import org.apache.tomcat.util.http.Cookies;
028: import org.apache.tomcat.util.http.ServerCookie;
029:
030: import org.apache.coyote.ActionCode;
031: import org.apache.coyote.Adapter;
032: import org.apache.coyote.Request;
033: import org.apache.coyote.Response;
034:
035: import org.apache.catalina.Globals;
036: import org.apache.catalina.Logger;
037: import org.apache.catalina.util.StringManager;
038:
039: /**
040: * Implementation of a request processor which delegates the processing to a
041: * Coyote processor.
042: *
043: * @author Craig R. McClanahan
044: * @author Remy Maucherat
045: * @version $Revision: 1.28 $ $Date: 2004/04/04 19:09:38 $
046: */
047:
048: final class CoyoteAdapter implements Adapter {
049:
050: // -------------------------------------------------------------- Constants
051:
052: public static final int ADAPTER_NOTES = 1;
053:
054: // ----------------------------------------------------------- Constructors
055:
056: /**
057: * Construct a new CoyoteProcessor associated with the specified connector.
058: *
059: * @param connector CoyoteConnector that owns this processor
060: * @param id Identifier of this CoyoteProcessor (unique per connector)
061: */
062: public CoyoteAdapter(CoyoteConnector connector) {
063:
064: super ();
065: this .connector = connector;
066: this .debug = connector.getDebug();
067:
068: }
069:
070: // ----------------------------------------------------- Instance Variables
071:
072: /**
073: * The CoyoteConnector with which this processor is associated.
074: */
075: private CoyoteConnector connector = null;
076:
077: /**
078: * The debugging detail level for this component.
079: */
080: private int debug = 0;
081:
082: /**
083: * The match string for identifying a session ID parameter.
084: */
085: private static final String match = ";"
086: + Globals.SESSION_PARAMETER_NAME + "=";
087:
088: /**
089: * The match string for identifying a session ID parameter.
090: */
091: private static final char[] SESSION_ID = match.toCharArray();
092:
093: /**
094: * The string manager for this package.
095: */
096: protected StringManager sm = StringManager
097: .getManager(Constants.Package);
098:
099: // -------------------------------------------------------- Adapter Methods
100:
101: /**
102: * Service method.
103: */
104: public void service(Request req, Response res) throws Exception {
105:
106: CoyoteRequest request = (CoyoteRequest) req
107: .getNote(ADAPTER_NOTES);
108: CoyoteResponse response = (CoyoteResponse) res
109: .getNote(ADAPTER_NOTES);
110:
111: if (request == null) {
112:
113: // Create objects
114: request = (CoyoteRequest) connector.createRequest();
115: request.setCoyoteRequest(req);
116: response = (CoyoteResponse) connector.createResponse();
117: response.setCoyoteResponse(res);
118:
119: // Link objects
120: request.setResponse(response);
121: response.setRequest(request);
122:
123: // Set as notes
124: req.setNote(ADAPTER_NOTES, request);
125: res.setNote(ADAPTER_NOTES, response);
126:
127: // Set query string encoding
128: req.getParameters().setQueryStringEncoding(
129: connector.getURIEncoding());
130:
131: }
132:
133: try {
134: // Parse and set Catalina and configuration specific
135: // request parameters
136: postParseRequest(req, request, res, response);
137: // Calling the container
138: connector.getContainer().invoke(request, response);
139: response.finishResponse();
140:
141: req.action(ActionCode.ACTION_POST_REQUEST, null);
142: } catch (IOException e) {
143: ;
144: } catch (Throwable t) {
145: log(sm.getString("coyoteAdapter.service"), t);
146: } finally {
147: // Recycle the wrapper request and response
148: request.recycle();
149: response.recycle();
150: }
151:
152: }
153:
154: // ------------------------------------------------------ Protected Methods
155:
156: /**
157: * Parse additional request parameters.
158: */
159: protected void postParseRequest(Request req, CoyoteRequest request,
160: Response res, CoyoteResponse response) throws Exception {
161: // XXX the processor needs to set a correct scheme and port prior to this point,
162: // in ajp13 protocols dont make sense to get the port from the connector..
163: // XXX the processor may have set a correct scheme and port prior to this point,
164: // in ajp13 protocols dont make sense to get the port from the connector...
165: // otherwise, use connector configuration
166: if (!req.scheme().isNull()) {
167: // use processor specified scheme to determine secure state
168: request.setSecure(req.scheme().equals("https"));
169: } else {
170: // use connector scheme and secure configuration, (defaults to
171: // "http" and false respectively)
172: req.scheme().setString(connector.getScheme());
173: request.setSecure(connector.getSecure());
174: }
175:
176: // Filter trace method
177: if (!connector.getAllowTrace()
178: && req.method().equalsIgnoreCase("TRACE")) {
179: res.setStatus(403);
180: res.setMessage("TRACE method is not allowed");
181: throw new IOException("TRACE method is not allowed");
182: }
183:
184: request.setAuthorization(req
185: .getHeader(Constants.AUTHORIZATION_HEADER));
186: // FIXME: the code below doesnt belongs to here, this is only have sense
187: // in Http11, not in ajp13..
188: // At this point the Host header has been processed.
189: // Override if the proxyPort/proxyHost are set
190: String proxyName = connector.getProxyName();
191: int proxyPort = connector.getProxyPort();
192: if (proxyPort != 0) {
193: request.setServerPort(proxyPort);
194: req.setServerPort(proxyPort);
195: } else {
196: request.setServerPort(req.getServerPort());
197: }
198: if (proxyName != null) {
199: request.setServerName(proxyName);
200: req.serverName().setString(proxyName);
201: } else {
202: request.setServerName(req.serverName().toString());
203: }
204:
205: // URI decoding
206: req.decodedURI().duplicate(req.requestURI());
207: try {
208: req.getURLDecoder().convert(req.decodedURI(), false);
209: } catch (IOException ioe) {
210: res.setStatus(400);
211: res.setMessage("Invalid URI");
212: throw ioe;
213: }
214:
215: // Normalize decoded URI
216: if (!normalize(req.decodedURI())) {
217: res.setStatus(400);
218: res.setMessage("Invalid URI");
219: throw new IOException("Invalid URI");
220: }
221:
222: // URI character decoding
223: convertURI(req.decodedURI(), request);
224:
225: // Parse session Id
226: parseSessionId(req, request);
227:
228: // Additional URI normalization and validation is needed for security
229: // reasons on Tomcat 4.0.x
230: if (connector.getUseURIValidationHack()) {
231: String uri = validate(request.getRequestURI());
232: if (uri == null) {
233: res.setStatus(400);
234: res.setMessage("Invalid URI");
235: throw new IOException("Invalid URI");
236: } else {
237: req.requestURI().setString(uri);
238: // Redoing the URI decoding
239: req.decodedURI().duplicate(req.requestURI());
240: req.getURLDecoder().convert(req.decodedURI(), true);
241: convertURI(req.decodedURI(), request);
242: }
243: }
244:
245: // Parse cookies
246: parseCookies(req, request);
247:
248: // Set the SSL properties
249: if (request.isSecure()) {
250: res.action(ActionCode.ACTION_REQ_SSL_ATTRIBUTE, request
251: .getCoyoteRequest());
252: //Set up for getAttributeNames
253: request.getAttribute(Globals.CERTIFICATES_ATTR);
254: request.getAttribute(Globals.CIPHER_SUITE_ATTR);
255: request.getAttribute(Globals.KEY_SIZE_ATTR);
256: }
257:
258: // Set the remote principal
259: String principal = req.getRemoteUser().toString();
260: if (principal != null) {
261: request.setUserPrincipal(new CoyotePrincipal(principal));
262: }
263:
264: // Set the authorization type
265: String authtype = req.getAuthType().toString();
266: if (authtype != null) {
267: request.setAuthType(authtype);
268: }
269:
270: }
271:
272: /**
273: * Parse session id in URL.
274: * FIXME: Optimize this.
275: */
276: protected void parseSessionId(Request req, CoyoteRequest request) {
277:
278: req.decodedURI().toChars();
279: CharChunk uriCC = req.decodedURI().getCharChunk();
280: int semicolon = uriCC.indexOf(match, 0, match.length(), 0);
281:
282: if (semicolon > 0) {
283:
284: // Parse session ID, and extract it from the decoded request URI
285: int start = uriCC.getStart();
286: int end = uriCC.getEnd();
287:
288: int sessionIdStart = start + semicolon + match.length();
289: int semicolon2 = uriCC.indexOf(';', sessionIdStart);
290: if (semicolon2 >= 0) {
291: request.setRequestedSessionId(new String(uriCC
292: .getBuffer(), sessionIdStart, semicolon2
293: - semicolon - match.length()));
294: req.decodedURI().setString(
295: new String(uriCC.getBuffer(), start, semicolon)
296: + new String(uriCC.getBuffer(),
297: semicolon2, end - semicolon2));
298: } else {
299: request.setRequestedSessionId(new String(uriCC
300: .getBuffer(), sessionIdStart, end
301: - sessionIdStart));
302: req.decodedURI()
303: .setString(
304: new String(uriCC.getBuffer(), start,
305: semicolon));
306: }
307: request.setRequestedSessionURL(true);
308:
309: // Extract session ID from request URI
310: String uri = req.requestURI().toString();
311: semicolon = uri.indexOf(match);
312:
313: if (semicolon > 0) {
314: String rest = uri.substring(semicolon + match.length());
315: semicolon2 = rest.indexOf(';');
316: if (semicolon2 >= 0) {
317: rest = rest.substring(semicolon2);
318: } else {
319: rest = "";
320: }
321: req.requestURI().setString(
322: uri.substring(0, semicolon) + rest);
323: }
324:
325: } else {
326: request.setRequestedSessionId(null);
327: request.setRequestedSessionURL(false);
328: }
329:
330: }
331:
332: /**
333: * Parse cookies.
334: */
335: protected void parseCookies(Request req, CoyoteRequest request) {
336:
337: Cookies serverCookies = req.getCookies();
338: int count = serverCookies.getCookieCount();
339: if (count <= 0)
340: return;
341:
342: Cookie[] cookies = new Cookie[count];
343:
344: int idx = 0;
345: for (int i = 0; i < count; i++) {
346: ServerCookie scookie = serverCookies.getCookie(i);
347: if (scookie.getName().equals(Globals.SESSION_COOKIE_NAME)) {
348: // Override anything requested in the URL
349: if (!request.isRequestedSessionIdFromCookie()) {
350: // Accept only the first session id cookie
351: request.setRequestedSessionId(scookie.getValue()
352: .toString());
353: request.setRequestedSessionCookie(true);
354: request.setRequestedSessionURL(false);
355: if (debug >= 1)
356: log(" Requested cookie session id is "
357: + ((HttpServletRequest) request
358: .getRequest())
359: .getRequestedSessionId());
360: }
361: }
362: try {
363: Cookie cookie = new Cookie(
364: scookie.getName().toString(), scookie
365: .getValue().toString());
366: cookie.setPath(scookie.getPath().toString());
367: cookie.setVersion(scookie.getVersion());
368: String domain = scookie.getDomain().toString();
369: if (domain != null) {
370: cookie.setDomain(scookie.getDomain().toString());
371: }
372: cookies[idx++] = cookie;
373: } catch (Exception ex) {
374: log("Bad Cookie Name: " + scookie.getName()
375: + " /Value: " + scookie.getValue(), ex);
376: }
377: }
378: if (idx < count) {
379: Cookie[] ncookies = new Cookie[idx];
380: System.arraycopy(cookies, 0, ncookies, 0, idx);
381: cookies = ncookies;
382: }
383:
384: request.setCookies(cookies);
385:
386: }
387:
388: /**
389: * Return a context-relative path, beginning with a "/", that represents
390: * the canonical version of the specified path after ".." and "." elements
391: * are resolved out. If the specified path attempts to go outside the
392: * boundaries of the current context (i.e. too many ".." path elements
393: * are present), return <code>null</code> instead.
394: * This code is not optimized, and is only needed for Tomcat 4.0.x.
395: *
396: * @param path Path to be validated
397: */
398: protected static String validate(String path) {
399:
400: if (path == null)
401: return null;
402:
403: // Create a place for the normalized path
404: String normalized = path;
405:
406: // Normalize "/%7E" and "/%7e" at the beginning to "/~"
407: if (normalized.startsWith("/%7E")
408: || normalized.startsWith("/%7e"))
409: normalized = "/~" + normalized.substring(4);
410:
411: // Prevent encoding '%', '/', '.' and '\', which are special reserved
412: // characters
413: if ((normalized.indexOf("%25") >= 0)
414: || (normalized.indexOf("%2F") >= 0)
415: || (normalized.indexOf("%2E") >= 0)
416: || (normalized.indexOf("%5C") >= 0)
417: || (normalized.indexOf("%2f") >= 0)
418: || (normalized.indexOf("%2e") >= 0)
419: || (normalized.indexOf("%5c") >= 0)) {
420: return null;
421: }
422:
423: if (normalized.equals("/."))
424: return "/";
425:
426: // Normalize the slashes and add leading slash if necessary
427: if (normalized.indexOf('\\') >= 0)
428: normalized = normalized.replace('\\', '/');
429: if (!normalized.startsWith("/"))
430: normalized = "/" + normalized;
431:
432: // Resolve occurrences of "//" in the normalized path
433: while (true) {
434: int index = normalized.indexOf("//");
435: if (index < 0)
436: break;
437: normalized = normalized.substring(0, index)
438: + normalized.substring(index + 1);
439: }
440:
441: // Resolve occurrences of "/./" in the normalized path
442: while (true) {
443: int index = normalized.indexOf("/./");
444: if (index < 0)
445: break;
446: normalized = normalized.substring(0, index)
447: + normalized.substring(index + 2);
448: }
449:
450: // Resolve occurrences of "/../" in the normalized path
451: while (true) {
452: int index = normalized.indexOf("/../");
453: if (index < 0)
454: break;
455: if (index == 0)
456: return (null); // Trying to go outside our context
457: int index2 = normalized.lastIndexOf('/', index - 1);
458: normalized = normalized.substring(0, index2)
459: + normalized.substring(index + 3);
460: }
461:
462: // Declare occurrences of "/..." (three or more dots) to be invalid
463: // (on some Windows platforms this walks the directory tree!!!)
464: if (normalized.indexOf("/...") >= 0)
465: return (null);
466:
467: // Return the normalized path that we have completed
468: return (normalized);
469:
470: }
471:
472: /**
473: * Character conversion of the URI.
474: */
475: protected void convertURI(MessageBytes uri, CoyoteRequest request)
476: throws Exception {
477:
478: ByteChunk bc = uri.getByteChunk();
479: CharChunk cc = uri.getCharChunk();
480: cc.allocate(bc.getLength(), -1);
481:
482: String enc = connector.getURIEncoding();
483: if (enc != null) {
484: B2CConverter conv = request.getURIConverter();
485: try {
486: if (conv == null) {
487: conv = new B2CConverter(enc);
488: request.setURIConverter(conv);
489: } else {
490: conv.recycle();
491: }
492: } catch (IOException e) {
493: // Ignore
494: log("Invalid URI encoding; using HTTP default", e);
495: connector.setURIEncoding(null);
496: }
497: if (conv != null) {
498: try {
499: conv.convert(bc, cc);
500: uri.setChars(cc.getBuffer(), cc.getStart(), cc
501: .getLength());
502: return;
503: } catch (IOException e) {
504: if (debug >= 1) {
505: log(
506: "Invalid URI character encoding; trying ascii",
507: e);
508: }
509: cc.recycle();
510: }
511: }
512: }
513:
514: // Default encoding: fast conversion
515: byte[] bbuf = bc.getBuffer();
516: char[] cbuf = cc.getBuffer();
517: int start = bc.getStart();
518: for (int i = 0; i < bc.getLength(); i++) {
519: cbuf[i] = (char) (bbuf[i + start] & 0xff);
520: }
521: uri.setChars(cbuf, 0, bc.getLength());
522:
523: }
524:
525: /**
526: * Normalize URI.
527: * <p>
528: * This method normalizes "\", "//", "/./" and "/../". This method will
529: * return false when trying to go above the root, or if the URI contains
530: * a null byte.
531: *
532: * @param uriMB URI to be normalized
533: */
534: public static boolean normalize(MessageBytes uriMB) {
535:
536: ByteChunk uriBC = uriMB.getByteChunk();
537: byte[] b = uriBC.getBytes();
538: int start = uriBC.getStart();
539: int end = uriBC.getEnd();
540:
541: // URL * is acceptable
542: if ((end - start == 1) && b[start] == (byte) '*')
543: return true;
544:
545: int pos = 0;
546: int index = 0;
547:
548: // Replace '\' with '/'
549: // Check for null byte
550: for (pos = start; pos < end; pos++) {
551: if (b[pos] == (byte) '\\')
552: b[pos] = (byte) '/';
553: if (b[pos] == (byte) 0)
554: return false;
555: }
556:
557: // The URL must start with '/'
558: if (b[start] != (byte) '/') {
559: return false;
560: }
561:
562: // Replace "//" with "/"
563: for (pos = start; pos < (end - 1); pos++) {
564: if (b[pos] == (byte) '/') {
565: while ((pos + 1 < end) && (b[pos + 1] == (byte) '/')) {
566: copyBytes(b, pos, pos + 1, end - pos - 1);
567: end--;
568: }
569: }
570: }
571:
572: // If the URI ends with "/." or "/..", then we append an extra "/"
573: // Note: It is possible to extend the URI by 1 without any side effect
574: // as the next character is a non-significant WS.
575: if (((end - start) > 2) && (b[end - 1] == (byte) '.')) {
576: if ((b[end - 2] == (byte) '/')
577: || ((b[end - 2] == (byte) '.') && (b[end - 3] == (byte) '/'))) {
578: b[end] = (byte) '/';
579: end++;
580: }
581: }
582:
583: uriBC.setEnd(end);
584:
585: index = 0;
586:
587: // Resolve occurrences of "/./" in the normalized path
588: while (true) {
589: index = uriBC.indexOf("/./", 0, 3, index);
590: if (index < 0)
591: break;
592: copyBytes(b, start + index, start + index + 2, end - start
593: - index - 2);
594: end = end - 2;
595: uriBC.setEnd(end);
596: }
597:
598: index = 0;
599:
600: // Resolve occurrences of "/../" in the normalized path
601: while (true) {
602: index = uriBC.indexOf("/../", 0, 4, index);
603: if (index < 0)
604: break;
605: // Prevent from going outside our context
606: if (index == 0)
607: return false;
608: int index2 = -1;
609: for (pos = start + index - 1; (pos >= 0) && (index2 < 0); pos--) {
610: if (b[pos] == (byte) '/') {
611: index2 = pos;
612: }
613: }
614: copyBytes(b, start + index2, start + index + 3, end - start
615: - index - 3);
616: end = end + index2 - index - 3;
617: uriBC.setEnd(end);
618: index = index2;
619: }
620:
621: uriBC.setBytes(b, start, end);
622:
623: return true;
624:
625: }
626:
627: // ------------------------------------------------------ Protected Methods
628:
629: /**
630: * Copy an array of bytes to a different position. Used during
631: * normalization.
632: */
633: protected static void copyBytes(byte[] b, int dest, int src, int len) {
634: for (int pos = 0; pos < len; pos++) {
635: b[pos + dest] = b[pos + src];
636: }
637: }
638:
639: /**
640: * Log a message on the Logger associated with our Container (if any)
641: *
642: * @param message Message to be logged
643: */
644: protected void log(String message) {
645:
646: Logger logger = connector.getContainer().getLogger();
647: if (logger != null)
648: logger.log("CoyoteAdapter " + message);
649:
650: }
651:
652: /**
653: * Log a message on the Logger associated with our Container (if any)
654: *
655: * @param message Message to be logged
656: * @param throwable Associated exception
657: */
658: protected void log(String message, Throwable throwable) {
659:
660: Logger logger = connector.getContainer().getLogger();
661: if (logger != null)
662: logger.log("CoyoteAdapter " + message, throwable);
663:
664: }
665:
666: }
|