Ejemplo n.º 1
0
  /**
   * Internal method that allows a redirect to be sent with a status other than {@link
   * HttpServletResponse#SC_FOUND} (302). No attempt is made to validate the status code.
   */
  public void sendRedirect(String location, int status) throws IOException {
    if (isCommitted()) {
      throw new IllegalStateException(sm.getString("coyoteResponse.sendRedirect.ise"));
    }

    // Ignore any call from an included servlet
    if (included) {
      return;
    }

    // Clear any data content that has been buffered
    resetBuffer(true);

    // Generate a temporary redirect to the specified location
    try {
      String absolute = toAbsolute(location);
      setStatus(status);
      setHeader("Location", absolute);
      if (getContext().getSendRedirectBody()) {
        PrintWriter writer = getWriter();
        writer.print(
            sm.getString("coyoteResponse.sendRedirect.note", RequestUtil.filter(absolute)));
        flushBuffer();
      }
    } catch (IllegalArgumentException e) {
      setStatus(SC_NOT_FOUND);
    }

    // Cause the response to be finished (from the application perspective)
    setSuspended(true);
  }
Ejemplo n.º 2
0
  /**
   * Set the location.
   *
   * @param location The new location
   */
  public void setLocation(String location) {

    //        if ((location == null) || !location.startsWith("/"))
    //            throw new IllegalArgumentException
    //                ("Error Page Location must start with a '/'");
    this.location = RequestUtil.URLDecode(location);
  }
Ejemplo n.º 3
0
  /**
   * Return a String representation of this user in XML format.
   *
   * <p><strong>IMPLEMENTATION NOTE</strong> - For backwards compatibility, the reader that
   * processes this entry will accept either <code>username</code> or </code>name</code> for the
   * username property.
   */
  public String toString() {

    StringBuffer sb = new StringBuffer("<user username=\"");
    sb.append(RequestUtil.filter(username));
    sb.append("\" password=\"");
    sb.append(RequestUtil.filter(password));
    sb.append("\"");
    if (fullName != null) {
      sb.append(" fullName=\"");
      sb.append(RequestUtil.filter(fullName));
      sb.append("\"");
    }
    synchronized (groups) {
      if (groups.size() > 0) {
        sb.append(" groups=\"");
        int n = 0;
        Iterator values = groups.iterator();
        while (values.hasNext()) {
          if (n > 0) {
            sb.append(',');
          }
          n++;
          sb.append(RequestUtil.filter(((Group) values.next()).getGroupname()));
        }
        sb.append("\"");
      }
    }
    synchronized (roles) {
      if (roles.size() > 0) {
        sb.append(" roles=\"");
        int n = 0;
        Iterator values = roles.iterator();
        while (values.hasNext()) {
          if (n > 0) {
            sb.append(',');
          }
          n++;
          sb.append(RequestUtil.filter(((Role) values.next()).getRolename()));
        }
        sb.append("\"");
      }
    }
    sb.append("/>");
    return (sb.toString());
  }
Ejemplo n.º 4
0
 public void addURLPattern(String urlPattern) {
   if ("*".equals(urlPattern)) {
     this.matchAllUrlPatterns = true;
   } else {
     String[] results = new String[urlPatterns.length + 1];
     System.arraycopy(urlPatterns, 0, results, 0, urlPatterns.length);
     results[urlPatterns.length] = RequestUtil.URLDecode(urlPattern);
     urlPatterns = results;
   }
 }
