예제 #1
0
  @Override
  public void doFilter(
      ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain)
      throws IOException, ServletException {
    HttpServletRequest httpRequest = (HttpServletRequest) servletRequest;
    HttpServletResponse httpResponse = (HttpServletResponse) servletResponse;

    // Skip oauth for local connections
    if (!"127.0.0.1".equals(servletRequest.getRemoteAddr())) {
      // Read the OAuth parameters from the request
      OAuthServletRequest request = new OAuthServletRequest(httpRequest);
      OAuthParameters params = new OAuthParameters();
      params.readRequest(request);

      String consumerKey = params.getConsumerKey();

      // Set the secret(s), against which we will verify the request
      OAuthSecrets secrets = new OAuthSecrets();
      secrets.setConsumerSecret(m_tokenStore.getToken(consumerKey));

      // Check that the timestamp has not expired
      String timestampStr = params.getTimestamp();
      if (timestampStr == null) {
        logger.warn("Missing OAuth headers");
        httpResponse.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Missing OAuth headers");
        return;
      }

      long msgTime = Util.parseLong(timestampStr) * 1000L; // Message time is in seconds
      long currentTime = System.currentTimeMillis();

      // if the message is older than 5 min it is no good
      if (Math.abs(msgTime - currentTime) > 300000) {
        logger.warn(
            "OAuth message time out, msg time: " + msgTime + " current time: " + currentTime);
        httpResponse.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Message expired");
        return;
      }

      // Verify the signature
      try {
        if (!OAuthSignature.verify(request, params, secrets)) {
          logger.warn("Invalid OAuth signature");

          httpResponse.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Invalid OAuth signature");
          return;
        }
      } catch (OAuthSignatureException e) {
        logger.warn("OAuth exception", e);

        httpResponse.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Invalid OAuth request");
        return;
      }
    }

    filterChain.doFilter(servletRequest, servletResponse);
  }
