Source Code Cross Referenced for Session.java in  » Portal » Open-Portal » com » sun » portal » rproxy » connectionhandler » Java Source Code / Java DocumentationJava Source Code and Java Documentation

Java Source Code / Java Documentation
1. 6.0 JDK Core
2. 6.0 JDK Modules
3. 6.0 JDK Modules com.sun
4. 6.0 JDK Modules com.sun.java
5. 6.0 JDK Modules sun
6. 6.0 JDK Platform
7. Ajax
8. Apache Harmony Java SE
9. Aspect oriented
10. Authentication Authorization
11. Blogger System
12. Build
13. Byte Code
14. Cache
15. Chart
16. Chat
17. Code Analyzer
18. Collaboration
19. Content Management System
20. Database Client
21. Database DBMS
22. Database JDBC Connection Pool
23. Database ORM
24. Development
25. EJB Server geronimo
26. EJB Server GlassFish
27. EJB Server JBoss 4.2.1
28. EJB Server resin 3.1.5
29. ERP CRM Financial
30. ESB
31. Forum
32. GIS
33. Graphic Library
34. Groupware
35. HTML Parser
36. IDE
37. IDE Eclipse
38. IDE Netbeans
39. Installer
40. Internationalization Localization
41. Inversion of Control
42. Issue Tracking
43. J2EE
44. JBoss
45. JMS
46. JMX
47. Library
48. Mail Clients
49. Net
50. Parser
51. PDF
52. Portal
53. Profiler
54. Project Management
55. Report
56. RSS RDF
57. Rule Engine
58. Science
59. Scripting
60. Search Engine
61. Security
62. Sevlet Container
63. Source Control
64. Swing Library
65. Template Engine
66. Test Coverage
67. Testing
68. UML
69. Web Crawler
70. Web Framework
71. Web Mail
72. Web Server
73. Web Services
74. Web Services apache cxf 2.0.1
75. Web Services AXIS2
76. Wiki Engine
77. Workflow Engines
78. XML
79. XML UI
Java
Java Tutorial
Java Open Source
Jar File Download
Java Articles
Java Products
Java by API
Photoshop Tutorials
Maya Tutorials
Flash Tutorials
3ds-Max Tutorials
Illustrator Tutorials
GIMP Tutorials
C# / C Sharp
C# / CSharp Tutorial
C# / CSharp Open Source
ASP.Net
ASP.NET Tutorial
JavaScript DHTML
JavaScript Tutorial
JavaScript Reference
HTML / CSS
HTML CSS Reference
C / ANSI-C
C Tutorial
C++
C++ Tutorial
Ruby
PHP
Python
Python Tutorial
Python Open Source
SQL Server / T-SQL
SQL Server / T-SQL Tutorial
Oracle PL / SQL
Oracle PL/SQL Tutorial
PostgreSQL
SQL / MySQL
MySQL Tutorial
VB.Net
VB.Net Tutorial
Flash / Flex / ActionScript
VBA / Excel / Access / Word
XML
XML Tutorial
Microsoft Office PowerPoint 2007 Tutorial
Microsoft Office Excel 2007 Tutorial
Microsoft Office Word 2007 Tutorial
Java Source Code / Java Documentation » Portal » Open Portal » com.sun.portal.rproxy.connectionhandler 
Source Cross Referenced  Class Diagram Java Document (Java Doc) 