Ejemplo n.º 5
0
  /**
   * This method is the simplified version of the similar method in
   * org.apache.catalina.connector.http.HttpProcessor. However, this method only parses some "easy"
   * headers, such as "cookie", "content-length", and "content-type", and ignore other headers.
   *
   * @param input The input stream connected to our socket
   * @exception IOException if an input/output error occurs
   * @exception ServletException if a parsing error occurs
   */
  private void parseHeaders(SocketInputStream input) throws IOException, ServletException {
    while (true) {
      HttpHeader header = new HttpHeader();
      ;

      // Read the next header
      input.readHeader(header);
      if (header.nameEnd == 0) {
        if (header.valueEnd == 0) {
          return;
        } else {
          throw new ServletException(sm.getString("httpProcessor.parseHeaders.colon"));
        }
      }

      String name = new String(header.name, 0, header.nameEnd);
      String value = new String(header.value, 0, header.valueEnd);
      request.addHeader(name, value);
      // do something for some headers, ignore others.
      if (name.equals("cookie")) {
        Cookie cookies[] = RequestUtil.parseCookieHeader(value);
        for (int i = 0; i < cookies.length; i++) {
          if (cookies[i].getName().equals("jsessionid")) {
            // Override anything requested in the URL
            if (!request.isRequestedSessionIdFromCookie()) {
              // Accept only the first session id cookie
              request.setRequestedSessionId(cookies[i].getValue());
              request.setRequestedSessionCookie(true);
              request.setRequestedSessionURL(false);
            }
          }
          request.addCookie(cookies[i]);
        }
      } else if (name.equals("content-length")) {
        int n = -1;
        try {
          n = Integer.parseInt(value);
        } catch (Exception e) {
          throw new ServletException(sm.getString("httpProcessor.parseHeaders.contentLength"));
        }
        request.setContentLength(n);
      } else if (name.equals("content-type")) {
        request.setContentType(value);
      }
    } // end while
  }
