private void logRequest(HttpServletRequest request) {
    if (logger.isInfoEnabled()) {
      logger.info("Request method: " + request.getMethod());
      logger.info("Request contextPath: " + request.getContextPath());
      logger.info("Request pathInfo: " + request.getPathInfo());
      logger.info("Request pathTranslated: " + request.getPathTranslated());
      logger.info("Request queryString: " + request.getQueryString());
      logger.info("Request requestURI: " + request.getRequestURI());
      logger.info("Request requestURL: " + request.getRequestURL());
      logger.info("Request servletPath: " + request.getServletPath());
      Enumeration headers = request.getHeaderNames();
      if (headers != null) {
        while (headers.hasMoreElements()) {
          Object headerName = headers.nextElement();
          logger.info(
              "Request header " + headerName + ":" + request.getHeader((String) headerName));
        }
      }

      Enumeration params = request.getParameterNames();
      if (params != null) {
        while (params.hasMoreElements()) {
          Object paramName = params.nextElement();
          logger.info(
              "Request parameter " + paramName + ":" + request.getParameter((String) paramName));
        }
      }
      logger.info("- End of request -");
    }
  }
예제 #2
0
  @Override
  public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
      throws IOException, ServletException {
    HttpServletRequest req = (HttpServletRequest) request;
    HttpServletResponse resp = (HttpServletResponse) response;

    log.entering("LoginFilter", "doFilter");
    if (!isAuth(req)) {
      log.info("Page non autorisé:" + req.getPathTranslated());
      resp.sendError(HttpServletResponse.SC_UNAUTHORIZED);
      log.exiting("LoginFilter", "doFilter");
      return; // break filter chain, requested JSP/servlet will not be executed
    }

    // propagate to next element in the filter chain, ultimately JSP/ servlet gets executed
    chain.doFilter(request, response);
    log.exiting("LoginFilter", "doFilter");
  }
