001: /*
002: * CookieManager.java
003: *
004: * Created on November 15, 2002, 2:28 PM
005: */
006:
007: package com.sun.portal.rproxy.connectionhandler;
008:
009: import java.util.Enumeration;
010: import java.util.Hashtable;
011: import java.util.Iterator;
012: import java.util.List;
013: import java.util.StringTokenizer;
014: import java.util.logging.Level;
015: import java.util.logging.Logger;
016:
017: import com.iplanet.sso.SSOException;
018: import com.iplanet.sso.SSOToken;
019: import com.sun.portal.log.common.PortalLogger;
020: import com.sun.portal.rproxy.configservlet.client.GatewayProfile;
021: import com.sun.portal.util.SSOUtil;
022: import com.sun.portal.util.ServiceIdentifier;
023:
024: /*
025: * @author Mridul Muralidharan
026: *
027: * @version
028: */
029: public class CookieManager {
030: // private static Logger logger =
031: // Logger.getLogger("com.sun.portal.sra.rproxy");
032: private static Logger logger = PortalLogger
033: .getLogger(CookieManager.class);
034:
035: /*
036: * private static final CookieManager cm = new CookieManager();
037: *
038: * private CookieManager() { }
039: */
040:
041: public static final boolean isCookieManager = GatewayProfile
042: .getBoolean("EnableCookieManager", true);
043:
044: private static final String sessionCookieName = com.iplanet.am.util.SystemProperties
045: .get("com.iplanet.am.cookie.name", "iPlanetDirectoryPro");
046:
047: private static final String SRAP_SET_COOKIE_PROPERTY = "internalSRAPSetCookieProperty";
048:
049: /*
050: * This is copy of HTTPRequest.getSessionID()
051: */
052: private static String getReqSessionCookie(Request req) {
053: String s = req.getRequestHeader("Cookie");
054: if (s == null) {
055: return null;
056: }
057:
058: String cookies = s.substring(s.indexOf(':') + 1);
059:
060: String result = null;
061: StringTokenizer st = new StringTokenizer(cookies, ";");
062: String curCookie;
063:
064: int indx;
065: while (st.hasMoreTokens() && result == null) {
066: curCookie = st.nextToken().trim();
067:
068: indx = curCookie.indexOf('=');
069: if (indx != -1
070: && curCookie.substring(0, indx).trim().equals(
071: sessionCookieName)) {
072: result = curCookie.substring(indx + 1).trim();
073: }
074: }
075: return result;
076: }
077:
078: /*
079: * Return the User Session either from the Request or (if this was the
080: * request that resulted in the User Session creation) the Response.
081: */
082: public static SSOToken getUserSession(Request req, HTTPResponse res) {
083:
084: String sessid = null;
085: SSOToken token = null;
086:
087: if (req instanceof HTTPRequest) {
088: sessid = ((HTTPRequest) req).getSessionID();
089: } else {
090: sessid = getReqSessionCookie(req);
091: }
092:
093: // logger.info("getUserSession :: sessid : " + sessid);
094: Object[] params0 = { sessid };
095: logger.log(Level.INFO, "PSSRRPROXY_CSPRCONHNDLR016", params0);
096:
097: if (sessid != null) {
098: try {
099: token = SSOUtil.getSSOToken(sessid);
100: // logger.info("Cookie Manager -> token " + token);
101: Object[] params1 = { token };
102: logger.log(Level.INFO, "PSSRRPROXY_CSPRCONHNDLR017",
103: params1);
104: } catch (Exception ex) {
105: token = null;
106: // Commenting the printStackTrace as this happens everytime
107: // during
108: // an unsucessful auth.
109: // ex.printStackTrace();
110: // logger.log(Level.SEVERE, "Cookie Manager -> Exception ", ex);
111: logger.log(Level.SEVERE, "PSSRRPROXY_CSPRCONHNDLR018",
112: ex);
113: }
114: }
115:
116: // logger.info("Cookie Manager -> token1 " + token);
117: Object[] params3 = { token };
118: logger.log(Level.INFO, "PSSRRPROXY_CSPRCONHNDLR019", params3);
119:
120: if (token != null) {
121: return token;
122: } else {
123: // logger.info("Cookie Manager -> Trying Response ");
124: logger.info("PSSRRPROXY_CSPRCONHNDLR020");
125: // Try getting this from the Response.
126: List list = res.getHeaderAttributeList("set-cookie");
127: Iterator iter = list.iterator();
128: String cookie;
129: String name;
130: int indx;
131:
132: sessid = null;
133:
134: while (iter.hasNext()) {
135: cookie = iter.next().toString();
136: indx = cookie.indexOf(':');
137:
138: if (indx != -1) {
139: cookie = cookie.substring(indx + 1).trim();
140:
141: indx = cookie.indexOf('=');
142: if (indx != -1) {
143: name = cookie.substring(0, indx).trim();
144: if (name.equals(sessionCookieName)) {
145: // Get the value.
146: int indx1 = cookie.indexOf(';', indx);
147: indx1 = indx1 == -1 ? cookie.length()
148: : indx1;
149: sessid = cookie.substring(indx + 1, indx1)
150: .trim();
151: break;
152: }
153: }
154: }
155: }
156:
157: if (sessid != null) {
158: try {
159: token = SSOUtil.getSSOToken(sessid);
160: } catch (Exception ex) {
161: token = null;
162: }
163: }
164: }
165:
166: if (token == null) {
167: // logger.info("Cookie Manager -> got SSOToken " + sessid);
168: Object[] params5 = { sessid };
169: logger.log(Level.INFO, "PSSRRPROXY_CSPRCONHNDLR021",
170: params5);
171: } else {
172: // logger.info("Cookie Manager -> DID NOT GET SSOToken " + sessid);
173: Object[] params6 = { sessid };
174: logger.log(Level.INFO, "PSSRRPROXY_CSPRCONHNDLR022",
175: params6);
176: }
177: return token;
178: }
179:
180: // There can be no Set-Cookies in any other type of responses
181: // since they all orginate from the gateway.
182: public static void processSetCookieHeaders(Request req,
183: HTTPResponse res) {
184:
185: List list = res.getHeaderAttributeList("set-cookie");
186: Iterator iter = list.iterator();
187: String cookie;
188: boolean sessionCookieDone = false;
189: boolean haveUserSession = false;
190: SSOToken ssotoken = null;
191: int indx, indx1;
192: boolean this SessionCookie;
193: String sessionValue;
194: CookieList cookieList = null;
195:
196: while (iter.hasNext()) {
197: cookie = iter.next().toString();
198: // Is this the Session cookie ?
199: indx = cookie.indexOf(sessionCookieName);
200: if (indx != -1) {
201: // Verify whether this is a Session Cookie.
202: this SessionCookie = false;
203: indx1 = cookie.indexOf("=", indx);
204:
205: if (indx1 != -1) {
206: if (cookie.substring(indx, indx1).trim().equals(
207: sessionCookieName)) {
208: // This is a session Cookie.
209: this SessionCookie = true;
210: }
211: }
212: if (this SessionCookie) {
213:
214: if (!sessionCookieDone) {
215: // Process this Session cookie.
216: // Get the cookie Value - which needs to be encoded in
217: // the URL.
218:
219: // indx1 starts at "= followed by value , ...".
220: sessionValue = null;
221: indx = cookie.indexOf(";", indx1 + 1);
222: if (indx == -1) {
223: indx = cookie.length();
224: }
225: sessionValue = cookie
226: .substring(indx1 + 1, indx).trim();
227: req.setSessionValue(sessionValue);
228: sessionCookieDone = true;
229: }
230: continue;
231: }
232: }
233: if (isCookieManager) {
234: // We have to become the cookie manager - hence store the
235: // cookie in user session.
236: if (!haveUserSession) {
237: ssotoken = getUserSession(req, res);
238:
239: if (ssotoken == null) {
240: // we cannot save cookies !
241: // logger.info("Cookie Manager unable to set Cookies :
242: // No valid Session.");
243: logger.info("PSSRRPROXY_CSPRCONHNDLR023");
244: // return ;
245: continue;
246: }
247: haveUserSession = true;
248: String savedCookies = null;
249: try {
250: savedCookies = ssotoken
251: .getProperty(SRAP_SET_COOKIE_PROPERTY);
252: } catch (Exception ex) {
253: // logger.log(Level.SEVERE, "Unable to get Cookie
254: // Manager properties", ex);
255: logger.log(Level.SEVERE,
256: "PSSRRPROXY_CSPRCONHNDLR024", ex);
257: // ex.printStackTrace();
258: }
259: if (savedCookies != null) {
260: cookieList = new CookieList(savedCookies);
261: // logger.info("Cookie Manager stored cookies : " +
262: // savedCookies);
263: Object[] params9 = { savedCookies };
264: logger.log(Level.INFO,
265: "PSSRRPROXY_CSPRCONHNDLR025", params9);
266: } else {
267: cookieList = new CookieList();
268: // logger.info("Cookie Manager properties -> no saved
269: // cookeis.");
270: logger.info("PSSRRPROXY_CSPRCONHNDLR026");
271: }
272: }
273: // Valid session exists , store cookie value in Session.
274: cookieList.processCookie(cookie, req.getHost());
275: }
276: }
277:
278: if (cookieList != null && cookieList.isModified()) {
279: // Set the property.
280: // logger.info("Cookie Manager : Saving cookies");
281: logger.info("PSSRRPROXY_CSPRCONHNDLR027");
282: try {
283: ssotoken.setProperty(SRAP_SET_COOKIE_PROPERTY,
284: cookieList.getEncodedValue());
285: } catch (SSOException ex) {
286: // logger.severe("Unable to set Cookie Manager properties");
287: logger.severe("PSSRRPROXY_CSPRCONHNDLR028");
288: }
289: } else {
290: if (cookieList != null) {
291: // logger.info("Cookie Manager : No modifications");
292: logger.info("PSSRRPROXY_CSPRCONHNDLR029");
293: } else {
294: // logger.info("Cookie Manager : cookieList == null !!");
295: logger.info("PSSRRPROXY_CSPRCONHNDLR030");
296: }
297: }
298: }
299:
300: public static void processCookies(Request req) {
301: // Add the cookies stored in the Session into the request.
302: // The Session cookie has already been processed when we come here.
303: if (!ServiceIdentifier.isGateway()) {
304: // Only for gateway.
305: return;
306: }
307: if (!CookieManager.isCookieManager) {
308: return;
309: }
310:
311: String session = req.getSessionID();
312:
313: SSOToken ssotoken = null;
314:
315: try {
316: ssotoken = SSOUtil.getSSOToken(session);
317: } catch (Exception ex) {
318: ssotoken = null;
319: }
320:
321: if (ssotoken == null) {
322: // logger.info("No session !!");
323: logger.info("PSSRRPROXY_CSPRCONHNDLR031");
324: // No Session.
325: return;
326: }
327:
328: // Cookies from the CookieManager take precedence.
329: String savedCookies = null;
330: try {
331: savedCookies = ssotoken
332: .getProperty(SRAP_SET_COOKIE_PROPERTY);
333: } catch (SSOException ex) {
334: // logger.severe("Unable to get Cookie Manager properties");
335: logger.severe("PSSRRPROXY_CSPRCONHNDLR032");
336: }
337: if (savedCookies == null || savedCookies.trim().length() == 0) {
338: // logger.info("savedCookies == !!" + savedCookies);
339: Object[] params17 = { savedCookies };
340: logger.log(Level.INFO, "PSSRRPROXY_CSPRCONHNDLR033",
341: params17);
342: return;
343: }
344:
345: CookieList cookieList = new CookieList(savedCookies);
346: if (cookieList.isModified()) {
347: // Save this back to User Session ('cos of Max-Age.)
348: try {
349: ssotoken.setProperty(SRAP_SET_COOKIE_PROPERTY,
350: cookieList.getEncodedValue());
351: } catch (SSOException ex) {
352: // logger.severe("Unable to set Cookie Manager properties");
353: logger.severe("PSSRRPROXY_CSPRCONHNDLR034");
354: }
355: }
356: Hashtable table = getCookiesAsHashtable(req
357: .getRequestHeader("Cookie"));
358: // logger.info("From Request : " + table);
359: Object[] params19 = { table };
360: logger.log(Level.INFO, "PSSRRPROXY_CSPRCONHNDLR035", params19);
361:
362: // Now process the cookies in cookieList stored in the User session.
363: if (processRequestCookieList(table, cookieList, req.getHost(),
364: req.getObject())) {
365: // Set the new Cookie header.
366: // logger.info("Cookie changed to " + table);
367: Object[] params20 = { table };
368: logger.log(Level.INFO, "PSSRRPROXY_CSPRCONHNDLR036",
369: params20);
370: Enumeration enumeration = table.elements();
371: StringBuffer sb = new StringBuffer().append("Cookie : ")
372: .append(enumeration.nextElement().toString());
373:
374: while (enumeration.hasMoreElements()) {
375: sb.append(" ; ").append(
376: enumeration.nextElement().toString());
377: }
378: req.setRequestHeader("Cookie", sb.toString());
379: } else {
380: // logger.info("No cookie change " + table);
381: Object[] params21 = { table };
382: logger.log(Level.INFO, "PSSRRPROXY_CSPRCONHNDLR037",
383: params21);
384: }
385: }
386:
387: private static boolean cookie_management = GatewayProfile
388: .getBoolean("CookieManagement", false)
389: && ServiceIdentifier.isGateway();
390:
391: /*
392: * Returns true if Cookie header needs to be changed ('cos of some
393: * CookieManager cookie).
394: */
395: private static boolean processRequestCookieList(Hashtable table,
396: CookieList cookieList, String host, String path) {
397:
398: // Replace any cookie from table which is defined in cookieList
399: // Add any required cookies from cookieList depending on the host
400: // to which this request is for.
401: boolean changed = false;
402:
403: if (cookieList == null || cookieList.length() == 0) {
404: // logger.info("processRequestCookieList :: cookieList : " +
405: // cookieList);
406: Object[] params22 = { cookieList };
407: logger.log(Level.INFO, "PSSRRPROXY_CSPRCONHNDLR038",
408: params22);
409: if (cookieList != null) {
410: // logger.info("processRequestCookieList :: cookieList length :
411: // " + cookieList.length());
412: Object[] params23 = { cookieList.length() + "" };
413: logger.log(Level.INFO, "PSSRRPROXY_CSPRCONHNDLR039",
414: params23);
415: }
416: return changed;
417: }
418:
419: if (cookie_management) {
420: // All cookies are added - To be parsed by HTTPRetriever.java
421: Enumeration enumeration = cookieList.enumerate();
422: InternalCookie cookie = null;
423:
424: while (enumeration.hasMoreElements()) {
425: cookie = (InternalCookie) enumeration.nextElement();
426: // logger.info("Cookie from Session : : " + cookie);
427: Object[] params24 = { cookie };
428: logger.log(Level.INFO, "PSSRRPROXY_CSPRCONHNDLR040",
429: params24);
430: table.put(cookie.getName(), cookie.getNameValue());
431: }
432: return true;
433: }
434:
435: if (host == null) {
436: // logger.info("processRequestCookieList :: host : " + host + "
437: // returning");
438: Object[] params25 = { host };
439: logger.log(Level.INFO, "PSSRRPROXY_CSPRCONHNDLR041",
440: params25);
441: return changed;
442: }
443:
444: host = host.trim().toLowerCase();
445: if (path != null) {
446: path = path.trim();
447: }
448:
449: Enumeration enumeration = cookieList.enumerate();
450: InternalCookie cookie = null;
451:
452: String cdomain;
453: String cpath;
454: String chost;
455:
456: boolean checkPath;
457:
458: while (enumeration.hasMoreElements()) {
459: cookie = (InternalCookie) enumeration.nextElement();
460: // logger.info("Cookie from Session : : " + cookie);
461: Object[] params26 = { cookie };
462: logger.log(Level.INFO, "PSSRRPROXY_CSPRCONHNDLR042",
463: params26);
464:
465: // Decide whether this has to be inserted into the Cookie Header.
466: checkPath = false;
467:
468: cdomain = cookie.getDomain();
469:
470: // logger.info("Cookie domain : " + cdomain);
471: Object[] params27 = { cdomain };
472: logger.log(Level.INFO, "PSSRRPROXY_CSPRCONHNDLR043",
473: params27);
474: // logger.info("Cookie domain : " + cookie.getPath());
475: Object[] params28 = { cookie.getPath() };
476: logger.log(Level.INFO, "PSSRRPROXY_CSPRCONHNDLR044",
477: params28);
478:
479: if (cdomain == null) {
480: // Process this based on the Host.
481: if (host.equalsIgnoreCase(cookie.getHost())) {
482: checkPath = true;
483: }
484: } else {
485: cdomain = cdomain.trim().toLowerCase();
486: if (host.endsWith(cdomain)) {
487: checkPath = true;
488: }
489: }
490:
491: if (checkPath) {
492: // domain / host test passed , now try the path.
493: cpath = cookie.getPath();
494:
495: if (cpath == null) {
496: // No path specified : add.
497: table.put(cookie.getName(), cookie.getNameValue());
498: changed = true;
499: } else {
500: if (path.startsWith(cpath.trim())) {
501: // Path check passed.
502: table.put(cookie.getName(), cookie
503: .getNameValue());
504: changed = true;
505: }
506: }
507: }
508: }
509: return changed;
510: }
511:
512: private static Hashtable getCookiesAsHashtable(String cookieHeader) {
513:
514: Hashtable retval = new Hashtable();
515: if (cookieHeader == null || cookieHeader.trim().length() == 0) {
516: return retval;
517: }
518: // Strip the Cookie: from the header.
519: int indx = cookieHeader.indexOf(':');
520:
521: if (indx == -1) {
522: return retval;
523: }
524: cookieHeader = cookieHeader.substring(indx + 1).trim();
525:
526: // Now string tokenize this based on ';' and add to Hashtable.
527: StringTokenizer st = new StringTokenizer(cookieHeader, ";");
528: String cookie;
529: while (st.hasMoreTokens()) {
530: cookie = st.nextToken();
531:
532: indx = cookie.indexOf('=');
533:
534: if (indx != -1) {
535: retval.put(cookie.substring(0, indx).trim(), cookie);
536: }
537: // else ignore this.
538: }
539: return retval;
540: }
541: }
|