Ejemplo n.º 6
0
  /**
   * Merge the parameters from the saved query parameter string (if any), and the parameters already
   * present on this request (if any), such that the parameter values from the query string show up
   * first if there are duplicate parameter names.
   */
  private void mergeParameters() {

    if ((queryParamString == null) || (queryParamString.length() < 1)) return;

    HashMap queryParameters = new HashMap();
    String encoding = getCharacterEncoding();
    if (encoding == null) encoding = "ISO-8859-1";
    try {
      RequestUtil.parseParameters(queryParameters, queryParamString, encoding);
    } catch (Exception e) {;
    }
    Iterator keys = parameters.keySet().iterator();
    while (keys.hasNext()) {
      String key = (String) keys.next();
      Object value = queryParameters.get(key);
      if (value == null) {
        queryParameters.put(key, parameters.get(key));
        continue;
      }
      queryParameters.put(key, mergeValues(value, parameters.get(key)));
    }
    parameters = queryParameters;
  }
  /**
   * Render a HTML list of the currently active Contexts in our virtual host, and memory and server
   * status information.
   *
   * @param request The request
   * @param response The response
   * @param message a message to display
   */
  public void list(
      HttpServletRequest request,
      HttpServletResponse response,
      String message,
      StringManager smClient)
      throws IOException {

    if (debug >= 1) {
      log(sm.getString("hostManagerServlet.list", engine.getName()));
    }

    PrintWriter writer = response.getWriter();

    // HTML Header Section
    writer.print(org.apache.catalina.manager.Constants.HTML_HEADER_SECTION);

    // Body Header Section
    Object[] args = new Object[2];
    args[0] = request.getContextPath();
    args[1] = smClient.getString("htmlHostManagerServlet.title");
    writer.print(MessageFormat.format(Constants.BODY_HEADER_SECTION, args));

    // Message Section
    args = new Object[3];
    args[0] = smClient.getString("htmlHostManagerServlet.messageLabel");
    if (message == null || message.length() == 0) {
      args[1] = "OK";
    } else {
      args[1] = RequestUtil.filter(message);
    }
    writer.print(MessageFormat.format(Constants.MESSAGE_SECTION, args));

    // Manager Section
    args = new Object[9];
    args[0] = smClient.getString("htmlHostManagerServlet.manager");
    args[1] = response.encodeURL(request.getContextPath() + "/html/list");
    args[2] = smClient.getString("htmlHostManagerServlet.list");
    args[3] =
        response.encodeURL(
            request.getContextPath()
                + "/"
                + smClient.getString("htmlHostManagerServlet.helpHtmlManagerFile"));
    args[4] = smClient.getString("htmlHostManagerServlet.helpHtmlManager");
    args[5] =
        response.encodeURL(
            request.getContextPath()
                + "/"
                + smClient.getString("htmlHostManagerServlet.helpManagerFile"));
    args[6] = smClient.getString("htmlHostManagerServlet.helpManager");
    args[7] = response.encodeURL("/manager/status");
    args[8] = smClient.getString("statusServlet.title");
    writer.print(MessageFormat.format(Constants.MANAGER_SECTION, args));

    // Hosts Header Section
    args = new Object[3];
    args[0] = smClient.getString("htmlHostManagerServlet.hostName");
    args[1] = smClient.getString("htmlHostManagerServlet.hostAliases");
    args[2] = smClient.getString("htmlHostManagerServlet.hostTasks");
    writer.print(MessageFormat.format(HOSTS_HEADER_SECTION, args));

    // Hosts Row Section
    // Create sorted map of host names.
    Container[] children = engine.findChildren();
    String hostNames[] = new String[children.length];
    for (int i = 0; i < children.length; i++) hostNames[i] = children[i].getName();

    TreeMap<String, String> sortedHostNamesMap = new TreeMap<String, String>();

    for (int i = 0; i < hostNames.length; i++) {
      String displayPath = hostNames[i];
      sortedHostNamesMap.put(displayPath, hostNames[i]);
    }

    String hostsStart = smClient.getString("htmlHostManagerServlet.hostsStart");
    String hostsStop = smClient.getString("htmlHostManagerServlet.hostsStop");
    String hostsRemove = smClient.getString("htmlHostManagerServlet.hostsRemove");

    Iterator<Map.Entry<String, String>> iterator = sortedHostNamesMap.entrySet().iterator();
    while (iterator.hasNext()) {
      Map.Entry<String, String> entry = iterator.next();
      String hostName = entry.getKey();
      Host host = (Host) engine.findChild(hostName);

      if (host != null) {
        args = new Object[2];
        args[0] = RequestUtil.filter(hostName);
        String[] aliases = host.findAliases();
        StringBuilder buf = new StringBuilder();
        if (aliases.length > 0) {
          buf.append(aliases[0]);
          for (int j = 1; j < aliases.length; j++) {
            buf.append(", ").append(aliases[j]);
          }
        }

        if (buf.length() == 0) {
          buf.append("&nbsp;");
          args[1] = buf.toString();
        } else {
          args[1] = RequestUtil.filter(buf.toString());
        }

        writer.print(MessageFormat.format(HOSTS_ROW_DETAILS_SECTION, args));

        args = new Object[4];
        if (host.getState().isAvailable()) {
          args[0] =
              response.encodeURL(
                  request.getContextPath()
                      + "/html/stop?name="
                      + URLEncoder.encode(hostName, "UTF-8"));
          args[1] = hostsStop;
        } else {
          args[0] =
              response.encodeURL(
                  request.getContextPath()
                      + "/html/start?name="
                      + URLEncoder.encode(hostName, "UTF-8"));
          args[1] = hostsStart;
        }
        args[2] =
            response.encodeURL(
                request.getContextPath()
                    + "/html/remove?name="
                    + URLEncoder.encode(hostName, "UTF-8"));
        args[3] = hostsRemove;
        if (host == this.installedHost) {
          writer.print(MessageFormat.format(MANAGER_HOST_ROW_BUTTON_SECTION, args));
        } else {
          writer.print(MessageFormat.format(HOSTS_ROW_BUTTON_SECTION, args));
        }
      }
    }

    // Add Section
    args = new Object[6];
    args[0] = smClient.getString("htmlHostManagerServlet.addTitle");
    args[1] = smClient.getString("htmlHostManagerServlet.addHost");
    args[2] = response.encodeURL(request.getContextPath() + "/html/add");
    args[3] = smClient.getString("htmlHostManagerServlet.addName");
    args[4] = smClient.getString("htmlHostManagerServlet.addAliases");
    args[5] = smClient.getString("htmlHostManagerServlet.addAppBase");
    writer.print(MessageFormat.format(ADD_SECTION_START, args));

    args = new Object[3];
    args[0] = smClient.getString("htmlHostManagerServlet.addAutoDeploy");
    args[1] = "autoDeploy";
    args[2] = "checked";
    writer.print(MessageFormat.format(ADD_SECTION_BOOLEAN, args));
    args[0] = smClient.getString("htmlHostManagerServlet.addDeployOnStartup");
    args[1] = "deployOnStartup";
    args[2] = "checked";
    writer.print(MessageFormat.format(ADD_SECTION_BOOLEAN, args));
    args[0] = smClient.getString("htmlHostManagerServlet.addDeployXML");
    args[1] = "deployXML";
    args[2] = "checked";
    writer.print(MessageFormat.format(ADD_SECTION_BOOLEAN, args));
    args[0] = smClient.getString("htmlHostManagerServlet.addUnpackWARs");
    args[1] = "unpackWARs";
    args[2] = "checked";
    writer.print(MessageFormat.format(ADD_SECTION_BOOLEAN, args));

    args[0] = smClient.getString("htmlHostManagerServlet.addManager");
    args[1] = "manager";
    args[2] = "checked";
    writer.print(MessageFormat.format(ADD_SECTION_BOOLEAN, args));

    args = new Object[1];
    args[0] = smClient.getString("htmlHostManagerServlet.addButton");
    writer.print(MessageFormat.format(ADD_SECTION_END, args));

    // Server Header Section
    args = new Object[7];
    args[0] = smClient.getString("htmlHostManagerServlet.serverTitle");
    args[1] = smClient.getString("htmlHostManagerServlet.serverVersion");
    args[2] = smClient.getString("htmlHostManagerServlet.serverJVMVersion");
    args[3] = smClient.getString("htmlHostManagerServlet.serverJVMVendor");
    args[4] = smClient.getString("htmlHostManagerServlet.serverOSName");
    args[5] = smClient.getString("htmlHostManagerServlet.serverOSVersion");
    args[6] = smClient.getString("htmlHostManagerServlet.serverOSArch");
    writer.print(MessageFormat.format(Constants.SERVER_HEADER_SECTION, args));

    // Server Row Section
    args = new Object[6];
    args[0] = ServerInfo.getServerInfo();
    args[1] = System.getProperty("java.runtime.version");
    args[2] = System.getProperty("java.vm.vendor");
    args[3] = System.getProperty("os.name");
    args[4] = System.getProperty("os.version");
    args[5] = System.getProperty("os.arch");
    writer.print(MessageFormat.format(Constants.SERVER_ROW_SECTION, args));

    // HTML Tail Section
    writer.print(Constants.HTML_TAIL_SECTION);

    // Finish up the response
    writer.flush();
    writer.close();
  }