예제 #2
0
  @Override
  public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
      throws IOException, ServletException {
    String longAddr = null, shortAddr, s, transactionKey = null;
    int count;
    boolean ignorable = false;

    synchronized (simultaneousRequestsByShortIPAddr) {
      if (totalSimultaneousRequests >= maxTotalSimultaneousRequests) {
        log.error(
            "This system has exceeded the maxTotalSimultaneousRequests limit of "
                + maxTotalSimultaneousRequests);
        log.error(simultaneousRequestsByShortIPAddr);
        for (String str : simultaneousRequests) log.error(str);
        ((HttpServletResponse) response).setStatus(HttpURLConnection.HTTP_UNAVAILABLE);
        response.setContentType("text/html");
        PrintWriter writer = response.getWriter();
        writer.println("<html><body><h1>Service Temporarily Unavailable</h1>");
        writer.println(
            "The system is experiencing a severe load and is temporarily unable to accept new requests");
        if (contactInfo != null)
          writer.println("<p>Contact " + contactInfo + " for more information</p>");
        writer.println("</body></html>");
        writer.close();
        return;
      }
      if (addressInHeader != null) {
        @SuppressWarnings("unchecked")
        Enumeration<String> addrs = ((HttpServletRequest) request).getHeaders(addressInHeader);
        while (addrs.hasMoreElements()) {
          longAddr = addrs.nextElement();
          if (longAddr == null) {
            if (++addressInHeaderErrorCount < 10)
              log.error("Expected a " + addressInHeader + " header but got null");
            continue;
          }
          if (longAddr.lastIndexOf('.') >= 0) break;
        }
      }
      if (longAddr == null) longAddr = request.getRemoteAddr();
      int i = longAddr.lastIndexOf('.');
      if (i < 0) {
        log.error("bogus IP address: '" + longAddr + "'");
        longAddr = "0.0.0.0";
      }
      shortAddr = longAddr.substring(0, i); // trim off 4th number group
      // that lets us spot requests from clusters
      s = equivalentAddresses.get(shortAddr); // map one short addr to another?
      if (s != null) shortAddr = s;
      if (ignorableAddresses.contains(shortAddr)) {
        ignorable = true;
      } else {
        Integer icount = simultaneousRequestsByShortIPAddr.get(shortAddr);
        if (icount != null) count = icount;
        else count = 0;

        int maxSimultaneousRequests =
            (maxTotalSimultaneousRequests - totalSimultaneousRequests) / 4;
        if (maxSimultaneousRequests == 0) maxSimultaneousRequests = 1;
        if (count >= maxSimultaneousRequests) {
          log.error(
              "IP addr "
                  + shortAddr
                  + ".* has exceeded "
                  + maxSimultaneousRequests
                  + " simultaneous requests!");
          log.error("maxTotalSimultaneousRequests=" + maxTotalSimultaneousRequests);
          log.error("totalSimultaneousRequests=" + totalSimultaneousRequests);
          for (String str : simultaneousRequests) log.error(str);
          //
          // ((HttpServletResponse)response).setStatus(HttpURLConnection.HTTP_TOO_MANY_REQUESTS); //
          // someday
          ((HttpServletResponse) response).setStatus(429); // too many requests
          response.setContentType("text/html");
          PrintWriter writer = response.getWriter();
          writer.println(
              "<html><head><title>Too Many Requests</title></head><body><h1>Too Many Requests</h1>");
          writer.println(
              "You have exceeded the maximum simultaneous request value of "
                  + maxSimultaneousRequests);
          writer.println("<p>This message and your IP address have been logged and reported</p>");
          if (contactInfo != null)
            writer.println("<p>Contact " + contactInfo + " for more information</p>");
          writer.println("</body></html>");
          writer.close();
          return;
        }
        simultaneousRequestsByShortIPAddr.put(shortAddr, count + 1);
        icount = totalRequests.get(shortAddr);
        if (icount != null) count = icount;
        else count = 0;
        totalRequests.put(shortAddr, count + 1);
        totalSimultaneousRequests++;
        transactionKey =
            new StringBuilder((new Date(System.currentTimeMillis())).toString())
                .append('|')
                .append(shortAddr)
                .append('|')
                .append(((HttpServletRequest) request).getQueryString())
                .toString();
        simultaneousRequests.add(transactionKey);
      }
    }

    try {
      HttpServletResponseWrapper wrapper =
          new HttpServletResponseWrapper((HttpServletResponse) response);
      chain.doFilter(request, wrapper);
    } finally {
      if (!ignorable)
        synchronized (simultaneousRequestsByShortIPAddr) {
          totalSimultaneousRequests--;
          simultaneousRequests.remove(transactionKey);
          count = simultaneousRequestsByShortIPAddr.get(shortAddr);
          if (count == 1) // prune them from the table
          simultaneousRequestsByShortIPAddr.remove(shortAddr);
          else simultaneousRequestsByShortIPAddr.put(shortAddr, count - 1);
        }
    }

    Calendar c = new GregorianCalendar();
    int hour = c.get(Calendar.HOUR_OF_DAY);
    if (hour == 0 && nextReportingHour == 24) { // new day!
      // you could reset your daily limits table here
      nextReportingHour = 0;
    }

    if (hour >= nextReportingHour) { // generate the hourly report
      // you could reset your hourly limits table here
      nextReportingHour = hour + 1;

      if (log.isInfoEnabled()) {
        HashMap<String, Integer> map = new LinkedHashMap<String, Integer>();
        List<String> yourMapKeys = new ArrayList<String>(totalRequests.keySet());
        List<Integer> yourMapValues = new ArrayList<Integer>(totalRequests.values());
        TreeSet<Integer> sortedSet = new TreeSet<Integer>(yourMapValues);
        Integer[] sortedArray = sortedSet.descendingSet().toArray(new Integer[0]);
        int size = sortedArray.length;

        for (int i = 0; i < size; i++)
          map.put(yourMapKeys.get(yourMapValues.indexOf(sortedArray[i])), sortedArray[i]);
        Iterator<String> it = map.keySet().iterator();
        String key;
        StringBuilder sb = new StringBuilder("Top 10 users in the last hour");
        for (int i = 0; i < 10 && it.hasNext(); i++) {
          key = it.next();
          sb.append("\n    ").append(key).append(" : ").append(map.get(key));
        }
        log.info(sb);
      }
      totalRequests.clear();
    }
  }
  /**
   * Creates REST request.
   *
   * @param cmd Command.
   * @param params Parameters.
   * @return REST request.
   * @throws GridException If creation failed.
   */
  @Nullable
  private GridRestRequest createRequest(
      GridRestCommand cmd, Map<String, Object> params, ServletRequest req) throws GridException {
    GridRestRequest restReq;

    switch (cmd) {
      case CACHE_GET:
      case CACHE_GET_ALL:
      case CACHE_PUT:
      case CACHE_PUT_ALL:
      case CACHE_REMOVE:
      case CACHE_REMOVE_ALL:
      case CACHE_ADD:
      case CACHE_CAS:
      case CACHE_METRICS:
      case CACHE_REPLACE:
      case CACHE_DECREMENT:
      case CACHE_INCREMENT:
      case CACHE_APPEND:
      case CACHE_PREPEND:
        {
          GridRestCacheRequest restReq0 = new GridRestCacheRequest();

          restReq0.cacheName((String) params.get("cacheName"));
          restReq0.key(params.get("key"));
          restReq0.value(params.get("val"));
          restReq0.value2(params.get("val2"));

          Object val1 = params.get("val1");

          if (val1 != null) restReq0.value(val1);

          restReq0.cacheFlags(intValue("cacheFlags", params, 0));
          restReq0.ttl(longValue("exp", params, null));
          restReq0.initial(longValue("init", params, null));
          restReq0.delta(longValue("delta", params, null));

          if (cmd == CACHE_GET_ALL || cmd == CACHE_PUT_ALL || cmd == CACHE_REMOVE_ALL) {
            List<Object> keys = values("k", params);
            List<Object> vals = values("v", params);

            if (keys.size() < vals.size())
              throw new GridException(
                  "Number of keys must be greater or equals to number of values.");

            Map<Object, Object> map = U.newHashMap(keys.size());

            Iterator<Object> keyIt = keys.iterator();
            Iterator<Object> valIt = vals.iterator();

            while (keyIt.hasNext()) map.put(keyIt.next(), valIt.hasNext() ? valIt.next() : null);

            restReq0.values(map);
          }

          restReq = restReq0;

          break;
        }

      case TOPOLOGY:
      case NODE:
        {
          GridRestTopologyRequest restReq0 = new GridRestTopologyRequest();

          restReq0.includeMetrics(Boolean.parseBoolean((String) params.get("mtr")));
          restReq0.includeAttributes(Boolean.parseBoolean((String) params.get("attr")));

          restReq0.nodeIp((String) params.get("ip"));

          restReq0.nodeId(uuidValue("id", params));

          restReq = restReq0;

          break;
        }

      case EXE:
      case RESULT:
      case NOOP:
        {
          GridRestTaskRequest restReq0 = new GridRestTaskRequest();

          restReq0.taskId((String) params.get("id"));
          restReq0.taskName((String) params.get("name"));

          restReq0.params(values("p", params));

          restReq0.async(Boolean.parseBoolean((String) params.get("async")));

          restReq0.timeout(longValue("timeout", params, 0L));

          restReq = restReq0;

          break;
        }

      case LOG:
        {
          GridRestLogRequest restReq0 = new GridRestLogRequest();

          restReq0.path((String) params.get("path"));

          restReq0.from(intValue("from", params, -1));
          restReq0.to(intValue("to", params, -1));

          restReq = restReq0;

          break;
        }

      case VERSION:
        {
          restReq = new GridRestRequest();

          break;
        }

      default:
        throw new GridException("Invalid command: " + cmd);
    }

    restReq.address(new InetSocketAddress(req.getRemoteAddr(), req.getRemotePort()));

    restReq.command(cmd);

    if (params.containsKey("gridgain.login") || params.containsKey("gridgain.password")) {
      GridSecurityCredentials cred =
          new GridSecurityCredentials(
              (String) params.get("gridgain.login"), (String) params.get("gridgain.password"));

      restReq.credentials(cred);
    }

    String clientId = (String) params.get("clientId");

    try {
      if (clientId != null) restReq.clientId(UUID.fromString(clientId));
    } catch (Exception ignored) {
      // Ignore invalid client id. Rest handler will process this logic.
    }

    String destId = (String) params.get("destId");

    try {
      if (destId != null) restReq.destinationId(UUID.fromString(destId));
    } catch (IllegalArgumentException ignored) {
      // Don't fail - try to execute locally.
    }

    String sesTokStr = (String) params.get("sessionToken");

    try {
      if (sesTokStr != null) restReq.sessionToken(U.hexString2ByteArray(sesTokStr));
    } catch (IllegalArgumentException ignored) {
      // Ignore invalid session token.
    }

    return restReq;
  }