0001:        /*
0002:         * Session.java
0003:         * Copyright (c) 1998 Sun Microsystems, Inc. All Rights Reserved.
0004:         *
0005:         * Developed by SunPS and SunIR
0006:         */
0007:
0008:        package com.sun.portal.rproxy.connectionhandler;
0009:
0010:        import java.io.BufferedInputStream;
0011:        import java.io.DataOutputStream;
0012:        import java.io.FileOutputStream;
0013:        import java.io.IOException;
0014:        import java.io.InputStream;
0015:        import java.io.OutputStream;
0016:        import java.net.MalformedURLException;
0017:        import java.net.Socket;
0018:        import java.net.URL;
0019:        import java.net.URLEncoder;
0020:        import java.net.URLDecoder;
0021:        import java.util.ArrayList;
0022:        import java.util.HashMap;
0023:        import java.util.Iterator;
0024:        import java.util.LinkedList;
0025:        import java.util.List;
0026:        import java.util.Set;
0027:        import java.util.StringTokenizer;
0028:        import java.util.logging.FileHandler;
0029:        import java.util.logging.Level;
0030:        import java.util.logging.Logger;
0031:
0032:        import javax.servlet.http.HttpServletRequest;
0033:        import javax.servlet.http.HttpServletResponse;
0034:
0035:        import org.mozilla.jss.ssl.SSLSocket;
0036:
0037:        import com.iplanet.services.comm.client.PLLNotificationServlet;
0038:        import com.iplanet.sso.SSOException;
0039:        import com.iplanet.sso.SSOToken;
0040:        import com.iplanet.sso.SSOTokenManager;
0041:        import com.sun.portal.cli.cert.JSSUtil;
0042:        import com.sun.portal.log.common.PortalLogger;
0043:        import com.sun.portal.rproxy.configservlet.client.GatewayProfile;
0044:        import com.sun.portal.rproxy.configservlet.client.PlatformProfile;
0045:        import com.sun.portal.rproxy.configservlet.client.SrapClient;
0046:        import com.sun.portal.rproxy.configservlet.client.UserProfile;
0047:        import com.sun.portal.rproxy.monitoring.MonitoringSubsystem;
0048:        import com.sun.portal.rproxy.monitoring.util.RProxyEvent;
0049:        import com.sun.portal.rproxy.rewriter.SRAPAdapter;
0050:        import com.sun.portal.rproxy.rewriter.SRAPTranslatorHelper;
0051:        import com.sun.portal.util.DomainWebProxyConfig;
0052:        import com.sun.portal.util.GWDebug;
0053:        import com.sun.portal.util.GWLocale;
0054:        import com.sun.portal.util.GWLogManager;
0055:        import com.sun.portal.util.LogInfoContainer;
0056:        import com.sun.portal.util.SRAEvent;
0057:        import com.sun.portal.util.SRAPSocket;
0058:        import com.sun.portal.util.SSOUtil;
0059:        import com.sun.portal.util.ServersList;
0060:        import com.sun.portal.util.ServiceIdentifier;
0061:        import com.sun.portal.util.SystemProperties;
0062:
0063:        /**
0064:         * This class processes the next request and sends a response back to the
0065:         * client.
0066:         *
0067:         * @author Gabriel Lawrence
0068:         */
0069:
0070:        public abstract class Session {
0071:
0072:            protected Socket _theSocket;
0073:
0074:            protected boolean _moreElements = true;
0075:
0076:            protected Integer _logId;
0077:
0078:            protected static String _platformloginURL;
0079:
0080:            protected static String _platformlogoutURL;
0081:
0082:            protected static boolean _useHTTPProxy;
0083:
0084:            protected static String _hpport;
0085:
0086:            // private static Logger logger =
0087:            // Logger.getLogger("com.sun.portal.sra.rproxy");
0088:            private static Logger logger = PortalLogger
0089:                    .getLogger(Session.class);
0090:
0091:            /**
0092:             * Changes to accomodate DSAME pdc support. Bug : 4670649
0093:             */
0094:
0095:            protected static String rphost;
0096:
0097:            protected static List srapGateway_certificateEnabledList_lc = GatewayProfile
0098:                    .getLowerCaseStringList("CertificateEnabledList");
0099:
0100:            // End of code change for bug : 4670649
0101:
0102:            private static List virtualHost = new ArrayList();
0103:
0104:            private static List virtualHostActual = new ArrayList();
0105:
0106:            private static List nonAuthPathList = GatewayProfile
0107:                    .getLowerCaseURLList("NonAuthenticatedURLPath");
0108:
0109:            // Lihue : 4.5
0110:            protected String _gwport;
0111:
0112:            protected String _gwprotocol;
0113:
0114:            protected int port;
0115:
0116:            // EOC :: Lihue : 4.5
0117:            private static int _numRequests = 0;
0118:
0119:            public static int _numBytesRead = 0;
0120:
0121:            public static int _numBytesSent = 0;
0122:
0123:            private final static String UNKNOWN_HOST = "Unknown Host";
0124:
0125:            private static Logger serverTraffic;
0126:
0127:            private static Logger browserTraffic;
0128:
0129:            // private static Hashtable resp_delay;
0130:
0131:            // Lihue PRD : 8.2
0132:            static final String defaultLocale;
0133:
0134:            static final String exceptionErrorMessage = "ExceptionErrorMessage";
0135:
0136:            static final String notificationErrorMessage = "NotificationErrorMessage";
0137:
0138:            static final String invalidGatewayHostNameErrorMessage = "InvalidGatewayHostNameErrorMessage";
0139:
0140:            static final String accessDeniedErrorMessage = "AccessDeniedErrorMessage";
0141:
0142:            static final String webProxErrorMessage = "WebProxErrorMessage";
0143:
0144:            static final String hostConnectErrorMessage = "HostConnectErrorMessage";
0145:
0146:            // End of Code - Lihue PRD : 8.2
0147:
0148:            // Lihue PRD : 7.4.4.1
0149:            private static final boolean isPerSessionLoggingEnabled;
0150:
0151:            // Bug ID - # 4195483
0152:            private static final boolean detailedRproxLog;
0153:
0154:            // End of Code : Bug ID - # 4195483
0155:            private Socket actualClientSocket = null;
0156:
0157:            private Socket nonsslsocket = null;
0158:
0159:            // EOC :: Lihue PRD : # 7.4.4.1
0160:
0161:            // Lihue - keepAlive
0162:            private static final int DEFAULT_TIMEOUT = 1000 * 60;
0163:
0164:            protected final int readTimeout = GatewayProfile.getInt(
0165:                    "RProxyPortTimeout", DEFAULT_TIMEOUT) * 1000;
0166:
0167:            protected int this _req = 0;
0168:
0169:            // public 'cos Used in RWGroupClear and ReaderWriterClear
0170:            // Only in Gateway , and not in any other part like proxy
0171:            //protected static final boolean processKeepAliveConnections =
0172:            public static final boolean processKeepAliveConnections = GatewayProfile
0173:                    .getBoolean("EProxyDoKeepAlive", true)
0174:                    && ServiceIdentifier.isGateway();
0175:
0176:            // The max time between persistent requests.
0177:            // specified in secs
0178:            private static final int timeoutseconds = GatewayProfile.getInt(
0179:                    "EProxyKeepAliveConnectionTimeout", 50);
0180:
0181:            // Grace time over and above the max time between persistent requests
0182:            // before the socket is actually closed
0183:            // Mainly for n/w delays - specified in secs
0184:            public static final int GRACE_PERIOD = GatewayProfile.getInt(
0185:                    "EProxyKeepAliveConnectionGraceTimeout", 20);
0186:
0187:            // In millisecs
0188:            public static final long maxTimeOutSetting = (long) (timeoutseconds + GRACE_PERIOD) * 1000;
0189:
0190:            // Maximum number of requests per socket - admin configurale
0191:            // option for admin to restrict / control socket use.
0192:            private int MAX_PER_SESS = GatewayProfile.getInt(
0193:                    "EProxyKeepAliveMaxConnection", 10);
0194:
0195:            // In case of null requests/ noo requests , the time the thread
0196:            // suspends itself
0197:            // should this be configurable ??
0198:            public static final long THREAD_SLEEP_TIME = 50;
0199:
0200:            // Timeout to use with null requests
0201:            private long nullTimeout = maxTimeOutSetting;
0202:
0203:            protected boolean this reqKeepAlive = processKeepAliveConnections;
0204:
0205:            // End of Code : Lihue - keepAlive
0206:            /**
0207:             * Changes to accomodate DSAME pdc support. Bug : 4670649
0208:             */
0209:            public static boolean doingPDC;
0210:
0211:            static final String defDomain = GatewayProfile.getString(
0212:                    "DefaultDomainAndSubdomains", "");
0213:
0214:            static final String sessionCookieName = com.iplanet.am.util.SystemProperties
0215:                    .get("com.iplanet.am.cookie.name", "iPlanetDirectoryPro");
0216:
0217:            static final int sessionCookieLen = sessionCookieName.length();
0218:
0219:            static final String pdcCookieName = "PDCCookie";
0220:
0221:            static final String authCookieName = com.iplanet.am.util.SystemProperties
0222:                    .get("com.sun.identity.auth.cookieName", "AMAuthCookie");
0223:
0224:            private static List ignoreURIList = new ArrayList();
0225:
0226:            /**
0227:             * Bug 4696175
0228:             */
0229:            protected static String defaultOrg = com.iplanet.am.util.SystemProperties
0230:                    .get("com.iplanet.am.defaultOrg", defDomain);
0231:            // End of code change for bug : 4670649
0232:
0233:            // End of code change for bug : 4670649
0234:            /*
0235:             * PRD 3.7 (4338513) Authentication chaining will work with Certificate
0236:             * authentication. In the previous implementation authentication chaining
0237:             * was not supported. If the PDC is enabled and the chaining is also
0238:             * enabled, every time the user will be redirected to the login page and the
0239:             * session ssl was getting invalidated. This was also resulting in the
0240:             * Netscape crashing. As part of lihue this problem has been resolved.
0241:             */
0242:            protected boolean pdcCookiePresent;
0243:
0244:            protected boolean invalidateSSL;
0245:
0246:            private static String gwDomain = null;
0247:
0248:            private final static String PDC_COOKIE_HEADER = "DoPDC@LOGOUT";
0249:
0250:            private static List serverList = GatewayProfile
0251:                    .getLowerCaseStringList("PortalServerList");
0252:
0253:            public final static String notificationURL;
0254:
0255:            private final static String REWRITER_PROXY = "__sra_rewriter_proxy__";
0256:
0257:            //End of code change for PRD 3.7
0258:
0259:            private static HashMap virtualHostOrgMapping;
0260:
0261:            //Fix for encoding CertInfo into the Session
0262:            public static final String PDC_CERT_INFO = "__sra_pdc_cert__";
0263:
0264:            static {
0265:
0266:                notificationURL = System.getProperty(
0267:                        "gateway.notification.url", "notification");
0268:
0269:                // Lihue PRD : 7.4.4.1
0270:                isPerSessionLoggingEnabled = GatewayProfile.getBoolean(
0271:                        "EProxyPerSessionLogging", false)
0272:                        && ServiceIdentifier.isGateway();
0273:                // Bug ID - # 4195483
0274:                detailedRproxLog = GatewayProfile.getBoolean(
0275:                        "EProxyDetailedPerSessionLogging", false);
0276:                // End of Code : Bug ID - # 4195483
0277:
0278:                // Lihue PRD : 8.2
0279:                defaultLocale = GatewayProfile.getString("locale", "en_US");
0280:                // End of Code - Lihue PRD : 8.2
0281:
0282:                browserTraffic = Logger
0283:                        .getLogger("debug.com.sun.portal.sra.rproxy.toFromBrowser");
0284:                serverTraffic = Logger
0285:                        .getLogger("debug.com.sun.portal.sra.rproxy.toFromServer");
0286:
0287:                // Read the properties and set up an XMLFormatter based logging file for the 
0288:                // traffic between the browser and the gateway and one for the traffic between
0289:                // gateway and the destination server.
0290:                try {
0291:                    int limit = Integer
0292:                            .parseInt(SystemProperties
0293:                                    .get("debug.com.sun.portal.handler.java.util.logging.FileHandler.limit"));
0294:                    int count = Integer
0295:                            .parseInt(SystemProperties
0296:                                    .get("debug.com.sun.portal.handler.java.util.logging.FileHandler.count"));
0297:                    Boolean append = new Boolean(
0298:                            SystemProperties
0299:                                    .get("debug.com.sun.portal.handler.java.util.logging.FileHandler.append"));
0300:
0301:                    String logFilePattern = SystemProperties
0302:                            .get("debug.com.sun.portal.sra.rproxy.toFromBrowser.handler.java.util.logging.FileHandler.pattern");
0303:                    browserTraffic.addHandler(new FileHandler(logFilePattern,
0304:                            limit, count, append.booleanValue()));
0305:
0306:                    logFilePattern = SystemProperties
0307:                            .get("debug.com.sun.portal.sra.rproxy.toFromServer.handler.java.util.logging.FileHandler.pattern");
0308:                    serverTraffic.addHandler(new FileHandler(logFilePattern,
0309:                            limit, count, append.booleanValue()));
0310:                } catch (SecurityException e) {
0311:                    logger.log(Level.SEVERE, "PSSRRPROXY_CSPRCONHNDLR187", e);
0312:                    e.printStackTrace();
0313:                } catch (Exception e) {
0314:                    logger.log(Level.SEVERE, "PSSRRPROXY_CSPRCONHNDLR187", e);
0315:                    e.printStackTrace();
0316:                }
0317:
0318:                rphost = SystemProperties.get("gateway.host", null);
0319:                setVirtualHostname();
0320:                populateVirtualHostDefaultOrgMapping();
0321:
0322:                _useHTTPProxy = GatewayProfile
0323:                        .getBoolean("UseHTTPProxy", false)
0324:                        && ServiceIdentifier.isGateway();
0325:
0326:                setupUrlsToIgnoreList();
0327:
0328:                _hpport = GatewayProfile.getString("HTTPProxyPort", "10443");
0329:
0330:                _platformloginURL = PlatformProfile.getString("login-url", "");
0331:                _platformlogoutURL = PlatformProfile
0332:                        .getString("logout-url", "");
0333:
0334:                //Obtain a list of Identity Servers from PlatformService
0335:                List platformServers = ServersList.getAMServerList();
0336:
0337:                Iterator serversIt = platformServers.iterator();
0338:
0339:                String isURL;
0340:                // Add the absolute URLs of "/amserver/UI/Login" to non-auth List
0341:
0342:                while (serversIt.hasNext()) {
0343:
0344:                    isURL = (String) serversIt.next();
0345:                    int pipeIndex = isURL.indexOf("|");
0346:                    if (pipeIndex > -1) {
0347:                        isURL = isURL.substring(0, pipeIndex);
0348:                    }
0349:                    //System.out.println("Adding " + isURL + "/amserver/LoginLogout etc etc");
0350:
0351:                    nonAuthPathList.add(isURL + _platformloginURL);
0352:                    nonAuthPathList.add(isURL + _platformlogoutURL);
0353:                }
0354:                nonAuthPathList.add(_platformloginURL);
0355:                nonAuthPathList.add(_platformlogoutURL);
0356:
0357:                /*
0358:                 * PRD 3.7 (4338513) Authentication chaining will work with Certificate
0359:                 * authentication. Getting the domain of the gateway.
0360:                 */
0361:                int index = rphost.indexOf('.');
0362:                if (index != -1) {
0363:                    gwDomain = rphost.substring(index);
0364:                } else {
0365:                    gwDomain = null;
0366:                }
0367:                // End of code change for PRD 3.7
0368:            }
0369:
0370:            /*
0371:             * The _servers set of SessionServers contains the session server URL's in
0372:             * the complete form as in with both protocol and port. For the purpose of
0373:             * fixing the perf goto bug , we need the list of all servers with both port
0374:             * and without port - in case it is default for the protocol. For this we
0375:             * have this list. This could be best considered a hack : too late into the
0376:             * rtm cycle to properly design a fix :-( - Mridul
0377:             */
0378:            static List expandedSessionServersList = null;
0379:
0380:            static {
0381:                expandedSessionServersList = new LinkedList();
0382:
0383:                Set sessionServers = ServersList.getAllSessionServersSet();
0384:                URL tmpUrl = null;
0385:                String tmpStr = null;
0386:                Iterator iter = sessionServers.iterator();
0387:
0388:                while (iter.hasNext()) {
0389:                    try {
0390:                        tmpStr = iter.next().toString();
0391:                        tmpUrl = new URL(tmpStr);
0392:
0393:                        expandedSessionServersList.add(tmpUrl.getProtocol()
0394:                                + "://" + tmpUrl.getHost() + ":"
0395:                                + tmpUrl.getPort());
0396:
0397:                        if ((tmpUrl.getProtocol().equalsIgnoreCase("http") && tmpUrl
0398:                                .getPort() == 80)
0399:                                || (tmpUrl.getProtocol().equalsIgnoreCase(
0400:                                        "https") && tmpUrl.getPort() == 443)) {
0401:                            expandedSessionServersList.add(tmpUrl.getProtocol()
0402:                                    + "://" + tmpUrl.getHost());
0403:                        }
0404:                    } catch (Exception ex) {
0405:                        // logger.log(Level.SEVERE, "Exception while parsing entry " +
0406:                        // tmpStr, ex);
0407:                        Object[] params0 = { tmpStr, ex };
0408:                        logger.log(Level.SEVERE, "PSSRRPROXY_CSPRCONHNDLR124",
0409:                                params0);
0410:                    }
0411:                }
0412:            }
0413:
0414:            /**
0415:             * Create a Session from a socket
0416:             */
0417:            // Lihue PRD : # 7.4.4.1
0418:            //public Session(Socket s, Integer logId) {
0419:            public Session(Socket s) {
0420:                _theSocket = s;
0421:                getLoggingInfo();
0422:                // EOC :: Lihue PRD : # 7.4.4.1
0423:            }
0424:
0425:            /*
0426:             * Problem : When using IE on XP, with Office, and discussions enabled, the
0427:             * gateway incorrectly authenticates to the wrong organization.
0428:             * 
0429:             * Reason: With discussion enabled, IE sends some extra info added to the gateway
0430:             * URL. i.e the request comes in as https://GW/ctlreq.asp
0431:             * Gateway assumes them as org and tries to do authentication with the newly
0432:             * created org.
0433:             * 
0434:             * Solution: Ignore these extra URLs send by the browser. The fix has been
0435:             * made in a way the list of URLs to be ignored is configurable. A new
0436:             * parameter gateway.ignoreURIList is included in the gateway.conf.
0437:             * 
0438:             * --- Sandeep Soni ( ss150821 )
0439:             */
0440:            private static void setupUrlsToIgnoreList() {
0441:                String uriList = SystemProperties.get("gateway.ignoreURIList");
0442:
0443:                if (uriList != null) {
0444:                    StringTokenizer strTok = new StringTokenizer(uriList, ",");
0445:                    while (strTok.hasMoreTokens())
0446:                        ignoreURIList.add(strTok.nextToken().trim());
0447:                }
0448:            }
0449:
0450:            private boolean shouldIgnoreURI(String s) {
0451:                for (int i = 0; i < ignoreURIList.size(); i++) {
0452:                    if (s.startsWith((String) ignoreURIList.get(i)))
0453:                        return true;
0454:                }
0455:                return false;
0456:            }
0457:
0458:            // Lihue PRD : # 7.4.4.1
0459:            //public Session(Socket s, Integer logId, String ip) {
0460:            public Session(Socket s, String ip) {
0461:                _theSocket = s;
0462:                getLoggingInfo();
0463:                // EOC :: Lihue PRD : # 7.4.4.1
0464:            }
0465:
0466:            // Lihue PRD : # 7.4.4.1
0467:            private void getLoggingInfo() {
0468:                //if (GWLogManager.loggingEnabled) {
0469:                Object tmp = GWLogManager.logIdMap.remove(new Integer(
0470:                        _theSocket.getPort()));
0471:                if (tmp != null) {
0472:                    LogInfoContainer info = (LogInfoContainer) tmp;
0473:                    _logId = info.getLogID();
0474:                    actualClientSocket = info.getClientSocket();
0475:                }
0476:
0477:                String unqID = actualClientSocket.getPort() + "_" + "A";
0478:                Object tmp_1 = GWLogManager.logIdMap.remove(unqID);
0479:                if (tmp_1 != null) {
0480:                    LogInfoContainer info = (LogInfoContainer) tmp_1;
0481:                    nonsslsocket = (Socket) info.getClientSocket();
0482:                }
0483:
0484:                //}
0485:            }
0486:
0487:            // EOC :: Lihue PRD : # 7.4.4.1
0488:
0489:            /**
0490:             * Check to see if a session is still active
0491:             */
0492:            public boolean isStillActive() {
0493:                return _moreElements;
0494:            }
0495:
0496:            /**
0497:             * Set Active state of a session
0498:             */
0499:            public void setStillActive(boolean v) {
0500:                _moreElements = v;
0501:            }
0502:
0503:            private static final String pdcHeaderKey = "PS-GW-PDC";
0504:
0505:            private static final String netletHeaderKey = "PS-Netlet";
0506:
0507:            private static final String proxyletHeaderKey = "PS-Proxylet";
0508:
0509:            private static String clientIPHeaderKey = "PS-GW-ClientIP";
0510:
0511:            private static String gatewayURLInfoHeaderKey = "PS-GW-URL";
0512:
0513:            private static String gatewayInstanceHeaderKey = "PS-GW-Instance";
0514:
0515:            private static String gatewayRWURLInfoHeaderKey = "PS-GW-Rewriting-URL";
0516:
0517:            public void addNetletCustomHeader(Request req) {
0518:                StringBuffer netletHeaderValue = new StringBuffer();
0519:                if (com.sun.portal.netlet.eproxy.EProxy.isNetletEnabled)
0520:                    if (req.isGatewayProtocolSecure())
0521:                        netletHeaderValue
0522:                                .append("enabled=true; encryption=ssl");
0523:                    else
0524:                        netletHeaderValue
0525:                                .append("enabled=true; encryption=plain");
0526:                else
0527:                    netletHeaderValue.append("enabled=false");
0528:
0529:                netletHeaderValue = new StringBuffer(netletHeaderKey).append(
0530:                        ": ").append(netletHeaderValue);
0531:
0532:                req.setRequestHeader(netletHeaderKey, netletHeaderValue
0533:                        .toString());
0534:                req.setRequestHeader("X-" + netletHeaderKey, "X-"
0535:                        + netletHeaderValue.toString());
0536:            }
0537:
0538:            private void addGatewayInstanceHeader(Request req) {
0539:                String profileName = System.getProperty("gateway.profilename",
0540:                        "default");
0541:                String gatewayInstanceHeaderValue = gatewayInstanceHeaderKey
0542:                        + ": " + profileName;
0543:                req.setRequestHeader(gatewayInstanceHeaderKey,
0544:                        gatewayInstanceHeaderValue);
0545:                req.setRequestHeader("X-" + gatewayInstanceHeaderKey, "X-"
0546:                        + gatewayInstanceHeaderValue);
0547:            }
0548:
0549:            private void addProxyletCustomHeader(Request req) {
0550:                String proxyletHeaderValue = "enabled=false";
0551:                if (com.sun.portal.netlet.eproxy.EProxy.isProxyletEnabled) {
0552:                    proxyletHeaderValue = "enabled=true";
0553:                    addGatewayInstanceHeader(req);
0554:                }
0555:                proxyletHeaderValue = proxyletHeaderKey + ": "
0556:                        + proxyletHeaderValue;
0557:                String pHeader = req.getRequestHeader(proxyletHeaderKey);
0558:                if (null != pHeader) {
0559:                    proxyletHeaderValue += "; RT-Proxylet=true";
0560:                }
0561:                req.setRequestHeader(proxyletHeaderKey, proxyletHeaderValue);
0562:                req.setRequestHeader("X-" + proxyletHeaderKey, "X-"
0563:                        + proxyletHeaderValue);
0564:            }
0565:
0566:            public void addClientIP(Request req) {
0567:
0568:                StringBuffer buff = new StringBuffer();
0569:                if (com.sun.portal.netlet.eproxy.EProxy.isProxyletEnabled == true
0570:                        && nonsslsocket != null) {
0571:                    buff = new StringBuffer().append(clientIPHeaderKey).append(
0572:                            ": ").append(
0573:                            nonsslsocket.getInetAddress().getHostAddress());
0574:                } else
0575:                    buff = new StringBuffer().append(clientIPHeaderKey).append(
0576:                            ": ").append(
0577:                            actualClientSocket.getInetAddress()
0578:                                    .getHostAddress());
0579:                String clientIPHeaderValue = buff.toString();
0580:                req.setRequestHeader(clientIPHeaderKey, clientIPHeaderValue);
0581:                req.setRequestHeader("X-" + clientIPHeaderKey, "X-"
0582:                        + clientIPHeaderValue);
0583:            }
0584:
0585:            /*
0586:             * public void addGatewayInfo(Request req){
0587:             *
0588:             * StringBuffer buff = null; if (req instanceof HTTPRequest){ buff = new
0589:             * StringBuffer().append(gatewayURLInfoHeaderKey).append(": " )
0590:             * .append(((HTTPRequest)req).getUnEncodedGatewayURL());
0591:             * req.setRequestHeader(gatewayURLInfoHeaderKey , buff.toString());
0592:             * req.setRequestHeader("X-"+gatewayURLInfoHeaderKey ,
0593:             * "X-"+buff.toString()); buff = new
0594:             * StringBuffer().append(gatewayRWURLInfoHeaderKey).append(": " )
0595:             * .append(req.getGatewayURL());
0596:             * req.setRequestHeader(gatewayRWURLInfoHeaderKey , buff.toString());
0597:             * req.setRequestHeader("X-"+gatewayRWURLInfoHeaderKey ,
0598:             * "X-"+buff.toString()); } else{ // What ???? buff = new
0599:             * StringBuffer().append(gatewayURLInfoHeaderKey).append(": " )
0600:             * .append(req.getGatewayURL());
0601:             * req.setRequestHeader(gatewayURLInfoHeaderKey , buff.toString());
0602:             * req.setRequestHeader("X-"+gatewayURLInfoHeaderKey ,
0603:             * "X-"+buff.toString()); buff = new
0604:             * StringBuffer().append(gatewayRWURLInfoHeaderKey).append(": " )
0605:             * .append(req.getGatewayURL());
0606:             * req.setRequestHeader(gatewayRWURLInfoHeaderKey , buff.toString());
0607:             * req.setRequestHeader("X-"+gatewayRWURLInfoHeaderKey ,
0608:             * "X-"+buff.toString()); } }
0609:             */
0610:            public void addGatewayInfo(Request req) {
0611:
0612:                StringBuffer buff = null;
0613:                if (req instanceof  HTTPRequest) {
0614:                    HTTPRequest httpreq = (HTTPRequest) req;
0615:
0616:                    buff = new StringBuffer().append(gatewayURLInfoHeaderKey)
0617:                            .append(": ").append(
0618:                                    httpreq.getUnEncodedGatewayURL());
0619:                    req.setRequestHeader(gatewayURLInfoHeaderKey, buff
0620:                            .toString());
0621:                    req.setRequestHeader("X-" + gatewayURLInfoHeaderKey, "X-"
0622:                            + buff.toString());
0623:                    /*
0624:                     * If Cookies supported just add the GW URL as it will not have
0625:                     * sessionID
0626:                     */
0627:                    if (httpreq.isCookieSupported()) {
0628:                        buff = new StringBuffer().append(
0629:                                gatewayRWURLInfoHeaderKey).append(": ").append(
0630:                                httpreq.getGatewayURL());
0631:
0632:                    } else {
0633:                        /*
0634:                         * Cookies are not supported add the GW URL only if the
0635:                         * destination server as it will not have sessionID
0636:                         */
0637:                        if (httpreq.isForwardCookieHost()) {
0638:                            buff = new StringBuffer().append(
0639:                                    gatewayRWURLInfoHeaderKey).append(": ")
0640:                                    .append(httpreq.getGatewayURL());
0641:                        } else {
0642:                            buff = new StringBuffer().append(
0643:                                    gatewayRWURLInfoHeaderKey).append(": ")
0644:                                    .append(
0645:                                            httpreq.getUnEncodedGatewayURL()
0646:                                                    + "$SessionID");
0647:                        }
0648:
0649:                    }
0650:
0651:                    req.setRequestHeader(gatewayRWURLInfoHeaderKey, buff
0652:                            .toString());
0653:                    req.setRequestHeader("X-" + gatewayRWURLInfoHeaderKey, "X-"
0654:                            + buff.toString());
0655:                } else {
0656:                    // What ????
0657:                    buff = new StringBuffer().append(gatewayURLInfoHeaderKey)
0658:                            .append(": ").append(req.getGatewayURL());
0659:                    req.setRequestHeader(gatewayURLInfoHeaderKey, buff
0660:                            .toString());
0661:                    req.setRequestHeader("X-" + gatewayURLInfoHeaderKey, "X-"
0662:                            + buff.toString());
0663:                    buff = new StringBuffer().append(gatewayRWURLInfoHeaderKey)
0664:                            .append(": ").append(req.getGatewayURL());
0665:                    req.setRequestHeader(gatewayRWURLInfoHeaderKey, buff
0666:                            .toString());
0667:                    req.setRequestHeader("X-" + gatewayRWURLInfoHeaderKey, "X-"
0668:                            + buff.toString());
0669:                }
0670:            }
0671:
0672:            public void addPDCInfo(Request req) {
0673:                String pdcHeaderKeyValue = pdcHeaderKey;
0674:                if (doingPDC && req.isGatewayProtocolSecure()) {
0675:                    pdcHeaderKeyValue += ": true";
0676:                } else {
0677:                    pdcHeaderKeyValue += ": false";
0678:                }
0679:                req.setRequestHeader(pdcHeaderKey, pdcHeaderKeyValue);
0680:                req.setRequestHeader("X-" + pdcHeaderKey, "X-"
0681:                        + pdcHeaderKeyValue);
0682:            }
0683:
0684:            public void addCustomHeaders(Request req) {
0685:                addNetletCustomHeader(req);
0686:                addProxyletCustomHeader(req);
0687:                //addClientIP(req);
0688:                addGatewayInfo(req);
0689:                addPDCInfo(req);
0690:                addClientIP(req);
0691:            }
0692:
0693:            private static int writeContent(OutputStream out, Response resp,
0694:                    Session sess) throws IOException {
0695:                String lContentLength = resp
0696:                        .getResponseHeader("Content-length");
0697:                BufferedInputStream buffIn = resp.getContentStream();
0698:                byte content[] = new byte[2048];
0699:
0700:                if (buffIn == null) {
0701:                    return 0;
0702:                }
0703:
0704:                if (lContentLength != null) {
0705:                    int length = Integer.parseInt(lContentLength.substring(
0706:                            lContentLength.indexOf(':') + 1).trim());
0707:
0708:                    int read = 0, totalRead = 0;
0709:                    int left;
0710:                    while (totalRead < length) {
0711:                        left = length - totalRead;
0712:                        read = buffIn.read(content, 0,
0713:                                left < content.length ? left : content.length);
0714:                        if (read == -1) {
0715:                            // We need to close connection !!
0716:                            sess.setStillActive(false);
0717:                            break;
0718:                        } else {
0719:                            if (read > 0) {
0720:                                totalRead += read;
0721:                                out.write(content, 0, read);
0722:                                out.flush();
0723:                            }
0724:                        }
0725:                    }
0726:
0727:                    return totalRead;
0728:                } else {
0729:                    int numbytes;
0730:                    int totalRead = 0;
0731:
0732:                    while (true) {
0733:                        numbytes = buffIn.read(content);
0734:                        if (numbytes == -1) {
0735:                            break;
0736:                        }
0737:
0738:                        totalRead += numbytes;
0739:
0740:                        out.write(content, 0, numbytes);
0741:                        out.flush();
0742:                    }//while loop
0743:                    return totalRead;
0744:                }//if/else
0745:            }
0746:
0747:            /**
0748:             * Method subclasses override to return a request class for a specific
0749:             * Session type
0750:             */
0751:            public abstract Request getRequest();
0752:
0753:            /**
0754:             * Process next request, gets the request by calling getRequest, Checks
0755:             * Authorization for object, Retrieves it, translates it, and sends it back
0756:             * to the client.
0757:             */
0758:            public final void processNextRequest() {
0759:
0760:                boolean needtoRewrite = false; // This is set to false, unless we find
0761:                // proxylet specific header in the request.
0762:
0763:                // Lihue - keepAlive
0764:                long initialtime = 0;
0765:                if (processKeepAliveConnections) {
0766:                    // To check whether we have exceeded the max timeout for
0767:                    // this socket
0768:                    initialtime = System.currentTimeMillis();
0769:                }
0770:                // End of Code : Lihue - keepAlive
0771:                Request req = getRequest();
0772:                Response rep = null;
0773:                boolean loop = true;
0774:                int repeatCount = 0;
0775:                MonitoringSubsystem.handleEvent(RProxyEvent.NEW_REQ);
0776:                //End of change of code for the bug : 4670649
0777:                // Bug ID - # 4195483 with Lihue PRD Req - # 7.4.4.1
0778:                String rep_code = null;
0779:                int responseLength = 0;
0780:                // End of Code : Bug ID - # 4195483 with Lihue PRD Req - # 7.4.4.1
0781:
0782:                // Lihue - keepAlive
0783:                // Doing it here , 'cos processKeepAlive() modifies the request.
0784:                if (req != null) {
0785:                    browserTraffic.info("Request sent from Browser:\n" + req);
0786:                }
0787:
0788:                if (req != null)
0789:                    needtoRewrite = isNeedToRewrite(req);
0790:
0791:                processKeepAlive(initialtime, req);
0792:                // End of Code : Lihue - keepAlive
0793:                // Start of Code
0794:                /*if (com.sun.portal.perf.rproxy.PerfContextObject.ENABLE_PERF){
0795:                        PerfContext context = PerfContextObject.getPerfContext();
0796:                        // Get record timerData
0797:                        TimerData td = new TimerData("Session.java , after getting request object");
0798:                        context.record(td);
0799:                  }*/
0800:                // End of Code
0801:                /*
0802:                 * PRD 3.7 (4338513)
0803:                 * Authentication chaining will work with Certificate authentication.
0804:                 */
0805:                invalidateSSL = false;
0806:                pdcCookiePresent = false;
0807:
0808:                while (loop) {
0809:                    /*
0810:                     * PRD 3.7 (4338513) Authentication chaining will work with
0811:                     * Certificate authentication.
0812:                     */
0813:                    invalidateSSL = false;
0814:                    pdcCookiePresent = false;
0815:                    String sid = null;
0816:
0817:                    if (doingPDC)
0818:                        sid = getSessionID(req);
0819:
0820:                    //End of code change for PRD 3.7
0821:
0822:                    // if Req is null processing the Request caused an error
0823:                    if (req != null) {
0824:                        // logger.info("Session: processNextRequest checking for "+
0825:                        // req.getURI() + "\nobject: " + req.getObject());
0826:                        Object[] params = { req.getURI(), "\n", req.getObject() };
0827:                        logger.log(Level.INFO, "PSSRRPROXY_CSPRCONHNDLR128",
0828:                                params);
0829:                        if (GWLogManager.loggingEnabled)
0830:                            GWLogManager.write("RProxy", GWLocale.getPFString(
0831:                                    "session1", new Object[] {
0832:                                            _logId,
0833:                                            new String(GWLogManager
0834:                                                    .getUserId(req
0835:                                                            .getSessionID())),
0836:                                            req.getURI() }));
0837:
0838:                        /**
0839:                         * Add Netlet custom header.
0840:                         */
0841:                        if (ServiceIdentifier.isGateway()) {
0842:                            addCustomHeaders(req);
0843:                        }
0844:
0845:                        if (req.getGatewayScheme().equals(notificationURL)) {
0846:                            MonitoringSubsystem
0847:                                    .handleEvent(SRAEvent.IS_NOTIFICATION);
0848:                            rep = processNotificationRequest(req);
0849:                            if (rep == null) {
0850:                                setStillActive(false);
0851:                                return;
0852:                            }
0853:                        } else if (req.getGatewayScheme().equals("statistics")) {
0854:                            rep = processStatisticsRequest(req);
0855:                        } else if (req.getObject().length() == 0
0856:                                && req.getProtocol() != null) {
0857:                            // logger.info(" ************* missing object");
0858:                            logger.info("PSSRRPROXY_CSPRCONHNDLR129");
0859:                            rep = processMissingObjectRequest(req);
0860:                        } else {
0861:                            rep = processRequest(req, sid);
0862:                        }
0863:
0864:                        if (GWLogManager.loggingEnabled)
0865:                            GWLogManager.write("RProxy", GWLocale.getPFString(
0866:                                    "session2", new Object[] {
0867:                                            _logId,
0868:                                            new String(GWLogManager
0869:                                                    .getUserId(req
0870:                                                            .getSessionID())),
0871:                                            new Integer(req.getSize()) }));
0872:
0873:                        // print out the entire send/receive from server
0874:                        serverTraffic.info("--> Session: Request:\n" + req
0875:                                + "Response\n" + rep);
0876:
0877:                        // Lihue - keepAlive
0878:                        // set "Connection: close" in HTTPResponse header. (Luke)
0879:                        //rep.setConnectionClose();
0880:                        // End of Code : Lihue - keepAlive
0881:
0882:                        /**
0883:                         * Bug 4618938 When "gateway.allow.client.caching" is set to
0884:                         * false in Platform.conf the client cache will be disabled.
0885:                         */
0886:                        rep.setClientCaching();
0887:                        //End of change of code for the bug 4618938
0888:
0889:                        // Write the result back to the client
0890:                        boolean cont = true;
0891:                        byte b[];
0892:                        int read;
0893:                        int ready;
0894:                        boolean hasBeenTranslated = false;
0895:                        OutputStream out = null;
0896:                        //BufferedInputStream in = null;
0897:                        InputStream in = null;
0898:                        if (rep instanceof  HTTPResponse) {
0899:                            ((HTTPResponse) rep).processSetCookieHeaders(req);
0900:                        }
0901:
0902:                        try {
0903:                            // Get a Translater for the specific type
0904:                            //Pending: Spell this correctly ;-)
0905:                            //Translater t = null;
0906:                            boolean needsTranslation = false;
0907:
0908:                            // Lihue PRD Req - # 7.4.4.1
0909:                            //String rep_code = rep.getStatusCode();
0910:                            rep_code = rep.getStatusCode();
0911:                            // EOC : Lihue PRD Req - # 7.4.4.1
0912:
0913:                            if (ServiceIdentifier.isGateway() && needtoRewrite) {
0914:                                if (rep_code != null
0915:                                        && (!rep_code.startsWith("1"))
0916:                                        && (!rep_code.startsWith("204"))
0917:                                        && (!rep_code.startsWith("304"))) {
0918:                                    // logger.info("NEED TO TRANSLATE");
0919:                                    logger.info("PSSRRPROXY_CSPRCONHNDLR135");
0920:
0921:                                    needsTranslation = true;
0922:                                    //t = TranslationFactory.getTranslater(
0923:                                    //rep.getContentType());
0924:                                }
0925:                            }
0926:
0927:                            // Set up a buffered input stream, either from the
0928:                            // translator or
0929:                            // the response.
0930:
0931:                            if (needsTranslation == false) {
0932:                                logger
0933:                                        .warning(" ************* No Translator available");
0934:                                String contentLength = rep
0935:                                        .getResponseHeader("Content-length");
0936:                                in = rep.getContentStream();
0937:                                if (contentLength == null) {
0938:                                    // Lihue - keepAlive
0939:                                    //setStillActive(false);
0940:                                    // Why do we have to do this ?
0941:                                    // Doesn't seem to work if we don't close here.
0942:                                    // - Mridul
0943:                                    this reqKeepAlive = false;
0944:                                    // End of Code : Lihue - keepAlive
0945:                                }
0946:                            } else {
0947:                                // logger.info(" ************* Got Translator");
0948:                                logger.info("PSSRRPROXY_CSPRCONHNDLR136");
0949:                                in = SRAPAdapter.rewrite(req, rep);
0950:                                //t.translate(rep, req);
0951:                                // logger.info(" ************* Translated !!! in = " +
0952:                                // in);
0953:                                Object[] params13 = { in };
0954:                                logger.log(Level.INFO,
0955:                                        "PSSRRPROXY_CSPRCONHNDLR137", params13);
0956:                                if (in != null) {
0957:                                    // PENDING: Should we do something smarter to figure
0958:                                    // out the
0959:                                    // content lenght here? This is a hack...
0960:                                    //rep.setContentLength(in.available());
0961:                                    hasBeenTranslated = true;
0962:                                    rep.setContentLength(in.available());
0963:                                } else {
0964:                                    in = rep.getContentStream();
0965:                                    String contentLength = rep
0966:                                            .getResponseHeader("Content-length");
0967:                                    if (contentLength == null) {
0968:                                        // Lihue - keepAlive
0969:                                        //setStillActive(false);
0970:                                        // Why do we have to do this ?
0971:                                        // Doesn't seem to work if we don't close here.
0972:                                        // - Mridul
0973:                                        this reqKeepAlive = false;
0974:                                        // End of Code : Lihue - keepAlive
0975:                                    }
0976:                                    // logger.info("Not rewritten , so in = " + in);
0977:                                    Object[] params14 = { in };
0978:                                    logger.log(Level.INFO,
0979:                                            "PSSRRPROXY_CSPRCONHNDLR138",
0980:                                            params14);
0981:                                }
0982:                                /*
0983:                                 * else if (repeatCount <3) { repeatCount++; continue; }
0984:                                 */
0985:                            }
0986:                            // Lihue - keepAlive
0987:                            if (this reqKeepAlive) {
0988:                                rep.setConnectionAlive(" timeout="
0989:                                        + timeoutseconds + ",max="
0990:                                        + (MAX_PER_SESS - this _req));
0991:                            } else {
0992:                                rep.setConnectionClose();
0993:                                setStillActive(false);
0994:                            }
0995:                            // End of Code : Lihue - keepAlive
0996:                            if (ServiceIdentifier.isGateway() && needtoRewrite) {
0997:                                // logger.info("TRANSLATE NOW");
0998:                                logger.info("PSSRRPROXY_CSPRCONHNDLR139");
0999:                                translateHeader(rep, req);
1000:                            }
1001:
1002:                            // Header sent back to Browser!
1003:                            browserTraffic
1004:                                    .info("Response sent back to Browser:\n"
1005:                                            + rep);
1006:
1007:                            out = _theSocket.getOutputStream();
1008:
1009:                            byte headerBytes[] = rep.getHeaderBytes();
1010:                            _numBytesSent += headerBytes.length;
1011:                            // Bug ID - # 4195483 with Lihue PRD Req - # 7.4.4.1
1012:                            responseLength += headerBytes.length;
1013:                            // EOC :: Bug ID - # 4195483 with Lihue PRD Req - # 7.4.4.1
1014:                            out.write(headerBytes);
1015:                            out.flush();
1016:                            if (rep_code != null
1017:                                    && (rep_code.startsWith("4") || rep_code
1018:                                            .startsWith("5"))) {
1019:                                MonitoringSubsystem
1020:                                        .handleEvent(RProxyEvent.BAD_REQUEST);
1021:                            }
1022:                            if (rep_code != null && (!rep_code.startsWith("1"))
1023:                                    && (!rep_code.startsWith("204"))
1024:                                    && (!rep_code.startsWith("304"))) {
1025:
1026:                                int readbytes = 0;
1027:                                if (!hasBeenTranslated) {
1028:                                    HTTPRequest hreq = (HTTPRequest) req;
1029:                                    String method = hreq.getMethod();
1030:                                    // HEAD method has no content
1031:                                    if (method != null
1032:                                            && !method.equals("HEAD")) {
1033:
1034:                                        readbytes = writeContent(out, rep, this );
1035:                                        // logger.info("Not rewritten for " + req.getURL() +
1036:                                        // " Bytes of content written as response : " +
1037:                                        // readbytes);
1038:                                        Object[] paramsx = { req.getURL(),
1039:                                                new Integer(readbytes) };
1040:                                        logger.log(Level.INFO,
1041:                                                "PSSRRPROXY_CSPRCONHNDLR140",
1042:                                                paramsx);
1043:                                    }
1044:
1045:                                } else {
1046:
1047:                                    b = new byte[2048];
1048:                                    while ((ready = in.read(b)) >= 0) {
1049:                                        if (ready > 0) {
1050:                                            readbytes += ready;
1051:                                            out.write(b, 0, ready);
1052:                                            out.flush();
1053:                                        }
1054:                                    }
1055:                                }
1056:                                // logger.info(readbytes + " bytes of content written as
1057:                                // response");
1058:                                Object[] params17 = { new Integer(readbytes) };
1059:                                logger.log(Level.INFO,
1060:                                        "PSSRRPROXY_CSPRCONHNDLR141", params17);
1061:                                // Bug ID - # 4195483 with Lihue PRD Req - # 7.4.4.1
1062:                                responseLength += readbytes;
1063:                                // End of Code : Bug ID - # 4195483 with Lihue PRD Req -
1064:                                // # 7.4.4.1
1065:                            }
1066:                        } catch (IOException ex) {
1067:                            try {
1068:                                out.flush();
1069:                                if (in instanceof  CSBufferedInputStream)
1070:                                    ((CSBufferedInputStream) in).getSocket()
1071:                                            .close();
1072:                            } catch (Exception ex1) {
1073:                            }
1074:                            // logger.log(Level.SEVERE, "Session failed to respond to
1075:                            // client", ex);
1076:                            logger.log(Level.SEVERE,
1077:                                    "PSSRRPROXY_CSPRCONHNDLR142", ex);
1078:
1079:                            setStillActive(false);
1080:                        } catch (NullPointerException ex) {
1081:                            setStillActive(false);
1082:                            // logger.log(Level.SEVERE, "Session failed to respond to
1083:                            // client", ex);
1084:                            logger.log(Level.SEVERE,
1085:                                    "PSSRRPROXY_CSPRCONHNDLR143", ex);
1086:                        } finally {
1087:                            try {
1088:                                out.flush();
1089:                            } catch (Exception ex1) {
1090:                            }
1091:                        }
1092:                    }
1093:                    loop = false;
1094:                }
1095:
1096:                // Lihue Keep-Alive
1097:                /*
1098:                 * if (logFile != null && rep != null){ try{ logFile.println("Actual
1099:                 * Response : "+rep); logFile.flush(); }catch(Exception ex){} }
1100:                 */
1101:                // EOC : Lihue Keep-Alive
1102:                // Lihue PRD Req - # 7.4.4.1
1103:                if (isPerSessionLoggingEnabled) {
1104:                    //String type = (_theSocket instanceof SSLSocket)?"https":"http";
1105:                    String type;
1106:                    if (_theSocket instanceof  SRAPSocket) {
1107:                        type = ((SRAPSocket) _theSocket).isSSLSocket() ? "https"
1108:                                : "http";
1109:                    } else {
1110:                        type = (_theSocket instanceof  SSLSocket) ? "https"
1111:                                : "http";
1112:                    }
1113:                    String fromAddress = actualClientSocket.getInetAddress()
1114:                            .toString();
1115:                    String destHost = req.getHost();
1116:                    // Also incorporating the changes for Bug ID - # 4195483
1117:                    if (detailedRproxLog && req instanceof  HTTPRequest) {
1118:                        HTTPRequest httpreq = (HTTPRequest) req;
1119:                        String method = httpreq.getMethod();
1120:                        String requestedUrl = httpreq.getURL();
1121:                        String sessidstr = null;
1122:
1123:                        String tmpsidstr = httpreq.getSessionID();
1124:
1125:                        if (tmpsidstr != null) {
1126:                            SSOToken token = getUserSession(req, tmpsidstr);
1127:                            if (token != null) {
1128:                                sessidstr = token.getTokenID().toString();
1129:                            }
1130:                        }
1131:
1132:                        Integer requestContentLength = null;
1133:                        if (method.trim().toLowerCase().equals("post")) {
1134:                            String len = httpreq
1135:                                    .getRequestHeader("Content-length");
1136:                            len = len.substring(len.indexOf(':') + 1);
1137:
1138:                            try {
1139:                                requestContentLength = new Integer(Integer
1140:                                        .parseInt(len));
1141:                            } catch (Exception ex) {
1142:                            }
1143:                        } else {
1144:                            requestContentLength = new Integer(0);
1145:                        }
1146:                        // Format -
1147:                        // logid , from (client browser) address , type - http/https
1148:                        // (e/r prox), destination host,
1149:                        // method - get/post/etc , requested url , length of content if
1150:                        // post , session ID ,
1151:                        // result code in response , size of data returned
1152:                        GWLogManager
1153:                                .write(
1154:                                        "RProxy",
1155:                                        GWLocale
1156:                                                .getPFString(
1157:                                                        "RproxyPerRequestDetailedLogFormat",
1158:                                                        new Object[] {
1159:                                                                _logId,
1160:                                                                new String(
1161:                                                                        GWLogManager
1162:                                                                                .getUserId(httpreq
1163:                                                                                        .getSessionID())),
1164:                                                                fromAddress,
1165:                                                                type,
1166:                                                                destHost,
1167:                                                                method,
1168:                                                                requestedUrl,
1169:                                                                requestContentLength,
1170:                                                                rep_code,
1171:                                                                new Integer(
1172:                                                                        responseLength) }));
1173:                    } else {
1174:                        GWLogManager.write("RProxy", GWLocale.getPFString(
1175:                                "RproxyPerRequestLogFormat", new Object[] {
1176:                                        _logId,
1177:                                        new String(GWLogManager.getUserId(req
1178:                                                .getSessionID())), fromAddress,
1179:                                        type, destHost }));
1180:                    }
1181:                    // End of Code : Bug ID - # 4195483
1182:                }
1183:                // End of Code : Lihue PRD Req - # 7.4.4.1
1184:
1185:                /*
1186:                 * PRD 3.7 (4338513) Authentication chaining will work with Certificate
1187:                 * authentication. With authentication chaining, the getUserSession will
1188:                 * always return null, until a valid session has been created. A valid
1189:                 * session will be created only after the authentication chaining has
1190:                 * been completed. There is no way to differentiate between the scenario
1191:                 * of the request is in between the chain or some error occured.
1192:                 */
1193:                if (doingPDC && invalidateSSL) {
1194:                    //End of code change for PRD 3.7
1195:                    // logger.info("SESSION: INVALIDATE SSL");
1196:                    logger.info("PSSRRPROXY_CSPRCONHNDLR144");
1197:                    //JSS3.1.1 change - begin
1198:                    try {
1199:                        //((SSLSocket)_theSocket).invalidateSession();
1200:                        getActualSocket().invalidateSession();
1201:                    } catch (java.net.SocketException se) {
1202:                        // logger.severe("Unable to invalidate SSL Session");
1203:                        logger.severe("PSSRRPROXY_CSPRCONHNDLR145");
1204:                    }
1205:                    //JSS3.1.1 change - end
1206:                }
1207:                /**
1208:                 * Changes to accomodate change for PRD 3.7
1209:                 */
1210:                //}
1211:                //End of code change for PRD 3.7
1212:                //End of code change for Bug : 4670649
1213:                if (rep != null) {
1214:                    MonitoringSubsystem.handleEvent(RProxyEvent.RESPONSE_SENT);
1215:                    rep.closeSocket();
1216:                }
1217:
1218:                // Lihue - KeepAlive
1219:                // always close connection. We change it to support keep-alive
1220:                // later. bug 4255645
1221:                // KeepAlive supported now !!!
1222:                // - Mridul
1223:                if (!this reqKeepAlive) {
1224:                    setStillActive(false);
1225:                }
1226:                // End of Code : Lihue - KeepAlive
1227:            }
1228:
1229:            // Lihue - KeepAlive
1230:
1231:            /**
1232:             * @param req
1233:             * @param sid
1234:             * @return
1235:             */
1236:            private Response processRequest(Request req, String sid) {
1237:                Response rep;
1238:                try {
1239:                    if (req.getProtocol() == null) {
1240:                        // logger.info(" ************* missing protocol");
1241:                        logger.info("PSSRRPROXY_CSPRCONHNDLR130");
1242:                        rep = processMissingProtocolRequest(req);
1243:                        // logger.info(" ************* GOT RESPONSE");
1244:                        logger.info("PSSRRPROXY_CSPRCONHNDLR131");
1245:                    } else if (doingPDC
1246:                            && req.getObject().startsWith(_platformloginURL)) {
1247:
1248:                        //find out if you need to do PDC  or process the request
1249:                        /*
1250:                         * The logic behind doing PDC is :
1251:                         * - When the PDCCookie is not found the Cookie send by the browser
1252:                         *   there is a need to do PDC
1253:                         * - If the PDCCookie is present, then it means, PDC has already been performed and
1254:                         *   pDC should not be performed again
1255:                         *
1256:                         *
1257:                         * When PDC completed, it sets the cookie to the browser.
1258:                         * When Logout or authentication failure happens, this cookie is cleared
1259:                         * to enable a condition for doPDC to perform.
1260:                         *
1261:                         */
1262:
1263:                        String s = req.getRequestHeader("Cookie");
1264:                        pdcCookiePresent = false;
1265:                        if (s != null) {
1266:                            String cookies = s.substring(s.indexOf(':') + 1);
1267:                            StringTokenizer st = new StringTokenizer(cookies,
1268:                                    ";");
1269:                            while (st.hasMoreTokens() && !pdcCookiePresent) {
1270:                                String cook = st.nextToken().trim();
1271:                                int indx = cook.indexOf('=');
1272:                                if (indx != -1
1273:                                        && cook.substring(0, indx).trim()
1274:                                                .equals(pdcCookieName)) {
1275:                                    pdcCookiePresent = true;
1276:                                }
1277:                            }
1278:                        }
1279:
1280:                        if (!hostFound(req.getURI())) {
1281:                            //End of code change for PRD 3.7
1282:                            rep = processProtocolRequest(req);
1283:                        } else {
1284:                            if (!pdcCookiePresent) {
1285:                                rep = processMissingProtocolRequest(req);
1286:                            } else {
1287:                                if (doingPDC && !pdcCookiePresent) {
1288:                                    invalidateSSL = true;
1289:                                    rep = new RedirectResponse(loginURL(req,
1290:                                            _platformloginURL));
1291:                                } else {
1292:                                    rep = processProtocolRequest(req);
1293:                                }
1294:                            }
1295:                            //End of code change for PRD 3.7
1296:                        }
1297:                    } else {
1298:                        // logger.info(" ************* process protocol");
1299:                        logger.info("PSSRRPROXY_CSPRCONHNDLR132");
1300:                        rep = processProtocolRequest(req);
1301:                    }
1302:                } catch (Exception ex) {
1303:                    // logger.log(Level.SEVERE, "Cannot process protocol
1304:                    // request", ex);
1305:                    logger.log(Level.SEVERE, "PSSRRPROXY_CSPRCONHNDLR133", ex);
1306:                    // Lihue PRD - 8.2
1307:                    String message = ex.toString();
1308:                    String language = req.getRequestHeader("Accept-Language");
1309:                    if (exceptionErrorMessage != null
1310:                            && exceptionErrorMessage.length() > 0) {
1311:                        String userLocale = getUserLocale(req);
1312:                        message = GWLocale.getPFString(exceptionErrorMessage,
1313:                                new Object[] { message }, userLocale);
1314:                    }
1315:                    rep = new ErrorResponse(message, null, language);
1316:                    //rep = new ErrorResponse(ex.toString(), null);
1317:                    // End of Code : Lihue PRD - 8.2
1318:                }
1319:                // logger.info("Session: Request:\n" + req + "Response\n" +
1320:                // rep);
1321:                Object[] param1 = { "\n", req, "\n", rep };
1322:                logger.log(Level.INFO, "PSSRRPROXY_CSPRCONHNDLR134", param1);
1323:                return rep;
1324:            }
1325:
1326:            /**
1327:             * @param req
1328:             * @return
1329:             */
1330:            private String getSessionID(Request req) {
1331:                String sid;
1332:                sid = req.getSessionID();
1333:                if (sid != null) {
1334:                    //Fix for encoding CertInfo into the Session
1335:                    if (com.sun.portal.netlet.eproxy.EProxy.isNetletEnabled) {
1336:                        try {
1337:                            SSOToken token = validateSSOToken(sid);
1338:                            //                                SSOTokenManager manager = SSOTokenManager.getInstance();
1339:                            //                                SSOToken token = SSOUtil.getSSOToken(sid);
1340:                            //                                manager.validateToken(token);
1341:                            String pdcCertInfo = token
1342:                                    .getProperty(PDC_CERT_INFO);
1343:                            if (pdcCertInfo == null) {
1344:                                org.mozilla.jss.crypto.X509Certificate clientCert = // ((SSLSocket)
1345:                                // _theSocket).getStatus().getPeerCertificate();
1346:                                getActualSocket().getStatus()
1347:                                        .getPeerCertificate();
1348:                                byte certbyte[] = clientCert.getEncoded();
1349:                                String xxb64Cert = JSSUtil.getDefaultDecoder()
1350:                                        .getEncodedStr(certbyte);
1351:                                String digest = JSSUtil.getDefaultDecoder()
1352:                                        .digest(xxb64Cert);
1353:                                MonitoringSubsystem
1354:                                        .handleEvent(SRAEvent.SSO_SET_PROPERTY_START);
1355:                                token.setProperty(PDC_CERT_INFO, digest);
1356:                                MonitoringSubsystem
1357:                                        .handleEvent(SRAEvent.SSO_SET_PROPERTY_END);
1358:                            }
1359:                        } catch (Exception ssoEx) {
1360:                            // logger.severe("Unable to encode the pdc cert
1361:                            // info");
1362:                            logger.severe("PSSRRPROXY_CSPRCONHNDLR127");
1363:                        }
1364:                    }
1365:                }
1366:                return sid;
1367:            }
1368:
1369:            /**
1370:             * @param req
1371:             * @return
1372:             */
1373:            private boolean isNeedToRewrite(Request req) {
1374:                boolean needtoRewrite;
1375:                //
1376:                // Check if request is being routed through proxylet
1377:                //
1378:                needtoRewrite = rewriteRequest(req);
1379:
1380:                // FQDN fix for Rewriter.
1381:                String gwhost = req.getGatewayHost();
1382:                if (gwhost != null) {
1383:                    String fqdnHost = getFQDN(gwhost);
1384:                    // logger.info("FQDN -> "+fqdnHost+" , gwhost -> "+gwhost+" ,
1385:                    // rphost -> "+rphost);
1386:                    Object[] params1 = { fqdnHost, " , gwhost -> ", gwhost,
1387:                            " , rphost -> ", rphost };
1388:                    logger.log(Level.INFO, "PSSRRPROXY_CSPRCONHNDLR125",
1389:                            params1);
1390:                    if (fqdnHost != null && !gwhost.equalsIgnoreCase(rphost)) {
1391:                        // Set the gatewayURL
1392:                        String newGatewayURL;
1393:
1394:                        String gatewayProtocol = req
1395:                                .getProtocolFromCustomUrl(_gwprotocol);
1396:                        String gatewayPort = req.getPortFromCustomUrl(_gwport);
1397:
1398:                        StringBuffer buff = new StringBuffer();
1399:
1400:                        buff.append(gatewayProtocol).append("://").append(
1401:                                fqdnHost);
1402:
1403:                        if (_gwprotocol.equalsIgnoreCase("http")) {
1404:                            if (!gatewayPort.equals("80")) {
1405:                                buff.append(':').append(gatewayPort);
1406:                            }
1407:                        } else if (!gatewayPort.equals("443")) {
1408:                            buff.append(':').append(gatewayPort);
1409:                        }
1410:                        buff.append('/');
1411:                        newGatewayURL = buff.toString();
1412:                        // logger.info("newGatewayURL -> "+newGatewayURL);
1413:                        Object[] params2 = { newGatewayURL };
1414:                        logger.log(Level.INFO, "PSSRRPROXY_CSPRCONHNDLR126",
1415:                                params2);
1416:                        req.setGatewayURL(newGatewayURL);
1417:                    }
1418:                }
1419:                return needtoRewrite;
1420:            }
1421:
1422:            private void processKeepAlive(long initialtime, Request req) {
1423:
1424:                this reqKeepAlive = processKeepAliveConnections;
1425:                if (processKeepAliveConnections) {
1426:                    if (req != null) {
1427:
1428:                        // Number of times this socket has been reused
1429:                        this _req++;
1430:                        nullTimeout = maxTimeOutSetting;
1431:                        if (req instanceof  HTTPRequest) {
1432:                            // KeepAlive only for HTTP Requests as far as I know
1433:                            // Well we dont support anything else for the time
1434:                            // being anyway :-)
1435:                            // - Mridul
1436:                            HTTPRequest httpreq = (HTTPRequest) req;
1437:                            if (this _req >= MAX_PER_SESS) {
1438:                                // Exceeded/Reached the max number of socket reuses
1439:                                this reqKeepAlive = false;
1440:                            } else {
1441:                                String keepAliveHeader = httpreq
1442:                                        .getRequestHeader("Connection");
1443:                                if (keepAliveHeader != null) {
1444:                                    keepAliveHeader = keepAliveHeader
1445:                                            .substring(
1446:                                                    keepAliveHeader
1447:                                                            .indexOf(':') + 1)
1448:                                            .trim().toLowerCase();
1449:                                    if (keepAliveHeader.equals("close")) {
1450:                                        // The browser has specifically asked for
1451:                                        // closing
1452:                                        // the connection after processing this request
1453:                                        this reqKeepAlive = false;
1454:                                    } else {
1455:                                        this reqKeepAlive = true;
1456:                                    }
1457:                                } else {
1458:                                    // By default for HTTP 1.1 all the connections are
1459:                                    // keepAlive
1460:                                    if (httpreq.getHTTPVersion().toUpperCase()
1461:                                            .compareTo("HTTP/1.1") >= 0) {
1462:                                        this reqKeepAlive = true;
1463:                                    } else {
1464:                                        this reqKeepAlive = false;
1465:                                    }
1466:                                }
1467:                            }
1468:                            // We don't want the internal server to do a KeepAlive with
1469:                            // us ;-)
1470:                            // - Mridul
1471:                            httpreq.setRequestHeader("Connection",
1472:                                    "Connection: close\r\n");
1473:                            // reset this to true to indicate more elements may be
1474:                            // subsequently coming
1475:                            _moreElements = true;
1476:                            if (!this reqKeepAlive) {
1477:                                if (this _req < MAX_PER_SESS && this _req > 1) {
1478:                                    // No KeepAlive for a socket that has already been
1479:                                    // reused
1480:
1481:                                    // Do not close as there may be more requests
1482:                                    // pending at
1483:                                    // the socket which the browser sent asychronously .
1484:                                    // If there are none remaining , the null request
1485:                                    // will
1486:                                    // be returned , which we are handling seperately
1487:                                    // below.
1488:                                    // According to RFC , this need not be seperately
1489:                                    // handled
1490:                                    // but should actually result only in code -
1491:                                    // _moreElements = false;
1492:                                    // to stop furthur processing from this socket.
1493:                                    // Making allowance for browser goofiness , and
1494:                                    // these
1495:                                    // do happpen sometimes with browser just waiting
1496:                                    // till
1497:                                    // timeout :-)
1498:                                    //  - Mridul
1499:                                    this reqKeepAlive = true;
1500:                                    _moreElements = true;
1501:                                } else {
1502:                                    // First request without "Connection: Keep-Alive" or
1503:                                    // with
1504:                                    // "Connection: Close" , or the last request
1505:                                    _moreElements = false;
1506:                                }
1507:                            }
1508:                        } else {
1509:                            // How can we test this part ??
1510:
1511:                            if (this _req < MAX_PER_SESS && this _req > 1) {
1512:                                // This is similar to the check above
1513:                                // for browser mistakes.
1514:                                this reqKeepAlive = true;
1515:                                _moreElements = true;
1516:                            } else {
1517:                                this reqKeepAlive = false;
1518:                                _moreElements = false;
1519:                            }
1520:                        }
1521:                    } else {
1522:                        // Handle null requests ...
1523:                        long timediff = System.currentTimeMillis()
1524:                                - initialtime;
1525:                        if (timediff < nullTimeout
1526:                                && timediff >= (readTimeout / 2)) {
1527:                            _moreElements = true;
1528:                            nullTimeout -= timediff;
1529:                            boolean diffed = false;
1530:                            try {
1531:                                Thread.currentThread().sleep(THREAD_SLEEP_TIME);
1532:                            } catch (Exception e) {
1533:                                diffed = true;
1534:                                nullTimeout -= (System.currentTimeMillis() - timediff);
1535:                            }
1536:                            if (!diffed) {
1537:                                nullTimeout -= THREAD_SLEEP_TIME;
1538:                            }
1539:                        } else {
1540:                            this reqKeepAlive = false;
1541:                            _moreElements = false;
1542:                        }
1543:                    }
1544:                } else {
1545:                    // Remove the KeepAlive Header from request
1546:                    // Helps with gateway chaining , wherein the first one gateway may
1547:                    // not support
1548:                    // KeepAlive but subsequent one may , causing the second gateway to
1549:                    // try to keep KeepAlive with first gateway , which should not be
1550:                    // the behaviour.
1551:                    // - Mridul
1552:                    if (req != null) {
1553:                        HTTPRequest httpreq = (HTTPRequest) req;
1554:                        httpreq.setRequestHeader("Connection",
1555:                                "Connection: close\r\n");
1556:                    }
1557:                }
1558:                if (this _req > 1) {
1559:                    // logger.info("Reusing the socket for : " + this_req);
1560:                    Object[] params22 = { new Integer(this _req) };
1561:                    logger.log(Level.INFO, "PSSRRPROXY_CSPRCONHNDLR146",
1562:                            params22);
1563:                }
1564:            }
1565:
1566:            // End of Code : Lihue - KeepAlive
1567:
1568:            private void translateHeader(Response rep, Request req) {
1569:                boolean isExternal = req.getGatewayScheme().equals("external");
1570:
1571:                if (rep instanceof  RedirectResponse) {
1572:                    if (!((RedirectResponse) rep).needTranslation()) {
1573:                        return;
1574:                    }
1575:                }
1576:
1577:                String location = rep.getResponseHeader("Location:");
1578:
1579:                if (location != null) {
1580:                    String result = SRAPTranslatorHelper.translateHeaderURL(
1581:                            location, rep, req, (location.toLowerCase())
1582:                                    .startsWith("location:"), isExternal);
1583:
1584:                    // logger.info("Translated from [" + location + "] to [" + result +
1585:                    // "]");
1586:                    Object[] params23 = { location, "] to [", result, "]" };
1587:                    logger.log(Level.INFO, "PSSRRPROXY_CSPRCONHNDLR147",
1588:                            params23);
1589:                    rep.setLocation(result);
1590:                }
1591:
1592:                if (!(rep instanceof  HTTPResponse)) {
1593:                    return;
1594:                }
1595:
1596:                String clocation = rep.getResponseHeader("Content-Location:");
1597:
1598:                if (clocation != null) {
1599:                    String cresult = SRAPTranslatorHelper.translateHeaderURL(
1600:                            clocation, rep, req, (clocation.toLowerCase())
1601:                                    .startsWith("content-location:"),
1602:                            isExternal);
1603:
1604:                    // logger.info("Translated from [" + clocation + "] to [" + cresult
1605:                    // + "]");
1606:                    Object[] params24 = { clocation, "] to [", cresult, "]" };
1607:                    logger.log(Level.INFO, "PSSRRPROXY_CSPRCONHNDLR148",
1608:                            params24);
1609:                    ((HTTPResponse) rep).setContentLocation(cresult);
1610:                }
1611:
1612:                // WebDav headers.
1613:                if (rep instanceof  HTTPResponse) {
1614:                    // Handle Web DAV support
1615:                    translateWebDAVHeaders(req, (HTTPResponse) rep, isExternal);
1616:                }
1617:            }
1618:
1619:            protected void translateWebDAVHeaders(Request req,
1620:                    HTTPResponse resp, boolean isExternal) {
1621:
1622:                translateSpecificHeader("Destination", req, resp, isExternal);
1623:                translateSpecificHeader("Status-URI", req, resp, isExternal);
1624:            }
1625:
1626:            protected void translateSpecificHeader(String headerName,
1627:                    Request req, HTTPResponse resp, boolean isExternal) {
1628:
1629:                // Typically number of destination headers <= 1
1630:                List toTranslateList = resp.getHeaderAttributeList(headerName);
1631:                Iterator iter = toTranslateList.iterator();
1632:                LinkedList translatedList = new LinkedList();
1633:
1634:                resp.removeHeader(headerName);
1635:
1636:                while (iter.hasNext()) {
1637:                    String header = iter.next().toString();
1638:                    String result = SRAPTranslatorHelper.translateHeaderURL(
1639:                            header, resp, req, true, isExternal);
1640:
1641:                    // logger.info(headerName + " Translated from [" + header + "] to ["
1642:                    // + result + "]");
1643:                    Object[] params = { headerName, header, result };
1644:                    logger
1645:                            .log(Level.INFO, "PSSRRPROXY_CSPRCONHNDLR149",
1646:                                    params);
1647:                    translatedList.add(result);
1648:                }
1649:
1650:                if (translatedList.size() != 0) {
1651:                    resp.setHeader(headerName, translatedList);
1652:                }
1653:            }
1654:
1655:            /**
1656:             * PROXYLET - Code block begin
1657:             */
1658:
1659:            private boolean rewriteRequest(Request req) {
1660:                boolean isRoutedThroughProxylet = routedThroughProxylet(req);
1661:                boolean isRequestForProxylet = currentRequestForProxylet(req);
1662:
1663:                // rewrite if request is not coming through proxylet and if current
1664:                // request is not for proxylet
1665:                return ((isRoutedThroughProxylet == false) && (isRequestForProxylet == false));
1666:            }
1667:
1668:            private boolean routedThroughProxylet(Request req) {
1669:                // logger.info("BEGIN comingThroughProxylet");
1670:                logger.info("PSSRRPROXY_CSPRCONHNDLR150");
1671:
1672:                String pheader = req.getRequestHeader(proxyletHeaderKey);
1673:                // logger.info("PS-Proxylet is " + pheader);
1674:                Object[] params27 = { pheader };
1675:                logger.log(Level.INFO, "PSSRRPROXY_CSPRCONHNDLR151", params27);
1676:
1677:                if (pheader == null)
1678:                    return false;
1679:
1680:                if (pheader.indexOf("RT-Proxylet=true") != -1)
1681:                    return true;
1682:
1683:                // logger.info("END comingThroughProxylet");
1684:                logger.info("PSSRRPROXY_CSPRCONHNDLR152");
1685:
1686:                return false;
1687:            }
1688:
1689:            private boolean currentRequestForProxylet(Request req) {
1690:                // logger.info("BEGIN isRequestForProxylet" + req.getObject());
1691:                Object[] params29 = { req.getObject() };
1692:                logger.log(Level.INFO, "PSSRRPROXY_CSPRCONHNDLR153", params29);
1693:
1694:                if (req.getObject().indexOf("/proxylet") != -1) {
1695:                    return true;
1696:                }
1697:
1698:                // logger.info("END isRequestForProxylet");
1699:                logger.info("PSSRRPROXY_CSPRCONHNDLR154");
1700:
1701:                return false;
1702:            }
1703:
1704:            /**
1705:             * PROXYLET - Code block End
1706:             */
1707:
1708:            private Response processMissingObjectRequest(Request req) {
1709:                // logger.info("Session: Redirecting-> " + req.getURL()
1710:                Object[] params31 = { req.getURL() };
1711:                logger.log(Level.INFO, "PSSRRPROXY_CSPRCONHNDLR155", params31);
1712:
1713:                String gwscheme = req.getGatewayScheme();
1714:                StringBuffer redirectURL = new StringBuffer(100);
1715:
1716:                String gatewayProtocol = req
1717:                        .getProtocolFromCustomUrl(_gwprotocol);
1718:                String gatewayPort = req.getPortFromCustomUrl(_gwport);
1719:
1720:                redirectURL.append(gatewayProtocol).append("://");
1721:
1722:                if ((gatewayPort.equals("443") && gatewayProtocol
1723:                        .equals("https"))
1724:                        || (gatewayPort.equals("80") && gatewayProtocol
1725:                                .equals("http"))) {
1726:                    redirectURL.append(req.getGatewayHost()).append("/");
1727:                } else {
1728:                    redirectURL.append(req.getGatewayHost()).append(":")
1729:                            .append(gatewayPort).append("/");
1730:                }
1731:
1732:                if (gwscheme.length() > 0) {
1733:                    redirectURL.append(gwscheme).append("/");
1734:                }
1735:
1736:                redirectURL.append(req.getURL()).append("/");
1737:                return (new RedirectResponse(redirectURL.toString(), false));
1738:            }
1739:
1740:            public Response processNotificationRequest(Request req) {
1741:                Response rep = null;
1742:                try {
1743:                    DataOutputStream dos;
1744:                    dos = new DataOutputStream(_theSocket.getOutputStream());
1745:                    GatewayServletResponse gsrep = new GatewayServletResponse(
1746:                            dos);
1747:                    PLLNotificationServlet notify = new PLLNotificationServlet();
1748:                    notify.doPost((HttpServletRequest) req,
1749:                            (HttpServletResponse) gsrep);
1750:                    rep = null;
1751:                } catch (Exception ex) {
1752:                    // logger.severe("Exception in processing notification request: " +
1753:                    // ex);
1754:                    logger.log(Level.SEVERE, "PSSRRPROXY_CSPRCONHNDLR156", ex);
1755:                    // Lihue PRD - 8.2
1756:                    //String msg = "Session: Unable to process notification";
1757:                    //rep = new ErrorResponse(msg, null);
1758:                    String language = req.getRequestHeader("Accept-Language");
1759:                    String msg = "Session: Unable to process notification";
1760:                    if (notificationErrorMessage != null
1761:                            && notificationErrorMessage.length() > 0) {
1762:                        String userLocale = getUserLocale(req);
1763:                        msg = GWLocale.getPFString(notificationErrorMessage,
1764:                                new Object[] { msg }, userLocale);
1765:                    }
1766:                    // rep = new ErrorResponse(msg, null,language);
1767:                    // End of Code : Lihue PRD - 8.2
1768:                }
1769:
1770:                return rep;
1771:            }
1772:
1773:            private Response processStatisticsRequest(Request req) {
1774:                StringBuffer message = new StringBuffer(50);
1775:                String uri;
1776:                String params;
1777:                String param;
1778:
1779:                if (!isUserSessionValid(req)) {
1780:                    return new RedirectResponse((loginURL(req,
1781:                            _platformloginURL)));
1782:                }
1783:
1784:                message.append("<html>");
1785:                uri = req.getURI();
1786:                // /statistics/......
1787:                if (uri.startsWith("/statistics/") && uri.length() > 12) {
1788:                    params = uri.substring(12);
1789:                } else {
1790:                    params = "req&read&sent";
1791:                }
1792:
1793:                if (params.equals("reset")) {
1794:                    _numRequests = 0;
1795:                    _numBytesRead = 0;
1796:                    HTTPRetriever.numBytesRead = 0;
1797:                    _numBytesSent = 0;
1798:                    message.append("<p>Reset is ok.</p></html>");
1799:                    return (new StatisticsResponse(message.toString()));
1800:                }
1801:
1802:                StringTokenizer st = new StringTokenizer(params, "&");
1803:                while (st.hasMoreTokens()) {
1804:                    param = st.nextToken();
1805:                    if (param.equals("req")) {
1806:                        message.append("<p>Number of Requests: ").append(
1807:                                _numRequests).append("</p>");
1808:                    } else if (param.equals("read")) {
1809:                        message.append("<p>Number of Bytes Read: ").append(
1810:                                (_numBytesRead + HTTPRetriever.numBytesRead))
1811:                                .append("</p>");
1812:                    } else if (param.equals("sent")) {
1813:                        message.append("<p>Number of Bytes Sent: ").append(
1814:                                _numBytesSent).append("</p>");
1815:                    }
1816:                }
1817:
1818:                message.append("</html>");
1819:
1820:                return (new StatisticsResponse(message.toString()));
1821:            }
1822:
1823:            protected static String faviconLocation = "";
1824:
1825:            static {
1826:                faviconLocation = SystemProperties.get("gateway.favicon", "");
1827:                if (faviconLocation != null
1828:                        && faviconLocation.trim().length() == 0) {
1829:                    faviconLocation = null;
1830:                }
1831:            }
1832:
1833:            private Response processMissingProtocolRequest(Request req) {
1834:                // favicon.ico
1835:
1836:                if (req.getGatewayScheme() != null
1837:                        && req.getGatewayScheme().equalsIgnoreCase(
1838:                                "favicon.ico")
1839:                        && (req.getURL() == null || req.getURL().trim()
1840:                                .length() == 0)) {
1841:                    // Ok return the URL specified in the property "gateway.favicon"
1842:                    // from
1843:                    // platform.conf
1844:                    // logger.info("favicon.ico match !");
1845:                    logger.info("PSSRRPROXY_CSPRCONHNDLR157");
1846:                    Response rep;
1847:                    if (faviconLocation != null) {
1848:                        // logger.info("Redirecting to : " + faviconLocation);
1849:                        Object[] params34 = { faviconLocation };
1850:                        logger.log(Level.INFO, "PSSRRPROXY_CSPRCONHNDLR158",
1851:                                params34);
1852:                        rep = new RedirectResponse(faviconLocation, true);
1853:                    } else {
1854:                        // logger.info("Returning Not Found message");
1855:                        logger.info("PSSRRPROXY_CSPRCONHNDLR159");
1856:                        rep = new FileNotFoundResponse();
1857:                    }
1858:                    return rep;
1859:                }
1860:
1861:                /*
1862:                 * Fix for bug # 6220853 Ignore additional URLs sent by IE when
1863:                 * discussions are enabled
1864:                 * 
1865:                 */
1866:                if (shouldIgnoreURI(req.getURI())) {
1867:                    Response rep;
1868:                    GWDebug.debug.error("Returning Not Found Message");
1869:                    rep = new FileNotFoundResponse();
1870:                    return rep;
1871:                }
1872:
1873:                String gwhost = req.getGatewayHost();
1874:                String fqdnhost = getFQDN(gwhost);
1875:                if (fqdnhost == null) {
1876:                    // Lihue PRD - 8.2
1877:                    String message = gwhost;
1878:                    String language = req.getRequestHeader("Accept-Language");
1879:                    if (invalidGatewayHostNameErrorMessage != null
1880:                            && invalidGatewayHostNameErrorMessage.length() > 0) {
1881:                        String userLocale = getUserLocale(req);
1882:                        message = GWLocale.getPFString(
1883:                                invalidGatewayHostNameErrorMessage,
1884:                                new Object[] { message }, userLocale);
1885:                    } else {
1886:                        message = message
1887:                                + " is not a valid gateway host name.";
1888:                    }
1889:                    return (new ErrorResponse(message, null, language));
1890:                    //return (new ErrorResponse(gwhost +
1891:                    //      " is not a valid gateway host name.", null));
1892:                    // End of Code : Lihue PRD - 8.2
1893:                }
1894:
1895:                if (!gwhost.equalsIgnoreCase(fqdnhost)) {
1896:                    if ((_gwport.equals("443") && _gwprotocol.equals("https"))
1897:                            || (_gwport.equals("80") && _gwprotocol
1898:                                    .equals("http"))) {
1899:                        return (new RedirectResponse(_gwprotocol + "://"
1900:                                + fqdnhost + req.getURI(), false));
1901:                    } else {
1902:                        return (new RedirectResponse(_gwprotocol + "://"
1903:                                + fqdnhost + ":" + _gwport + req.getURI(),
1904:                                false));
1905:                    }
1906:                }
1907:
1908:                if (doingPDC == false) {
1909:                    // logger.info("Session: not doing PDC");
1910:                    logger.info("PSSRRPROXY_CSPRCONHNDLR160");
1911:                    return (new RedirectResponse(loginURL(req,
1912:                            _platformloginURL)));
1913:                }
1914:
1915:                boolean doingCert = false;
1916:                String tmpurl = req.getURL();
1917:                if (tmpurl != null) {
1918:                    //PDC Fix to support IS 6.1
1919:                    if (tmpurl.trim().toLowerCase().indexOf(
1920:                            "service=gatewaypdc") != -1) {
1921:                        doingCert = true;
1922:                    }
1923:                }
1924:                /*
1925:                 * PRD 3.7 (4338513) Authentication chaining will work with Certificate
1926:                 * authentication.
1927:                 */
1928:
1929:                if (!pdcCookiePresent && !doingCert) {
1930:                    invalidateSSL = true;
1931:                    return (new RedirectResponse(loginURL(req,
1932:                            _platformloginURL)));
1933:                }
1934:                //End of change of code for PRD 3.7
1935:                // logger.info("Session: doing PDC");
1936:                logger.info("PSSRRPROXY_CSPRCONHNDLR161");
1937:                if ((_gwport.equals("443") && _gwprotocol.equals("https"))
1938:                        || (_gwport.equals("80") && _gwprotocol.equals("http"))) {
1939:                    return (doPDC(gwhost, req));
1940:                } else {
1941:                    return (doPDC(gwhost + ":" + _gwport, req));
1942:                }
1943:            }
1944:
1945:            private Response processProtocolRequest(Request req) {
1946:                // Access control
1947:                SSOToken token = null;
1948:
1949:                /*
1950:                 * PRD 3.7 (4338513) Authentication chaining will work with Certificate
1951:                 * authentication. To handle the scenario of the session timeout or
1952:                 * invalidation happening at the portalserver side,
1953:                 */
1954:                //This flag keeps track of the session state from the response.
1955:                boolean setCookieFlagExist = false;
1956:                //End of code change for PRD 3.7
1957:
1958:                boolean rwpAclCheckEnforced = new Boolean(SystemProperties.get(
1959:                        "rewriterproxy.checkacl", "false")).booleanValue();
1960:
1961:                // Rewriter Proxy will check ACL if acl check is enabled and the URL being asked for is not in the non-auth list
1962:                if (ServiceIdentifier.isRewriterProxy()
1963:                        && !isNonAuthenticatedURL(req)) {
1964:                    if (rwpAclCheckEnforced && !isAccessControlAllowed(req))
1965:                        return getAccessDeniedResponse(req, token);
1966:                }
1967:
1968:                if (ServiceIdentifier.isGateway()) {
1969:                    if (isNonAuthenticatedURL(req)) {
1970:                        if (req.getURL().endsWith(_platformloginURL)) {
1971:                            /*
1972:                             * PRD 3.7 (4338513) Authentication chaining will work with
1973:                             * Certificate authentication.
1974:                             */
1975:                            if (doingPDC && !pdcCookiePresent)
1976:                                invalidateSSL = true;
1977:                            //End of change of code for PRD 3.7
1978:                        }
1979:                        /*
1980:                         * PRD 3.7 (4338513) Authentication chaining will work with
1981:                         * Certificate authentication.
1982:                         */
1983:                        if (doingPDC) {
1984:                            setCookieFlagExist = true;
1985:                        }
1986:                        //End of code change for PRD 3.7
1987:                    } else { // not platform url
1988:
1989:                        String sidstr = req.getSessionID();
1990:
1991:                        if (sidstr == null) {
1992:                            if (GWLogManager.loggingEnabled)
1993:                                GWLogManager.write("RProxy", GWLocale
1994:                                        .getPFString("session4",
1995:                                                new Object[] { _logId }));
1996:                            return (new RedirectResponse(loginURL(req,
1997:                                    _platformloginURL)));
1998:                        }
1999:
2000:                        try {
2001:                            token = validateSSOToken(sidstr);
2002:                        } catch (SSOException ssoEx) {
2003:                            // logger.log(Level.SEVERE, "Error creating SSOToken ",
2004:                            // ssoEx);
2005:                            logger.log(Level.SEVERE,
2006:                                    "PSSRRPROXY_CSPRCONHNDLR162", ssoEx);
2007:                            /**
2008:                             * PRD 3.7 (4338513) Authentication chaining will work with
2009:                             * Certificate authentication.
2010:                             */
2011:                            if (doingPDC) {
2012:                                return doPDC(req.getGatewayHost(), req);
2013:                            }
2014:                            //End of code change for PRD 3.7
2015:
2016:                            // Mridul - iDSAME migration
2017:                            return (new RedirectResponse(loginURL(req,
2018:                                    _platformloginURL)));
2019:                            // EOC : Mridul - iDSAME migration
2020:                        } catch (Exception e) {
2021:                            // logger.log(Level.SEVERE, "Error creating SSOToken ", e);
2022:
2023:                            logger.log(Level.SEVERE,
2024:                                    "PSSRRPROXY_CSPRCONHNDLR163", e);
2025:                            /**
2026:                             * PRD 3.7 (4338513) Authentication chaining will work with
2027:                             * Certificate authentication.
2028:                             */
2029:                            if (doingPDC) {
2030:                                return doPDC(req.getGatewayHost(), req);
2031:                            }
2032:                            //End of code change for PRD 3.7
2033:
2034:                            // Mridul - iDSAME migration
2035:                            return (new RedirectResponse(loginURL(req,
2036:                                    _platformloginURL)));
2037:                            // EOC : Mridul - iDSAME migration
2038:                        }
2039:
2040:                        SSOToken sess = token;
2041:
2042:                        /*
2043:                         * PRD 3.7 (4338513) Authentication chaining will work with
2044:                         * Certificate authentication. If a valid session exists, the
2045:                         * response should not contain a set-cookie for the IPS_COOKIE
2046:                         * cookie. This means that the session got invalidated before
2047:                         * the response was retrieved.
2048:                         */
2049:                        if (doingPDC) {
2050:                            setCookieFlagExist = true;
2051:                        }
2052:                        //End of code change for PRD 3.7
2053:
2054:                        try {
2055:                            if (GWLogManager.loggingEnabled)
2056:                                GWLogManager
2057:                                        .write(
2058:                                                "RProxy",
2059:                                                GWLocale
2060:                                                        .getPFString(
2061:                                                                "session3",
2062:                                                                new Object[] {
2063:                                                                        _logId,
2064:                                                                        new String(
2065:                                                                                GWLogManager
2066:                                                                                        .getUserId(req
2067:                                                                                                .getSessionID())),
2068:                                                                        token
2069:                                                                                .getIPAddress()
2070:                                                                                .toString() }));
2071:                        } catch (SSOException ex) {
2072:                        }
2073:
2074:                        if (!isAccessControlAllowed(req)) {
2075:                            return getAccessDeniedResponse(req, token);
2076:                        }
2077:                    }
2078:                }
2079:
2080:                String oldHost = req.getHost();
2081:                String oldPort = req.getPort();
2082:                String oldProtocol = req.getProtocol();
2083:                String oldObject = req.getObject();
2084:
2085:                // djl:  put ssl mode flag/check here...
2086:                Retriever retr = null;
2087:                // Mridul - iDSAME migration
2088:                // Uncommented the comment around this -
2089:                // This was commented 'cos , getProxyHost() uses internal api of iDSAME
2090:                // to get SessionServer - for drop 1 , this seems to be the only way
2091:                // to go , until the iDSAME guys fix/implement this ...
2092:                if (_useHTTPProxy) {
2093:
2094:                    String hphost = getProxyHost(req);
2095:                    // logger.info("GW using Rewriter Proxy :" + hphost);
2096:                    Object[] params40 = { hphost };
2097:                    logger.log(Level.INFO, "PSSRRPROXY_CSPRCONHNDLR164",
2098:                            params40);
2099:                    URL url = null;
2100:                    try {
2101:                        url = new URL(hphost);
2102:                    } catch (MalformedURLException mae) {
2103:                        // logger.severe("Malformed Rewriter Proxy URL :" + hphost);
2104:                        Object[] params41 = { hphost };
2105:                        logger.log(Level.SEVERE, "PSSRRPROXY_CSPRCONHNDLR165",
2106:                                params41);
2107:                    }
2108:
2109:                    req.setHost(url.getHost());
2110:                    if (url.getPort() != -1) {
2111:                        req.setPort(Integer.toString(url.getPort()));
2112:                    } else {
2113:                        req.setPort("10443");
2114:                    }
2115:                    req.setProtocol(url.getProtocol());
2116:                    req.setObject("/" + req.getURL());
2117:
2118:                    retr = RetrievalFactory.getRetriever(url.getProtocol());
2119:                    if (req instanceof  HTTPRequest) {
2120:                        ((HTTPRequest) req).populateWebProxyInfo();
2121:                    }
2122:                }
2123:                // EOC : Mridul - iDSAME migration
2124:                else {
2125:                    retr = RetrievalFactory.getRetriever(req.getProtocol());
2126:                    // logger.info("Session: HTTP not in HTTPS mode");
2127:                    logger.info("PSSRRPROXY_CSPRCONHNDLR166");
2128:
2129:                }
2130:
2131:                MonitoringSubsystem.handleEvent(
2132:                        RProxyEvent.IDENTIFY_DESTINATION, oldHost + "_"
2133:                                + oldPort);
2134:                Response rep = retrieveResponse(req, oldHost, retr, token);
2135:
2136:                if (_useHTTPProxy) {
2137:                    req.setHost(oldHost);
2138:                    req.setPort(oldPort);
2139:                    req.setProtocol(oldProtocol);
2140:                    req.setObject(oldObject);
2141:                }
2142:
2143:                /*
2144:                 * PRD 3.7 (4338513) Authentication chaining will work with Certificate
2145:                 * authentication.
2146:                 */
2147:                String rep_code = rep.getStatusCode();
2148:
2149:                /*
2150:                 * if the request url starts with platform logout url, remove the PDCCookie
2151:                 * from the browser. This ensures that the next time a request is sent for Login
2152:                 * PDC authentication happens
2153:                 */
2154:                if (doingPDC && req.getObject().startsWith(_platformlogoutURL)) {
2155:                    removePDCCookieFromBrowser(req, rep);
2156:                    setCookieFlagExist = false;
2157:                }
2158:
2159:                /*
2160:                 * If the setCookieFlagExist is set (i.e., a valid session exist) and
2161:                 * the response contains the set-cookie flag redo the PDC.
2162:                 */
2163:
2164:                else if (doingPDC && setCookieFlagExist
2165:                        && (rep instanceof  HTTPResponse)) {
2166:                    String iplanetCookie = null;
2167:                    List cookieList = ((HTTPResponse) rep)
2168:                            .getHeaderAttributeList("Set-Cookie");
2169:
2170:                    if ((cookieList != null) && (cookieList.size() > 0)) {
2171:                        boolean isSessionFound = false;
2172:                        for (Iterator it = cookieList.iterator(); it.hasNext();) {
2173:                            iplanetCookie = (String) it.next();
2174:
2175:                            int bindx = iplanetCookie
2176:                                    .indexOf(sessionCookieName);
2177:                            int eindx = iplanetCookie.indexOf('=', bindx);
2178:                            if (bindx > 1) {
2179:                                String temp = iplanetCookie.substring(bindx
2180:                                        + sessionCookieLen, eindx);
2181:                                if (!(temp.trim().equals("")))
2182:                                    bindx = -1;
2183:                            }
2184:
2185:                            if (iplanetCookie != null && bindx != -1) {
2186:                                String sidstr = req.getSessionID();
2187:                                isSessionFound = true;
2188:                                if (sidstr != null) {
2189:                                    SSOToken ssoToken = null;
2190:                                    try {
2191:                                        ssoToken = SSOUtil.getSSOToken(sidstr);
2192:                                    } catch (SSOException se) {
2193:                                        // logger.log(Level.SEVERE, "**** ssoToken =
2194:                                        // null ****", se);
2195:                                        logger.log(Level.SEVERE,
2196:                                                "PSSRRPROXY_CSPRCONHNDLR167",
2197:                                                se);
2198:                                    } catch (Exception e) {
2199:                                        // logger.log(Level.SEVERE, "**** ssoToken =
2200:                                        // null ****", e);
2201:                                        logger
2202:                                                .log(
2203:                                                        Level.SEVERE,
2204:                                                        "PSSRRPROXY_CSPRCONHNDLR168",
2205:                                                        e);
2206:                                    }
2207:                                    if (ssoToken == null) {
2208:                                        // return doPDC(req.getGatewayHost(),req);
2209:                                        // Bug # 5103906 - Can not see login fail page
2210:                                        // for invalid credentials
2211:                                        // when PDC enabled on GW --- Sandeep Soni
2212:                                        return rep;
2213:                                    }
2214:
2215:                                }
2216:                            }
2217:                        }
2218:                        /*
2219:                         * iPlanetDirectoryPro cookie is not present. But CookieList is present.
2220:                         * This is a condition where PDC has passed and the next Auth module has failed
2221:                         * So its necessary to remove the Cookie from the browser, so that
2222:                         * PDC is performed when the next request is sent
2223:                         */
2224:                        if (!isSessionFound) {
2225:                            for (Iterator itr1 = cookieList.iterator(); itr1
2226:                                    .hasNext();) {
2227:                                String cookie = (String) itr1.next();
2228:                                int index = cookie.indexOf(authCookieName);
2229:                                String value = null;
2230:                                if (index != -1) {
2231:                                    index = cookie.indexOf("=");
2232:                                    value = cookie.substring(index + 1);
2233:                                    if (value != null
2234:                                            && value.trim()
2235:                                                    .startsWith("LOGOUT")) {
2236:                                        removePDCCookieFromBrowser(req, rep);
2237:                                        break;
2238:                                    }
2239:                                }
2240:                            }
2241:                        }
2242:                    }
2243:                    //End of code change for the bug 4711442
2244:                    /*
2245:                     * IF the response is a redirected response and the redirect url is
2246:                     * the platform login url, redo the PDC.
2247:                     */
2248:                    else if (rep_code.startsWith("302")) {
2249:                        String s = rep.getResponseHeader("Location");
2250:                        if (s != null) {
2251:                            int indx = s.indexOf(":");
2252:                            if (indx != -1) {
2253:                                s = s.substring(indx + 1, s.length()).trim();
2254:                                if (s.toUpperCase().startsWith(
2255:                                        _platformloginURL.toUpperCase())) {
2256:                                    if (hostFound(req.getURI())) {
2257:                                        removePDCCookieFromBrowser(req, rep);
2258:                                    }
2259:                                } else {
2260:                                    int start, end;
2261:                                    start = s.indexOf("://");
2262:                                    if (start != -1) {
2263:                                        end = s.indexOf('/', start + 3);
2264:                                        if (end != -1) {
2265:                                            String rest = s.substring(0, end);
2266:                                            if (rest.toUpperCase().startsWith(
2267:                                                    _platformloginURL
2268:                                                            .toUpperCase())
2269:                                                    && (hostFound(req.getURI()))) {
2270:                                                removePDCCookieFromBrowser(req,
2271:                                                        rep);
2272:
2273:                                            }
2274:                                        }
2275:                                    }
2276:                                }
2277:                            }
2278:                        }
2279:                    }
2280:                }
2281:
2282:                //End of code change for PRD 3.7
2283:
2284:                return rep;
2285:            }
2286:
2287:            private Response getAccessDeniedResponse(Request req, SSOToken token) {
2288:                // Ok , this could be a redirect request that came in from
2289:                // the client side that the client side rewriter re-wrote !
2290:                // Handle that too ....
2291:                String sidstr = req.getSessionID();
2292:
2293:                Response rep = handleRedirectRequest(req, req.getHost());
2294:
2295:                if (rep != null) {
2296:                    return rep;
2297:                }
2298:
2299:                // Lihue PRD - 8.2
2300:                String message = "Access Denied";
2301:                String language = req.getRequestHeader("Accept-Language");
2302:                if (accessDeniedErrorMessage != null
2303:                        && accessDeniedErrorMessage.length() > 0) {
2304:                    String userLocale = getUserLocale(sidstr);
2305:                    message = GWLocale.getPFString(accessDeniedErrorMessage,
2306:                            new Object[] { message }, userLocale);
2307:                }
2308:                return (new ErrorResponse(message, token, language));
2309:                // End of Code : Lihue PRD - 8.2
2310:            }
2311:
2312:            private SSOToken validateSSOToken(String sid) throws Exception {
2313:                SSOTokenManager manager = SSOTokenManager.getInstance();
2314:                SSOToken token = SSOUtil.getSSOToken(sid);
2315:                MonitoringSubsystem.handleEvent(SRAEvent.SSO_VALIDATION_START);
2316:                manager.validateToken(token);
2317:                MonitoringSubsystem.handleEvent(SRAEvent.SSO_VALIDATION_END);
2318:                return token;
2319:            }
2320:
2321:            private boolean isNonAuthenticatedURLImpl(String requestURL) {
2322:                int numElements = nonAuthPathList.size();
2323:                String elem;
2324:                for (int i = 0; i < numElements; i++) {
2325:                    elem = (String) nonAuthPathList.get(i);
2326:                    if (requestURL.startsWith(elem)) {
2327:                        return true;
2328:                    }
2329:                }
2330:                return false;
2331:            }
2332:
2333:            private boolean isNonAuthenticatedURL(Request req) {
2334:
2335:                if (req.getProtocol() == null || req.getHost() == null) {
2336:                    return false;
2337:                }
2338:                String host = req.getProtocol().toLowerCase() + "://"
2339:                        + req.getHost().toLowerCase() + ":" + req.getPort();
2340:                String requestURL = null;
2341:                if (host == null) {
2342:                    return false;
2343:                }
2344:                String path = req.getObject();
2345:                if (path == null || path.trim().length() == 0) {
2346:                    path = "/";
2347:                }
2348:                if (serverList.contains(host)) {
2349:                    // For PS servers , it could be relative or absolute !
2350:                    requestURL = path;
2351:                    if (isNonAuthenticatedURLImpl(requestURL)) {
2352:                        return true;
2353:                    }
2354:                }
2355:                requestURL = host + path;
2356:                return isNonAuthenticatedURLImpl(requestURL);
2357:            }
2358:
2359:            private SSOToken getUserSession(Request req, String sid) {
2360:                SSOToken s = null;
2361:
2362:                try {
2363:                    SSOTokenManager ssoTokenManager = SSOTokenManager
2364:                            .getInstance();
2365:                    s = SSOUtil.getSSOToken(sid);
2366:
2367:                    if (!ssoTokenManager.isValidToken(s)) {
2368:                        // logger.info("Session: state is not VALID");
2369:                        logger.info("PSSRRPROXY_CSPRCONHNDLR169");
2370:                        if (GWLogManager.loggingEnabled)
2371:                            GWLogManager.write("RProxy", GWLocale.getPFString(
2372:                                    "session5", new Object[] { _logId, sid }));
2373:                        return null;
2374:                    }
2375:                } catch (Exception e) {
2376:                    // logger.log(Level.SEVERE, "Failed to get session", e);
2377:                    logger.log(Level.SEVERE, "PSSRRPROXY_CSPRCONHNDLR170", e);
2378:                    return null;
2379:                }
2380:
2381:                return s;
2382:            }
2383:
2384:            /*
2385:             * This method is taken from Profile.java of sp3 codebase and modified for
2386:             * use with Lihue - Mridul Does suffix or prefix or regular wildchar match
2387:             * depending on match value. If str1 matches str2 based on match type,
2388:             * return true, otherwise false. @param str1 string to be matched @param
2389:             * str2 string may contain one or more wildcard character '*' @return
2390:             * boolean value
2391:             */
2392:
2393:            private boolean wildcardMatch(String str1, String str2) {
2394:                int beginIndex1 = 0;
2395:                int endIndex1 = 0;
2396:                int beginIndex2 = 0;
2397:                int endIndex2 = 0;
2398:                int strlen1 = str1.length();
2399:                int strlen2 = str2.length();
2400:                String substr = null;
2401:
2402:                // if one of the string is null, consider it no match.
2403:                if ((str1.length() == 0) || (str2.length() == 0))
2404:                    return (false);
2405:                if ((str1 == null) || (str2 == null))
2406:                    return (false);
2407:
2408:                if ((endIndex2 = str2.indexOf('*', beginIndex2)) != -1) {
2409:                    // get the substring prior to the first '*'
2410:                    substr = str2.substring(beginIndex2, endIndex2);
2411:
2412:                    // check if the first char in str2 is '*', i.e. the substring is
2413:                    // null
2414:                    if (endIndex2 > beginIndex2) {
2415:                        // str1 contains the substring too? if not, no match
2416:                        if ((beginIndex1 = str1.indexOf(substr, beginIndex1)) == -1)
2417:                            return (false);
2418:                        // if it is not a SUFFIX match, then the prefixes should be
2419:                        // equal
2420:                        //if ((beginIndex1 != beginIndex2) && (match != SUFFIX))
2421:                        if (beginIndex1 != beginIndex2)
2422:                            return (false);
2423:                    }
2424:                    // move the pointer to next char after the substring already matched
2425:                    beginIndex1 = beginIndex1 + (endIndex2 - beginIndex2);
2426:                    if (endIndex2 >= strlen2 - 1)
2427:                        return (true);
2428:                    beginIndex2 = endIndex2 + 1;
2429:                } else // str2 doesn't contain wildcard '*'
2430:                {
2431:                    if ((beginIndex1 = str1.indexOf(str2)) == -1)
2432:                        return (false);
2433:                    //if ((match == PREFIX) && (beginIndex1 == beginIndex2))
2434:                    if (beginIndex1 == beginIndex2)
2435:                        return (true);
2436:                    //if ((match == REGULAR) && (strlen1 == strlen2))
2437:                    //return(true);
2438:                    //if ((match == SUFFIX) && ((strlen1 - beginIndex1) == strlen2))
2439:                    //return(true);
2440:                    return (false);
2441:                }
2442:
2443:                // There are more than '*'s in str2, repeat what we have done
2444:                while ((endIndex2 = str2.indexOf('*', beginIndex2)) != -1) {
2445:                    substr = str2.substring(beginIndex2, endIndex2);
2446:                    if (endIndex2 > beginIndex2)
2447:                        if ((beginIndex1 = str1.indexOf(substr, beginIndex1)) == -1)
2448:                            return (false);
2449:                    beginIndex1 = beginIndex1 + (endIndex2 - beginIndex2);
2450:                    if (endIndex2 >= strlen2 - 1)
2451:                        return (true);
2452:                    beginIndex2 = endIndex2 + 1;
2453:                }
2454:                // The substring after the last '*'
2455:                substr = str2.substring(beginIndex2, strlen2);
2456:
2457:                if ((endIndex1 = str1.lastIndexOf(substr, strlen1 - 1)) == -1)
2458:                    return (false);
2459:
2460:                if (beginIndex1 > endIndex1)
2461:                    return (false);
2462:
2463:                //beginIndex1 = endIndex1;
2464:                // if ((match == PREFIX) || ((strlen1 - beginIndex1) == (strlen2 -
2465:                // beginIndex2)))
2466:                return (true);
2467:                //return(false);
2468:            }
2469:
2470:            /*
2471:             The following are the results of the getDomain(url) function:
2472:            
2473:             * Intially we assume any string between first occurence of // and / is the hostname.domain
2474:             * "scheme://hostname.domain:port" portion of any url is case insensitive
2475:             * if we cannot find the hostname.domain portion, we take complete url for case insensitive 
2476:             * comparision
2477:            
2478:             "hostname" => "hostname"
2479:             "http://hostname" => "http://hostname"
2480:             "http://hostname.india.sun.com/" => "http://hostname.india.sun.com/"
2481:             "*://hostname.india.sun.com/" => "*://hostname.india.sun.com/" 
2482:             "*hostname.india.sun.com*portal*.html" => "*hostname.india.sun.com*portal*.html"
2483:             "*.india.sun.com/portal*.html" => "*.india.sun.com"
2484:             */
2485:            private String getDomain(String url) {
2486:                //System.out.println("\n" + url + "=>\n");
2487:                String domain = "";
2488:                if (url.indexOf("//") >= 0) {
2489:                    int str1Index = url.indexOf("//", 0);
2490:                    int str2Index = url.indexOf("/", str1Index + 2);
2491:                    if (str2Index >= 0)
2492:                        domain = url.substring(0, str2Index);
2493:                    else
2494:                        domain = url;
2495:                } else if (url.indexOf("/") >= 0) {
2496:                    domain = url.substring(0, url.indexOf("/"));
2497:                } else {
2498:                    domain = url;
2499:                }
2500:                return domain;
2501:            }
2502:
2503:            private boolean isAccessControlAllowed(Request req) {
2504:
2505:                boolean allowed = false;
2506:                String sessid = req.getSessionID();
2507:                try {
2508:                    //System.out.println("Getting profile ..... Sessid : " +sessid);
2509:                    UserProfile prof = new UserProfile(sessid);
2510:                    //System.out.println("Got Profile  : " + prof);
2511:                    boolean matchFound = false;
2512:
2513:                    //Obtain GatewayMinAuthLevel attribute
2514:                    //Check if it is wild card (*)
2515:                    // Other wise check if the user Auth Level Satisfies Minimum
2516:                    // requirement
2517:                    //for accessing Gateway.
2518:                    String gwMinAuthLevel = (String) GatewayProfile.getString(
2519:                            "MinAuthLevel", "*");
2520:
2521:                    int minAuthLevel = 999;
2522:                    if (!gwMinAuthLevel.equals("*")) {
2523:
2524:                        try {
2525:                            minAuthLevel = Integer.parseInt(gwMinAuthLevel);
2526:                        } catch (NumberFormatException nfe) {
2527:                            // logger.severe("Illegal Value for Gateway Min
2528:                            // // Authentication Level");
2529:                            logger.severe("PSSRRPROXY_CSPRCONHNDLR171");
2530:                            return false;
2531:                        }
2532:                        SSOTokenManager ssoTokenManager = SSOTokenManager
2533:                                .getInstance();
2534:                        SSOToken validToken = SSOUtil.getSSOToken(sessid);
2535:                        if (validToken.getAuthLevel() < minAuthLevel) {
2536:                            return false;
2537:                        }
2538:                    }
2539:                    // Check whether Access is allowed by auth level.
2540:                    if (prof.getString(
2541:                            "sunPortalGatewayAllowedAuthLevelResult", "true")
2542:                            .equalsIgnoreCase("false")) {
2543:                        return false;
2544:                    }
2545:
2546:                    List list = prof
2547:                            .getStringList("sunportalgatewayaccessdenylist");
2548:                    Iterator iter = list.iterator();
2549:                    String denyString;
2550:                    String requrl = req.getURL();
2551:                    //System.out.println("Deny list - "+list);
2552:                    while (iter.hasNext()) {
2553:                        denyString = iter.next().toString();
2554:                        if (denyString.equals("*")) {
2555:                            allowed = false;
2556:                            matchFound = true;
2557:                            break;
2558:                        }
2559:
2560:                        String domain = getDomain(denyString);
2561:                        String lowerDomain = domain.toLowerCase();
2562:                        denyString = denyString.replaceAll(domain, lowerDomain);
2563:                        domain = getDomain(requrl);
2564:                        lowerDomain = domain.toLowerCase();
2565:                        requrl = requrl.replaceAll(domain, lowerDomain);
2566:
2567:                        if (wildcardMatch(requrl, denyString)) {
2568:                            allowed = false;
2569:                            matchFound = true;
2570:                            break;
2571:                        }
2572:                    }
2573:
2574:                    if (!matchFound) {
2575:
2576:                        list = prof
2577:                                .getStringList("sunportalgatewayaccessallowlist");
2578:                        iter = list.iterator();
2579:                        String allowString;
2580:                        //System.out.println("Allow list - "+list);
2581:                        while (iter.hasNext()) {
2582:                            allowString = iter.next().toString();
2583:                            /*
2584:                             * if (requrl.startsWith(url)){ allowed = false; break; }
2585:                             */
2586:                            if (allowString.equals("*")) {
2587:                                allowed = true;
2588:                                matchFound = true;
2589:                                break;
2590:                            }
2591:
2592:                            String domain = getDomain(allowString);
2593:                            String lowerDomain = domain.toLowerCase();
2594:                            denyString = allowString.replaceAll(domain,
2595:                                    lowerDomain);
2596:                            domain = getDomain(requrl);
2597:                            lowerDomain = domain.toLowerCase();
2598:                            requrl = requrl.replaceAll(domain, lowerDomain);
2599:
2600:                            if (wildcardMatch(requrl, allowString)) {
2601:                                allowed = true;
2602:                                matchFound = true;
2603:                                break;
2604:                            }
2605:                        }
2606:                    }
2607:
2608:                    if (!matchFound) {
2609:                        // If not there in both lists - hence deny it.
2610:                        allowed = false;
2611:                    }
2612:
2613:                    if (!allowed) {
2614:                        logger.warning("Session: request is not allowed");
2615:                        if (GWLogManager.loggingEnabled)
2616:                            GWLogManager
2617:                                    .write(
2618:                                            "RProxy",
2619:                                            GWLocale
2620:                                                    .getPFString(
2621:                                                            "session8",
2622:                                                            new Object[] {
2623:                                                                    _logId,
2624:                                                                    req
2625:                                                                            .getURL(),
2626:                                                                    new String(
2627:                                                                            GWLogManager
2628:                                                                                    .getUserId(req
2629:                                                                                            .getSessionID())) }));
2630:                    }
2631:                } catch (Exception e) {
2632:                    // logger.log(Level.SEVERE, "Session: failed to get URLPrivList",
2633:                    // e);
2634:                    logger.log(Level.SEVERE, "PSSRRPROXY_CSPRCONHNDLR172", e);
2635:                    allowed = false;
2636:                }
2637:
2638:                return allowed;
2639:            }
2640:
2641:            Response handleRedirectRequest(Request req, String destinationHost) {
2642:                if (req.getGatewayScheme().equals("redirect")) {
2643:                    // If this is a redrect response - just send a corresponding request
2644:                    // to browser
2645:                    // and don't try to fetch the page
2646:                    String cliUrl = req.getURL();
2647:                    // Check if this belongs to one of the Proxies
2648:                    if (!DomainWebProxyConfig.containHost(destinationHost)) {
2649:                        // Url points to some other (external) server - needs no url
2650:                        // rewriting
2651:                        MonitoringSubsystem
2652:                                .handleEvent(RProxyEvent.EXTERNAL_URL_REQ);
2653:                        return new RedirectResponse(cliUrl, false);
2654:                    }
2655:                }
2656:                return null;
2657:            }
2658:
2659:            Response retrieveResponse(Request req, String destinationHost,
2660:                    Retriever retr, SSOToken token) {
2661:                Response rep;
2662:
2663:                String acceptEncoding = req.getRequestHeader("Accept-Encoding");
2664:                if (acceptEncoding != null) {
2665:                    // Remove header
2666:                    req.setRequestHeader("Accept-Encoding", "");
2667:                }
2668:
2669:                rep = handleRedirectRequest(req, destinationHost);
2670:
2671:                if (rep != null) {
2672:                    return rep;
2673:                }
2674:
2675:                MonitoringSubsystem.handleEvent(RProxyEvent.REQUEST_SENT);
2676:                rep = retr.getResponse(req, destinationHost, _logId);
2677:                MonitoringSubsystem.handleEvent(RProxyEvent.RESPONSE_RECVD);
2678:                if (rep == null) {
2679:                    logger.warning("Session: Unable to connect to host:  "
2680:                            + req.getHost());
2681:                    if (req.getGatewayScheme().equals("redirect")) {
2682:                        if (req.getUseProxy()) {
2683:                            // Lihue PRD - 8.2
2684:                            String message = req.getProxyHost() + ":"
2685:                                    + req.getProxyPort();
2686:                            if (webProxErrorMessage != null
2687:                                    && webProxErrorMessage.length() > 0) {
2688:                                String userLocale = getUserLocale(token);
2689:                                message = GWLocale.getPFString(
2690:                                        webProxErrorMessage,
2691:                                        new Object[] { message }, userLocale);
2692:                            } else {
2693:                                message = "Session: Unable to connect to web prox host: "
2694:                                        + message + ".";
2695:                            }
2696:                            String language = req
2697:                                    .getRequestHeader("Accept-Language");
2698:                            rep = new ErrorResponse(message, token, language);
2699:                            // rep = new ErrorResponse("Session: Unable to connect to
2700:                            // web prox host: " + req.getProxyHost() + ":" +
2701:                            // req.getProxyPort() + ".", token);
2702:                            // End of Code : Lihue PRD - 8.2
2703:                        } else {
2704:                            MonitoringSubsystem
2705:                                    .handleEvent(RProxyEvent.EXTERNAL_URL_REQ);
2706:                            rep = new RedirectResponse(req.getURL(), false);
2707:                        }
2708:                    } else {
2709:                        if (ServiceIdentifier.isGateway()) {
2710:                            // Lihue PRD - 8.2
2711:                            String message = req.getHost();
2712:                            if (hostConnectErrorMessage != null
2713:                                    && hostConnectErrorMessage.length() > 0) {
2714:                                String userLocale = getUserLocale(token);
2715:                                message = GWLocale.getPFString(
2716:                                        hostConnectErrorMessage,
2717:                                        new Object[] { message }, userLocale);
2718:                            } else {
2719:                                message = "Session: Unable to connect to host:  "
2720:                                        + message + ".";
2721:                            }
2722:                            String language = req
2723:                                    .getRequestHeader("Accept-Language");
2724:                            rep = new ErrorResponse(message, token, language);
2725:                            // rep = new ErrorResponse("Session: Unable to connect to
2726:                            // host: " + req.getHost() + ".", token);
2727:                            // End of Code : Lihue PRD - 8.2
2728:                        } else {
2729:                            // Lihue PRD - 8.2
2730:                            String message = "Session: Unable to connect to host:  "
2731:                                    + req.getHost() + ".";
2732:                            if (hostConnectErrorMessage != null
2733:                                    && hostConnectErrorMessage.length() > 0) {
2734:                                String userLocale = getUserLocale(token);
2735:                                message = GWLocale.getPFString(
2736:                                        hostConnectErrorMessage,
2737:                                        new Object[] { message }, userLocale);
2738:                            }
2739:                            String language = req
2740:                                    .getRequestHeader("Accept-Language");
2741:                            rep = new ErrorResponse(message, UNKNOWN_HOST,
2742:                                    token, language);
2743:                            // rep = new ErrorResponse("Session: Unable to connect to
2744:                            // host: " + req.getHost() + ".", UNKNOWN_HOST, token);
2745:                            // End of Code : Lihue PRD - 8.2
2746:                        }
2747:                    }
2748:                } else {
2749:                    if (ServiceIdentifier.isGateway()) {
2750:                        String statusText = rep.getStatusText();
2751:                        if (statusText != null) {
2752:                            if (statusText.equals(UNKNOWN_HOST)) {
2753:                                if (req.getGatewayScheme().equals("redirect")) {
2754:                                    BufferedInputStream in = null;
2755:                                    in = rep.getContentStream();
2756:                                    try {
2757:                                        if (in instanceof  CSBufferedInputStream) {
2758:                                            ((CSBufferedInputStream) in)
2759:                                                    .getSocket().close();
2760:                                        }
2761:                                    } catch (Exception ex1) {
2762:                                    }
2763:                                    rep = new RedirectResponse(req.getURL(),
2764:                                            false);
2765:                                } else {
2766:                                    rep.setStatusText("Bad Gateway");
2767:                                }
2768:                            }
2769:                        }
2770:                    }
2771:                }
2772:                return rep;
2773:            }
2774:
2775:            /*
2776:             * Removing dependency on DSAME private API's esp SessionID classes. Session
2777:             * Stickyness is maintained by storing the rewriter proxy value on to the
2778:             * users session
2779:             */
2780:
2781:            private String getProxyHost(Request req) {
2782:                String sid = req.getSessionID();
2783:                String server = null;
2784:                SSOToken validToken = null;
2785:
2786:                try {
2787:                    SSOTokenManager ssoTokenManager = SSOTokenManager
2788:                            .getInstance();
2789:                    validToken = SSOUtil.getSSOToken(sid);
2790:
2791:                    if (ssoTokenManager.isValidToken(validToken)) {
2792:                        server = validToken.getProperty(REWRITER_PROXY);
2793:                        /*
2794:                         * Is the Session valid, if so check for rewriter proxy that
2795:                         * this session is using.
2796:                         */
2797:
2798:                        if (server != null) {
2799:                            /*
2800:                             * Got a rewrite proxy check whether its alive if so
2801:                             * associate with the session
2802:                             */
2803:
2804:                            if (RewriterProxyRouter.getInstance()
2805:                                    .isRewriterProxyAlive(server)) {
2806:                                return server;
2807:
2808:                            } else {
2809:
2810:                                /*
2811:                                 * Rewrite proxy associated with this session is not
2812:                                 * alive so choose new
2813:                                 */
2814:                                server = RewriterProxyRouter.getInstance()
2815:                                        .getRewriterProxyAlive();
2816:                                if (server == null) {
2817:
2818:                                    /*
2819:                                     * Is the new Rewrite proxy a valid one. IF not let
2820:                                     * it fail return any RWP
2821:                                     */
2822:
2823:                                    return RewriterProxyRouter.getServer();
2824:
2825:                                } else {
2826:
2827:                                    /*
2828:                                     * New Rewrite proxy a valid one use this from
2829:                                     * thereon
2830:                                     */
2831:                                    MonitoringSubsystem
2832:                                            .handleEvent(SRAEvent.SSO_SET_PROPERTY_START);
2833:                                    validToken.setProperty(REWRITER_PROXY,
2834:                                            server);
2835:                                    MonitoringSubsystem
2836:                                            .handleEvent(SRAEvent.SSO_SET_PROPERTY_END);
2837:                                    return server;
2838:
2839:                                }
2840:                            }
2841:
2842:                        } else {
2843:                            /*
2844:                             *  No Rewrite proxy associated with session so choose one
2845:                             */
2846:                            server = RewriterProxyRouter.getInstance()
2847:                                    .getRewriterProxyAlive();
2848:                            if (server == null) {
2849:                                return RewriterProxyRouter.getServer();
2850:                            } else {
2851:                                MonitoringSubsystem
2852:                                        .handleEvent(SRAEvent.SSO_SET_PROPERTY_START);
2853:                                validToken.setProperty(REWRITER_PROXY, server);
2854:                                MonitoringSubsystem
2855:                                        .handleEvent(SRAEvent.SSO_SET_PROPERTY_END);
2856:                                return server;
2857:                            }
2858:                        }
2859:
2860:                    } else {
2861:
2862:                        /*
2863:                         * Session is invalid, so can't maintain a sticky session so
2864:                         * randomly choose a rewriter proxy
2865:                         */
2866:                        server = RewriterProxyRouter.getInstance()
2867:                                .getRewriterProxyAlive();
2868:                        if (server == null) {
2869:                            return RewriterProxyRouter.getServer();
2870:
2871:                        } else {
2872:                            return server;
2873:                        }
2874:
2875:                    }
2876:
2877:                } catch (Exception soe) {
2878:                    /*
2879:                     * Session is invalid, so cant maintain a sticky session so randomly
2880:                     * choose a rewriter proxy
2881:                     */
2882:                    server = RewriterProxyRouter.getInstance()
2883:                            .getRewriterProxyAlive();
2884:                    if (server == null) {
2885:                        return RewriterProxyRouter.getServer();
2886:
2887:                    } else {
2888:                        return server;
2889:                    }
2890:                }
2891:            }
2892:
2893:            private String loginURL(Request req, String loginURLObject) {
2894:
2895:                String server;
2896:
2897:                String sid = req.getSessionID();
2898:
2899:                server = ServersList.getInstance().getServeraLive();
2900:
2901:                String _gw = req.getGatewayHost();
2902:                String _uri = req.getURI();
2903:
2904:                /**
2905:                 * Changes to accomodate DSAME pdc support. Bug : 4670649
2906:                 */
2907:                //PDC Fix to support IS 6.1
2908:                //String dm = _gw;
2909:                String org = getDefaultOrg(req.getGatewayHost());
2910:
2911:                // Bug ID - 4628539
2912:                //Change of code for Bug : 4670649
2913:                String gotoParam = null;
2914:                boolean addGotoParam = false;
2915:                if (req.getProtocol() != null) {
2916:                    addGotoParam = true;
2917:                    gotoParam = req.getURL();
2918:                    if (gotoParam == null) {
2919:                        // Should not happen
2920:                        addGotoParam = false;
2921:                    }
2922:                } else {
2923:                    if (_uri.length() > 1) {
2924:                        /**
2925:                         * Changes to accomodate DSAME pdc support. Bug : 4670649
2926:                         */
2927:
2928:                        int indx = _uri.toLowerCase().indexOf("org=");
2929:                        if (indx != -1) {
2930:                            indx += 4;
2931:                            int indx1 = _uri.indexOf('&', indx);
2932:                            if (indx1 == -1) {
2933:                                indx1 = _uri.length();
2934:                            }
2935:                            org = _uri.substring(indx, indx1);
2936:                            if (org.equalsIgnoreCase("statistics")) {
2937:                                org = defaultOrg;
2938:                            }
2939:                        }
2940:                        //Change of code for Bug : 4670649
2941:                        else if (req.getProtocol() == null
2942:                                && !(_uri.endsWith(_platformloginURL))) {
2943:                            //PDC Fix to support IS 6.1
2944:                            //dm += _uri;
2945:                            // Fix for 5072021 - Sandeep Soni
2946:                            // if org= is not found, we need to get the URI and make
2947:                            // sure there are no & in the URI
2948:                            // if there are then remove the org parameter and encode
2949:                            // only that.
2950:                            indx = _uri.toLowerCase().indexOf("&");
2951:                            if (indx != -1)
2952:                                org = _uri.substring(1, indx);
2953:                            else
2954:                                org = _uri.substring(1);
2955:
2956:                            if (org.equalsIgnoreCase("statistics")) {
2957:                                org = defaultOrg;
2958:                            }
2959:                        }
2960:                    }
2961:                }
2962:
2963:                /**
2964:                 * Changes to accomodate support to login in to different domains. Bug :
2965:                 * 4692270
2966:                 */
2967:
2968:                String _param = null;
2969:                String decodeParam = null;
2970:
2971:                if (addGotoParam && gotoParam != null
2972:                        && gotoParam.indexOf("goto=") != -1) {
2973:
2974:                    // As part of perf bug - decide whether the goto param should really
2975:                    // be added.
2976:                    // See if gotoParam starts with a login URL to a portalserver and
2977:                    // also
2978:                    // contains the "goto" parameter within it - in that case dont
2979:                    // append
2980:                    // it.
2981:                    // All servers in the list are lowercased .... atleast in the
2982:                    // current implementation.
2983:                    Iterator iter = expandedSessionServersList.iterator();
2984:                    String tmpServer;
2985:
2986:                    try {
2987:                        decodeParam = URLDecoder.decode(gotoParam.trim()
2988:                                .toLowerCase());
2989:                    } catch (Exception e) {
2990:                        logger.log(Level.SEVERE, "Error in decoding : "
2991:                                + e.getMessage());
2992:                        decodeParam = gotoParam;
2993:                    }
2994:
2995:                    int ix = decodeParam.indexOf("goto=");
2996:                    decodeParam = decodeParam.substring(ix + 5);
2997:                    ix = decodeParam.indexOf("&");
2998:                    if (ix != -1)
2999:                        decodeParam = decodeParam.substring(0, ix);
3000:
3001:                    //loginURLObject
3002:                    while (iter.hasNext()) {
3003:                        tmpServer = (String) iter.next();
3004:                        if (tmpServer != null) {
3005:                            if (decodeParam.startsWith(tmpServer)) {
3006:                                // Maybe .. check if the object is loginURLObject.
3007:                                if (decodeParam.indexOf(loginURLObject
3008:                                        .toLowerCase()) != //tmpServer.length()
3009:                                -1) {
3010:                                    addGotoParam = false;
3011:                                    break;
3012:                                }
3013:                            }
3014:                            // The host/protocol/port has already matched , so break.
3015:                            break;
3016:                        }
3017:                    }
3018:                }
3019:
3020:                try {
3021:                    if (org.indexOf('=') != -1) {
3022:                        org = URLEncoder.encode(org);
3023:                    }
3024:                    // Now if there was a & in the URI and we removed it to get the org,
3025:                    // put it back there.
3026:                    int indx = _uri.toLowerCase().indexOf("&");
3027:                    if (indx != -1)
3028:                        org += _uri.substring(indx);
3029:
3030:                } catch (Exception ex) {
3031:                }
3032:                /*
3033:                 *Check for the gotoParam
3034:                 *If the gotoParam already exists, meaning the user wishes to go already somewhere else
3035:                 *on the intranet and knows about the URL, so proceed in the normal fashion as handled
3036:                 *by the bug id 4628539
3037:                 *In case there is  no gotoParam, obtain a portal server URL and append goto to the redirection
3038:                 * url.
3039:
3040:                 */
3041:
3042:                //Added for fix for bug id 6440920 Date June 20,2006
3043:                String defaultGoToParam = "";
3044:                boolean addDefaultGoToParam = false;
3045:                String portalHost = "";
3046:                if (gotoParam == null) {
3047:                    portalHost = SrapClient.getNextAvailablePortalHost();
3048:                    String portalHost1 = portalHost.substring(0, portalHost
3049:                            .lastIndexOf("/"));
3050:                    String unEncodedDefaultGoToParam = portalHost1 + "/dt";
3051:                    //String hardCodedPortalHost = "http://vihang.india.sun.com/portal/dt";
3052:                    //defaultGoToParam = URLEncoder.encode(hardCodedPortalHost);
3053:                    defaultGoToParam = URLEncoder
3054:                            .encode(unEncodedDefaultGoToParam);
3055:                    addDefaultGoToParam = true;
3056:                }
3057:                //End Of Addition
3058:                if (addGotoParam) {
3059:
3060:                    try {
3061:
3062:                        gotoParam = URLEncoder.encode(decodeParam);
3063:                    } catch (Exception ex) {
3064:                    }
3065:
3066:                    _param = new StringBuffer().append("gw=").append(_gw)
3067:                            .append("&org=").append(org).append("&goto=")
3068:                            .append(gotoParam).toString();
3069:                } else {
3070:                    //Added for fix for bug id 6440920 Date June 20,2006
3071:                    if (addDefaultGoToParam) {
3072:                        _param = new StringBuffer().append("gw=")
3073:                                .append(_gw)
3074:                                .
3075:                                //append("&dm=").
3076:                                //append(dm).
3077:                                append("&org=").append(org).append("&goto=")
3078:                                .append(defaultGoToParam).toString();
3079:                    } else {
3080:                        _param = new StringBuffer().append("gw=").append(_gw).
3081:                        //append("&dm=").
3082:                                //append(dm).
3083:                                append("&org=").append(org).toString();
3084:                    }
3085:                    //End Of Addition
3086:                }
3087:
3088:                //Change of code for Bug : 4692270
3089:                // EOC : 4628539
3090:
3091:                /**
3092:                 * Changes to accomodate DSAME pdc support. Bug : 4670649
3093:                 */
3094:                if (doingPDC) {
3095:                    _param = _param + "&service=gatewaypdc";
3096:                }
3097:                //Change of code for Bug : 4670649
3098:                /*
3099:                 * if (GatewayProfile.getBoolean("MapForceURLSession", false)) return
3100:                 * server + loginURLObject +"?"+URLEncoder.encode(_param); else
3101:                 */
3102:                return server + loginURLObject + "?" + _param;
3103:            }
3104:
3105:            /**
3106:             * Close the session.
3107:             */
3108:            public void close() {
3109:
3110:                try {
3111:                    _theSocket.getOutputStream().flush();
3112:                } catch (Exception ex) {
3113:                }
3114:                // Lihue - KeepAlive
3115:                if (_theSocket != null) {
3116:                    try {
3117:                        _theSocket.close();
3118:                    } catch (Exception ex) {
3119:                    }
3120:                    _theSocket = null;
3121:                }
3122:
3123:                if (processKeepAliveConnections && actualClientSocket != null) {
3124:                    /*
3125:                     * Necessary when we dont have a direct connection from RProxy to
3126:                     * the browser in https mode and go through RWGroupClear. This is a
3127:                     * workaround for the JSS bug , due to which the socket is not
3128:                     * getting closed properly (observed especially for applet
3129:                     * connections). Hence from Session.java , we request the
3130:                     * RWGroupClear to close its plain sockets to RProxy and to browser.
3131:                     * This is workaround only and may not be necessary when this bug is
3132:                     * fixed or we move to JSSE which doesn't seem to have this problem
3133:                     * (??) - Mridul
3134:                     */
3135:                    try {
3136:                        Thread.currentThread().sleep(100);
3137:                    } catch (Exception ex) {
3138:                    }
3139:                    try {
3140:                        actualClientSocket.close();
3141:                    } catch (Exception ex) {
3142:                    }
3143:                    actualClientSocket = null;
3144:                }
3145:                // End of Code : Lihue - KeepAlive
3146:            }
3147:
3148:            private static void setVirtualHostname() {
3149:                virtualHost.add(rphost);
3150:                String s = SystemProperties.get("gateway.virtualhost", null);
3151:                if (s == null) {
3152:                    return;
3153:                }
3154:
3155:                StringTokenizer tokens = new StringTokenizer(s);
3156:                while (tokens.hasMoreTokens()) {
3157:                    s = tokens.nextToken().trim();
3158:                    virtualHost.add(s.toLowerCase());
3159:                    virtualHostActual.add(s);
3160:                }
3161:            }
3162:
3163:            protected String getDefaultOrg(String gwhost) {
3164:
3165:                if (gwhost == null || gwhost.trim().length() == 0) {
3166:                    return defaultOrg;
3167:                }
3168:
3169:                String org = (String) virtualHostOrgMapping.get(gwhost
3170:                        .toLowerCase());
3171:
3172:                return org == null ? defaultOrg : org;
3173:            }
3174:
3175:            private static void populateVirtualHostDefaultOrgMapping() {
3176:
3177:                // For each virtual host 'host' , check whether there is a corresponding
3178:                // entry
3179:                // host.defaultOrg
3180:                // If yes , use its value as defaultOrg for Login URL for this
3181:                // virtualHost
3182:
3183:                Iterator iter = virtualHostActual.iterator();
3184:                virtualHostOrgMapping = new HashMap();
3185:
3186:                while (iter.hasNext()) {
3187:
3188:                    String vhost = iter.next().toString().trim();
3189:
3190:                    String virtualHostOrgMappingStr = SystemProperties
3191:                            .get(vhost + ".defaultOrg");
3192:
3193:                    if (virtualHostOrgMappingStr != null
3194:                            && virtualHostOrgMappingStr.trim().length() > 0) {
3195:                        virtualHostOrgMapping.put(vhost.toLowerCase(),
3196:                                virtualHostOrgMappingStr.trim());
3197:                    }
3198:                }
3199:            }
3200:
3201:            private String getFQDN(String name) {
3202:                String host;
3203:                int numHosts = virtualHost.size();
3204:                for (int i = 0; i < numHosts; ++i) {
3205:                    host = (String) virtualHost.get(i);
3206:                    if (host.regionMatches(true, 0, name, 0, name.length())) {
3207:                        return host;
3208:                    }
3209:                }
3210:
3211:                return null;
3212:            }
3213:
3214:            // Lihue PRD - 8.2
3215:            private String getUserLocale(Request req) {
3216:
3217:                if (req == null) {
3218:                    return defaultLocale;
3219:                }
3220:
3221:                return getUserLocale(req.getSessionID());
3222:            }
3223:
3224:            private String getUserLocale(SSOToken token) {
3225:
3226:                if (token == null) {
3227:                    return defaultLocale;
3228:                }
3229:
3230:                return getUserLocale(token.getTokenID().toString());
3231:            }
3232:
3233:            private String getUserLocale(String sessid) {
3234:                try {
3235:                    UserProfile prof = new UserProfile(sessid);
3236:                    return prof.getString("preferredlocale", "en_US");
3237:                } catch (Exception ex) {
3238:                    return defaultLocale;
3239:                }
3240:            }
3241:
3242:            // End of Code : Lihue PRD - 8.2
3243:
3244:            private Response doPDC(String _rpName, Request req) {
3245:                /**
3246:                 * Changes to accomodate PRD 3.7.
3247:                 */
3248:                //hasPDCBeenDone = true;
3249:                // End of code change for the PRD 3.7
3250:                MonitoringSubsystem.handleEvent(RProxyEvent.PDC_AUTH_REQ);
3251:                Response rep = null;
3252:                /*
3253:                 * we are doing pdc. need to get the cert and pass it to the server.
3254:                 */
3255:                /* change the url and add the cert.  */
3256:                /* make sure the retriever does not screw up or rewrite or url */
3257:
3258:                /* prepare the parameter stream */
3259:                /*
3260:                 * netscape server does not let you get the content as input strea.
3261:                 */
3262:                // logger.info("Session: now doingPDC");
3263:                logger.info("PSSRRPROXY_CSPRCONHNDLR173");
3264:
3265:                String gwLabel = "gw=";
3266:                byte gwLableByte[] = gwLabel.getBytes();
3267:                String gwContentEn = URLEncoder.encode(_rpName);
3268:                byte gwContentByte[] = gwContentEn.getBytes();
3269:
3270:                // TODO: need to fill it in with gateway ip (fake client IP), so that
3271:                // server
3272:                // side doesn't have to change
3273:
3274:                String clntLabel = "&client=";
3275:                byte clntLabelByte[] = clntLabel.getBytes();
3276:                String clntContentEnc = "127.0.0.1"; //URLEncoder.encode(_clientIP);
3277:                byte clntContentByte[] = clntContentEnc.getBytes();
3278:                String certLabel = "&Login.Token0=";
3279:                //End of code change for Bug : 4670649
3280:                byte certLabelByte[] = certLabel.getBytes();
3281:
3282:                String testLabel = "&testxyz=";
3283:                byte testLabelByte[] = testLabel.getBytes();
3284:                String testContentStr = "justatest";
3285:                String testContentEnc = URLEncoder.encode(testContentStr);
3286:                byte testContentByte[] = testContentEnc.getBytes();
3287:
3288:                // logger.info("Session: ABOUT TO DO CERT LOGIN");
3289:                logger.info("PSSRRPROXY_CSPRCONHNDLR174");
3290:                /* JSS3.1.1 change - begin */
3291:                org.mozilla.jss.crypto.X509Certificate clientCert = null;
3292:                /* JSS3.1.1 change - end */
3293:                Base64 _base64 = new Base64();
3294:                String b64Cert = null;
3295:                byte certparam[] = null;
3296:
3297:                /* get the cert from the ssl 	*/
3298:                /* it returns the user cert and the ca cert */
3299:                /* wonder if it does more than one user cert?  */
3300:                //SSLSocket sslsock = (SSLSocket) _theSocket;
3301:                SSLSocket sslsock = getActualSocket();
3302:                try {
3303:
3304:                    /*
3305:                     * prepare the cert to send over to the server by first converting
3306:                     * it into x509 "encoded" format, then do base64 encoded it to get
3307:                     * rid of non-displayable character.
3308:                     */
3309:
3310:                    // logger.info("Session: prepare the cert to send over to the
3311:                    // server.");
3312:                    logger.info("PSSRRPROXY_CSPRCONHNDLR175");
3313:
3314:                    // let just send one for now.
3315:                    // according Aravindan: browser only send one cert.
3316:                    // we get 2 becasue the second is the CA cert.
3317:                    // for (int theindex = 0; theindex < x509certs.length; theindex++)
3318:
3319:                    /* JSS3.1.1 change - begin */
3320:                    try {
3321:                        clientCert = sslsock.getStatus().getPeerCertificate();
3322:                    } catch (java.net.SocketException se) {
3323:                        // logger.severe("Unable to get peer certificate");
3324:                        logger.severe("PSSRRPROXY_CSPRCONHNDLR176");
3325:                        return null;
3326:                    }
3327:                    /* JSS3.1.1 change - end */
3328:
3329:                    byte certbyte[] = clientCert.getEncoded();
3330:                    byte xxb64Cert[] = _base64.encode(certbyte);
3331:                    String strb64Cert = new String(xxb64Cert);
3332:                    b64Cert = URLEncoder.encode(strb64Cert);
3333:                    byte byteb64Cert[] = b64Cert.getBytes();
3334:
3335:                    try {
3336:                        OutputStream fout = new FileOutputStream(
3337:                                "/tmp/base64cert.certbyte");
3338:                        DataOutputStream out = new DataOutputStream(fout);
3339:                        for (int lindex = 0; lindex < xxb64Cert.length; lindex++)
3340:                            out.writeByte(xxb64Cert[lindex]);
3341:                        out.close();
3342:                    } catch (java.io.IOException ex3) {
3343:                        // logger.severe("Session: see file /tmp/base64cert");
3344:                        logger.severe("PSSRRPROXY_CSPRCONHNDLR177");
3345:                    }
3346:
3347:                    certparam = new byte[gwLableByte.length
3348:                            + gwContentByte.length
3349:                            + clntLabelByte.length
3350:                            + clntContentByte.length
3351:                            +
3352:                            //PDC Fix to support IS 6.1
3353:                            //domainLabelByte.length +
3354:                            //domainContentByte.length +
3355:                            certLabelByte.length + testLabelByte.length
3356:                            + testContentByte.length + byteb64Cert.length + 200];
3357:
3358:                    // logger.info("Session: certparam.length=" + certparam.length);
3359:                    Object[] params54 = { new Integer(certparam.length) };
3360:                    logger.log(Level.INFO, "PSSRRPROXY_CSPRCONHNDLR178",
3361:                            params54);
3362:                    // logger.info("Session: b64Cert.length=" + b64Cert.length());
3363:                    Object[] params55 = { new Integer(b64Cert.length()) };
3364:                    logger.log(Level.INFO, "PSSRRPROXY_CSPRCONHNDLR179",
3365:                            params55);
3366:
3367:                    int j = 0; // current location of certparam.
3368:                    for (int i = 0; i < gwLableByte.length; i++) {
3369:                        certparam[i] = gwLableByte[i];
3370:                    }
3371:                    j = gwLableByte.length;
3372:
3373:                    for (int i = 0; i < gwContentByte.length; i++) {
3374:                        certparam[j] = gwContentByte[i];
3375:                        j++;
3376:                    }
3377:
3378:                    for (int i = 0; i < clntLabelByte.length; i++) {
3379:                        certparam[j] = clntLabelByte[i];
3380:                        j++;
3381:                    }
3382:
3383:                    for (int i = 0; i < clntContentByte.length; i++) {
3384:                        certparam[j] = clntContentByte[i];
3385:                        j++;
3386:                    }
3387:                    //PDC Fix to support IS 6.1
3388:                    /*
3389:                     * for (int i = 0; i < domainLabelByte.length; i++) { certparam[j] =
3390:                     * domainLabelByte[i]; j++; }
3391:                     *
3392:                     * for (int i = 0; i < domainContentByte.length; i++) { certparam[j] =
3393:                     * domainContentByte[i]; j++; }
3394:                     */
3395:                    for (int i = 0; i < certLabelByte.length; i++) {
3396:                        certparam[j] = certLabelByte[i];
3397:                        j++;
3398:                    }
3399:
3400:                    for (int i = 0; i < byteb64Cert.length; i++) {
3401:                        certparam[j] = byteb64Cert[i];
3402:                        j++;
3403:                    }
3404:
3405:                    for (int i = 0; i < testLabelByte.length; i++) {
3406:                        certparam[j] = testLabelByte[i];
3407:                        j++;
3408:                    }
3409:
3410:                    for (int i = 0; i < testContentByte.length; i++) {
3411:                        certparam[j] = testContentByte[i];
3412:                        j++;
3413:                    }
3414:
3415:                    //String foobar = new String(certparam);
3416:                    // logger.info("Session: certificate version: getSubjectDN " +
3417:                    // clientCert.getSubjectDN());
3418:                    Object[] params56 = { clientCert.getSubjectDN() };
3419:                    logger.log(Level.INFO, "PSSRRPROXY_CSPRCONHNDLR180",
3420:                            params56);
3421:
3422:                    /* prepare the  http request ... */
3423:                    /* a get request has byte limits. so we need to do a POST */
3424:
3425:                    Retriever retr = null;
3426:                    // Lihue PRD : 4.5
3427:                    HTTPRequest tmpreq = new HTTPRequest(_gwprotocol, port);
3428:                    // EOC :: Lihue PRD : 4.5
3429:                    if (req.getObject().startsWith(_platformloginURL)) {
3430:
3431:                        /**
3432:                         * Bug 4525919 : problem of SSL client authentication. The
3433:                         * loginURL() method will append the domain name to the gateway
3434:                         * host only if the request is a missingProtocolRequest. The
3435:                         * following block of code is a workaround for requests which
3436:                         * are not missingProtocolRequest.
3437:                         */
3438:                        HTTPRequest blkreq = null;
3439:                        String _tmpurl = req.getURL().trim();
3440:                        int indx = _tmpurl.toLowerCase().indexOf("org=");
3441:                        if (indx != -1) {
3442:                            indx += 4;
3443:                            int indx1 = _tmpurl.indexOf('&', indx);
3444:                            if (indx1 == -1) {
3445:                                indx1 = _tmpurl.length();
3446:                            }
3447:                            _tmpurl = _tmpurl.substring(indx, indx1);
3448:                            if (_tmpurl.startsWith("/"))
3449:                                _tmpurl = _tmpurl.substring(1);
3450:                            blkreq = new HTTPRequest(_tmpurl);
3451:                        } else {
3452:                            blkreq = new HTTPRequest();
3453:                        }
3454:                        //End of code change for Bug 4525919
3455:
3456:                        blkreq.setHost(req.getHost());
3457:                        blkreq.setPort(req.getPort());
3458:                        blkreq.setGatewayHost(req.getGatewayHost());
3459:                        blkreq.setURL(req.getURL().trim());
3460:                        blkreq.setProtocol(req.getProtocol());
3461:
3462:                        /**
3463:                         * Changes to accomodate DSAME pdc support. Bug : 4670649
3464:                         */
3465:                        tmpreq
3466:                                .addHeaderLine("POST  /"
3467:                                        + loginURL(blkreq, _platformloginURL)
3468:                                        + " "
3469:                                        + ((HTTPRequest) req).getHTTPVersion()
3470:                                        + "\r\n");
3471:                        //End of code change for Bug : 4670649
3472:                    } else {
3473:                        /*
3474:                         * KWL for cert login we need to go to login.certificate (login
3475:                         * slash cert)
3476:                         */
3477:                        /**
3478:                         * Changes to accomodate DSAME pdc support. Bug : 4670649
3479:                         */
3480:                        tmpreq
3481:                                .addHeaderLine("POST  /"
3482:                                        + loginURL(req, _platformloginURL)
3483:                                        + " "
3484:                                        + ((HTTPRequest) req).getHTTPVersion()
3485:                                        + "\r\n");
3486:                        //End of code change for Bug : 4670649
3487:                    }
3488:                    //PDC Fix to support IS 6.1
3489:                    tmpreq.addHeaderLine("Content-Type: "
3490:                            + "application/x-www-form-urlencoded" + "\r\n");
3491:                    tmpreq.addHeaderLine("Content-Length: " + certparam.length
3492:                            + "\r\n");
3493:
3494:                    retr = RetrievalFactory.getRetriever(tmpreq.getProtocol());
3495:                    rep = retr.getResponse2(tmpreq, tmpreq.getHost(), _logId,
3496:                            certparam);
3497:
3498:                    /*
3499:                     * after completing PDC set the cookie
3500:                     * This makes sures that the PDC is not done again
3501:                     */
3502:
3503:                    addPDCCookie(req, rep);
3504:
3505:                    req.setHost(tmpreq.getHost());
3506:                    req.setPort(tmpreq.getPort());
3507:                    req.setProtocol(tmpreq.getProtocol());
3508:                    req.setObject(tmpreq.getObject());
3509:                    //PDC Fix to support IS 6.1
3510:                    req.setURL(tmpreq.getURL());
3511:
3512:                } catch (java.security.cert.CertificateEncodingException ex2) {
3513:                    // logger.severe("Session: CertificateEncodingException");
3514:                    logger.severe("PSSRRPROXY_CSPRCONHNDLR181");
3515:                }
3516:                return rep;
3517:            }
3518:
3519:            private void removePDCCookieFromBrowser(Request req, Response res) {
3520:                String cookie = null;
3521:                cookie = req.getRequestHeader("Cookie");
3522:                if (cookie != null) {
3523:                    StringBuffer sb = new StringBuffer();
3524:                    int index = cookie.indexOf(pdcCookieName);
3525:                    if (index != -1) {
3526:                        int end = cookie.indexOf(';', index);
3527:                        end = (end == -1) ? cookie.length() : end;
3528:                        String rest = cookie.substring(
3529:                                cookie.indexOf('=', index) + 1, end).trim();
3530:                        sb.append("Set-Cookie: ");
3531:                        sb.append(pdcCookieName);
3532:                        sb.append("=");
3533:                        sb.append(rest);
3534:                        sb.append(";path = /;");
3535:                        if (gwDomain != null) {
3536:                            sb.append(" domain =");
3537:                            sb.append(gwDomain);
3538:                            sb.append(";");
3539:                        }
3540:                        sb.append("Expires=Thu, 01-Jan-1970 00:00:10 GMT;");
3541:                        res.setResponseHeader("Set-Cookie", sb.toString());
3542:                    } else {
3543:                        sb.append("Set-Cookie: ");
3544:                        sb.append(pdcCookieName);
3545:                        sb.append("=");
3546:                        sb.append(";path = /;");
3547:                        if (gwDomain != null) {
3548:                            sb.append(" domain =");
3549:                            sb.append(gwDomain);
3550:                            sb.append(";");
3551:                        }
3552:                        sb.append("Expires=Thu, 01-Jan-1970 00:00:10 GMT;");
3553:                        res.setResponseHeader("Set-Cookie", sb.toString());
3554:                    }
3555:
3556:                }
3557:            }
3558:
3559:            private void addPDCCookie(Request req, Response res) {
3560:                /*
3561:                 * Bug 4711442 problem with PDC auth users relogin with Auth chaining
3562:                 * enabled.
3563:                 */
3564:                if (!(res instanceof  com.sun.portal.rproxy.connectionhandler.HTTPResponse))
3565:                    return;
3566:                String cookie = null;
3567:                List cookieList = ((HTTPResponse) res)
3568:                        .getHeaderAttributeList("Set-Cookie");
3569:
3570:                StringBuffer sb = new StringBuffer();
3571:                sb.append("Set-Cookie: ");
3572:                sb.append(pdcCookieName);
3573:                sb.append("=" + PDC_COOKIE_HEADER);
3574:                sb.append(";path = /;");
3575:                if (gwDomain != null) {
3576:                    sb.append(" domain =");
3577:                    sb.append(gwDomain);
3578:                    sb.append(";");
3579:                }
3580:
3581:                if ((cookieList != null) && (cookieList.size() > 0)) {
3582:
3583:                    ((HTTPResponse) res).appendResponseHeader("Set-Cookie", sb
3584:                            .toString());
3585:                } else {
3586:                    res.setResponseHeader("Set-Cookie", sb.toString());
3587:                }
3588:            }
3589:
3590:            private boolean hostFound(String reqUri) {
3591:
3592:                for (Iterator it = serverList.iterator(); it.hasNext();) {
3593:                    /* fix for 4718232 - begin */
3594:                    String fullhost = (String) it.next().toString()
3595:                            .toLowerCase();
3596:                    String hostname = null;
3597:                    int lastColonIndex = -1;
3598:
3599:                    if (fullhost.startsWith("http:")) {
3600:                        if (4 == (lastColonIndex = fullhost.lastIndexOf(':')))
3601:                            hostname = fullhost.substring(7);
3602:                        else
3603:                            hostname = fullhost.substring(7, lastColonIndex);
3604:                    } else if (fullhost.startsWith("https:")) {
3605:                        if (5 == (lastColonIndex = fullhost.lastIndexOf(':')))
3606:                            hostname = fullhost.substring(8);
3607:                        else
3608:                            hostname = fullhost.substring(8, lastColonIndex);
3609:                    } else {
3610:                        // logger.severe("Server list entry is not in the right format:
3611:                        // " + fullhost);
3612:                        Object[] params58 = { fullhost };
3613:                        logger.log(Level.SEVERE, "PSSRRPROXY_CSPRCONHNDLR182",
3614:                                params58);
3615:                    }
3616:                    String reqUriSub = (reqUri
3617:                            .substring(reqUri.indexOf(':') + 3)).toLowerCase();
3618:                    if (hostname == null)
3619:                        return false;
3620:                    /* fix for 4718232 - end */
3621:                    if (reqUriSub.startsWith(hostname)) {
3622:                        return true;
3623:                    }
3624:
3625:                }
3626:                return false;
3627:            }
3628:
3629:            //End of code change for PRD 3.7
3630:
3631:            /*
3632:             * Changes for statistics response to be shown only for authenticated users
3633:             */
3634:            private boolean isUserSessionValid(Request req) {
3635:                String tmpsidstr = req.getSessionID();
3636:                if (tmpsidstr == null || tmpsidstr.equals("null")
3637:                        || tmpsidstr.trim().length() == 0)
3638:                    return false;
3639:                if (getUserSession(req, tmpsidstr) == null) {
3640:                    return false;
3641:                }
3642:                return true;
3643:            }
3644:
3645:            SSLSocket getActualSocket() {
3646:                if (_theSocket instanceof  SRAPSocket) {
3647:                    SRAPSocket sock = (SRAPSocket) _theSocket;
3648:                    return (SSLSocket) sock.getActualSocket();
3649:                } else {
3650:                    return (SSLSocket) _theSocket;
3651:                }
3652:            }
3653:        }
www.java2java.com | Contact Us
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.