Ejemplo n.º 8
0
  /**
   * Prints out an error report.
   *
   * @param request The request being processed
   * @param response The response being generated
   * @param throwable The exception that occurred (which possibly wraps a root cause exception
   */
  protected void report(Request request, Response response, Throwable throwable) {

    // Do nothing on non-HTTP responses
    int statusCode = response.getStatus();

    // Do nothing on a 1xx, 2xx and 3xx status
    // Do nothing if anything has been written already
    if (statusCode < 400 || response.getContentWritten() > 0 || !response.isError()) {
      return;
    }

    String message = RequestUtil.filter(response.getMessage());
    if (message == null) {
      if (throwable != null) {
        String exceptionMessage = throwable.getMessage();
        if (exceptionMessage != null && exceptionMessage.length() > 0) {
          message = RequestUtil.filter((new Scanner(exceptionMessage)).nextLine());
        }
      }
      if (message == null) {
        message = "";
      }
    }

    // Do nothing if there is no report for the specified status code
    String report = null;
    try {
      report = sm.getString("http." + statusCode);
    } catch (Throwable t) {
      ExceptionUtils.handleThrowable(t);
    }
    if (report == null) {
      return;
    }

    StringBuilder sb = new StringBuilder();

    sb.append("<html><head><title>");
    sb.append(ServerInfo.getServerInfo()).append(" - ");
    sb.append(sm.getString("errorReportValve.errorReport"));
    sb.append("</title>");
    sb.append("<style><!--");
    sb.append(org.apache.catalina.util.TomcatCSS.TOMCAT_CSS);
    sb.append("--></style> ");
    sb.append("</head><body>");
    sb.append("<h1>");
    sb.append(sm.getString("errorReportValve.statusHeader", "" + statusCode, message))
        .append("</h1>");
    sb.append("<HR size=\"1\" noshade=\"noshade\">");
    sb.append("<p><b>type</b> ");
    if (throwable != null) {
      sb.append(sm.getString("errorReportValve.exceptionReport"));
    } else {
      sb.append(sm.getString("errorReportValve.statusReport"));
    }
    sb.append("</p>");
    sb.append("<p><b>");
    sb.append(sm.getString("errorReportValve.message"));
    sb.append("</b> <u>");
    sb.append(message).append("</u></p>");
    sb.append("<p><b>");
    sb.append(sm.getString("errorReportValve.description"));
    sb.append("</b> <u>");
    sb.append(report);
    sb.append("</u></p>");

    if (throwable != null) {

      String stackTrace = getPartialServletStackTrace(throwable);
      sb.append("<p><b>");
      sb.append(sm.getString("errorReportValve.exception"));
      sb.append("</b> <pre>");
      sb.append(RequestUtil.filter(stackTrace));
      sb.append("</pre></p>");

      int loops = 0;
      Throwable rootCause = throwable.getCause();
      while (rootCause != null && (loops < 10)) {
        stackTrace = getPartialServletStackTrace(rootCause);
        sb.append("<p><b>");
        sb.append(sm.getString("errorReportValve.rootCause"));
        sb.append("</b> <pre>");
        sb.append(RequestUtil.filter(stackTrace));
        sb.append("</pre></p>");
        // In case root cause is somehow heavily nested
        rootCause = rootCause.getCause();
        loops++;
      }

      sb.append("<p><b>");
      sb.append(sm.getString("errorReportValve.note"));
      sb.append("</b> <u>");
      sb.append(sm.getString("errorReportValve.rootCauseInLogs", ServerInfo.getServerInfo()));
      sb.append("</u></p>");
    }

    sb.append("<HR size=\"1\" noshade=\"noshade\">");
    sb.append("<h3>").append(ServerInfo.getServerInfo()).append("</h3>");
    sb.append("</body></html>");

    try {
      try {
        response.setContentType("text/html");
        response.setCharacterEncoding("utf-8");
      } catch (Throwable t) {
        ExceptionUtils.handleThrowable(t);
        if (container.getLogger().isDebugEnabled()) {
          container.getLogger().debug("status.setContentType", t);
        }
      }
      Writer writer = response.getReporter();
      if (writer != null) {
        // If writer is null, it's an indication that the response has
        // been hard committed already, which should never happen
        writer.write(sb.toString());
      }
    } catch (IOException e) {
      // Ignore
    } catch (IllegalStateException e) {
      // Ignore
    }
  }
