0001: /*
0002: * HTTPRequest.java
0003: *
0004: * Copyright (c) 1998 Sun Microsystems, Inc. All Rights Reserved.
0005: *
0006: * Developed by SunPS and SunIR
0007: */
0008:
0009: package com.sun.portal.rproxy.connectionhandler;
0010:
0011: import java.io.BufferedInputStream;
0012: import java.io.BufferedReader;
0013: import java.io.ByteArrayOutputStream;
0014: import java.io.DataOutputStream;
0015: import java.io.IOException;
0016: import java.net.InetAddress;
0017: import java.net.MalformedURLException;
0018: import java.net.URL;
0019: import java.net.URLDecoder;
0020: import java.net.URLEncoder;
0021: import java.util.ArrayList;
0022: import java.util.Enumeration;
0023: import java.util.HashMap;
0024: import java.util.Iterator;
0025: import java.util.LinkedList;
0026: import java.util.List;
0027: import java.util.Map;
0028: import java.util.NoSuchElementException;
0029: import java.util.Properties;
0030: import java.util.StringTokenizer;
0031: import java.util.logging.Level;
0032: import java.util.logging.Logger;
0033:
0034: import javax.servlet.ServletInputStream;
0035: import javax.servlet.http.Cookie;
0036: import javax.servlet.http.HttpServletRequest;
0037: import javax.servlet.http.HttpSession;
0038:
0039: import com.iplanet.sso.SSOToken;
0040: import com.iplanet.sso.SSOTokenManager;
0041: import com.sun.portal.log.common.PortalLogger;
0042: import com.sun.portal.rproxy.configservlet.client.ClientDetector;
0043: import com.sun.portal.rproxy.configservlet.client.GatewayProfile;
0044: import com.sun.portal.rproxy.connectionhandler.webdav.DavIf;
0045: import com.sun.portal.rproxy.connectionhandler.webdav.ParseException;
0046: import com.sun.portal.rproxy.connectionhandler.webdav.UnRewriter;
0047: import com.sun.portal.rproxy.monitoring.MonitoringSubsystem;
0048: import com.sun.portal.rproxy.monitoring.util.RProxyEvent;
0049: import com.sun.portal.rproxy.rewriter.SRAPTranslatorHelper;
0050: import com.sun.portal.rproxy.server.GatewayContext;
0051: import com.sun.portal.rproxy.server.GatewayContextFactory;
0052: import com.sun.portal.util.DomainWebProxyConfig;
0053: import com.sun.portal.util.SSOUtil;
0054: import com.sun.portal.util.ServiceIdentifier;
0055: import com.sun.portal.util.SystemProperties;
0056:
0057: /**
0058: * This class represents a single HTTP request.
0059: *
0060: * @author Gabriel Lawrence
0061: */
0062: public class HTTPRequest implements Request, HttpServletRequest {
0063: private List _headerLines = new ArrayList();
0064:
0065: private boolean _firstLine = true;
0066:
0067: private boolean _useProxy = false;
0068:
0069: private boolean _forwardCookie = false;
0070:
0071: private boolean _archiveTranslate = true;
0072:
0073: private String _protocol = null;
0074:
0075: private String _crlf = new String(new byte[] { 13, 10 });
0076:
0077: // Bug ID : 4646296
0078: private char lf = '\n';
0079:
0080: // EOC :: Bug ID : 4646296
0081: private String _method = null;
0082:
0083: private String _url = "";
0084:
0085: private String _uri = "";
0086:
0087: private String _port = null;
0088:
0089: private String _host = null;
0090:
0091: private String _gatewayhost = null;
0092:
0093: private String _object = "";
0094:
0095: private String _gwscheme = "";
0096:
0097: private String _proxyHost;
0098:
0099: private int _proxyPort;
0100:
0101: private String _httpVersion = null;
0102:
0103: private boolean _headerComplete = false;
0104:
0105: private Map _headerCache = new HashMap();
0106:
0107: private BufferedInputStream _contentStream;
0108:
0109: private int _size = 0;
0110:
0111: // document base
0112: // private String _baseHref = null;
0113: // private String _baseObj = null;
0114: // private String _baseUrlWithoutObj = "";
0115:
0116: private static final String STRING_HTTP_PORT = "80";
0117:
0118: private static final String STRING_HTTPS_PORT = "443";
0119:
0120: private static String _cookieName;
0121:
0122: private static String cookiePrefix;
0123:
0124: private static String _colonString = "%3A";
0125:
0126: private static boolean _useProxyFlag;
0127:
0128: private static final int PROXY_HTTP_PORT = 8080;
0129:
0130: private static MatchHttps UseWebProxyURL = new MatchHttps(
0131: "UseWebProxyURL");
0132:
0133: private static MatchHttps DontUseWebProxyURL = new MatchHttps(
0134: "DontUseWebProxyURL");
0135:
0136: // private static MatchHttps secureURL = new MatchHttps("secure-url");
0137: private static MatchHttps ForwardCookieURL = new MatchHttps(
0138: "ForwardCookieURL");
0139:
0140: // Not used anywhere - Commenting it
0141: // private static final String DEFAULT_SSL_PORT = "443";
0142: // private static String sslPort;
0143: private static String defaultGW;
0144:
0145: private static final String HTTP_1_0 = "HTTP/1.0";
0146:
0147: // Lihue PRD : 4.5
0148: // private static final String gatewayURL;
0149: // MAP Support
0150: // private String gatewayURL;
0151: // private static final String gatewayURL;
0152: protected String gatewayURL;
0153:
0154: protected String encodedGatewayURL;
0155:
0156: protected String urlSessionInfo = null;
0157:
0158: // EOC : MAP
0159:
0160: // EOC :: Lihue PRD : 4.5
0161:
0162: protected static boolean usePlatformConfURL = false;
0163:
0164: protected static String httpPlatformConfURLString = "";
0165:
0166: protected static String httpsPlatformConfURLString = "";
0167:
0168: protected static URL httpPlatformConfURL = null;
0169:
0170: protected static URL httpsPlatformConfURL = null;
0171:
0172: private static Logger logger = PortalLogger
0173: .getLogger(HTTPRequest.class);
0174:
0175: static {
0176:
0177: /*
0178: * String gatewayHost = SystemProperties.get( "gateway.host").trim();
0179: * String gatewayProtocol = SystemProperties.get(
0180: * "gateway.protocol").trim(); gatewayURL = gatewayProtocol + "://" +
0181: * gatewayHost;
0182: */
0183: /*
0184: * String logic = SystemProperties.get("gateway.newDomainLogic",
0185: * "false"); useNewDomainLogic = logic.equalsIgnoreCase("true");
0186: */
0187: // sslPort = STRING_HTTPS_PORT;
0188: _useProxyFlag = GatewayProfile.getBoolean("UseProxy", false);
0189:
0190: List all_servers = GatewayProfile
0191: .getStringList("PortalServerList");
0192: Iterator iterator = all_servers.iterator();
0193:
0194: while (iterator.hasNext()) {
0195: try {
0196: String name = iterator.next().toString();
0197: URL url = new URL(name);
0198: String protocol = url.getProtocol();
0199: String host = url.getHost();
0200: int port = url.getPort();
0201:
0202: boolean isDefaultPort = false;
0203: ForwardCookieURL.add(name);
0204:
0205: if ((port == 80 && protocol.equals("http"))
0206: || (port == 443 && protocol.equals("https"))) {
0207: isDefaultPort = true;
0208: ForwardCookieURL.add(protocol + "://" + host);
0209: }
0210:
0211: String ip = InetAddress.getByName(host)
0212: .getHostAddress();
0213: ForwardCookieURL
0214: .add(protocol + "://" + ip + ":" + port);
0215: if (isDefaultPort) {
0216: ForwardCookieURL.add(protocol + "://" + ip);
0217: }
0218: } catch (Exception e) {
0219: }
0220: }
0221:
0222: defaultGW = SystemProperties.get("gateway.host", "");
0223:
0224: // iDSAME Migration for cookies
0225: // _cookieName = SystemProperties.get("cookie.name",
0226: // "iPlanetPortalServer");
0227: _cookieName = com.iplanet.am.util.SystemProperties.get(
0228: "com.iplanet.am.cookie.name", "iPlanetDirectoryPro");
0229: // EOC : iDSAME Migration for cookies
0230: cookiePrefix = _cookieName + "=";
0231:
0232: String strUsePlatformConfURL = SystemProperties.get(
0233: "gateway.enable.customurl", "false");
0234: if (strUsePlatformConfURL != null) {
0235: usePlatformConfURL = strUsePlatformConfURL.trim()
0236: .equalsIgnoreCase("true");
0237: }
0238:
0239: httpPlatformConfURLString = SystemProperties
0240: .get("gateway.httpurl");
0241: if (httpPlatformConfURLString != null) {
0242: httpPlatformConfURLString = httpPlatformConfURLString
0243: .trim();
0244: if (!httpPlatformConfURLString.endsWith("/"))
0245: httpPlatformConfURLString = httpPlatformConfURLString
0246: .concat("/");
0247:
0248: try {
0249: httpPlatformConfURL = new URL(httpPlatformConfURLString);
0250: } catch (MalformedURLException mfex) {
0251: httpPlatformConfURL = null;
0252: httpPlatformConfURLString = null;
0253: }
0254: }
0255: httpsPlatformConfURLString = SystemProperties
0256: .get("gateway.httpsurl");
0257: if (httpsPlatformConfURLString != null) {
0258: httpsPlatformConfURLString = httpsPlatformConfURLString
0259: .trim();
0260:
0261: if (!httpsPlatformConfURLString.endsWith("/"))
0262: httpsPlatformConfURLString = httpsPlatformConfURLString
0263: .concat("/");
0264:
0265: try {
0266: httpsPlatformConfURL = new URL(
0267: httpsPlatformConfURLString);
0268: } catch (MalformedURLException mfex) {
0269: httpsPlatformConfURL = null;
0270: httpsPlatformConfURLString = null;
0271: }
0272: }
0273: }
0274:
0275: public HTTPRequest() {
0276: super ();
0277: _gatewayhost = defaultGW;
0278: }
0279:
0280: public HTTPRequest(String urlstr) {
0281: super ();
0282: _gatewayhost = "";
0283: _method = "GET";
0284: parseURI("/" + urlstr);
0285: _httpVersion = "HTTP/1.0";
0286: // logger = Logger.getLogger("com.sun.portal.sra.rproxy");
0287: }
0288:
0289: // Lihue PRD : 4.5
0290: // will change while refactoring this code - sanjib.ghosh@sun.com
0291: public HTTPRequest(String protocol, int dummyPort) {
0292:
0293: super ();
0294: GatewayContext gatewayContext = GatewayContextFactory
0295: .getGatewayContext();
0296:
0297: boolean urlDone = false;
0298:
0299: if (usePlatformConfURL) {
0300: if (protocol.equalsIgnoreCase("http")
0301: && httpPlatformConfURL != null) {
0302: _gatewayhost = httpPlatformConfURL.getHost();
0303: gatewayURL = httpPlatformConfURLString;
0304: urlDone = true;
0305: }
0306: if (protocol.equalsIgnoreCase("https")
0307: && httpsPlatformConfURL != null) {
0308: _gatewayhost = httpsPlatformConfURL.getHost();
0309: gatewayURL = httpsPlatformConfURLString;
0310: urlDone = true;
0311: }
0312: }
0313:
0314: if (!urlDone) {
0315: int port = (protocol.equalsIgnoreCase("http")) ? gatewayContext
0316: .getHttpPort()
0317: : gatewayContext.getHttpsPort();
0318: _gatewayhost = defaultGW;
0319: StringBuffer buff = new StringBuffer();
0320: buff.append(protocol).append("://").append(defaultGW);
0321: if (protocol.equalsIgnoreCase("http")) {
0322: if (port != 80) {
0323: buff.append(':').append(port);
0324: }
0325: } else if (port != 443) {
0326: buff.append(':').append(port);
0327: }
0328: buff.append('/');
0329: gatewayURL = buff.toString();
0330: }
0331: // MAP support
0332: encodedGatewayURL = gatewayURL;
0333: urlSessionInfo = null;
0334: // EOC : MAP
0335: }
0336:
0337: // EOC :: Lihue PRD : 4.5
0338:
0339: public void addCustomHeader(String key, String value) {
0340: int vallen = value.length();
0341: if (value.charAt(vallen - 1) != '\n'
0342: || value.charAt(vallen - 2) != '\r') {
0343: value = value + _crlf;
0344: }
0345: _headerLines.add(key + ": " + value);
0346: }
0347:
0348: public void addHeader(String key, String value) {
0349: setRequestHeader(key, value + _crlf);
0350: }
0351:
0352: public void setMethod(String method) {
0353: _method = method;
0354: }
0355:
0356: /**
0357: * Request Method
0358: */
0359: public String getMethod() {
0360: return _method;
0361: }
0362:
0363: /**
0364: * request url, minus the first /
0365: */
0366: public String getURL() {
0367: return _url;
0368: }
0369:
0370: // PDC Fix to support IS 6.1
0371: public void setURL(String url) {
0372: _url = url;
0373: }
0374:
0375: public String getURI() {
0376: return _uri;
0377: }
0378:
0379: /**
0380: * HTTP Version
0381: */
0382: public String getHTTPVersion() {
0383: // when we see 1.1 request, we will change it to 1.0
0384: // we will support 1.1 later.
0385: if (_httpVersion.equals("HTTP/1.1")) {
0386: return HTTP_1_0;
0387: }
0388:
0389: return _httpVersion;
0390: }
0391:
0392: /**
0393: * Byte array of header suitable for sending across network
0394: */
0395: public byte[] getRequestHeaderBytes() {
0396: ByteArrayOutputStream outBAOS = new ByteArrayOutputStream();
0397:
0398: try {
0399: DataOutputStream out = new DataOutputStream(outBAOS);
0400: try {
0401: out.write((getMethod() + " ").getBytes());
0402: } catch (NullPointerException ex) {
0403: }
0404:
0405: try {
0406: if (_useProxy && (!_protocol.equals("https"))) {
0407: out.write((stripPsScriptReferrer(getURL()))
0408: .getBytes("ISO-8859-1"));
0409: } else {
0410: out.write((stripPsScriptReferrer(getObject()))
0411: .getBytes("ISO-8859-1"));
0412: }
0413: } catch (NullPointerException ex) {
0414: }
0415:
0416: try {
0417: String httpVersion = getHTTPVersion();
0418: if (httpVersion.compareTo("HTTP/0.9") > 0) {
0419: out.write((" " + getHTTPVersion()).getBytes());
0420: }
0421: } catch (NullPointerException ex) {
0422: }
0423:
0424: out.write("\r\n".getBytes());
0425: if (_protocol != null && _port != null) {
0426: if ((_protocol.equals("http") && _port.equals("80"))
0427: || (_protocol.equals("https") && _port
0428: .equals("443"))) {
0429: out.write(("Host: " + getHost() + "\r\n")
0430: .getBytes());
0431: } else {
0432: out
0433: .write(("Host: " + getHost() + ":"
0434: + getPort() + "\r\n").getBytes());
0435: }
0436: } else {
0437: out.write(("Host: " + getHost() + "\r\n").getBytes());
0438: }
0439:
0440: String s, sc;
0441: int numHeaders = _headerLines.size();
0442: for (int i = 0; i < numHeaders; ++i) {
0443: s = (String) _headerLines.get(i);
0444: if (!s.regionMatches(true, 0, "host", 0, 4))// &&
0445: // !s.regionMatches(true, 0, "referer", 0, 7))
0446: {
0447: if (s.regionMatches(true, 0, "referer", 0, 7)) {
0448: // logger.info(" ******* " + s);
0449: Object[] params0 = { s };
0450: logger.log(Level.INFO,
0451: "PSSRRPROXY_CSPRCONHNDLR045", params0);
0452: int doubleSlash = s.indexOf("//");
0453: if (doubleSlash == -1) {
0454: out.write(s.getBytes());
0455: } else {
0456: int singleSlash = s.indexOf("/http",
0457: doubleSlash + 2);
0458: if (singleSlash == -1) {
0459: out.write(s.getBytes());
0460: } else {
0461: out.write(("Referer: " + s
0462: .substring(singleSlash + 1))
0463: .getBytes());
0464: // logger.info(" ******* " + "Referer: " +
0465: // s.substring(singleSlash + 1));
0466: Object[] params1 = { "Referer: ",
0467: s.substring(singleSlash + 1) };
0468: logger.log(Level.INFO,
0469: "PSSRRPROXY_CSPRCONHNDLR046",
0470: params1);
0471: }
0472: }
0473: } else if (s.regionMatches(true, 0, "Destination",
0474: 0, 11)) {
0475: // logger.info(" ******* " + s);
0476: Object[] params2 = { s };
0477: logger.log(Level.INFO,
0478: "PSSRRPROXY_CSPRCONHNDLR047", params2);
0479: int doubleSlash = s.indexOf("//");
0480: if (doubleSlash == -1) {
0481: out.write(s.getBytes());
0482: } else {
0483: int singleSlash = s.indexOf("/http",
0484: doubleSlash + 2);
0485: if (singleSlash == -1) {
0486: out.write(s.getBytes());
0487: } else {
0488: out.write(("Destination: " + s
0489: .substring(singleSlash + 1))
0490: .getBytes());
0491: // logger.info(" ******* " + "Destination: " +
0492: // s.substring(singleSlash + 1));
0493: Object[] params3 = { "Destination: ",
0494: s.substring(singleSlash, 1) };
0495: logger.log(Level.INFO,
0496: "PSSRRPROXY_CSPRCONHNDLR048",
0497: params3);
0498: }
0499: }
0500: } else if (!s
0501: .regionMatches(true, 0, "cookie", 0, 6)
0502: || _forwardCookie) {
0503: out.write(s.getBytes());
0504: } else {
0505: sc = removeSidFromCookie(s);
0506:
0507: if (sc != null) {
0508: out.write(sc.getBytes());
0509: }
0510: }
0511: }
0512: }
0513: out.write("\r\n".getBytes());
0514: out.flush();
0515: } catch (IOException ex) {
0516: }
0517: byte[] result = outBAOS.toByteArray();
0518: MonitoringSubsystem.handleEvent(RProxyEvent.REQUEST_READ,
0519: new Long(result.length));
0520: return result;
0521:
0522: }
0523:
0524: private String removeSidFromCookie(String cookies) {
0525: if (cookies.length() < 8) {
0526: return cookies;
0527: }
0528: String cookie;
0529: String sc = cookies.substring(7);
0530: StringBuffer result = new StringBuffer("Cookie:");
0531: StringTokenizer st = new StringTokenizer(sc, ";");
0532:
0533: while (st.hasMoreTokens()) {
0534: cookie = st.nextToken().trim();
0535: if (!cookie.startsWith(cookiePrefix)) {
0536: result.append(" ").append(cookie).append(";");
0537: }
0538: }
0539:
0540: if (result.charAt(result.length() - 1) == ':') {
0541: return null;
0542: } else {
0543: result.setLength(result.length() - 1);
0544: result.append(_crlf);
0545: return result.toString();
0546: }
0547: }
0548:
0549: /**
0550: * Method to retrieve an arbitrary header.
0551: */
0552: public String getRequestHeader(String header) {
0553: String result = (String) _headerCache.get(header);
0554: if (result != null) {
0555: return result;
0556: }
0557:
0558: String s;
0559: int numHeaders = _headerLines.size();
0560: for (int i = 0; i < numHeaders; ++i) {
0561: s = (String) _headerLines.get(i);
0562: String tmps = (s.substring(0, s.indexOf(":"))).trim();
0563: if (tmps.equalsIgnoreCase(header)) {
0564: _headerCache.put(header, s);
0565: return s;
0566: }
0567: }
0568:
0569: return null;
0570: }
0571:
0572: // Modifying this method to support header removal.
0573: // For removing a header , value must be an empty string.
0574: public void setRequestHeader(String header, String value) {
0575: // System.out.println("setRequestHeader : ( "+header+" , "+value+" );");
0576: boolean removeHeader = false;
0577: if (header == null || value == null) {
0578: return;
0579: }
0580: /*
0581: * PRD 3.7 (4338513) Authentication chaining will work with Certificate
0582: * authentication. To handle the scenario of the session timeout or
0583: * invalidation happening at the portalserver side,
0584: */
0585:
0586: int vallen = value.length();
0587: if (vallen == 0) {
0588: removeHeader = true;
0589: } else {
0590: if (value.charAt(vallen - 1) != '\n'
0591: || value.charAt(vallen - 2) != '\r') {
0592: value = value + _crlf;
0593: }
0594: }
0595: // End of code change for PRD 3.7
0596: String s;
0597: int headerLen = header.length();
0598: int numHeaders = _headerLines.size();
0599: for (int i = 0; i < numHeaders; ++i) {
0600: s = (String) _headerLines.get(i);
0601: if (s.regionMatches(true, 0, header, 0, headerLen)) {
0602: _headerLines.remove(i);
0603: if (!removeHeader) {
0604: _headerLines.add(value);
0605: }
0606: _headerCache.remove(header);
0607: return;
0608: }
0609: }
0610: if (!removeHeader) {
0611: _headerLines.add(value);
0612: }
0613: }
0614:
0615: public String getProtocol() {
0616: return _protocol;
0617: }
0618:
0619: public String getHost() {
0620: return _host;
0621: }
0622:
0623: public String getGatewayHost() {
0624: return _gatewayhost;
0625: }
0626:
0627: public String getPort() {
0628: return _port;
0629: }
0630:
0631: public String getGatewayScheme() {
0632: return _gwscheme;
0633: }
0634:
0635: public String getProxyHost() {
0636: return _proxyHost;
0637: }
0638:
0639: public int getProxyPort() {
0640: return _proxyPort;
0641: }
0642:
0643: public boolean getUseProxy() {
0644: return _useProxy;
0645: }
0646:
0647: public String getObject() {
0648: return _object;
0649: }
0650:
0651: public int getSize() {
0652: return _size;
0653: }
0654:
0655: public void addSize(int size) {
0656: _size += size;
0657: }
0658:
0659: public void setHost(String host) {
0660: _host = host;
0661: }
0662:
0663: public void setPort(String port) {
0664: _port = port;
0665: }
0666:
0667: public void setProtocol(String protocol) {
0668: _protocol = protocol;
0669: }
0670:
0671: public void setObject(String object) {
0672: _object = object;
0673: }
0674:
0675: public void setGatewayHost(String gwhost) {
0676: _gatewayhost = gwhost;
0677: }
0678:
0679: public void setArchiveTranslate(boolean t) {
0680: _archiveTranslate = t;
0681: }
0682:
0683: public boolean getArchiveTranslate() {
0684: return _archiveTranslate;
0685: }
0686:
0687: public BufferedInputStream getContentStream() {
0688: return _contentStream;
0689: }
0690:
0691: public void setContentStream(BufferedInputStream in) {
0692: _contentStream = in;
0693: }
0694:
0695: /**
0696: * Method called by HTTPSession when construction the Request Object.
0697: */
0698: public void addHeaderLine(String s) {
0699: if (_firstLine) {
0700: // Bug ID : # 4646296
0701: if (s.equals(_crlf)) {
0702: // logger.info("Persistence Return !!");
0703: logger.info("PSSRRPROXY_CSPRCONHNDLR049");
0704: return;
0705: }
0706:
0707: // logger.info("First header : " + s);
0708: Object[] params5 = { s };
0709: logger.log(Level.INFO, "PSSRRPROXY_CSPRCONHNDLR050",
0710: params5);
0711: // if (!s.equals(_crlf)) {
0712: int strLength = s.length();
0713: if (strLength > 0 && s.charAt(strLength - 1) == lf) {
0714: if (!s.endsWith(_crlf)) {
0715: s = s.substring(0, strLength - 1) + _crlf;
0716: }
0717:
0718: if (s.startsWith(_crlf)) {
0719: s = s.substring(2);
0720: } else if (s.charAt(0) == lf) {
0721: s = s.substring(1);
0722: }
0723: if (s.equals(_crlf)) {
0724: return;
0725: }
0726: // strLength = s.length();
0727: // EOC :: Bug ID : # 4646296
0728: _firstLine = false;
0729: StringTokenizer st = new StringTokenizer(s);
0730: int count = st.countTokens();
0731: boolean versionDone = false;
0732: _method = st.nextToken();
0733: if (count <= 2) {
0734: String tmp = st.nextToken();
0735:
0736: if (tmp.toLowerCase().startsWith("http/")) {
0737: // No path , direct version.
0738: // Thouggh this is against the spec , some
0739: // browsers\simulators
0740: // do do this.
0741: parseURI("/");
0742: _httpVersion = tmp;
0743: } else {
0744: parseURI(URLDecode(tmp));
0745: _httpVersion = "HTTP/0.9";
0746: }
0747: _headerComplete = true;
0748: versionDone = true;
0749: } else {
0750: parseURI(URLDecode(st.nextToken()));
0751: }
0752:
0753: if (!versionDone) {
0754:
0755: try {
0756: _httpVersion = st.nextToken();
0757: } catch (NoSuchElementException ex) {
0758: _httpVersion = "HTTP/0.9";
0759: _headerComplete = true;
0760: }
0761: }
0762: }
0763: } else {
0764: // Bug ID : # 4646296
0765: int strLength = s.length();
0766: if (!s.endsWith(_crlf) && strLength > 0) {
0767: s = s.substring(0, strLength - 1) + _crlf;
0768: }
0769: // EOC :: Bug ID : # 4646296
0770: if (s.equals(_crlf)) {
0771: _headerComplete = true;
0772: requestPostReadProcessor();
0773: } else if (s.regionMatches(true, 0, "host:", 0, 5)) {
0774: if (s.length() > 5) {
0775: _gatewayhost = s.substring(5).trim();
0776: int index = _gatewayhost.indexOf(':');
0777: if (index != -1) {
0778: _gatewayhost = _gatewayhost.substring(0, index);
0779: }
0780: // logger.info("HTTPRequest: gateway host is " +
0781: // _gatewayhost);
0782: Object[] params6 = { _gatewayhost };
0783: logger.log(Level.INFO,
0784: "PSSRRPROXY_CSPRCONHNDLR051", params6);
0785: }
0786: } else {
0787: _headerLines.add(s);
0788: }
0789: }
0790: }
0791:
0792: public String getProtocolFromCustomUrl(String knownProtocol) {
0793: if (httpPlatformConfURL != null && usePlatformConfURL)
0794: return httpPlatformConfURL.getProtocol();
0795: else
0796: return knownProtocol;
0797: }
0798:
0799: public String getPortFromCustomUrl(String knownPort) {
0800: if (httpPlatformConfURL != null && usePlatformConfURL)
0801: return httpPlatformConfURL.getPort() == -1 ? STRING_HTTP_PORT
0802: : httpPlatformConfURL.getPort() + "";
0803: else
0804: return knownPort;
0805: }
0806:
0807: /**
0808: * @return
0809: */
0810:
0811: private String URLDecode(String url) {
0812: { // Ofuscation Code Block
0813: if (ServiceIdentifier.isGateway() && url.length() > 1) {
0814: url = "/"
0815: + SRAPTranslatorHelper.decodeOfuscatedURI(url
0816: .substring(1));
0817: }
0818: }
0819: StringBuffer sb = new StringBuffer();
0820: int i;
0821: int start = 0;
0822:
0823: // Bug ID : # 4656810
0824: /*
0825: * The rewriter expects a valid URL of form protocol://host/path Hence
0826: * in this case (most probably due to proxy stripping off the extra
0827: * slash and making the _url as protocol:/host/path, we are adding an
0828: * extra slash - this should solve the problem - Mridul
0829: */
0830: start = url.indexOf("://");
0831: if (start == -1) {
0832: start = url.indexOf(":/");
0833: if (start != -1) {
0834: // System.out.println("Before : "+url);
0835: sb.append(url.substring(0, start + 2)).append('/')
0836: .append(url.substring(start + 2));
0837: url = sb.toString();
0838: // System.out.println("After : "+url);
0839: sb.setLength(0);
0840: }
0841: }
0842: start = 0;
0843: // EOC : Bug ID : # 4656810
0844:
0845: // don't need to translate URL parameters
0846: int indexParam = url.indexOf('?');
0847:
0848: if (indexParam == -1)
0849: indexParam = url.length();
0850:
0851: do {
0852: i = url.indexOf(_colonString, start);
0853: if (i == -1 || i > indexParam) {
0854: sb.append(url.substring(start));
0855: break;
0856: }
0857:
0858: sb.append(url.substring(start, i));
0859: sb.append(':');
0860: start = i + _colonString.length();
0861: } while (i != -1);
0862:
0863: return sb.toString();
0864: }
0865:
0866: private String parseGatewayScheme(String url) {
0867: if (url.length() < 2) {
0868: return url;
0869: }
0870:
0871: int index = url.indexOf('/', 1);
0872: if (index == -1) {
0873: _gwscheme = url.substring(1);
0874: return new String("/");
0875: }
0876:
0877: if (index == 1) {
0878: return url.substring(1);
0879: }
0880:
0881: int index2 = url.indexOf(':', 1);
0882: if ((index2 == -1) || (index2 > index)) {
0883: // Multiple schemes for MAP.
0884: if (index2 != -1) {
0885: index = url.lastIndexOf('/', index2);
0886: }
0887: // EOC : MAP
0888: _gwscheme = url.substring(1, index);
0889: return (url.substring(index));
0890: }
0891:
0892: return url;
0893: }
0894:
0895: /*
0896: * Bug Id - 4501739 Synopsis : URI parsing incorrect : requires / following
0897: * hostname for url of type protocol://gateway?params ( without a path being
0898: * specified )
0899: *
0900: * Fix - check for ? in the url in case there is no path specified and
0901: * prepend a slash before it
0902: */
0903: private String checkURL(String s, int andBegin) {
0904:
0905: // Modify _uri and _url also
0906: s = s.substring(0, andBegin) + "/" + s.substring(andBegin);
0907: _url = s.substring(1);
0908: int tmpUriIndex = _uri.indexOf('?', andBegin);
0909: _uri = _uri.substring(0, tmpUriIndex) + "/"
0910: + _uri.substring(tmpUriIndex);
0911: return s;
0912: }
0913:
0914: /* End of Code Bug Id - 4501739 */
0915: private void parseURI(String s) {
0916:
0917: _uri = s;
0918: int colonSlashIndex = _uri.indexOf(":/");
0919:
0920: if (colonSlashIndex != -1) {
0921: int colonIndex = _uri.indexOf(':', colonSlashIndex + 1);
0922: int slashIndex = _uri.indexOf('/', colonSlashIndex + 3);
0923: if (slashIndex == -1) {
0924: slashIndex = _uri.indexOf('?', colonSlashIndex + 3);
0925: if (slashIndex == -1) {
0926: slashIndex = _uri.length();
0927: }
0928: }
0929: if (colonIndex == -1 || colonIndex > slashIndex) {
0930: int percentIndex = _uri.indexOf('%',
0931: colonSlashIndex + 1);
0932: if (percentIndex != -1) {
0933: // Possible Netscape 6.2 bug where
0934: // /protocol://hostname:port/ will have the
0935: // ':' before the port encoded.
0936: try {
0937: StringBuffer sb = new StringBuffer();
0938: sb.append(_uri.substring(0, colonIndex + 3));
0939: sb.append(URLDecoder.decode(_uri.substring(
0940: colonIndex + 3, slashIndex)));
0941: if (slashIndex != _uri.length()) {
0942: sb.append(_uri.substring(slashIndex));
0943: }
0944: _uri = sb.toString();
0945: } catch (Exception encodeEx) {
0946: }
0947: }
0948: }
0949: }
0950:
0951: s = _uri;
0952: s = parseGatewayScheme(s);
0953:
0954: _url = s.substring(1);
0955: int start, end;
0956:
0957: start = s.indexOf(':');
0958: if (start != -1) {
0959: _protocol = s.substring(1, s.indexOf(':'));
0960: }
0961:
0962: start = s.indexOf("//");
0963: if (start == -1)
0964: start = s.indexOf(":/");
0965:
0966: if (start != -1) {
0967: end = s.indexOf('/', start + 2);
0968:
0969: /* Bug Id - 4501739 */
0970: if (end == -1) {
0971: end = s.indexOf('?', start + 2);
0972: if (end != -1) {
0973: s = checkURL(s, end);
0974: }
0975: }
0976: /* End of Code Bug Id - 4501739 */
0977:
0978: String hostport = s.substring(start, end == -1 ? s.length()
0979: : end);
0980:
0981: int endHost = hostport.indexOf(':', 1);
0982:
0983: // Checking for url's of form http://user:passwd@host:port
0984: int checkBasicAuth = hostport.indexOf("@");
0985: if (checkBasicAuth != -1) {
0986: String user = null;
0987: String password = null;
0988: user = hostport.substring(2, hostport.indexOf(":"));
0989: password = hostport.substring(
0990: hostport.indexOf(":") + 1, hostport
0991: .indexOf('@'));
0992: hostport = hostport
0993: .substring(hostport.indexOf('@') + 1);
0994: endHost = hostport.indexOf(':', 1);
0995: addBasicAuthInfo(user, password);
0996: } else {
0997: hostport = hostport.substring(2);
0998: endHost = hostport.indexOf(':', 1);
0999: }
1000:
1001: if (endHost == -1) {
1002: if (_protocol.equals("https")) {
1003: _port = STRING_HTTPS_PORT;
1004: } else {
1005: _port = STRING_HTTP_PORT;
1006: }
1007: _host = hostport;
1008:
1009: } else {
1010: _host = hostport.substring(0, endHost);
1011: _port = hostport.substring(endHost + 1);
1012: }
1013: if (end != -1) {
1014: _object = s.substring(end);
1015: }
1016: }
1017:
1018: String testURL = getCondensedURL(_protocol, _host, _port);
1019: /*
1020: * if (secureURL.hasMatch(testURL)) { _protocol = new String("https");
1021: * _port = sslPort; }
1022: */
1023: populateWebProxyInfo();
1024: if (!ServiceIdentifier.isGateway()) {
1025: _forwardCookie = true;
1026: } else {
1027:
1028: _forwardCookie = ForwardCookieURL.hasMatch(testURL)
1029: || ForwardCookieURL.hasMatchPattern(_url);
1030: }
1031: if (_useProxyFlag) {
1032: if ((_proxyHost != null)
1033: && (!DontUseWebProxyURL.hasMatch(testURL))) {
1034: _useProxy = true;
1035: } else {
1036: _useProxy = false;
1037: _proxyHost = null;
1038: }
1039: } else {
1040: if ((_proxyHost != null)
1041: && (UseWebProxyURL.hasMatch(testURL))) {
1042: _useProxy = true;
1043: } else {
1044: _useProxy = false;
1045: _proxyHost = null;
1046: }
1047: }
1048: // logger.info("_useProxy : " + _useProxy + " testURL : " + testURL + "
1049: // _proxyHost : " + _proxyHost);
1050: Object[] params7 = { new Boolean(_useProxy), " testURL : ",
1051: testURL, " _proxyHost : ", _proxyHost };
1052: logger.log(Level.INFO, "PSSRRPROXY_CSPRCONHNDLR052", params7);
1053: }
1054:
1055: private String getCondensedURL(String protocol, String host,
1056: String port) {
1057:
1058: if (protocol == null) {
1059: protocol = "";
1060: }
1061:
1062: if (port == null
1063: || (port.equals("80") && protocol.equals("http"))
1064: || (port.equals("443") && protocol.equals("https"))) {
1065: return protocol + "://" + host;
1066: } else {
1067: return protocol + "://" + host + ":" + port;
1068: }
1069: }
1070:
1071: public void populateWebProxyInfo() {
1072:
1073: // Lihue PRD : 7.4.3.1
1074: String proxy_port = DomainWebProxyConfig.getWebProxy(_protocol,
1075: _host);
1076: // End of Code - Lihue PRD : 7.4.3.1
1077:
1078: // logger.info("HTTPRequest: proxy:port = " + proxy_port);
1079: Object[] params8 = { proxy_port };
1080: logger.log(Level.INFO, "PSSRRPROXY_CSPRCONHNDLR053", params8);
1081:
1082: if (proxy_port == null || proxy_port.length() == 0) {
1083: _proxyHost = null;
1084: _useProxy = false;
1085: } else {
1086: _useProxy = true;
1087: int i = proxy_port.indexOf(':');
1088:
1089: if (i == -1 || (i + 1) >= proxy_port.length()) {
1090: _proxyHost = proxy_port;
1091: _proxyPort = PROXY_HTTP_PORT;
1092: } else {
1093: _proxyHost = proxy_port.substring(0, i);
1094: _proxyPort = Integer.parseInt(proxy_port
1095: .substring(i + 1));
1096: }
1097: }
1098: }
1099:
1100: /**
1101: * True - valid http header parsed, false not enough info yet
1102: */
1103: public boolean isHeaderComplete() {
1104: return _headerComplete;
1105: }
1106:
1107: // Accessible Impl
1108: public String getSessionID() {
1109:
1110: String s = getRequestHeader("Cookie");
1111: if (s == null) {
1112: // return SessionEncodeURL.getSidFromURL(_url);
1113: return null;
1114: }
1115:
1116: String cookies = s.substring(s.indexOf(':') + 1);
1117:
1118: String result = null;
1119: StringTokenizer st = new StringTokenizer(cookies, ";");
1120: String curCookie;
1121:
1122: // TODO : Make this proper implementation -
1123: // It is not necessary that cookie should be name=value - whitespaces
1124: // are allowed.
1125: int indx;
1126: while (st.hasMoreTokens() && result == null) {
1127: curCookie = st.nextToken().trim();
1128: indx = curCookie.indexOf('=');
1129: if (indx != -1
1130: && curCookie.substring(0, indx).trim().equals(
1131: _cookieName)) {
1132: // if (curCookie.startsWith(cookiePrefix)) {
1133: // result = curCookie.substring(curCookie.indexOf("=") +
1134: // 1).trim();
1135: result = curCookie.substring(indx + 1).trim();
1136: }
1137: }
1138: /*
1139: * if ( result == null ) { return SessionEncodeURL.getSidFromURL(_url); }
1140: */
1141: return result;
1142: }
1143:
1144: public Properties getNetworkInfo() {
1145: return null;
1146: }
1147:
1148: public byte[] getCertificate() {
1149: return null;
1150: }
1151:
1152: /**
1153: * Something informative to print out
1154: */
1155: public String toString() {
1156: // return getMethod()+" "+getObject()+" "+getHTTPVersion();
1157: /*
1158: * return "Host: " + getHost() + "Protocol:" + getProtocol() +
1159: * "BaseHRef: " + getBaseHref() + "BaseUrlWithoutObjL:" +
1160: * getBaseUrlWithoutObj() + "BaseObj: " + getBaseObj() + "Object:" +
1161: * getObject() + "\n\nURL:" + getURL() + "\nURI:" + getURI() +"\n\n";
1162: * //"Headder Bytes: " + new String(getRequestHeaderBytes());
1163: */
1164: return new String(getRequestHeaderBytes());
1165: }
1166:
1167: /**
1168: * Method in servlet
1169: */
1170: public Object getAttribute(String name) {
1171: return null;
1172: }
1173:
1174: public Enumeration getAttributeNames() {
1175: return null;
1176: }
1177:
1178: public String getAuthType() {
1179: throw new UnsupportedOperationException(
1180: "getAuthType() not supported");
1181: }
1182:
1183: public Cookie[] getCookies() {
1184: return null;
1185: // throw new UnsupportedOperationException("getCookies() not
1186: // supported");
1187: }
1188:
1189: public String getCharacterEncoding() {
1190: return null;
1191: }
1192:
1193: public int getContentLength() {
1194: String line = getRequestHeader("Content-length");
1195: StringTokenizer tokens = new StringTokenizer(line, " ");
1196: tokens.nextToken();
1197: String length = tokens.nextToken().trim();
1198: return Integer.parseInt(length);
1199: }
1200:
1201: public String getContentType() {
1202: return null;
1203: }
1204:
1205: public String getContextPath() {
1206: return null;
1207: }
1208:
1209: public long getDateHeader(String name) {
1210: // return 0;
1211: throw new UnsupportedOperationException(
1212: "getDateHeader() not supported");
1213: }
1214:
1215: public String getHeader(String name) {
1216: // return null;
1217: // Call getRequestHeader().
1218: return getRequestHeader(name);
1219: }
1220:
1221: public Enumeration getHeaders(String name) {
1222: // return null;
1223: throw new UnsupportedOperationException(
1224: "getHeaders() not supported");
1225: }
1226:
1227: public Enumeration getHeaderNames() {
1228: // return null;
1229: throw new UnsupportedOperationException(
1230: "getHeaderNames() not supported");
1231: }
1232:
1233: public ServletInputStream getInputStream() {
1234: GatewayServletInputStream ret = new GatewayServletInputStream(
1235: _contentStream);
1236: return (ServletInputStream) ret;
1237: }
1238:
1239: public int getIntHeader(String name) {
1240: // return 0;
1241: throw new UnsupportedOperationException(
1242: "getIntHeader() not supported");
1243: }
1244:
1245: public java.util.Locale getLocale() {
1246: return null;
1247: }
1248:
1249: public Enumeration getLocales() {
1250: return null;
1251: }
1252:
1253: public String getParameter(String name) {
1254: return null;
1255: }
1256:
1257: public Enumeration getParameterNames() {
1258: return null;
1259: }
1260:
1261: public String[] getParameterValues(String name) {
1262: return null;
1263: }
1264:
1265: public String getPathInfo() {
1266: // return null;
1267: throw new UnsupportedOperationException(
1268: "getPathInfo() not supported");
1269: }
1270:
1271: public String getPathTranslated() {
1272: // return null;
1273: throw new UnsupportedOperationException(
1274: "getPathTranslated() not supported");
1275: }
1276:
1277: public String getQueryString() {
1278: // return null;
1279: throw new UnsupportedOperationException(
1280: "getQueryString() not supported");
1281: }
1282:
1283: public BufferedReader getReader() {
1284: return null;
1285: }
1286:
1287: /*
1288: * @deprecated
1289: */
1290: public String getRealPath(String name) {
1291: return null;
1292: }
1293:
1294: public String getRemoteAddr() {
1295: return null;
1296: }
1297:
1298: public String getRemoteHost() {
1299: return null;
1300: }
1301:
1302: public String getRemoteUser() {
1303: // return null;
1304: throw new UnsupportedOperationException(
1305: "getRemoteUser() not supported");
1306: }
1307:
1308: public javax.servlet.RequestDispatcher getRequestDispatcher(String s) {
1309: return null;
1310: }
1311:
1312: public String getRequestedSessionId() {
1313: // return null;
1314: throw new UnsupportedOperationException(
1315: "getRequestedSessionId() not supported");
1316: }
1317:
1318: public String getRequestURI() {
1319: // return null;
1320: throw new UnsupportedOperationException(
1321: "getRequestURI() not supported");
1322: }
1323:
1324: public String getScheme() {
1325: return null;
1326: }
1327:
1328: public String getServerName() {
1329: return null;
1330: }
1331:
1332: public int getServerPort() {
1333: return 0;
1334: }
1335:
1336: public String getServletPath() {
1337: // return null;
1338: throw new UnsupportedOperationException(
1339: "getServletPath() not supported");
1340: }
1341:
1342: public HttpSession getSession() {
1343: // return null;
1344: throw new UnsupportedOperationException(
1345: "getSession() not supported");
1346: }
1347:
1348: public HttpSession getSession(boolean create) {
1349: // return null;
1350: throw new UnsupportedOperationException(
1351: "getSession() not supported");
1352: }
1353:
1354: public java.security.Principal getUserPrincipal() {
1355: return null;
1356: }
1357:
1358: public void removeAttribute(String name) {
1359: }
1360:
1361: public void setAttribute(String name, Object obj) {
1362: }
1363:
1364: public boolean isRequestedSessionIdFromCookie() {
1365: // return true;
1366: throw new UnsupportedOperationException(
1367: "isRequestedSessionIdFromCookie() not supported");
1368: }
1369:
1370: /*
1371: * @deprecated
1372: */
1373: public boolean isRequestedSessionIdFromUrl() {
1374: // return true;
1375: throw new UnsupportedOperationException(
1376: "isRequestedSessionIdFromUrl() not supported");
1377: }
1378:
1379: public boolean isRequestedSessionIdFromURL() {
1380: // return true;
1381: throw new UnsupportedOperationException(
1382: "isRequestedSessionIdFromURL() not supported");
1383: }
1384:
1385: public boolean isRequestedSessionIdValid() {
1386: // return true;
1387: throw new UnsupportedOperationException(
1388: "isRequestedSessionIdValid() not supported");
1389: }
1390:
1391: public boolean isSecure() {
1392: return false;
1393: }
1394:
1395: public boolean isUserInRole(String s) {
1396: return false;
1397: }
1398:
1399: // nag
1400: /*
1401: * public void setBase(String originalBase, OldHTMLTranslator translator) {
1402: *
1403: * if (!originalBase.endsWith("/")) { int lastSlash =
1404: * originalBase.lastIndexOf("/"); if (lastSlash == -1) return; originalBase =
1405: * originalBase.substring(0, lastSlash+1); }
1406: *
1407: * int start,end;
1408: *
1409: * start = originalBase.indexOf("//");
1410: *
1411: * if (start == -1) start = originalBase.indexOf(":/");
1412: *
1413: * if (start != -1) { // the base url is absolute _baseHref = originalBase; }
1414: * else { // even the base url is relative // use translateURL() to change
1415: * relative base url to absolute base url // but have to get rid of gateway
1416: * prefix String translatedBase = translator.translateURL(originalBase,
1417: * this, false, false); // need to take out the gateway prefix int a =
1418: * translatedBase.indexOf("//"); if (a == -1) a =
1419: * translatedBase.indexOf(":/"); int z = -1; if (a != -1) z =
1420: * translatedBase.indexOf('/', a+2); if (z != -1) _baseHref =
1421: * translatedBase.substring(z+1); else return;
1422: *
1423: * start = _baseHref.indexOf("//"); if (start == -1) start =
1424: * _baseHref.indexOf(":/"); if (start == -1) return; }
1425: *
1426: * end = _baseHref.indexOf('/',start+2); if (end != -1) { _baseObj =
1427: * _baseHref.substring(end); if (!_baseObj.endsWith("/")) _baseObj =
1428: * _baseObj + "/"; _baseUrlWithoutObj = _baseHref.substring(0,end); } else {
1429: * _baseUrlWithoutObj = _baseHref; } }
1430: *
1431: * public String getBaseHref() { return _baseHref; }
1432: *
1433: * public String getBaseObj() { return _baseObj; } public String
1434: * getBaseUrlWithoutObj() { return _baseUrlWithoutObj; }
1435: */
1436:
1437: /*
1438: * To handle the MAP requirement. Idea is the following : If the gateway
1439: * scheme contains the Session Information , insert it as a Cookie so that
1440: * subsequent handling is transparent.
1441: */
1442: public String getGatewayURL() {
1443: // return gatewayURL;
1444: return encodedGatewayURL;
1445: }// getGatewayURL()
1446:
1447: public String getUnEncodedGatewayURL() {
1448: return gatewayURL;
1449: }
1450:
1451: // WebDAV Support
1452: public List getHeaderAttributeList(String header) {
1453: String s;
1454: int numElements = _headerLines.size();
1455: LinkedList list = new LinkedList();
1456: String tHeader;
1457: int indx;
1458:
1459: for (int i = 0; i < numElements; ++i) {
1460: s = _headerLines.get(i).toString();
1461: indx = s.indexOf(':');
1462: if (indx == -1) {
1463: continue;
1464: }
1465: tHeader = s.substring(0, indx).trim();
1466: // if (s.regionMatches(true, 0, header, 0, headerLength))
1467: if (tHeader.equalsIgnoreCase(header)) {
1468: list.addLast(s);
1469: }
1470: }
1471: return list;
1472: }
1473:
1474: public boolean removeHeader(String header) {
1475: boolean removed = false;
1476: String s;
1477: Iterator iter = _headerLines.iterator();
1478: header = header.trim().toLowerCase();
1479:
1480: String tHeader;
1481: int indx;
1482:
1483: while (iter.hasNext()) {
1484: s = iter.next().toString();
1485: indx = s.indexOf(':');
1486:
1487: if (indx == -1) {
1488: continue;
1489: }
1490: tHeader = s.substring(0, indx).trim();
1491: if (tHeader.equalsIgnoreCase(header)) {
1492: iter.remove();
1493: removed = true;
1494: }
1495: }
1496: _headerCache.remove(header);
1497: return removed;
1498: }
1499:
1500: /*
1501: * All the code that needs to be executed AFTER a request has been read 1)
1502: * Unrewrite Destination Header. 2) Unrewrite the IF header.
1503: */
1504: protected void requestPostReadProcessor() {
1505: parseUrlCookie();
1506: List ifHeaders = getHeaderAttributeList("If");
1507:
1508: if (ifHeaders.size() > 0) {
1509: removeHeader("If");
1510: // Now parse and add the new headers.
1511: List newList = new LinkedList();
1512: Iterator iter = ifHeaders.iterator();
1513: while (iter.hasNext()) {
1514: // Parser is supposed to strip off the crlf at end.
1515: String ifHeaderStr = iter.next().toString();
1516: try {
1517: newList.add(DavIf.parseIfHeader(ifHeaderStr,
1518: getGatewayURL(), true)
1519: + _crlf);
1520: } catch (ParseException pex) {
1521: newList.add(ifHeaderStr);
1522: }
1523: }
1524: iter = newList.iterator();
1525: while (iter.hasNext()) {
1526: addHeader("if", iter.next().toString());
1527: }
1528: }
1529:
1530: // Now parse the destination Header.
1531: String dest = getHeader("Destination");
1532:
1533: if (dest != null) {
1534: removeHeader("Destination");
1535: addHeader("Destination", "Destination: "
1536: + UnRewriter.unrewrite(dest.substring(
1537: dest.indexOf(':') + 1).trim()));
1538: }
1539: }
1540:
1541: /*
1542: * This method is to be called with _NO_ Session information encoded in the
1543: * gateway URL
1544: */
1545: public void setGatewayURL(String url) {
1546: gatewayURL = url;
1547: if (!gatewayURL.endsWith("/")) {
1548: gatewayURL = gatewayURL + "/";
1549: }
1550: if (urlSessionInfo != null) {
1551: encodedGatewayURL = new StringBuffer(gatewayURL).append(
1552: urlSessionInfo).append("/").toString();
1553: } else {
1554: encodedGatewayURL = gatewayURL;
1555: }
1556: }
1557:
1558: protected boolean isCookieSupported = true;
1559:
1560: // TODO - Do not hard code ??
1561: protected static final String SessionInURLDelimiter = "SessIDVal";
1562:
1563: protected static boolean forceURLSession = GatewayProfile
1564: .getBoolean("MapForceURLSession", false);
1565:
1566: public boolean isCookieSupported() {
1567: return isCookieSupported;
1568: }
1569:
1570: protected String removeAndGetSIDFromScheme() {
1571:
1572: String retval = "";
1573: if (_gwscheme == null || _gwscheme.length() == 0) {
1574: return retval;
1575: }
1576: int indx = _gwscheme.indexOf(SessionInURLDelimiter);
1577:
1578: if (indx == -1) {
1579: return retval;
1580: }
1581: // SessionInURLDelimiter present in URL.
1582: // Remove it.
1583: int indx1 = _gwscheme.indexOf('/', indx);
1584:
1585: if (indx != 0) {
1586: // skip trailing '/' from prev scheme.
1587: String prevscheme = _gwscheme;
1588: _gwscheme = prevscheme.substring(0, indx - 1);
1589: if (indx1 != -1) {
1590: // More than two schemes , one before SessionInURLDelimiter and
1591: // one
1592: // after it.
1593: _gwscheme += prevscheme.substring(indx1);
1594: retval = prevscheme.substring(indx, indx1);
1595: retval = retval.substring(
1596: SessionInURLDelimiter.length()).trim();
1597: } else {
1598: retval = prevscheme.substring(indx);
1599: retval = retval.substring(
1600: SessionInURLDelimiter.length()).trim();
1601: }
1602: } else {
1603: if (indx1 != -1 && indx1 < _gwscheme.length()) {
1604: // One or more schemes after SessionInURLDelimiter
1605: retval = _gwscheme.substring(0, indx1);
1606: retval = retval.substring(
1607: SessionInURLDelimiter.length()).trim();
1608: _gwscheme = _gwscheme.substring(indx1 + 1);
1609: } else {
1610: // No other scheme.
1611: retval = _gwscheme;
1612: retval = retval.substring(
1613: SessionInURLDelimiter.length()).trim();
1614: _gwscheme = "";
1615: }
1616: }
1617: return retval;
1618: }
1619:
1620: protected void parseUrlCookie() {
1621:
1622: if (!ServiceIdentifier.isGateway()) {
1623: // Only for gateway.
1624: return;
1625: }
1626:
1627: isCookieSupported = detectCookie() && !forceURLSession;
1628: // isCookieSupported = true;
1629:
1630: if (isCookieSupported) {
1631: // Strip the cookie info from the gateway scheme and ignore that
1632: // value.
1633: // We also do not act as a Cookie Manager for this client.
1634: // System.out.println("isCookieSupported");
1635: removeAndGetSIDFromScheme();
1636: return;
1637: }
1638:
1639: // logger.info("Cookies not Supported : forceURLSession : " +
1640: // forceURLSession);
1641: Object[] params9 = { new Boolean(forceURLSession) };
1642: logger.log(Level.INFO, "PSSRRPROXY_CSPRCONHNDLR054", params9);
1643:
1644: // Cookies not supported !!
1645: // Check if the SessionInURLDelimiter is present in the URL.
1646: // If it is present , replace it in the Cookie header.
1647: String ourSid = removeAndGetSIDFromScheme();
1648: // logger.info("removeAndGetSIDFromScheme : " + ourSid);
1649: Object[] params10 = { ourSid };
1650: logger.log(Level.INFO, "PSSRRPROXY_CSPRCONHNDLR055", params10);
1651:
1652: String sid = null;
1653:
1654: if (sid == null || sid.trim().length() == 0) {
1655: // Check if the session info is present in the URL itself.
1656: if (_url != null && _url.trim().length() > 0) {
1657: HttpServletRequest request = null;
1658: try {
1659: // TODO :: Call DSAME API here.
1660: SSOTokenManager manager = SSOTokenManager
1661: .getInstance();
1662: /*
1663: * Mridul - Not sure which request will be accepeted by
1664: * DSAME API.
1665: */
1666: request = new ServletHTTPRequest(this );
1667: /*
1668: * request.addHeaderLine( new StringBuffer()
1669: * .append(_method) .append(" ") .append(getURL()) .append(" ")
1670: * .append(_httpVersion) .append("\r\n") .toString());
1671: * request.addHeaderLine("\r\n");
1672: */
1673: // logger.info("Create SSOToken Dummy Servlet HTTP request :
1674: // " + request);
1675: Object[] params11 = { request };
1676: logger.log(Level.INFO,
1677: "PSSRRPROXY_CSPRCONHNDLR056", params11);
1678: // logger.info("***********************EOF Dummy
1679: // Request******************************");
1680: logger.info("PSSRRPROXY_CSPRCONHNDLR057");
1681: SSOToken token = manager.createSSOToken(request);
1682: sid = token.getTokenID().toString();
1683: sid = URLEncoder.encode(sid);
1684: // logger.info("Got SSoToken from Dummy Request: " + sid);
1685: Object[] params13 = { sid };
1686: logger.log(Level.INFO,
1687: "PSSRRPROXY_CSPRCONHNDLR058", params13);
1688: // Extra checks ....
1689: SSOUtil.getSSOToken(sid);
1690: } catch (Exception ex) {
1691: // logger.info("Failed Value for Dummy Request
1692: // ::::::::::::::" + request.getRequestURI());
1693: Object[] params14 = { request.getRequestURI() };
1694: logger.log(Level.INFO,
1695: "PSSRRPROXY_CSPRCONHNDLR059", params14);
1696: // logger.log(Level.SEVERE, "Exception while creating
1697: // SSOToken from URL .", ex);
1698: logger.log(Level.SEVERE,
1699: "PSSRRPROXY_CSPRCONHNDLR060", ex);
1700: }
1701: }
1702: }
1703: if (sid == null) {
1704: if (ourSid != null && ourSid.trim().length() > 0) {
1705: // logger.info("OurSid :::: " + ourSid);
1706: Object[] params16 = { ourSid };
1707: logger.log(Level.INFO, "PSSRRPROXY_CSPRCONHNDLR061",
1708: params16);
1709: sid = new String(Base64.decode(ourSid.getBytes()));
1710: }
1711: }
1712:
1713: // logger.info("sid : " + sid);
1714: Object[] params17 = { sid };
1715: logger.log(Level.INFO, "PSSRRPROXY_CSPRCONHNDLR062", params17);
1716: // logger.info("Cookie : " + getRequestHeader("Cookie"));
1717: Object[] params18 = { getRequestHeader("Cookie") };
1718: logger.log(Level.INFO, "PSSRRPROXY_CSPRCONHNDLR063", params18);
1719:
1720: if (sid != null && sid.length() > 0) {
1721: urlSessionInfo = new StringBuffer().append(
1722: SessionInURLDelimiter).append(Base64.encode(sid))
1723: .toString();
1724: encodedGatewayURL = new StringBuffer().append(gatewayURL)
1725: .append(urlSessionInfo).append("/").toString();
1726: // Base64 decode it.
1727: // sid = new String(Base64.decode(sid.getBytes()));
1728: // Insert this as a Cookie header.
1729: String cookie = getRequestHeader("Cookie");
1730: if (cookie != null && cookie.length() > 0) {
1731: // Remove trailing '\r\n'
1732: int cookieLen = cookie.length();
1733: if (cookie.charAt(cookieLen - 1) == '\r'
1734: || cookie.charAt(cookieLen - 1) == '\n') {
1735: cookie = cookie.substring(0, cookieLen - 1);
1736: cookieLen--;
1737: }
1738: if (cookie.charAt(cookieLen - 1) == '\r'
1739: || cookie.charAt(cookieLen - 1) == '\n') {
1740: cookie = cookie.substring(0, cookieLen - 1);
1741: cookieLen--;
1742: }
1743: // Is this header already present ?
1744: int indx = cookie.indexOf(_cookieName);
1745:
1746: while (indx != -1) {
1747: // Verify whether this is a Session Cookie.
1748: int indx1 = cookie.indexOf("=", indx + 1);
1749: if (indx1 == -1) {
1750: // This is not the Session cookie.
1751: indx = -1;
1752: } else {
1753: // Check whether this is a Session Cookie.
1754: if (!cookie.substring(indx, indx1).trim()
1755: .equals(_cookieName)) {
1756: // nope this is not the one.
1757: // Check for more offsets.
1758: indx = cookie
1759: .indexOf(_cookieName, indx + 1);
1760: } else {
1761: // This is the Session Cookie.
1762: break;
1763: }
1764: }
1765: }
1766: // logger.info("After loop indx : " + indx);
1767: Object[] params19 = { new Integer(indx) };
1768: logger.log(Level.INFO, "PSSRRPROXY_CSPRCONHNDLR064",
1769: params19);
1770: // logger.info("forceURLSession : " + forceURLSession);
1771: Object[] params20 = { new Boolean(forceURLSession) };
1772: logger.log(Level.INFO, "PSSRRPROXY_CSPRCONHNDLR065",
1773: params20);
1774: // logger.info("cookie : " + cookie);
1775: Object[] params21 = { cookie };
1776: logger.log(Level.INFO, "PSSRRPROXY_CSPRCONHNDLR066",
1777: params21);
1778: if (indx != -1) {
1779: if (forceURLSession) {
1780: // We give sid from URL more priority only if
1781: // forceURLSession is true.
1782: // else ignore the URL sid.
1783: StringBuffer sb = new StringBuffer();
1784: sb.append(cookie.substring(0, indx));
1785: sb.append(cookiePrefix);
1786: indx = cookie.indexOf(';', indx);
1787: sb.append(sid);
1788: if (indx != -1) {
1789: sb.append(cookie.substring(indx));
1790: }
1791: // Set the Cookie header to the sb.toString()
1792: setRequestHeader("Cookie", sb.toString());
1793: } else {
1794: // What do we do ?
1795: /*
1796: * Scenario : 1) forceURLSession has not been enabled 2)
1797: * CDM says cookies are not supported 3) We have a
1798: * cookie ! // For now just setting cookie supoprt to
1799: * true for this request.
1800: */
1801: // isCookieSupported = true;
1802: // logger.info("CDM says cookies not supported though we
1803: // found cookie in request !\n");
1804: Object[] params = { "\n" };
1805: logger.log(Level.INFO,
1806: "PSSRRPROXY_CSPRCONHNDLR067", params);
1807: // logger.info("Inserting Session Cookie anyway ...");
1808: logger.info("PSSRRPROXY_CSPRCONHNDLR068");
1809: StringBuffer sb = new StringBuffer();
1810: sb.append(cookie.substring(0, indx));
1811: sb.append(cookiePrefix);
1812: indx = cookie.indexOf(';', indx);
1813: sb.append(sid);
1814: if (indx != -1) {
1815: sb.append(cookie.substring(indx));
1816: }
1817: // Set the Cookie header to the sb.toString()
1818: setRequestHeader("Cookie", sb.toString());
1819: }
1820: } else {
1821: // Cookies found , but no Session Cookie - insert the
1822: // Session cookie here.
1823: StringBuffer sb = new StringBuffer().append(cookie);
1824: if (!cookie.trim().endsWith(";")) {
1825: sb.append(";");
1826: }
1827: sb.append(cookiePrefix).append(sid).append(_crlf)
1828: .toString();
1829: setRequestHeader("Cookie", sb.toString());
1830: }
1831: } else {
1832: // Add this as a new header.
1833: setRequestHeader("Cookie", new StringBuffer().append(
1834: "Cookie: ").append(cookiePrefix).append(sid)
1835: .append(_crlf).toString());
1836: }
1837: }
1838: // Add the new Cookies from the Cookie Manager.
1839: CookieManager.processCookies(this );
1840: // removeHeader("Cookie");
1841: }
1842:
1843: public void setSessionValue(String value) {
1844: if (value == null) {
1845: return;
1846: }
1847: // if (GatewayProfile.getBoolean("MapForceURLSession", false)) {
1848: urlSessionInfo = new StringBuffer().append(
1849: SessionInURLDelimiter).append(Base64.encode(value))
1850: .toString();
1851: encodedGatewayURL = new StringBuffer().append(gatewayURL)
1852: .append(urlSessionInfo).append("/").toString();
1853: // } else {
1854: // encodedGatewayURL = new StringBuffer().append(gatewayURL).toString();
1855: // }
1856: }
1857:
1858: // EOC : WebDAV Support
1859: /*
1860: * Converting url's of form http://user:passwd@host:port to HTTP
1861: * Authorization Header
1862: */
1863: private void addBasicAuthInfo(String user, String password) {
1864: addHeader("Authorization", "Authorization: Basic "
1865: + Base64.encode(user + ":" + password));
1866: }
1867:
1868: /*
1869: * @ returns the request accepted GW's Port
1870: */
1871:
1872: public int getGatewayPort() {
1873: try {
1874: URL gwURL = new URL(encodedGatewayURL);
1875: return gwURL.getPort();
1876: } catch (MalformedURLException mae) {
1877: // logger.log(Level.SEVERE, "Gateway Encoded URL throws
1878: // MalformedURLException" + encodedGatewayURL, mae);
1879: Object[] params24 = { encodedGatewayURL, mae };
1880: logger.log(Level.SEVERE, "PSSRRPROXY_CSPRCONHNDLR069",
1881: params24);
1882: }
1883: return -1;
1884: }
1885:
1886: /*
1887: * @ returns the request accepted GW's Protocol
1888: */
1889:
1890: public String getGatewayProtocol() {
1891: if (encodedGatewayURL.toLowerCase().startsWith("https")) {
1892: return "https";
1893: } else {
1894: return "http";
1895: }
1896: }
1897:
1898: /*
1899: * @ returns the request accepted GW's mode.
1900: */
1901:
1902: public boolean isGatewayProtocolSecure() {
1903: if (encodedGatewayURL.toLowerCase().startsWith("https")) {
1904: return true;
1905: } else {
1906: return false;
1907: }
1908: }
1909:
1910: /*
1911: * Detect Cookie based on CDM return type CDM returns either one of these
1912: * true - If Cookies are supported false - If cookies are not supported
1913: * autodetect - GW detects itself by checking the cookie header
1914: */
1915:
1916: private boolean detectCookie() {
1917: String cookieSupport = ClientDetector.isCookieSupported(this );
1918: if (cookieSupport.trim().toLowerCase().equals("false")) {
1919: return false;
1920: } else if (cookieSupport.trim().toLowerCase().equals("true")) {
1921: return true;
1922: } else {
1923: String s = getRequestHeader("Cookie");
1924: if (s == null) {
1925: return false;
1926: }
1927: return true;
1928: }
1929: }
1930:
1931: public boolean isForwardCookieHost() {
1932: return _forwardCookie;
1933: }
1934:
1935: private String stripPsScriptReferrer(String url) {
1936: int startIdx = url.indexOf("?psScriptReferrer=");
1937: if (startIdx == -1)
1938: return url;
1939:
1940: String result = "";
1941: result += url.substring(0, startIdx);
1942: int endIdx = url.indexOf(".END.");
1943: if (endIdx > -1) {
1944: result += url.substring(endIdx + 5);
1945: }
1946: return result;
1947: }
1948: }// class HTTPRequest
|