예제 #3
0
  /** {@inheritDoc} */
  public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
      throws IOException, ServletException {

    HttpServletRequest rqst = (HttpServletRequest) request;
    HttpServletResponse rsp = (HttpServletResponse) response;

    if (LOG.isDebugEnabled()) {
      StringBuilder b =
          new StringBuilder("Request from ")
              .append(rqst.getRemoteHost())
              .append("/")
              .append(rqst.getRemoteAddr())
              .append(":")
              .append(rqst.getRemotePort());

      @SuppressWarnings("unchecked")
      Enumeration<String> e = rqst.getAttributeNames();
      for (; e.hasMoreElements(); ) {
        String attribute = e.nextElement();
        b.append("\n  " + attribute + " => " + rqst.getAttribute(attribute));
      }

      X509Certificate[] userCerts =
          (X509Certificate[]) rqst.getAttribute("javax.servlet.request.X509Certificate");
      if (userCerts != null)
        for (X509Certificate cert : userCerts)
          b.append(
              "\n Client certificate Subject Name is " + cert.getSubjectX500Principal().getName());

      b.append("\n The Scheme is " + rqst.getScheme());
      b.append("\n The Auth Type is " + rqst.getAuthType());
      b.append("\n The Path Info is " + rqst.getPathInfo());
      b.append("\n The Translated Path Info is " + rqst.getPathTranslated());
      b.append("\n The Context Path is " + rqst.getContextPath());
      b.append("\n The Query String is " + rqst.getQueryString());
      b.append("\n The Remote User is " + rqst.getRemoteUser());
      b.append("\n The User Principal is " + rqst.getUserPrincipal());
      b.append("\n The Request URI is " + rqst.getRequestURI());
      b.append("\n The Request URL is " + rqst.getRequestURL());
      b.append("\n The Servlet Path is " + rqst.getServletPath());

      LOG.debug(b.toString());
    }

    if (rqst.getScheme().equalsIgnoreCase("https")) {
      boolean isAuthorized = false;
      X509Certificate[] certs =
          (X509Certificate[]) rqst.getAttribute("javax.servlet.request.X509Certificate");
      if (certs == null || certs.length == 0) {
        rsp.sendError(HttpServletResponse.SC_BAD_REQUEST, "No client SSL certificate received");
        return;
      }
      for (X509Certificate cert : certs) {
        try {
          cert.checkValidity();
        } catch (CertificateExpiredException e) {
          LOG.info("Received cert for " + cert.getSubjectX500Principal().getName() + " expired");
          rsp.sendError(HttpServletResponse.SC_FORBIDDEN, "Certificate expired");
          return;
        } catch (CertificateNotYetValidException e) {
          LOG.info(
              "Received cert for "
                  + cert.getSubjectX500Principal().getName()
                  + " is not yet valid");
          rsp.sendError(HttpServletResponse.SC_FORBIDDEN, "Certificate is not yet valid");
          return;
        }
      }

      String[] tokens = certs[0].getSubjectX500Principal().getName().split("\\s*,\\s*");
      String userID = null;
      for (String s : tokens) {
        if (s.startsWith("CN=")) {
          userID = s;
          break;
        }
      }
      if (userID == null || userID.length() < 4) {
        LOG.info("Can't retrieve user ID from SSL certificate");
        rsp.sendError(
            HttpServletResponse.SC_FORBIDDEN, "Can't retrieve user ID from SSL certificate");
        return;
      }
      userID = userID.substring(3);

      String servletPath = rqst.getServletPath();
      if (HFTP_PATTERN.matcher(servletPath).matches()) {
        // request is an HSFTP request
        if (FILEPATH_PATTERN.matcher(servletPath).matches()) {
          // file path as part of the URL
          isAuthorized =
              checkPath(userID, certs[0], rqst.getPathInfo() != null ? rqst.getPathInfo() : "/");
        } else {
          // file path is stored in "filename" parameter
          isAuthorized = checkPath(userID, certs[0], rqst.getParameter("filename"));
        }
      } else if (RELOAD_PATTERN.matcher(servletPath).matches() && checkUser("Admin", certs[0])) {
        Configuration conf = new Configuration(false);
        conf.addResource("hdfsproxy-default.xml");
        Map<String, Set<Path>> permsMap = getPermMap(conf);
        Map<String, Set<BigInteger>> certsMap = getCertsMap(conf);
        if (permsMap == null || certsMap == null) {
          LOG.warn("Permission files reloading failed");
          rsp.sendError(
              HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Permission files reloading failed");
          return;
        }
        ProxyFilter.permsMap = permsMap;
        ProxyFilter.certsMap = certsMap;
        LOG.info("User permissions and user certs files reloaded");
        rsp.setStatus(HttpServletResponse.SC_OK);
        return;
      } else if (CLEAR_PATTERN.matcher(servletPath).matches() && checkUser("Admin", certs[0])) {
        ProxyUgiManager.clearCache();
        LOG.info("Ugi cache cleared");
        rsp.setStatus(HttpServletResponse.SC_OK);
        return;
      }

      if (!isAuthorized) {
        rsp.sendError(HttpServletResponse.SC_FORBIDDEN, "Unauthorized access");
        return;
      }
      // request is authorized, set ugi for servlets
      UnixUserGroupInformation ugi = ProxyUgiManager.getUgiForUser(userID);
      if (ugi == null) {
        LOG.info("Can't retrieve ugi for user " + userID);
        rsp.sendError(
            HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Can't retrieve ugi for user " + userID);
        return;
      }
      rqst.setAttribute("authorized.ugi", ugi);
    } else { // http request, set ugi for servlets, only for testing purposes
      String ugi = rqst.getParameter("ugi");
      rqst.setAttribute("authorized.ugi", new UnixUserGroupInformation(ugi.split(",")));
    }

    chain.doFilter(request, response);
  }
예제 #4
0
파일: Start.java 프로젝트: cad188/eecs4413
  /** @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */
  protected void doGet(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    // Redirects to /Start if the Startup/YorkRedirect address is attempted
    if (request.getRequestURI().equals("/mCalc0/Startup/YorkRedirect")) {
      response.sendRedirect("/mCalc0/Start");
      System.out.println("Redirect successful\n");
    }

    // Send message to the console
    System.out.println("doGet Hello World\n");
    response.setContentType("plain");
    // Output message in the browser
    response.getWriter().println("doGet Hello World\n");

    double i = extractParameter("interest", request) / 100; // interest in %
    double a = extractParameter("amortization", request); // amortization
    double p = extractParameter("principle", request); // principle
    DecimalFormat truncate = new DecimalFormat("#.##");

    PrintWriter out = response.getWriter();
    out.println(
        "\tThe Networking Layer\n"
            + "Server IP: "
            + request.getLocalAddr()
            + "\n"
            + "Server Port: "
            + request.getLocalPort()
            + "\n"
            + "Client IP: "
            + request.getRemoteAddr()
            + "\n"
            + "Client Port: "
            + request.getRemotePort()
            + "\n"
            + "\n"
            + "\tThe HTTP Layer\n"
            + "Request Protocol: "
            + request.getProtocol()
            + "\n"
            + "Request Method: "
            + request.getMethod()
            + "\n"
            + "Client's query string: ("
            + request.getQueryString()
            + ")\n"
            + "Named Request Parameter: "
            + request.getParameter("name")
            + "\n"
            + "\n\tThe URL\n"
            + "URI: "
            + request.getRequestURI()
            + "\n"
            + "Context Path: "
            + request.getContextPath()
            + "\n"
            + "Servlet/Extra Path: "
            + request.getServletPath()
            + "\n"
            + "Translated Path: "
            + request.getPathTranslated()
            + "\n"
            + "\n\tContext Parameter\n"
            + "name - "
            + request.getSession().getServletContext().getServletContextName()
            + "\n"
            + "value - "
            + request.getSession().getServletContext().getInitParameter("ContextParameter")
            + "\n"
            + "\n\tThe Computation"
            + "\n"
            + "Principle: "
            + p
            + "\n"
            + "Amortization: "
            + a
            + "\n"
            + "Interest: "
            + i
            + "\n"
            + "Monthly payment: $"
            + truncate.format(computePayment(p, i, a))
            + "\n");
    // Error to be caught
    // int x = 0;
    // int y = 20/x;

  }
 public String getPathTranslated() {
   return request.getPathTranslated();
 }
예제 #6
0
파일: ToNcServlet.java 프로젝트: xxs/lpf
  public void doPost(HttpServletRequest request, HttpServletResponse response)
      throws IOException, ServletException {
    String qryDoc;
    String username;
    username = "";
    PrintWriter out = response.getWriter();
    request.setCharacterEncoding("GBK");
    try {
      request.getSession().setMaxInactiveInterval(60000);
      username =
          request.getSession().getAttribute("USERNAME") != null
              ? request.getSession().getAttribute("USERNAME").toString()
              : "";
    }
    // Misplaced declaration of an exception variable
    catch (Exception e) {
      e.printStackTrace();
    }
    if (request.getPathInfo() == null)
      qryDoc = getServletConfig().getServletContext().getRealPath(request.getServletPath());
    else qryDoc = request.getPathTranslated();
    try {
      WebApp app = new WebApp(FunctionLib.openFile(qryDoc));
      String path = getServletContext().getRealPath("/");
      VelocityEngine ve = new VelocityEngine();
      ve.setProperty(Velocity.FILE_RESOURCE_LOADER_PATH, path);
      VelocityContext context = new VelocityContext();

      BufferedOutputStream outb = null;
      InputStream in = null;
      String msg = null;

      ve.init();

      ToNcEngine mainMod = new ToNcEngine(request, response, app, context, getServletConfig());
      // 处理用户请求
      Vector vsqls = app.getSqls();
      if (app.getSqlType().equals("select")) {
        List ldata = null;
        for (int i = 0; i < vsqls.size(); i++) {
          ldata = new ArrayList();
          ldata = mainMod.getData(vsqls.elementAt(i).toString(), app.getEscape());
          context.put(vsqls.elementAt(i).toString(), ldata);
        }
        context.put("CGI_url", request.getRequestURL().toString());
      }
      Template t = ve.getTemplate(app.getTemplate());
      StringWriter sw = new StringWriter();
      t.merge(context, sw);
      System.out.println("aaaaaaaa" + sw.toString());
      // String url = "http://10.7.3.225:8080/service/XchangeServlet";
      URL realURL = new URL(server);
      HttpURLConnection connection = (HttpURLConnection) realURL.openConnection();
      connection.setDoOutput(true);
      connection.setRequestProperty("Content-type", "text/xml");
      connection.setRequestMethod("POST");
      outb = new BufferedOutputStream(connection.getOutputStream());
      outb.write(sw.toString().getBytes());
      outb.close();
      in = new DataInputStream(connection.getInputStream());
      byte[] b = new byte[in.available()];
      in.read(b);
      msg = new String(b, "UTF-8");
      // System.out.println("返回信息:"+msg);
      Document resDoc = DocumentHelper.parseText(msg);

      List resCode_list = resDoc.selectNodes("ufinterface/sendresult/resultcode");
      List resDes_list = resDoc.selectNodes("ufinterface/sendresult/resultdescription");
      // 从回执信息中获得错误信息详细描述
      String invaliddoc_value = null;
      returnMsg.clear();
      for (Object obj : resDes_list) {
        Element invaliddoc = (Element) obj;
        invaliddoc_value = invaliddoc.getText();
        System.out.println("返回信息:" + invaliddoc_value);
        // 将回执信息赋值给静态变量returnMsg
        returnMsg.add(invaliddoc_value);
      }
      // 从回执信息中获取错误信息编号
      List<String> resCodeList = new ArrayList<String>();
      for (Object obj : resCode_list) {
        Element resCode = (Element) obj;
        String resCode_value = resCode.getText();
        // System.out.println("失败信息:"+resCode_value);
        // 只有resCode编号为1时才是正常处理完毕,没有错误
        if (!resCode_value.equals("1")) {
          resCodeList.add(resCode_value);
        }
      }
      if (resCodeList.size() == 0) {
        if (app.getUrl().equals("qbTonc")) {
          out.println("OK");
          out.close();
        } else {
          if (!app.getSuccessMsg().equals("")) invaliddoc_value = app.getSuccessMsg();
          out.println("<html>\n");
          out.println("<head>\n");
          out.println(
              "<script type=\"text/javascript\" language=\"JavaScript\" src=\"../js/title.js\"></script>\n");
          out.println("<meta http-equiv=\"Content-Type\" content=\"text/html; charset=gb2312\">\n");
          out.println("<script>");
          out.println(FunctionLib.gbToIso("alert('" + invaliddoc_value + "')"));
          out.println("window.location='" + app.getUrl() + "'");
          out.println("</script>");
          out.println("</head>\n");
          out.println("  </html>\n");
          out.close();
        }
      } else {
        if (!app.getFailMsg().equals("")) invaliddoc_value = app.getFailMsg();
        out.println("<html>\n");
        out.println("<head>\n");
        out.println(
            "<script type=\"text/javascript\" language=\"JavaScript\" src=\"../js/title.js\"></script>\n");
        out.println("<meta http-equiv=\"Content-Type\" content=\"text/html; charset=gb2312\">\n");
        out.println("<script>");
        out.println(FunctionLib.gbToIso("alert('" + invaliddoc_value + "')"));
        out.println("window.history.go(-1);");
        out.println("</script>");
        out.println("</head>\n");
        out.println("  </html>\n");
        out.close();
      }
    } catch (Exception e) {
      System.out.println(e.getMessage());
      e.printStackTrace();
      out.println("<html>\n");
      out.println("<head>\n");
      out.println(
          "<script type=\"text/javascript\" language=\"JavaScript\" src=\"../js/title.js\"></script>\n");
      out.println("<meta http-equiv=\"Content-Type\" content=\"text/html; charset=gb2312\">\n");
      out.println("<script>");
      out.println(FunctionLib.gbToIso("alert('提取数据时出错!')"));
      out.println("</script>");
      out.println("</head>\n");
      out.println("  </html>\n");
      out.close();
    }
  }
  /**
   * Constructs the CGI environment to be supplied to the invoked CGI script; relies heavliy on
   * Servlet API methods and findCGI
   *
   * @param HttpServletRequest request associated with the CGI invokation
   * @return true if environment was set OK, false if there was a problem and no environment was set
   */
  protected boolean deriveProcessEnvironment(HttpServletRequest req) {
    /*
     * This method is slightly ugly; c'est la vie.
     * "You cannot stop [ugliness], you can only hope to contain [it]"
     * (apologies to Marv Albert regarding MJ)
     */

    Hashtable envp;
    super.deriveProcessEnvironment(req);
    envp = getEnvironment();

    String sPathInfoOrig = null;
    String sPathTranslatedOrig = null;
    String sPathInfoCGI = null;
    String sPathTranslatedCGI = null;
    String sCGIFullPath = null;
    String sCGIScriptName = null;
    String sCGIFullName = null;
    String sCGIName = null;
    String[] sCGINames;
    sPathInfoOrig = this.pathInfo;
    sPathInfoOrig = sPathInfoOrig == null ? "" : sPathInfoOrig;
    sPathTranslatedOrig = req.getPathTranslated();
    sPathTranslatedOrig = sPathTranslatedOrig == null ? "" : sPathTranslatedOrig;
    sCGINames =
        findCGI(
            sPathInfoOrig, getWebAppRootDir(), getContextPath(), getServletPath(), cgiPathPrefix);
    sCGIFullPath = sCGINames[0];
    sCGIScriptName = sCGINames[1];
    sCGIFullName = sCGINames[2];
    sCGIName = sCGINames[3];
    if (sCGIFullPath == null
        || sCGIScriptName == null
        || sCGIFullName == null
        || sCGIName == null) {
      return false;
    }
    envp.put("SERVER_SOFTWARE", "TOMCAT");
    envp.put("SERVER_NAME", nullsToBlanks(req.getServerName()));
    envp.put("GATEWAY_INTERFACE", "CGI/1.1");
    envp.put("SERVER_PROTOCOL", nullsToBlanks(req.getProtocol()));
    int port = req.getServerPort();
    Integer iPort = (port == 0 ? new Integer(-1) : new Integer(port));
    envp.put("SERVER_PORT", iPort.toString());
    envp.put("REQUEST_METHOD", nullsToBlanks(req.getMethod()));

    /*-
     * PATH_INFO should be determined by using sCGIFullName:
     * 1) Let sCGIFullName not end in a "/" (see method findCGI)
     * 2) Let sCGIFullName equal the pathInfo fragment which
     *    corresponds to the actual cgi script.
     * 3) Thus, PATH_INFO = request.getPathInfo().substring(
     *                      sCGIFullName.length())
     *
     * (see method findCGI, where the real work is done)
     *
     */

    if (pathInfo == null || (pathInfo.substring(sCGIFullName.length()).length() <= 0)) {
      sPathInfoCGI = "";
    } else {
      sPathInfoCGI = pathInfo.substring(sCGIFullName.length());
    }
    envp.put("PATH_INFO", sPathInfoCGI);

    /*-
     * PATH_TRANSLATED must be determined after PATH_INFO (and the
     * implied real cgi-script) has been taken into account.
     *
     * The following example demonstrates:
     *
     * servlet info   = /servlet/cgigw/dir1/dir2/cgi1/trans1/trans2
     * cgifullpath    = /servlet/cgigw/dir1/dir2/cgi1
     * path_info      = /trans1/trans2
     * webAppRootDir  = servletContext.getRealPath("/")
     *
     * path_translated = servletContext.getRealPath("/trans1/trans2")
     *
     * That is, PATH_TRANSLATED = webAppRootDir + sPathInfoCGI
     * (unless sPathInfoCGI is null or blank, then the CGI
     * specification dictates that the PATH_TRANSLATED metavariable
     * SHOULD NOT be defined.
     *
     */

    if (sPathInfoCGI != null && !("".equals(sPathInfoCGI))) {
      sPathTranslatedCGI = getContext().getRealPath(sPathInfoCGI);
    } else {
      sPathTranslatedCGI = null;
    }
    if (sPathTranslatedCGI == null || "".equals(sPathTranslatedCGI)) {
      // NOOP
    } else {
      envp.put("PATH_TRANSLATED", nullsToBlanks(sPathTranslatedCGI));
    }
    envp.put("SCRIPT_NAME", nullsToBlanks(sCGIScriptName));
    envp.put("QUERY_STRING", nullsToBlanks(req.getQueryString()));
    envp.put("REMOTE_HOST", nullsToBlanks(req.getRemoteHost()));
    envp.put("REMOTE_ADDR", nullsToBlanks(req.getRemoteAddr()));
    envp.put("AUTH_TYPE", nullsToBlanks(req.getAuthType()));
    envp.put("REMOTE_USER", nullsToBlanks(req.getRemoteUser()));
    envp.put("REMOTE_IDENT", ""); // not necessary for full compliance
    envp.put("CONTENT_TYPE", nullsToBlanks(req.getContentType()));

    /* Note CGI spec says CONTENT_LENGTH must be NULL ("") or undefined
     * if there is no content, so we cannot put 0 or -1 in as per the
     * Servlet API spec.
     */

    int contentLength = req.getContentLength();
    String sContentLength = (contentLength <= 0 ? "" : (new Integer(contentLength)).toString());
    envp.put("CONTENT_LENGTH", sContentLength);
    Enumeration headers = req.getHeaderNames();
    String header = null;
    while (headers.hasMoreElements()) {
      header = null;
      header = ((String) headers.nextElement()).toUpperCase();
      // REMIND: rewrite multiple headers as if received as single
      // REMIND: change character set
      // REMIND: I forgot what the previous REMIND means
      if ("AUTHORIZATION".equalsIgnoreCase(header)
          || "PROXY_AUTHORIZATION".equalsIgnoreCase(header)) {
        // NOOP per CGI specification section 11.2
      } else if ("HOST".equalsIgnoreCase(header)) {
        String host = req.getHeader(header);
        envp.put("HTTP_" + header.replace('-', '_'), host.substring(0, host.indexOf(":")));
      } else {
        envp.put("HTTP_" + header.replace('-', '_'), req.getHeader(header));
      }
    }
    command = sCGIFullPath;
    workingDirectory = new File(command.substring(0, command.lastIndexOf(File.separator)));
    envp.put("X_TOMCAT_COMMAND_PATH", command); // for kicks
    this.setEnvironment(envp);
    return true;
  }
예제 #8
0
  /*
   * @param root
   * @param path
   * @param req
   * @param res
   * @exception IOException
   */
  private void exec(File command, String pathInfo, HttpServletRequest req, HttpServletResponse res)
      throws IOException {
    String path = command.toString();
    File dir = command.getParentFile();
    if (log.isDebugEnabled()) log.debug("CGI: execing: " + path);

    EnvList env = new EnvList(_env);

    // these ones are from "The WWW Common Gateway Interface Version 1.1"
    // look at : http://Web.Golux.Com/coar/cgi/draft-coar-cgi-v11-03-clean.html#6.1.1
    env.set("AUTH_TYPE", req.getAuthType());
    env.set("CONTENT_LENGTH", Integer.toString(req.getContentLength()));
    env.set("CONTENT_TYPE", req.getContentType());
    env.set("GATEWAY_INTERFACE", "CGI/1.1");
    env.set("PATH_INFO", pathInfo);
    env.set("PATH_TRANSLATED", req.getPathTranslated());
    env.set("QUERY_STRING", req.getQueryString());
    env.set("REMOTE_ADDR", req.getRemoteAddr());
    env.set("REMOTE_HOST", req.getRemoteHost());
    // The identity information reported about the connection by a
    // RFC 1413 [11] request to the remote agent, if
    // available. Servers MAY choose not to support this feature, or
    // not to request the data for efficiency reasons.
    // "REMOTE_IDENT" => "NYI"
    env.set("REMOTE_USER", req.getRemoteUser());
    env.set("REQUEST_METHOD", req.getMethod());
    String scriptName =
        req.getRequestURI().substring(0, req.getRequestURI().length() - pathInfo.length());
    env.set("SCRIPT_NAME", scriptName);
    env.set("SCRIPT_FILENAME", getServletContext().getRealPath(scriptName));
    env.set("SERVER_NAME", req.getServerName());
    env.set("SERVER_PORT", Integer.toString(req.getServerPort()));
    env.set("SERVER_PROTOCOL", req.getProtocol());
    env.set("SERVER_SOFTWARE", getServletContext().getServerInfo());
    Enumeration enm = req.getHeaderNames();
    while (enm.hasMoreElements()) {
      String name = (String) enm.nextElement();
      String value = req.getHeader(name);
      env.set("HTTP_" + name.toUpperCase().replace('-', '_'), value);
    }

    // these extra ones were from printenv on www.dev.nomura.co.uk
    env.set("HTTPS", (req.isSecure() ? "ON" : "OFF"));
    // "DOCUMENT_ROOT" => root + "/docs",
    // "SERVER_URL" => "NYI - http://us0245",
    // "TZ" => System.getProperty("user.timezone"),

    // are we meant to decode args here ? or does the script get them
    // via PATH_INFO ?  if we are, they should be decoded and passed
    // into exec here...

    String execCmd = path;
    if (execCmd.indexOf(" ") >= 0) execCmd = "\"" + execCmd + "\"";
    if (_cmdPrefix != null) execCmd = _cmdPrefix + " " + execCmd;

    Process p =
        dir == null
            ? Runtime.getRuntime().exec(execCmd, env.getEnvArray())
            : Runtime.getRuntime().exec(execCmd, env.getEnvArray(), dir);

    // hook processes input to browser's output (async)
    final InputStream inFromReq = req.getInputStream();
    final OutputStream outToCgi = p.getOutputStream();
    final int inputLength = req.getContentLength();

    new Thread(
            new Runnable() {
              public void run() {
                try {
                  if (inputLength > 0) IO.copy(inFromReq, outToCgi, inputLength);
                  outToCgi.close();
                } catch (IOException e) {
                  LogSupport.ignore(log, e);
                }
              }
            })
        .start();

    // hook processes output to browser's input (sync)
    // if browser closes stream, we should detect it and kill process...
    try {
      // read any headers off the top of our input stream
      LineInput li = new LineInput(p.getInputStream());
      HttpFields fields = new HttpFields();
      fields.read(li);

      String ContentStatus = "Status";
      String redirect = fields.get(HttpFields.__Location);
      String status = fields.get(ContentStatus);

      if (status != null) {
        log.debug("Found a Status header - setting status on response");
        fields.remove(ContentStatus);

        // NOTE: we ignore any reason phrase, otherwise we
        // would need to use res.sendError() selectively.
        int i = status.indexOf(' ');
        if (i > 0) status = status.substring(0, i);

        res.setStatus(Integer.parseInt(status));
      }

      // copy remaining headers into response...
      for (Iterator i = fields.iterator(); i.hasNext(); ) {
        HttpFields.Entry e = (HttpFields.Entry) i.next();
        res.addHeader(e.getKey(), e.getValue());
      }

      if (status == null && redirect != null) {
        // The CGI has set Location and is counting on us to do the redirect.
        // See http://CGI-Spec.Golux.Com/draft-coar-cgi-v11-03-clean.html#7.2.1.2
        if (!redirect.startsWith("http:/") && !redirect.startsWith("https:/"))
          res.sendRedirect(redirect);
        else res.setStatus(HttpServletResponse.SC_MOVED_TEMPORARILY);
      }

      // copy remains of input onto output...
      IO.copy(li, res.getOutputStream());

      p.waitFor();
      int exitValue = p.exitValue();
      if (log.isDebugEnabled()) log.debug("CGI: p.exitValue(): " + exitValue);
      if (0 != exitValue) {
        log.warn("Non-zero exit status (" + exitValue + ") from CGI program: " + path);
        if (!res.isCommitted()) res.sendError(500, "Failed to exec CGI");
      }
    } catch (IOException e) {
      // browser has probably closed its input stream - we
      // terminate and clean up...
      log.debug("CGI: Client closed connection!");
    } catch (InterruptedException ie) {
      log.debug("CGI: interrupted!");
    } finally {
      p.destroy();
    }

    if (log.isDebugEnabled()) log.debug("CGI: Finished exec: " + p);
  }
예제 #9
0
  /**
   * Show details about the request
   *
   * @param servlet used to get teh servlet context, may be null
   * @param req the request
   * @return string showing the details of the request.
   */
  public static String showRequestDetail(HttpServlet servlet, HttpServletRequest req) {
    StringBuilder sbuff = new StringBuilder();

    sbuff.append("Request Info\n");
    sbuff.append(" req.getServerName(): ").append(req.getServerName()).append("\n");
    sbuff.append(" req.getServerPort(): ").append(req.getServerPort()).append("\n");
    sbuff.append(" req.getContextPath:").append(req.getContextPath()).append("\n");
    sbuff.append(" req.getServletPath:").append(req.getServletPath()).append("\n");
    sbuff.append(" req.getPathInfo:").append(req.getPathInfo()).append("\n");
    sbuff.append(" req.getQueryString:").append(req.getQueryString()).append("\n");
    sbuff
        .append(" getQueryStringDecoded:")
        .append(EscapeStrings.urlDecode(req.getQueryString()))
        .append("\n");
    /*try {
      sbuff.append(" getQueryStringDecoded:").append(URLDecoder.decode(req.getQueryString(), "UTF-8")).append("\n");
    } catch (UnsupportedEncodingException e1) {
      e1.printStackTrace();
    }*/
    sbuff.append(" req.getRequestURI:").append(req.getRequestURI()).append("\n");
    sbuff.append(" getRequestBase:").append(getRequestBase(req)).append("\n");
    sbuff.append(" getRequestServer:").append(getRequestServer(req)).append("\n");
    sbuff.append(" getRequest:").append(getRequest(req)).append("\n");
    sbuff.append("\n");

    sbuff.append(" req.getPathTranslated:").append(req.getPathTranslated()).append("\n");
    String path = req.getPathTranslated();
    if ((path != null) && (servlet != null)) {
      ServletContext context = servlet.getServletContext();
      sbuff.append(" getMimeType:").append(context.getMimeType(path)).append("\n");
    }
    sbuff.append("\n");
    sbuff.append(" req.getScheme:").append(req.getScheme()).append("\n");
    sbuff.append(" req.getProtocol:").append(req.getProtocol()).append("\n");
    sbuff.append(" req.getMethod:").append(req.getMethod()).append("\n");
    sbuff.append("\n");
    sbuff.append(" req.getContentType:").append(req.getContentType()).append("\n");
    sbuff.append(" req.getContentLength:").append(req.getContentLength()).append("\n");

    sbuff.append(" req.getRemoteAddr():").append(req.getRemoteAddr());
    try {
      sbuff
          .append(" getRemoteHost():")
          .append(java.net.InetAddress.getByName(req.getRemoteHost()).getHostName())
          .append("\n");
    } catch (java.net.UnknownHostException e) {
      sbuff.append(" getRemoteHost():").append(e.getMessage()).append("\n");
    }
    sbuff.append(" getRemoteUser():").append(req.getRemoteUser()).append("\n");

    sbuff.append("\n");
    sbuff.append("Request Parameters:\n");
    Enumeration params = req.getParameterNames();
    while (params.hasMoreElements()) {
      String name = (String) params.nextElement();
      String values[] = req.getParameterValues(name);
      if (values != null) {
        for (int i = 0; i < values.length; i++) {
          sbuff
              .append("  ")
              .append(name)
              .append("  (")
              .append(i)
              .append("): ")
              .append(values[i])
              .append("\n");
        }
      }
    }
    sbuff.append("\n");

    sbuff.append("Request Headers:\n");
    Enumeration names = req.getHeaderNames();
    while (names.hasMoreElements()) {
      String name = (String) names.nextElement();
      Enumeration values = req.getHeaders(name); // support multiple values
      if (values != null) {
        while (values.hasMoreElements()) {
          String value = (String) values.nextElement();
          sbuff.append("  ").append(name).append(": ").append(value).append("\n");
        }
      }
    }
    sbuff.append(" ------------------\n");

    return sbuff.toString();
  }
예제 #10
0
  public TaskHttpServletRequest(HttpServletRequest wrapping, Task task) {
    this.session = wrapping.getSession();
    String location = wrapping.getParameter("url");

    cookies = wrapping.getCookies();
    characterEncoding = wrapping.getCharacterEncoding();
    authType = wrapping.getAuthType();
    headerNames = new Vector<String>();
    headers = new MultiMap();
    for (Enumeration e = wrapping.getHeaderNames(); e.hasMoreElements(); ) {
      String headerName = (String) e.nextElement();
      for (Enumeration f = wrapping.getHeaders(headerName); f.hasMoreElements(); ) {
        String headerValue = (String) f.nextElement();
        headers.add(headerName, headerValue);
      }
    }
    contextPath = wrapping.getContextPath();
    pathInfo = wrapping.getPathInfo();
    pathTranslated = wrapping.getPathTranslated();
    remoteUser = wrapping.getRemoteUser(); // TODO check if needed
    requestedSessionId = wrapping.getRequestedSessionId(); // TODO check if needed
    userPrincipal = wrapping.getUserPrincipal(); // TODO check if needed
    requestedSessionIdFromCookie = wrapping.isRequestedSessionIdFromCookie();
    requestedSessionIdFromURL = wrapping.isRequestedSessionIdFromURL();
    requestedSessionIdValid = wrapping.isRequestedSessionIdValid();
    localAddr = wrapping.getLocalAddr();
    localName = wrapping.getLocalName();
    localPort = wrapping.getLocalPort();
    locale = wrapping.getLocale();
    locales = new Vector<Locale>();
    for (Enumeration e = wrapping.getLocales();
        e.hasMoreElements();
        locales.add((Locale) e.nextElement())) ;
    protocol = wrapping.getProtocol();
    remoteAddr = wrapping.getRemoteAddr();
    remoteHost = wrapping.getRemoteHost();
    remotePort = wrapping.getRemotePort();
    scheme = wrapping.getScheme();
    serverName = wrapping.getServerName();
    serverPort = wrapping.getServerPort();
    secure = wrapping.isSecure();

    // Extract the query (everything after ?)
    int idx = location.indexOf('?');
    query = null;
    if (idx != -1) {
      query = location.substring(idx + 1);
    }

    // Extract the URI (everything before ?)
    uri = location;
    if (idx != -1) {
      uri = uri.substring(0, idx);
    }

    // Servlet path (same as URI?)
    servletPath = uri;

    // Extract parameters
    params = new Hashtable<String, String[]>();
    if (query != null) {
      StringTokenizer t = new StringTokenizer(query, "&");
      while (t.hasMoreTokens()) {
        String token = t.nextToken();
        idx = token.indexOf('=');
        String name = token;
        String val = null;
        if (idx != -1) {
          name = token.substring(0, idx);
          val = token.substring(idx + 1);
        } else {
          val = "";
        }
        String[] vals = params.get(name);
        if (vals == null) {
          vals = new String[] {val};
        } else {
          String[] nvals = new String[vals.length + 1];
          System.arraycopy(vals, 0, nvals, 0, vals.length);
          nvals[vals.length] = val;
          vals = nvals;
        }
        params.put(name, vals);
      }
    }

    // Initialise attributes
    attributes = new Hashtable<String, Object>();

    // Create the URL (the URL with protocol / host / post)
    try {
      URL u = new URL(new URL(wrapping.getRequestURL().toString()), uri);
      url = new StringBuffer(u.toExternalForm());
    } catch (MalformedURLException e) {
    }

    setAttribute(ATTR_TASK, task);
  }
  protected void doGet(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    response.setContentType("text/html");
    response.setCharacterEncoding("UTF-8");
    PrintWriter writer = response.getWriter();
    String message = "Bilinmeyen Bir Browser Kullanýyorsunuz.";

    if (request.getHeader("User-Agent").indexOf("Firefox") != -1)
      message = "Siz Firefox Kullanýcýsýnýz";
    if (request.getHeader("User-Agent").indexOf("MSIE") != -1)
      message = "Siz Microsoft Internet Explorer Kullanýcýsýnýz";
    if (request.getHeader("User-Agent").indexOf("Chrome") != -1)
      message = "Siz Google Chrome Kullanýcýsýnýz";

    writer.println(
        "<!DOCTYPE html 4.0>"
            + "<html>"
            + "<head><title>requestHeadaer</title></head>"
            + "<body bgcolor = \"pink\" style=\"text-align = center;\">"
            + message
            + "<form>"
            + "<table border=2>"
            + "<tr>"
            + "<td>"
            + "<b>RequestCharacterEncoding : </b>"
            + request.getCharacterEncoding()
            + " ---- <b>RequestContentLength : </b>"
            + request.getContentLength()
            + "<p><b>RequestContentType : </b>"
            + request.getContentType()
            + " ---- <b>RequestContextPath : </b>"
            + request.getContextPath()
            + "<p><b>RequestLocalAddress : </b>"
            + request.getLocalAddr()
            + " ---- <b>RequestLocalName : </b>"
            + request.getLocalName()
            + "<p><b>RequestLocalPort : </b>"
            + request.getLocalPort()
            + " ---- <b>RequestMethod : </b>"
            + request.getMethod()
            + "<p><b>RequestPathInfo : </b>"
            + request.getPathInfo()
            + " ---- <b>RequestPathTranslated : </b>"
            + request.getPathTranslated()
            + "<p><b>RequestProtocol : </b>"
            + request.getProtocol()
            + " ---- <b>RequestQueryString : </b>"
            + request.getQueryString()
            + "<p><b>RequestSessionID : </b>"
            + request.getRequestedSessionId()
            + " ---- <b>RequestServerName : </b>"
            + request.getServerName()
            + "<p><b>RequestServerPort : </b>"
            + request.getServerPort()
            + " ---- <b>RequestPath : </b>"
            + request.getServletPath()
            + "<p><b>RequestURL : </b>"
            + request.getRequestURL()
            + " ---- <b>RequestSession : </b>"
            + request.getSession()
            + "<td>"
            + "<table border = 2>");
    Enumeration<String> headerNames = request.getHeaderNames();
    while (headerNames.hasMoreElements()) {
      String headerName = headerNames.nextElement();
      String headerValues = request.getHeader(headerName);
      writer.println("<tr><th>" + headerName + "<td><i>" + headerValues + "</i></tr>");
    }
    writer.println("</table></td></tr></table></body></html>");
  }