Ejemplo n.º 9
0
  /**
   * Parse the incoming HTTP request headers, and set the appropriate request headers.
   *
   * @param input The input stream connected to our socket
   * @exception IOException if an input/output error occurs
   * @exception ServletException if a parsing error occurs
   */
  private void parseHeaders(SocketInputStream input) throws IOException, ServletException {

    while (true) {

      HttpHeader header = request.allocateHeader();

      // Read the next header
      input.readHeader(header);
      if (header.nameEnd == 0) {
        if (header.valueEnd == 0) {
          return;
        } else {
          throw new ServletException(sm.getString("httpProcessor.parseHeaders.colon"));
        }
      }

      String value = new String(header.value, 0, header.valueEnd);
      if (debug >= 1) log(" Header " + new String(header.name, 0, header.nameEnd) + " = " + value);

      // Set the corresponding request headers
      if (header.equals(DefaultHeaders.AUTHORIZATION_NAME)) {
        request.setAuthorization(value);
      } else if (header.equals(DefaultHeaders.ACCEPT_LANGUAGE_NAME)) {
        parseAcceptLanguage(value);
      } else if (header.equals(DefaultHeaders.COOKIE_NAME)) {
        Cookie cookies[] = RequestUtil.parseCookieHeader(value);
        for (int i = 0; i < cookies.length; i++) {
          if (cookies[i].getName().equals(Globals.SESSION_COOKIE_NAME)) {
            // Override anything requested in the URL
            if (!request.isRequestedSessionIdFromCookie()) {
              // Accept only the first session id cookie
              request.setRequestedSessionId(cookies[i].getValue());
              request.setRequestedSessionCookie(true);
              request.setRequestedSessionURL(false);
              if (debug >= 1)
                log(
                    " Requested cookie session id is "
                        + ((HttpServletRequest) request.getRequest()).getRequestedSessionId());
            }
          }
          if (debug >= 1)
            log(" Adding cookie " + cookies[i].getName() + "=" + cookies[i].getValue());
          request.addCookie(cookies[i]);
        }
      } else if (header.equals(DefaultHeaders.CONTENT_LENGTH_NAME)) {
        int n = -1;
        try {
          n = Integer.parseInt(value);
        } catch (Exception e) {
          throw new ServletException(sm.getString("httpProcessor.parseHeaders.contentLength"));
        }
        request.setContentLength(n);
      } else if (header.equals(DefaultHeaders.CONTENT_TYPE_NAME)) {
        request.setContentType(value);
      } else if (header.equals(DefaultHeaders.HOST_NAME)) {
        int n = value.indexOf(':');
        if (n < 0) {
          if (connector.getScheme().equals("http")) {
            request.setServerPort(80);
          } else if (connector.getScheme().equals("https")) {
            request.setServerPort(443);
          }
          if (proxyName != null) request.setServerName(proxyName);
          else request.setServerName(value);
        } else {
          if (proxyName != null) request.setServerName(proxyName);
          else request.setServerName(value.substring(0, n).trim());
          if (proxyPort != 0) request.setServerPort(proxyPort);
          else {
            int port = 80;
            try {
              port = Integer.parseInt(value.substring(n + 1).trim());
            } catch (Exception e) {
              throw new ServletException(sm.getString("httpProcessor.parseHeaders.portNumber"));
            }
            request.setServerPort(port);
          }
        }
      } else if (header.equals(DefaultHeaders.CONNECTION_NAME)) {
        if (header.valueEquals(DefaultHeaders.CONNECTION_CLOSE_VALUE)) {
          keepAlive = false;
          response.setHeader("Connection", "close");
        }
        // request.setConnection(header);
        /*
          if ("keep-alive".equalsIgnoreCase(value)) {
          keepAlive = true;
          }
        */
      } else if (header.equals(DefaultHeaders.EXPECT_NAME)) {
        if (header.valueEquals(DefaultHeaders.EXPECT_100_VALUE)) sendAck = true;
        else
          throw new ServletException(sm.getString("httpProcessor.parseHeaders.unknownExpectation"));
      } else if (header.equals(DefaultHeaders.TRANSFER_ENCODING_NAME)) {
        // request.setTransferEncoding(header);
      }

      request.nextHeader();
    }
  }