1 19 20 package com.sslexplorer.core; 21 22 import java.io.ByteArrayOutputStream ; 23 import java.io.File ; 24 import java.io.FileInputStream ; 25 import java.io.IOException ; 26 import java.io.ObjectOutputStream ; 27 import java.io.PrintWriter ; 28 import java.io.Serializable ; 29 import java.io.StringWriter ; 30 import java.lang.reflect.Field ; 31 import java.lang.reflect.Method ; 32 import java.net.MalformedURLException ; 33 import java.net.URI ; 34 import java.net.URISyntaxException ; 35 import java.net.URL ; 36 import java.text.DateFormat ; 37 import java.text.ParseException ; 38 import java.text.SimpleDateFormat ; 39 import java.util.ArrayList ; 40 import java.util.Iterator ; 41 import java.util.List ; 42 import java.util.Locale ; 43 import java.util.Map ; 44 import java.util.Properties ; 45 import java.util.StringTokenizer ; 46 import java.util.zip.Adler32 ; 47 import java.util.zip.CheckedInputStream ; 48 49 import javax.servlet.ServletContext ; 50 import javax.servlet.http.Cookie ; 51 import javax.servlet.http.HttpServletRequest ; 52 import javax.servlet.http.HttpServletRequestWrapper ; 53 import javax.servlet.http.HttpServletResponse ; 54 import javax.servlet.http.HttpSession ; 55 import javax.servlet.http.HttpSessionBindingEvent ; 56 import javax.servlet.http.HttpSessionBindingListener ; 57 import javax.servlet.jsp.PageContext ; 58 import javax.servlet.jsp.tagext.Tag ; 59 60 import org.apache.commons.cache.Cache; 61 import org.apache.commons.cache.CacheStat; 62 import org.apache.commons.lang.StringUtils; 63 import org.apache.commons.logging.Log; 64 import org.apache.commons.logging.LogFactory; 65 import org.apache.struts.Globals; 66 import org.apache.struts.action.Action; 67 import org.apache.struts.action.ActionForm; 68 import org.apache.struts.action.ActionForward; 69 import org.apache.struts.action.ActionMapping; 70 import org.apache.struts.action.ActionMessages; 71 import org.apache.struts.config.ModuleConfig; 72 import org.apache.struts.taglib.tiles.ComponentConstants; 73 import org.apache.struts.tiles.ComponentContext; 74 import org.apache.struts.util.MessageResources; 75 import org.apache.struts.util.ModuleUtils; 76 77 import com.sslexplorer.boot.ContextHolder; 78 import com.sslexplorer.boot.Util; 79 import com.sslexplorer.core.actions.CoreAction; 80 import com.sslexplorer.core.actions.LicenseAgreementDispatchAction; 81 import com.sslexplorer.core.forms.CoreForm; 82 import com.sslexplorer.extensions.types.Plugin; 83 import com.sslexplorer.extensions.types.PluginType; 84 import com.sslexplorer.policyframework.NoPermissionException; 85 import com.sslexplorer.policyframework.Permission; 86 import com.sslexplorer.policyframework.PolicyDatabaseFactory; 87 import com.sslexplorer.policyframework.ResourceStack; 88 import com.sslexplorer.policyframework.ResourceType; 89 import com.sslexplorer.properties.Property; 90 import com.sslexplorer.properties.PropertyProfile; 91 import com.sslexplorer.properties.impl.profile.ProfilePropertyKey; 92 import com.sslexplorer.security.AuthenticationScheme; 93 import com.sslexplorer.security.Constants; 94 import com.sslexplorer.security.DefaultAuthenticationScheme; 95 import com.sslexplorer.security.LogonControllerFactory; 96 import com.sslexplorer.security.Role; 97 import com.sslexplorer.security.SessionInfo; 98 import com.sslexplorer.security.SystemDatabaseFactory; 99 import com.sslexplorer.security.User; 100 import com.sslexplorer.security.UserDatabase; 101 import com.sslexplorer.tasks.TaskHttpServletRequest; 102 import com.sslexplorer.vfs.UploadDetails; 103 import com.sslexplorer.vfs.UploadManager; 104 import com.sslexplorer.vfs.store.downloads.TempStore; 105 import com.sslexplorer.vfs.webdav.DAVUtilities; 106 107 112 public class CoreUtil { 113 final static Log log = LogFactory.getLog(CoreUtil.class); 114 115 122 public static File getTempDownloadDirectory(SessionInfo session) throws Exception { 123 final File tempDownloadDirectory = new File (ContextHolder.getContext().getTempDirectory(), TempStore.TEMP_DOWNLOAD_MOUNT_NAME); 124 if (!tempDownloadDirectory.exists()) { 126 if (!tempDownloadDirectory.mkdirs()) { 127 throw new Exception ("Could not create temporary download directory " + tempDownloadDirectory.getAbsolutePath() 128 + "."); 129 } 130 } 131 final File tempSessionDownloadDirectory = new File (tempDownloadDirectory, session.getUser().getPrincipalName() + "." 133 + session.getHttpSession().getId()); 134 if (!tempSessionDownloadDirectory.exists()) { 135 136 session.getHttpSession().setAttribute(DownloadContent.FILES_DOWNLOAD_CLEANUP_SESSION_HOOK, new HttpSessionBindingListener () { 138 139 public void valueBound(HttpSessionBindingEvent event) { 140 } 141 142 public void valueUnbound(HttpSessionBindingEvent event) { 143 if(log.isInfoEnabled()) { 144 log.info("Cleaning up temporary download directory " + tempSessionDownloadDirectory); 145 } 146 Util.delTree(tempSessionDownloadDirectory); 147 } 148 }); 149 150 151 if (!tempSessionDownloadDirectory.mkdirs()) { 152 throw new Exception ("Could not create temporary session download directory " + tempSessionDownloadDirectory.getAbsolutePath() 153 + " for user " 154 + session.getUser().getPrincipalName() 155 + "."); 156 } 157 } 158 return tempSessionDownloadDirectory; 159 } 160 161 162 171 public static void storeToCache(Cache cache, String key, Serializable object, long ttl, long cost) { 172 if (log.isDebugEnabled()) { 173 log.debug("Caching under " + key + ", ttl=" + ttl + ", cost=" 174 + cost); 175 } 176 177 if ("true".equals(System.getProperty("sslexplorer.useDevConfig")) | "true".equals(System.getProperty("sslexplorer.testing"))) { 179 ByteArrayOutputStream baos = new ByteArrayOutputStream (); 180 try { 181 ObjectOutputStream oos = new ObjectOutputStream (baos); 182 oos.writeObject(object); 183 } catch (Exception e) { 184 String string = "********** Failed to cache policy database object. There is probably a non-serializable object somewhere in the object graph. PLEASE FIX ME ****************"; 185 System.err 186 .println(string); 187 e.printStackTrace(); 188 throw new RuntimeException (string); 189 } 190 } 191 192 cache.store(key, object, new Long (ttl 193 + System.currentTimeMillis()), cost); 194 if (log.isDebugEnabled()) { 195 log.debug("NUM_RETRIEVE_REQUESTED " 196 + cache.getStat(CacheStat.NUM_RETRIEVE_REQUESTED)); 197 log.debug("NUM_RETRIEVE_FOUND " 198 + cache.getStat(CacheStat.NUM_RETRIEVE_FOUND)); 199 log.debug("NUM_RETRIEVE_NOT_FOUND " 200 + cache.getStat(CacheStat.NUM_RETRIEVE_NOT_FOUND)); 201 log.debug("NUM_STORE_REQUESTED " 202 + cache.getStat(CacheStat.NUM_STORE_REQUESTED)); 203 log.debug("NUM_STORE_STORED " 204 + cache.getStat(CacheStat.NUM_STORE_STORED)); 205 log.debug("NUM_STORE_NOT_STORED " 206 + cache.getStat(CacheStat.NUM_STORE_NOT_STORED)); 207 log.debug("CUR_CAPACITY " 208 + cache.getStat(CacheStat.CUR_CAPACITY)); 209 } 210 } 211 212 220 public static Cookie getCookie(String name, HttpServletRequest request) { 221 Cookie [] cookies = request.getCookies(); 222 if (cookies != null) { 223 for (int i = 0; i < cookies.length; i++) { 224 if (cookies[i].getName().equals(name)) { 225 return cookies[i]; 226 } 227 } 228 } 229 return null; 230 } 231 232 241 public static String getCookieValue(String name, HttpServletRequest request, String defaultValue) { 242 Cookie c = getCookie(name, request); 243 return c == null ? defaultValue : c.getValue(); 244 } 245 246 252 public static int getCurrentPropertyProfileId(HttpSession session) { 253 PropertyProfile p = (PropertyProfile) session.getAttribute(Constants.SELECTED_PROFILE); 254 if (p != null) { 255 return p.getResourceId(); 256 } 257 return 0; 258 } 259 260 267 public static String getThemePath(HttpSession session) { 268 try { 269 SessionInfo info = LogonControllerFactory.getInstance().getSessionInfo(session); 270 if (info == null) { 271 return Property.getProperty(new ProfilePropertyKey(0, null, "ui.theme", UserDatabaseManager.getInstance() 272 .getDefaultUserDatabase().getRealm().getResourceId())); 273 } else { 274 return Property.getProperty(new ProfilePropertyKey(getCurrentPropertyProfileId(session), info.getUser().getPrincipalName(), 275 "ui.theme", info.getUser().getRealm().getResourceId())); 276 } 277 } catch (Exception e) { 278 } 279 return "/theme/default"; 280 } 281 282 287 public static boolean getToolTipsEnabled(HttpSession session) { 288 try { 289 SessionInfo info = LogonControllerFactory.getInstance().getSessionInfo(session); 290 if (info == null) { 291 return Property.getPropertyBoolean(new ProfilePropertyKey(0, null, "ui.toolTips", UserDatabaseManager.getInstance() 292 .getDefaultUserDatabase().getRealm().getResourceId())); 293 } else { 294 return Property.getPropertyBoolean(new ProfilePropertyKey(getCurrentPropertyProfileId(session), info.getUser().getPrincipalName(), 295 "ui.toolTips", info.getUser().getRealm().getResourceId())); 296 } 297 } catch (Exception e) { 298 } 299 return true; 300 } 301 302 311 @SuppressWarnings ("unchecked") 312 public static void addPageInterceptListener(HttpSession servletSession, PageInterceptListener listener) { 313 synchronized (servletSession) { 314 List <PageInterceptListener> pagetInterceptListeners = (List <PageInterceptListener>) servletSession.getAttribute(Constants.PAGE_INTERCEPT_LISTENERS); 315 if (pagetInterceptListeners == null) { 316 pagetInterceptListeners = new ArrayList <PageInterceptListener>(); 317 servletSession.setAttribute(Constants.PAGE_INTERCEPT_LISTENERS, pagetInterceptListeners); 318 } 319 pagetInterceptListeners.add(listener); 320 } 321 } 322 323 330 @SuppressWarnings ("unchecked") 331 public static void removePageInterceptListener(HttpSession servletSession, PageInterceptListener listener) { 332 synchronized (servletSession) { 333 List <PageInterceptListener> pagetInterceptListeners = (List <PageInterceptListener>) servletSession.getAttribute(Constants.PAGE_INTERCEPT_LISTENERS); 334 if (pagetInterceptListeners != null) { 335 pagetInterceptListeners.remove(listener); 336 if (pagetInterceptListeners.size() == 0) { 337 servletSession.removeAttribute(Constants.PAGE_INTERCEPT_LISTENERS); 338 } 339 PageInterceptListener pil = (PageInterceptListener) servletSession.getAttribute(Constants.PAGE_INTERCEPTED); 340 if (pil == listener) { 341 servletSession.removeAttribute(Constants.PAGE_INTERCEPTED); 342 } 343 } 344 } 345 } 346 347 355 @SuppressWarnings ("unchecked") 356 public static PageInterceptListener getPageInterceptListenerById(HttpSession servletSession, String id) { 357 synchronized (servletSession) { 358 List <PageInterceptListener> pagetInterceptListeners = (List <PageInterceptListener>) servletSession.getAttribute(Constants.PAGE_INTERCEPT_LISTENERS); 359 if (pagetInterceptListeners != null) { 360 361 for (PageInterceptListener listener : pagetInterceptListeners) { 362 if (listener.getId().equals(id)) { 363 return listener; 364 } 365 } 366 } 367 } 368 return null; 369 } 370 371 379 public static void removePageInterceptListener(HttpSession session, String id) { 380 PageInterceptListener l = getPageInterceptListenerById(session, id); 381 if (l != null) { 382 removePageInterceptListener(session, l); 383 } 384 } 385 386 397 @SuppressWarnings ("unchecked") 398 public static ActionForward checkIntercept(Action action, ActionMapping mapping, HttpServletRequest request, 399 HttpServletResponse response) throws Exception { 400 401 if ("XMLHttpRequest".equals(request.getHeader("X-Requested-With"))) { 403 return null; 404 } 405 406 if(request.getAttribute(TaskHttpServletRequest.ATTR_TASK) != null) { 408 return null; 409 } 410 411 ActionForward fwd = null; 412 try { 413 List <PageInterceptListener> pagetInterceptListeners = (List <PageInterceptListener>) request.getSession() 414 .getAttribute(Constants.PAGE_INTERCEPT_LISTENERS); 415 if (pagetInterceptListeners != null) { 416 PageInterceptListener currentIntercept = (PageInterceptListener) request.getSession() 417 .getAttribute(Constants.PAGE_INTERCEPTED); 418 PageInterceptListener pil = null; 419 if (currentIntercept != null) { 420 pil = currentIntercept; 421 fwd = currentIntercept.checkForForward(action, mapping, request, response); 422 } else { 423 for (Iterator i = pagetInterceptListeners.iterator(); fwd == null && i.hasNext();) { 424 pil = (PageInterceptListener) i.next(); 425 fwd = pil.checkForForward(action, mapping, request, response); 426 } 427 } 428 if (fwd != null) { 429 if (!pil.isRedirect()) { 430 request.getSession().setAttribute(Constants.PAGE_INTERCEPTED, pil); 431 } else { 432 CoreUtil.removePageInterceptListener(request.getSession(), pil); 433 } 434 return fwd; 435 } 436 } 437 return null; 438 } catch (Exception e) { 439 log.error("Page intercept failed.", e); 440 throw e; 441 } 442 } 443 444 453 @SuppressWarnings ("unchecked") 454 public static void addGlobalWarning(ResourceType requiredResourceType, Permission[] requiredPermissions, 455 BundleActionMessage message) { 456 HttpSession servletSession; 457 for (Iterator i = CoreRequestProcessor.getSessions().entrySet().iterator(); i.hasNext();) { 458 servletSession = (HttpSession ) ((Map.Entry ) i.next()).getValue(); 459 SessionInfo info = LogonControllerFactory.getInstance().getSessionInfo(servletSession); 460 if (info != null) { 461 try { 462 if(PolicyDatabaseFactory.getInstance().isPermitted(requiredResourceType, requiredPermissions, info.getUser(), false)) { 463 addSingleSessionGlobalWarning(servletSession, message); 464 } 465 } catch (Exception e) { 466 log.error("Failed to add global warning. ", e); 467 } 468 } 469 } 470 List <GlobalWarning> servletContextGlobalWarnings = (List <GlobalWarning>) CoreServlet.getServlet() 471 .getServletContext() 472 .getAttribute(Constants.SESSION_GLOBAL_WARNINGS); 473 if (servletContextGlobalWarnings == null) { 474 servletContextGlobalWarnings = new ArrayList <GlobalWarning>(); 475 } 476 servletContextGlobalWarnings.add(new GlobalWarning(requiredResourceType, requiredPermissions, message)); 477 CoreServlet.getServlet().getServletContext().setAttribute(Constants.SESSION_GLOBAL_WARNINGS, servletContextGlobalWarnings); 478 } 479 480 489 @SuppressWarnings ("unchecked") 490 public static void addMultipleGlobalWarning(int type, BundleActionMessage message) { 491 HttpSession servletSession = null; 492 for (Iterator i = CoreRequestProcessor.getSessions().entrySet().iterator(); i.hasNext();) { 493 servletSession = (HttpSession ) ((Map.Entry ) i.next()).getValue(); 494 SessionInfo info = LogonControllerFactory.getInstance().getSessionInfo(servletSession); 495 if (info != null) { 496 try { 497 if ((type == GlobalWarning.SUPER_USER && LogonControllerFactory.getInstance() 498 .isAdministrator(info.getUser())) || (type == GlobalWarning.MANAGEMENT_USERS && PolicyDatabaseFactory.getInstance() 499 .isAnyAccessRightAllowed(info.getUser(), true, true, false)) 500 || type == GlobalWarning.ALL_USERS) { 501 addSingleSessionGlobalWarning(servletSession, message); 502 } 503 } catch (Exception e) { 504 log.error("Failed to add global warning.", e); 505 } 506 } 507 } 508 List <GlobalWarning> servletContextGlabalWarnings = (List <GlobalWarning>) CoreServlet.getServlet() 509 .getServletContext() 510 .getAttribute(Constants.SESSION_GLOBAL_WARNINGS); 511 if (servletContextGlabalWarnings == null) { 512 servletContextGlabalWarnings = new ArrayList <GlobalWarning>(); 513 } 514 servletContextGlabalWarnings.add(new GlobalWarning(type, message)); 515 CoreServlet.getServlet().getServletContext().setAttribute(Constants.SESSION_GLOBAL_WARNINGS, servletContextGlabalWarnings); 516 } 517 518 526 @SuppressWarnings ("unchecked") 527 public static void addSingleSessionGlobalWarning(HttpSession servletSession, BundleActionMessage message) { 528 synchronized (servletSession) { 529 SessionInfo info = LogonControllerFactory.getInstance().getSessionInfo(servletSession); 530 if (info != null) { 531 List <BundleActionMessage> l = (List <BundleActionMessage>) servletSession.getAttribute(Constants.GLOBAL_WARNINGS); 532 if (l == null) { 533 l = new ArrayList <BundleActionMessage>(); 534 servletSession.setAttribute(Constants.GLOBAL_WARNINGS, l); 535 } 536 BundleActionMessage m = null; 537 boolean found = false; 538 for (Iterator <BundleActionMessage> i = l.iterator(); !found && i.hasNext();) { 539 m = i.next(); 540 if (m.getBundle().equals(message.getBundle()) && m.getKey().equals(message.getKey())) { 541 found = true; 542 } 543 } 544 if (!found) { 545 l.add(message); 546 } 547 } 548 } 549 } 550 551 560 public static void removeGlobalWarning(HttpSession servletSession, String key) { 561 if (servletSession == null) { 562 for (Iterator i = CoreRequestProcessor.getSessions().entrySet().iterator(); i.hasNext();) { 563 servletSession = (HttpSession ) ((Map.Entry ) i.next()).getValue(); 564 removeGlobalWarning(servletSession, key); 565 } 566 List servletContextGlabalWarnings = (List ) CoreServlet.getServlet() 567 .getServletContext() 568 .getAttribute(Constants.SESSION_GLOBAL_WARNINGS); 569 if (servletContextGlabalWarnings != null) { 570 Iterator iter = servletContextGlabalWarnings.iterator(); 571 while (iter.hasNext()) { 572 GlobalWarning gw = (GlobalWarning) iter.next(); 573 BundleActionMessage element = gw.getMessage(); 574 if (element.getKey().equals(key)) { 575 servletContextGlabalWarnings.remove(element); 576 break; 577 } 578 } 579 } 580 } else { 581 synchronized (servletSession) { 582 List l = (List ) servletSession.getAttribute(Constants.GLOBAL_WARNINGS); 583 if (l == null) { 584 l = new ArrayList (); 585 servletSession.setAttribute(Constants.GLOBAL_WARNINGS, l); 586 } 587 for (int i = l.size() - 1; i >= 0; i--) { 588 BundleActionMessage msg = (BundleActionMessage) l.get(i); 589 if (msg.getKey().equals(key)) { 590 l.remove(i); 591 break; 592 } 593 } 594 } 595 } 596 } 597 598 604 public static void removeGlobalWarningFromAllSessions(String key) { 605 removeGlobalWarning(null, key); 606 } 607 608 615 public static void initCoreForm(CoreForm f, HttpServletRequest request) { 616 f.setReferer(CoreUtil.getReferer(request)); 617 } 618 619 623 @SuppressWarnings ("unchecked") 624 public static void requestLicenseAgreement(HttpSession session, LicenseAgreement agreement) { 625 List <LicenseAgreement> l = (List <LicenseAgreement>) session.getAttribute(Constants.LICENSE_AGREEMENTS); 626 if (l == null) { 627 l = new ArrayList <LicenseAgreement>(); 628 session.setAttribute(Constants.LICENSE_AGREEMENTS, l); 629 log.info("Requesting license agreement for " + agreement.getLicenseTextFile().getAbsolutePath()); 630 addPageInterceptListener(session, new PageInterceptListener() { 631 public String getId() { 632 return "licenseAgreement"; 633 } 634 635 public boolean isRedirect() { 636 return true; 637 } 638 639 public ActionForward checkForForward(Action action, ActionMapping mapping, HttpServletRequest request, 640 HttpServletResponse response) throws PageInterceptException { 641 if (!(action instanceof LicenseAgreementDispatchAction)) { 642 return new ActionForward("/showLicenseAgreement.do", true); 643 } 644 return null; 645 } 646 }); 647 } 648 l.add(agreement); 649 } 650 651 655 public static void addWarnings(HttpServletRequest request, ActionMessages warnings) { 656 if (warnings == null) { 657 return; 658 } 659 ActionMessages requestWarnings = (ActionMessages) request.getAttribute(Constants.REQ_ATTR_WARNINGS); 660 if (requestWarnings == null) { 661 requestWarnings = new ActionMessages(); 662 } 663 requestWarnings.add(warnings); 664 if (requestWarnings.isEmpty()) { 665 request.removeAttribute(Constants.REQ_ATTR_WARNINGS); 666 return; 667 } 668 request.setAttribute(Constants.REQ_ATTR_WARNINGS, requestWarnings); 669 } 670 671 678 public static ActionMessages getWarnings(HttpServletRequest request) { 679 ActionMessages warnings = (ActionMessages) request.getAttribute(Constants.REQ_ATTR_WARNINGS); 680 if (warnings == null) { 681 warnings = new ActionMessages(); 682 } 683 return warnings; 684 } 685 686 692 public static void saveWarnings(HttpServletRequest request, ActionMessages warnings) { 693 if ((warnings == null) || warnings.isEmpty()) { 694 request.removeAttribute(Constants.REQ_ATTR_WARNINGS); 695 return; 696 } 697 request.setAttribute(Constants.REQ_ATTR_WARNINGS, warnings); 698 } 699 700 704 public static String getReferer(HttpServletRequest request) { 705 String ref = request.getHeader("Referer"); 706 if (ref != null) { 707 ref = processRefererString(ref); 708 } else { 709 714 ref = getRequestReferer(request); 715 } 716 return ref; 717 } 718 719 723 public static String getRequestReferer(HttpServletRequest request) { 724 if (isRefererInRequest(request)) { 725 return processRefererString(request.getParameter("referer")); 726 } 727 return null; 728 } 729 730 734 public static boolean isRefererInRequest(HttpServletRequest request) { 735 return request.getParameter("referer") != null; 736 } 737 738 742 static String processRefererString(String redirect) { 743 try { 744 URL u = new URL (redirect); 745 String query = u.getQuery(); 746 if (query != null && !query.equals("")) { 747 StringBuffer nq = new StringBuffer (); 748 StringTokenizer t = new StringTokenizer (query, "&"); 749 String parm = null; 750 while (t.hasMoreTokens()) { 751 parm = t.nextToken(); 752 if (!parm.startsWith("referer=") && !parm.startsWith("vpnMessage=") && !parm.startsWith("vpnError=")) { 753 if (nq.length() > 0) { 754 nq.append("&"); 755 } 756 nq.append(parm); 757 } 758 } 759 query = nq.length() == 0 ? null : nq.toString(); 760 } 761 StringBuffer file = new StringBuffer (); 762 if (u.getPath() != null) { 763 file.append(u.getPath()); 764 } 765 if (query != null) { 766 file.append("?"); 767 file.append(query); 768 } 769 if (u.getRef() != null) { 770 file.append("#"); 771 file.append(u.getRef()); 772 } 773 u = new URL (u.getProtocol(), u.getHost(), u.getPort(), file.toString()); 774 return u.toExternalForm(); 775 } catch (MalformedURLException mrule) { 776 int idx = redirect.indexOf("?"); 777 if (idx != -1) { 778 String query = redirect.substring(idx + 1); 779 redirect = redirect.substring(0, idx); 780 if (query.length() > 0) { 781 StringBuffer nq = new StringBuffer (); 782 StringTokenizer t = new StringTokenizer (query, "&"); 783 String parm = null; 784 while (t.hasMoreTokens()) { 785 parm = t.nextToken(); 786 if (!parm.startsWith("vpnMessage=") && !parm.startsWith("vpnError=")) { 787 if (nq.length() > 0) { 788 nq.append("&"); 789 } 790 nq.append(parm); 791 } 792 } 793 query = nq.length() == 0 ? null : nq.toString(); 794 if (query != null) { 795 redirect = redirect + "?" + query; 796 } 797 } 798 } 799 return redirect; 800 } 801 } 802 803 810 public static String removeParameterFromPath(String path, String name) { 811 boolean first = true; 812 int idx = path.indexOf("?" + name + "="); 813 if(idx == -1) { 814 first = false; 815 idx = path.indexOf("&" + name + "="); 816 } 817 if(idx != -1) { 818 int eidx = path.indexOf('&', idx + 1); 819 if(eidx == -1) { 820 path = path.substring(0, idx); 821 } 822 else { 823 path = path.substring(0, idx) + ( first ? "?" : "&" ) + path.substring(eidx + 1, path.length()); 824 } 825 } 826 return path; 827 } 828 829 837 public static String addParameterToPath(String path, String name, String value) { 838 StringBuffer buf = new StringBuffer (path); 839 int idx = path.indexOf("?"); 840 if (idx != -1) { 841 buf.append("&"); 842 } else { 843 buf.append("?"); 844 } 845 buf.append(name); 846 buf.append("="); 847 buf.append(Util.urlEncode(value)); 848 return buf.toString(); 849 } 850 851 857 public static ActionForward addParameterToForward(ActionForward forward, String name, String value) { 858 ActionForward f = new ActionForward(forward); 859 f.setPath(addParameterToPath(forward.getPath(), name, value)); 860 return f; 861 } 862 863 866 public static void dumpComponentContext(PageContext pageContext) { 867 ComponentContext compContext = (ComponentContext) pageContext.getAttribute(ComponentConstants.COMPONENT_CONTEXT, 868 PageContext.REQUEST_SCOPE); 869 if (log.isInfoEnabled()) 870 log.info("Component context dump"); 871 for (Iterator e = compContext.getAttributeNames(); e.hasNext();) { 872 String n = (String ) e.next(); 873 Object value = compContext.getAttribute(n); 874 if (log.isInfoEnabled()) 875 log.info(" " + n + " = " + value); 876 } 877 } 878 879 887 public static String getProxyURL(User user, int propertyProfile) throws Exception { 888 String type = Property.getProperty(new ProfilePropertyKey(propertyProfile, user.getPrincipalName(), "clientProxy.type", user.getRealm().getResourceId())); 889 if (type.equals("http") || type.equals("https")) { 890 String hostname = Property.getProperty(new ProfilePropertyKey(propertyProfile, user.getPrincipalName(), "clientProxy.hostname", user.getRealm().getResourceId())); 891 if (!hostname.equals("")) { 892 StringBuffer url = new StringBuffer (); 893 url.append(type); 894 url.append("://"); 895 896 String username = Property.getProperty(new ProfilePropertyKey(propertyProfile, user.getPrincipalName(), "clientProxy.username", user.getRealm().getResourceId())); 897 String domain = Property.getProperty(new ProfilePropertyKey(propertyProfile, user.getPrincipalName(), "clientProxy.ntlmDomain", user.getRealm().getResourceId())); 898 String auth = Property.getProperty(new ProfilePropertyKey(propertyProfile, user.getPrincipalName(), "clientProxy.preferredAuthentication", user.getRealm().getResourceId())); 899 900 if (!username.equals("")) { 901 902 if (!domain.equals("")) { 903 url.append(DAVUtilities.encodeURIUserInfo(domain + "\\")); 904 } 905 906 url.append(DAVUtilities.encodeURIUserInfo(username)); 907 String password = Property.getProperty(new ProfilePropertyKey(propertyProfile, user.getPrincipalName(), "clientProxy.password", user.getRealm().getResourceId())); 908 if (!password.equals("")) { 909 url.append(":"); 910 url.append(DAVUtilities.encodeURIUserInfo(password)); 911 } 912 url.append("@"); 913 } 914 url.append(hostname); 915 int port = Property.getPropertyInt(new ProfilePropertyKey(propertyProfile, user.getPrincipalName(), "clientProxy.port", user.getRealm().getResourceId())); 916 if (port != 0) { 917 url.append(":"); 918 url.append(port); 919 } 920 url.append("?"); 921 url.append(auth); 922 return url.toString(); 923 } 924 } else if (type.equals("browser")) { 925 String auth = Property.getProperty(new ProfilePropertyKey(propertyProfile, user.getPrincipalName(), "clientProxy.preferredAuthentication", user.getRealm().getResourceId())); 926 return "browser://" + auth; 927 } 928 return null; 929 } 930 931 939 public static void checkNavigationContext(CoreAction action, ActionMapping mapping, ActionForm form, 940 HttpServletRequest request, HttpServletResponse response) throws Exception { 941 int navigationContext = action.getNavigationContext(mapping, form, request, response); 942 if (!ContextHolder.getContext().isSetupMode()) { 943 SessionInfo info = LogonControllerFactory.getInstance().getSessionInfo(request); 944 if ((navigationContext & info.getNavigationContext()) == 0) { 945 if ((navigationContext & SessionInfo.MANAGEMENT_CONSOLE_CONTEXT) != 0) { 946 if(!PolicyDatabaseFactory.getInstance().isAnyAccessRightAllowed(info.getUser(), true, true, false)) { 947 throw new NoPermissionException("You do not have permission to use the management console."); 948 } 949 info.setNavigationContext(SessionInfo.MANAGEMENT_CONSOLE_CONTEXT); 950 CoreUtil.resetMainNavigation(request.getSession()); 951 } else if ((navigationContext & SessionInfo.USER_CONSOLE_CONTEXT) != 0) { 952 info.setNavigationContext(SessionInfo.USER_CONSOLE_CONTEXT); 953 CoreUtil.resetMainNavigation(request.getSession()); 954 } else if ((navigationContext & SessionInfo.HELP_CONTEXT) != 0) { 955 } else { 957 throw new NoPermissionException("Action does not define any valid navigation contexts that it should be available in."); 958 } 959 } 960 } 961 } 962 963 968 public static Properties parseActionParameter(String parameterList) throws ParseException { 969 Properties p = new Properties (); 970 String [] properties = parameterList.split(","); 971 for (int i = 0; i < properties.length; i++) { 972 String n = properties[i]; 973 int idx = n.indexOf('='); 974 if (idx == -1) { 975 throw new ParseException ("Parameter list in incorrect format. [<name>=<value>[,<name>=<value>] ..]", 0); 976 } 977 String v = n.substring(idx + 1); 978 n = n.substring(0, idx); 979 p.setProperty(n, v); 980 } 981 return p; 982 } 983 984 988 public static List <CoreSelectableItem> getSelectedItems(List serverInterfaceItem) { 989 List <CoreSelectableItem> l = new ArrayList <CoreSelectableItem>(); 990 for (Iterator i = serverInterfaceItem.iterator(); i.hasNext();) { 991 CoreSelectableItem item = (CoreSelectableItem) i.next(); 992 if (item.getSelected()) { 993 l.add(item); 994 } 995 } 996 return l; 997 } 998 999 1003 public static List <CoreSelectableItem> getDeselectedItems(List serverInterfaceItem) { 1004 List <CoreSelectableItem> l = new ArrayList <CoreSelectableItem>(); 1005 for (Iterator i = serverInterfaceItem.iterator(); i.hasNext();) { 1006 CoreSelectableItem item = (CoreSelectableItem) i.next(); 1007 if (!item.getSelected()) { 1008 l.add(item); 1009 } 1010 } 1011 return l; 1012 } 1013 1014 1017 public static void deselectAllItems(List items) { 1018 for (Iterator i = items.iterator(); i.hasNext();) { 1019 CoreSelectableItem item = (CoreSelectableItem) i.next(); 1020 item.setSelected(false); 1021 } 1022 } 1023 1024 1027 public static void selectAllItems(List items) { 1028 for (Iterator i = items.iterator(); i.hasNext();) { 1029 CoreSelectableItem item = (CoreSelectableItem) i.next(); 1030 item.setSelected(false); 1031 } 1032 } 1033 1034 1040 public static boolean isInWizard(HttpSession session) { 1041 return session.getAttribute(Constants.WIZARD_SEQUENCE) != null; 1042 } 1043 1044 1050 public static void resetMainNavigation(HttpSession session) { 1051 session.removeAttribute(Constants.MENU_TREE); 1052 session.removeAttribute(Constants.NAV_BAR); 1053 } 1054 1055 1063 public static boolean isMenuAvailable(HttpServletRequest request) { 1064 return request.getAttribute(Constants.SELECTED_MENU) != null && request.getSession() 1065 .getAttribute(Constants.PAGE_INTERCEPTED) == null; 1066 } 1067 1068 1072 public static void addRequiredFieldMessage(Action action, HttpServletRequest request) { 1073 ActionMessages mesgs = (ActionMessages) request.getAttribute(Globals.MESSAGE_KEY); 1074 if (mesgs == null) { 1075 mesgs = new ActionMessages(); 1076 request.setAttribute(Globals.MESSAGE_KEY, mesgs); 1077 } 1078 mesgs.add(Globals.MESSAGE_KEY, new BundleActionMessage("navigation", 1079 "info.requiredFieldIndicator", 1080 "<img SRC=\"" + getThemePath(request.getSession()) + "/images/required.gif" + "\" border=\"0\"/>")); 1081 } 1082 1083 1087 public static String platformPath(String originalPath) { 1088 String p = originalPath.replace("/", File.separator).replace("\\", File.separator); 1089 if (log.isDebugEnabled()) 1090 log.debug("Original path of '" + originalPath + "' is '" + p + "' for platform"); 1091 return p; 1092 } 1093 1094 1099 public static long generateChecksum(File f) throws IOException { 1100 Adler32 alder = new Adler32 (); 1101 FileInputStream fin = new FileInputStream (f); 1102 CheckedInputStream in = new CheckedInputStream (fin, alder); 1103 byte[] buf = new byte[32768]; 1104 Util.readFullyIntoBuffer(in, buf); 1105 alder = (Adler32 ) in.getChecksum(); 1106 try { 1107 in.close(); 1108 } catch (IOException ex) { 1109 } 1110 try { 1111 fin.close(); 1112 } catch (IOException ex1) { 1113 } 1114 return alder.getValue(); 1115 } 1116 1117 1123 public static User[] getUsersInRole(Role role, UserDatabase database) throws Exception { 1124 User[] u = database.listAllUsers("*"); 1125 List <User> ur = new ArrayList <User>(); 1126 for (int i = 0; i < u.length; i++) { 1127 Role[] r = u[i].getRoles(); 1128 for (int j = 0; j < r.length; j++) { 1129 if (r[j].getPrincipalName().equals(role.getPrincipalName())) { 1130 ur.add(u[i]); 1131 break; 1132 } 1133 } 1134 } 1135 return (User[]) ur.toArray(new User[ur.size()]); 1136 } 1137 1138 1143 public static void dumpTileScope(PageContext pageContext) { 1144 ComponentContext compContext = (ComponentContext) pageContext.getAttribute(ComponentConstants.COMPONENT_CONTEXT, 1145 PageContext.REQUEST_SCOPE); 1146 System.err.println("Tile attributes"); 1147 for (Iterator i = compContext.getAttributeNames(); i.hasNext();) { 1148 String n = (String ) i.next(); 1149 System.err.println(" " + n + " = " + compContext.getAttribute(n)); 1150 } 1151 } 1152 1153 1161 public static MessageResources getMessageResources(HttpSession session, String key) { 1162 ServletContext context = session.getServletContext(); 1163 ModuleConfig moduleConfig = ModuleUtils.getInstance().getModuleConfig("", context); 1164 return (MessageResources) context.getAttribute(key + moduleConfig.getPrefix()); 1165 } 1166 1167 public static String getMessage(HttpSession session, String bundle, String key) { 1168 MessageResources resources = getMessageResources(session, bundle); 1169 Locale locale = (Locale )session.getAttribute(Globals.LOCALE_KEY); 1170 return resources.getMessage(locale, key); 1171 } 1172 1173 public static String getMessage(SessionInfo session, String bundle, String key) { 1174 return getMessage(session.getHttpSession(), bundle, key); 1175 } 1176 1177 public static String getMessage(HttpServletRequest request, String bundle, String key) { 1178 return getMessage(request.getSession(), bundle, key); 1179 } 1180 1181 1190 public static void addLibraryPath(String path) throws IOException { 1191 try { 1192 Field field = ClassLoader .class.getDeclaredField("usr_paths"); 1193 field.setAccessible(true); 1194 String [] paths = (String []) field.get(null); 1195 for (int i = 0; i < paths.length; i++) { 1196 if (path.equals(paths[i])) { 1197 return; 1198 } 1199 } 1200 String [] tmp = new String [paths.length + 1]; 1201 System.arraycopy(paths, 0, tmp, 0, paths.length); 1202 tmp[paths.length] = path; 1203 field.set(null, tmp); 1204 } catch (IllegalAccessException e) { 1205 throw new IOException ("Failed to get permissions to set library path"); 1206 } catch (NoSuchFieldException e) { 1207 1211 System.setProperty("java.library.path", System.getProperty("java.library.path") + File.pathSeparator + path); 1212 log.warn("Failed to set library path using Sun JDK workaround. Just setting java.library.path in case " + "it works. If it doesn't, plugins that use native libraries will probably fail. To fix " 1213 + "this you will have to alter " 1214 + ContextHolder.getContext().getConfDirectory().getAbsolutePath() 1215 + File.separator 1216 + "wrapper.conf to include the additional library path '" 1217 + path 1218 + "'."); 1219 } 1220 } 1221 1222 1231 public static String replaceAllTokens(String source, String token, String value) { 1232 return StringUtils.replace(source, token, value); 1233 } 1234 1235 1242 public static int addUpload(HttpSession session, UploadDetails upload) { 1243 synchronized (session) { 1244 UploadManager mgr = (UploadManager) session.getAttribute(Constants.UPLOAD_MANAGER); 1245 if (mgr == null) { 1246 mgr = new UploadManager(); 1247 session.setAttribute(Constants.UPLOAD_MANAGER, mgr); 1248 } 1249 return mgr.addUpload(upload); 1250 } 1251 } 1252 1253 1261 public static UploadDetails removeUpload(HttpSession session, int uploadId) { 1262 UploadManager mgr = (UploadManager) session.getAttribute(Constants.UPLOAD_MANAGER); 1263 if (mgr != null) { 1264 UploadDetails details = mgr.removeUpload(uploadId); 1265 if (mgr.isEmpty()) { 1266 session.removeAttribute(Constants.UPLOAD_MANAGER); 1267 } 1268 return details; 1269 } 1270 return null; 1271 } 1272 1273 1281 public static UploadDetails getUpload(HttpSession session, int id) { 1282 UploadManager mgr = (UploadManager) session.getAttribute(Constants.UPLOAD_MANAGER); 1283 if (mgr != null) { 1284 return mgr.getUpload(id); 1285 } 1286 return null; 1287 } 1288 1289 1294 public static Tag getParentTagOfClass(Class clazz, Tag tag) { 1295 while ((tag = tag.getParent()) != null) { 1296 if (tag.getClass().equals(clazz)) { 1297 return tag; 1298 } 1299 } 1300 return null; 1301 } 1302 1303 1311 public static boolean isAuthenticationModuleInUse(String moduleName) throws Exception { 1312 List authenticationSchemes = SystemDatabaseFactory.getInstance().getAuthenticationSchemeSequences(); 1313 for (Iterator i = authenticationSchemes.iterator(); i.hasNext();) { 1314 AuthenticationScheme seq = (DefaultAuthenticationScheme) i.next(); 1315 if (seq.hasModule(moduleName) && seq.getEnabled()) { 1316 return true; 1317 } 1318 } 1319 return false; 1320 } 1321 1322 1330 public static void storeUIState(String name, String value, HttpServletRequest request, HttpServletResponse response) { 1331 Cookie c = getCookie(name, request); 1332 if (c != null) { 1333 c.setValue(value); 1334 } else { 1335 c = new Cookie (name, value); 1336 } 1337 c.setMaxAge(-1); 1338 response.addCookie(c); 1339 } 1340 1341 1348 public static String getRealRequestURI(HttpServletRequest request) { 1349 HttpServletRequest tmpRequest = request; 1350 while (tmpRequest instanceof HttpServletRequestWrapper ) { 1351 tmpRequest = (HttpServletRequest ) ((HttpServletRequestWrapper ) tmpRequest).getRequest(); 1352 } 1353 return tmpRequest.getRequestURI(); 1354 } 1355 1356 1362 public static boolean isInUserConsole(HttpServletRequest request) { 1363 SessionInfo session = (SessionInfo) request.getSession().getAttribute(Constants.SESSION_INFO); 1364 return session != null && session.getNavigationContext() == SessionInfo.USER_CONSOLE_CONTEXT; 1365 } 1366 1367 1373 public static boolean isInManagementConsole(HttpServletRequest request) { 1374 SessionInfo session = (SessionInfo) request.getSession().getAttribute(Constants.SESSION_INFO); 1375 return session != null && session.getNavigationContext() == SessionInfo.MANAGEMENT_CONSOLE_CONTEXT; 1376 } 1377 1378 1384 public static String getUsersProfileProperty(HttpSession session, String propertyName, User user) { 1385 return Property.getProperty(new ProfilePropertyKey(getCurrentPropertyProfileId(session), 1386 user == null ? null : user.getPrincipalName(), propertyName, user == null ? UserDatabaseManager 1387 .getInstance().getDefaultUserDatabase().getRealm().getResourceId() : user 1388 .getRealm().getResourceId())); 1389 } 1390 1391 1397 public static boolean getUsersProfilePropertyBoolean(HttpSession session, String propertyName, User user) { 1398 return Property.getPropertyBoolean(new ProfilePropertyKey(getCurrentPropertyProfileId(session), 1399 user == null ? null : user.getPrincipalName(), propertyName, user == null ? UserDatabaseManager 1400 .getInstance().getDefaultUserDatabase().getRealm().getResourceId() : user 1401 .getRealm().getResourceId())); 1402 } 1403 1404 1410 public static int getUsersProfilePropertyInt(HttpSession session, String propertyName, User user) { 1411 return Property.getPropertyInt(new ProfilePropertyKey(getCurrentPropertyProfileId(session), 1412 user == null ? null : user.getPrincipalName(), propertyName, user == null ? UserDatabaseManager 1413 .getInstance().getDefaultUserDatabase().getRealm().getResourceId() : user 1414 .getRealm().getResourceId())); 1415 } 1416 1417 1429 public static void updateEventsTable(String bundle, Class clazz) { 1430 Plugin auditingPlugin = PluginType.getPlugin("sslexplorer-enterprise-auditing"); 1431 if (auditingPlugin == null) { 1432 if(log.isDebugEnabled()) 1433 log.warn("Could not locate auditing plugin. No events codes can be updated."); 1434 } else { 1435 try { 1436 Method m = auditingPlugin.getClass().getMethod("getDatabase", new Class [] {}); 1437 Database d = (Database) m.invoke(auditingPlugin, new Object [] {}); 1438 m = d.getClass().getMethod("updateEventsTable", new Class [] { String .class, Class .class }); 1439 m.invoke(d, new Object [] { bundle, clazz }); 1440 } catch (Exception e) { 1441 log.error("Failed to register event codes.", e); 1442 } 1443 } 1444 } 1445 1446 1451 public static void clearFlow(HttpServletRequest request) { 1452 request.getSession().removeAttribute(Constants.WIZARD_SEQUENCE); 1453 request.getSession().removeAttribute(Constants.SUSPENDED_WIZARD_SEQUENCE); 1454 ResourceStack.popFromEditingStack(request.getSession()); 1455 request.getSession().removeAttribute(Constants.EDITING_ITEM); 1456 } 1457 1458 1466 public static void checkSafeURI(String uri) { 1467 URI location; 1468 try { 1469 location = new URI (uri); 1470 } catch (URISyntaxException e) { 1471 throw new IllegalArgumentException (uri + " is not safe."); 1472 } 1473 if( location.getScheme() != null && !"http".equalsIgnoreCase(location.getScheme()) && 1474 !"https".equalsIgnoreCase(location.getScheme()) ) { 1475 throw new IllegalArgumentException (uri + " is not safe."); 1476 } 1477 } 1478 1479 1487 public static String filterSafeURI(String uri, String replacement) { 1488 try { 1489 checkSafeURI(uri); 1490 } catch (IllegalArgumentException e) { 1491 return replacement; 1492 } 1493 return uri; 1494 } 1495 1496 1497 1504 public static DateFormat getDateFormat(HttpServletRequest request) { 1505 return getDateFormat(request, null); 1506 } 1507 1508 1509 1517 public static DateFormat getDateFormat(HttpServletRequest request, String timeFormat) { 1518 return new SimpleDateFormat ( 1519 Property.getProperty( 1520 new ProfilePropertyKey("ui.dateFormat", 1521 LogonControllerFactory.getInstance().getSessionInfo(request))) + ( timeFormat == null ? "" : ( " " + timeFormat )) ); 1522 } 1523 1524 1529 public static String toString(Throwable t) { 1530 StringWriter stringWriter = new StringWriter (); 1531 PrintWriter printWriter = new PrintWriter (stringWriter); 1532 t.printStackTrace(printWriter); 1533 return stringWriter.toString(); 1534 } 1535} | Popular Tags |